From ac032be74a1ce78c2c3cbf0ff11f5a08ae7d44a6 Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Thu, 19 Nov 2026 16:26:02 -0800 Subject: [PATCH 1/8] Add runtime physical columns for batched-sequence off-graph KV (ABI 2) Decouple sequence IDs from physical storage columns so the batched-sequence cache can start with 2 physical columns and grow or shrink at runtime instead of always allocating max_seqs + 1 columns. - CudaKVPool gains resize_columns() with declared vs physical column counts, transactional replacement copies, and binding invalidation on column moves (mirroring grow()). - CudaBatchedSequenceCache tracks IDs and physical columns separately, uploads a 5-wide seq_info whose last field is the runtime pitch, and adds ensure_columns()/compact_columns() behind an inflight guard. - The lowering pass gains manifest version 2 with runtime_columns, the SDPA kernel reads the runtime pitch via INFO_WIDTH, and CudaExecutor reads get_offgraph_kv_sequence_info_abi (1 or 2) from the program. - ABI-1 behaviour is unchanged: the new paths are gated on CacheConfig::runtime_sequence_columns and manifest version 2. Tests: extended test_cuda_kv_cache and test_offgraph_kv_batched_sequence, plus an opt-in Muse-Glimmer runtime KV probe. The SDPA ring-scan logic from the experiment patch was intentionally not ported: main's ring handling is kept and only the runtime-pitch change is included. This is PR 1 of the runtime-columns series; per-owner capacities (ABI 3) build on the ID/column split introduced here. --- backends/cuda/batching/cuda_executor.cpp | 16 + backends/cuda/batching/cuda_executor.h | 3 +- backends/cuda/passes/lower_offgraph_kv.py | 28 +- backends/cuda/runtime/cuda_kv_cache.cpp | 191 +++++++-- backends/cuda/runtime/cuda_kv_cache.h | 9 + backends/cuda/runtime/cuda_kv_pool.cpp | 170 +++++++- backends/cuda/runtime/cuda_kv_pool.h | 26 +- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 380 ++++++++++++++++++ .../test_offgraph_kv_batched_sequence.py | 122 ++++++ backends/cuda/triton/kernels/sdpa_varlen.py | 40 +- examples/models/muse-glimmer/CMakeLists.txt | 21 + .../models/muse-glimmer/export/export_solo.py | 27 +- .../tests/runtime_kv_columns_probe.cpp | 289 +++++++++++++ extension/llm/cache/cache.h | 2 + 14 files changed, 1273 insertions(+), 51 deletions(-) create mode 100644 examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index b33cb492fbf..01e1b51862c 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -369,6 +369,15 @@ Result> CudaExecutor::create( declared_seqs, metadata::detail::read_int_method(*module, kMaxSeqsMethod)); const bool sequence_layout = declared_seqs.has_value(); + ET_ASSIGN_OR_RETURN( + sequence_info_abi, + metadata::detail::read_int_method( + *module, "get_offgraph_kv_sequence_info_abi")); + ET_CHECK_OR_RETURN_ERROR( + sequence_info_abi.value_or(1) == 1 || + (sequence_layout && sequence_info_abi == 2), + InvalidProgram, + "CudaExecutor: unsupported sequence-info ABI"); std::int64_t max_cells = 0; if (sequence_layout) { ET_CHECK_OR_RETURN_ERROR( @@ -527,6 +536,7 @@ Result> CudaExecutor::create( static_cast(sequence_layout ? max_context_length : max_cells); cfg.kv_dtype = kv_dtype; cfg.max_write = max_step_tokens; + cfg.runtime_sequence_columns = sequence_info_abi == 2; if (sequence_layout) { cfg.max_seqs = static_cast(*declared_seqs); } @@ -1089,6 +1099,12 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const { return kv_->metrics(); } +Error CudaExecutor::compact_kv_columns(int spare_columns) { + ET_CHECK_OR_RETURN_ERROR( + !raw_executing_, InvalidState, "CudaExecutor: compact between executes"); + return kv_->compact_columns(spare_columns); +} + 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..48baf7ffa1e 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -227,6 +227,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // The cache's pool usage, for memory reporting. OffGraphKVMetrics kv_metrics() const; + ::executorch::runtime::Error compact_kv_columns(int spare_columns = 1); // Every method, narrowest first, with how many forwards it ran. Read it // between executes, not while one runs. @@ -273,7 +274,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { llm_cache::InstallGuard install_guard_; std::unique_ptr<::executorch::extension::Module> module_; llm_cache::BatchControl* const ctl_; - const CudaKVCache* const kv_; + CudaKVCache* const kv_; std::string backend_id_; std::int32_t vocab_size_; int max_session_tokens_; diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index 15c994a9708..b71f9e4961b 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -84,8 +84,8 @@ def ring_physical_capacity(window: int, max_write: int) -> int: def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 manifest = json.loads(value.decode("utf-8")) - if manifest.get("version") != 1: - raise ValueError("off-graph KV manifest version must be 1") + if manifest.get("version") not in (1, 2): + raise ValueError("off-graph KV manifest version must be 1 or 2") maximum_capacity = manifest.get("maximum_capacity") if not isinstance(maximum_capacity, int) or maximum_capacity <= 0: raise ValueError("off-graph maximum_capacity must be positive") @@ -95,6 +95,16 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 layout = manifest.setdefault("layout", "sequence") if layout not in ("sequence", *PACKED_LAYOUTS): raise ValueError(f"invalid off-graph KV layout {layout!r}") + runtime_columns = manifest.setdefault("runtime_columns", False) + if not isinstance(runtime_columns, bool): + raise ValueError("off-graph runtime_columns must be a bool") + if manifest["version"] == 2: + if layout != "batched-sequence" or not runtime_columns: + raise ValueError( + "off-graph version 2 requires batched-sequence runtime columns" + ) + elif runtime_columns: + raise ValueError("off-graph runtime columns require manifest version 2") if layout == "batched-sequence": for key in ("max_seqs", "max_segments"): if not isinstance(manifest.get(key), int) or manifest[key] <= 0: @@ -297,6 +307,7 @@ def batched_sequence_step( causal: bool, out_dtype: torch.dtype | None = None, context_window: bool = False, + runtime_columns: bool = False, ) -> torch.Tensor: """Write this step's K/V into each sequence's column, then attend. @@ -311,9 +322,12 @@ def batched_sequence_step( K/V-width entries. ``k``/``v`` are BHSD; the storage is BSHD. ``context_window`` gives every draft block query the same retained context before the block; ordinary attention uses each query's own window. + With ``runtime_columns``, ABI-5 ``seq_info[:, 4]`` 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) if runtime_columns else columns + 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] @@ -342,6 +356,7 @@ def _batched_sequence_step_fn( causal: bool, out_dtype, context_window: bool = False, + runtime_columns: bool = False, ): def fn(q, k, v, position, k_storage, v_storage, seq_cols, seq_info): return batched_sequence_step( @@ -361,6 +376,7 @@ def fn(q, k, v, position, k_storage, v_storage, seq_cols, seq_info): causal, out_dtype, context_window, + runtime_columns, ) return fn @@ -737,7 +753,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 if self._manifest.get("runtime_columns", False) else 4, + ), torch.int32, device, ) @@ -753,6 +772,7 @@ def _lower_batched_sequence( self._manifest["causal"], out_dtype, self._manifest.get("context_window", False), + self._manifest.get("runtime_columns", False), ) return fn, call_args, example_args diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 98bc447449c..5a716ab336c 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -833,18 +833,22 @@ class CudaBatchedSequenceCache final : public cache::Cache, : geometry_(geometry), cfg_(cfg), max_seqs_(*cfg.max_seqs), - columns_(*cfg.max_seqs + 1), + columns_(cfg.runtime_sequence_columns ? 2 : *cfg.max_seqs + 1), max_write_(*cfg.max_write), max_segments_(batched_sequence_max_segments(*cfg.max_seqs)), + info_width_(cfg.runtime_sequence_columns ? 5 : 4), dflash_block_size_(geometry.dflash_block_size), 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), + cfg.runtime_sequence_columns ? 5 : 4}}}, storage_dtype, - static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1)) { + static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1), + *cfg.max_seqs + 1, + cfg.runtime_sequence_columns ? 2 : *cfg.max_seqs + 1) { for (const cache::LayerGeometry& layer : geometry.layers) { layer_rows_.push_back(rows_of(layer, cfg)); } @@ -874,7 +878,8 @@ 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_ || cfg_.runtime_sequence_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 +893,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 +935,15 @@ 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) { return std::nullopt; } - seqs_.emplace( - *column, Sequence{*column, cache::SequenceCache(geometry_, cfg_)}); - return *column; + const int column = cfg_.runtime_sequence_columns + ? free_physical_column().value_or(-1) + : *id; + seqs_.emplace(*id, Sequence{column, cache::SequenceCache(geometry_, cfg_)}); + return *id; } // Copies the retained prefix into a free column: a sequence's history is @@ -944,8 +952,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() || + (cfg_.runtime_sequence_columns && inflight_)) { return std::nullopt; } // The copies below run on this thread's stream, which may not be the @@ -958,17 +967,38 @@ 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 || + if (keep <= 0 || !plan.rewind(keep)) { + return std::nullopt; + } + const int column = cfg_.runtime_sequence_columns + ? free_physical_column().value_or(-1) + : *id; + seqs_.emplace(*id, Sequence{column, std::move(plan)}); + if (cfg_.runtime_sequence_columns && + ensure_columns(false, 0, pool_.stream()) != Error::Ok) { + seqs_.erase(*id); + return std::nullopt; + } + if (copy_column(source->second.column, seqs_.at(*id).column, keep) != + Error::Ok || pool_.mark_step_done() != Error::Ok) { + if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + } + seqs_.erase(*id); return std::nullopt; } - seqs_.emplace(*column, Sequence{*column, std::move(plan)}); - return *column; + return *id; } bool seq_rm(int32_t seq_id) override { std::lock_guard guard(mutex_); + if (cfg_.runtime_sequence_columns && + (inflight_ || + std::find(step_seq_ids_.begin(), step_seq_ids_.end(), seq_id) != + step_seq_ids_.end())) { + return false; + } return seqs_.erase(seq_id) > 0; } @@ -1017,7 +1047,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::lock_guard guard(mutex_); ET_CHECK_OK_OR_RETURN_ERROR(error_); ET_CHECK_OR_RETURN_ERROR( - !poisoned_ && (!dflash_block_size_ || pending_owners_.empty()), + !poisoned_ && (!cfg_.runtime_sequence_columns || !inflight_) && + (!dflash_block_size_ || pending_owners_.empty()), InvalidState, "offgraph_kv: uncommitted or failed draft co-batch; clear required"); if (!validated_) { @@ -1066,6 +1097,9 @@ class CudaBatchedSequenceCache final : public cache::Cache, for (const auto& [seq_id, end] : ends) { required = std::max(required, end); } + if (cfg_.runtime_sequence_columns) { + ET_CHECK_OK_OR_RETURN_ERROR(ensure_columns(false, 0, stream)); + } ET_CHECK_OK_OR_RETURN_ERROR(pool_.prepare( std::min(required, cfg_.capacity) * columns_, live * columns_, @@ -1073,17 +1107,22 @@ 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_) * info_width_ * 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_ * info_width_, 0); + if (cfg_.runtime_sequence_columns) { + for (int index = 0; index < max_segments_; ++index) { + info[index * info_width_ + 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 * info_width_; 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 +1151,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, } } step_seq_ids_.clear(); + inflight_ = cfg_.runtime_sequence_columns; return Error::Ok; } @@ -1125,6 +1165,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, InvalidState, "offgraph_kv: uncommitted or failed draft co-batch; clear required"); ET_CHECK_OK_OR_RETURN_ERROR(pool_.mark_step_done()); + 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); @@ -1151,9 +1192,31 @@ 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; } + Error compact_columns(int spare_columns) override { + std::lock_guard guard(mutex_); + ET_CHECK_OR_RETURN_ERROR( + cfg_.runtime_sequence_columns, + NotSupported, + "offgraph_kv: program uses fixed physical columns"); + ET_CHECK_OR_RETURN_ERROR( + !poisoned_ && !inflight_ && step_seq_ids_.empty() && + pending_owners_.empty(), + InvalidState, + "offgraph_kv: compact only between committed steps"); + ET_CHECK_OR_RETURN_ERROR( + spare_columns >= 0 && spare_columns <= max_seqs_, + InvalidArgument, + "offgraph_kv: invalid spare columns"); + return ensure_columns(true, spare_columns, pool_.stream()); + } + protected: void* face(cache::FaceId id) override { return cache::expose(this, id); @@ -1193,7 +1256,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, return layers; } - std::optional free_column() const { + std::optional free_sequence_id() const { for (int column = 0; column < max_seqs_; ++column) { if (seqs_.count(column) == 0) { return column; @@ -1202,6 +1265,85 @@ class CudaBatchedSequenceCache final : public cache::Cache, return std::nullopt; } + std::optional free_physical_column() const { + for (int column = 0; column < columns_ - 1; ++column) { + bool used = false; + for (const auto& [id, sequence] : seqs_) { + used |= sequence.column == column; + } + if (!used) { + return column; + } + } + return std::nullopt; + } + + Error ensure_columns(bool compact, int spare_columns, cudaStream_t stream) { + const int live = static_cast(seqs_.size()); + const int target = compact + ? std::min(max_seqs_, std::max(1, live + spare_columns)) + 1 + : std::max(columns_, live + 1); + std::map next; + std::unordered_set used; + bool relocate = false; + for (const auto& [id, sequence] : seqs_) { + if (compact) { + const int column = static_cast(next.size()); + next.emplace(id, column); + used.insert(column); + relocate |= sequence.column >= 0 && sequence.column != column; + } else 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_ || relocate || compact) { + std::vector> retained; + for (const auto& [id, sequence] : seqs_) { + if (sequence.column >= 0) { + retained.emplace_back(sequence.column, next.at(id)); + } + } + bool committed = false; + const Error error = pool_.resize_columns( + target, retained, stream, /*trim_unused=*/true, &committed); + if (error != Error::Ok && !committed) { + return error; + } + columns_ = target; + for (auto& [id, sequence] : seqs_) { + sequence.column = next.at(id); + } + if (error != Error::Ok) { + poisoned_ = true; + return error; + } + } else { + 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 @@ -1257,7 +1399,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::tuple{ kSeqInfoBuffer, cols_bytes, - static_cast(max_segments_) * 4 * sizeof(int32_t)}}) { + static_cast(max_segments_) * info_width_ * + sizeof(int32_t)}}) { const cudaError_t error = cudaMemcpyAsync( pool_.side_buffer(index), staging_ + offset, @@ -1331,9 +1474,11 @@ class CudaBatchedSequenceCache final : public cache::Cache, const cache::CacheGeometry geometry_; const cache::CacheConfig cfg_; const int max_seqs_; - const int columns_; + int columns_; const int max_write_; const int max_segments_; + const int info_width_; + bool inflight_{false}; const std::optional dflash_block_size_; std::vector layer_rows_; CudaKVPool pool_; diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index 82430e40e3e..f10fb75a9a2 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -34,6 +34,10 @@ struct OffGraphKVMetrics { // so this also identifies the addresses a compiled program was bound to. int64_t growth_count{0}; int64_t allocated_bytes{0}; + int64_t physical_columns{0}; + int64_t declared_columns{0}; + 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 @@ -83,6 +87,11 @@ class CudaKVCache { virtual runtime::Error commit_step(int64_t write_length) = 0; virtual OffGraphKVMetrics metrics() const = 0; + + // An explicit idle boundary; callers must serialize this with execution. + virtual runtime::Error compact_columns(int) { + return runtime::Error::NotSupported; + } }; // Compile spec naming where a method's inputs carry the step width. diff --git a/backends/cuda/runtime/cuda_kv_pool.cpp b/backends/cuda/runtime/cuda_kv_pool.cpp index 74fcf6a2be8..46ff31a183b 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)); } } } @@ -220,6 +224,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 +303,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 +385,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 +426,19 @@ 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; +} + +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 +458,143 @@ Error CudaKVPool::grow( graph.warmup_remaining = std::max(graph.warmup_remaining, 1); } } +} + +Error CudaKVPool::resize_columns( + int columns, + const std::vector>& retained_columns, + cudaStream_t stream, + bool trim_unused, + bool* committed) { + if (committed != nullptr) { + *committed = false; + } + ET_CHECK_OR_RETURN_ERROR( + declared_columns_ > 1 && columns >= 2 && columns <= declared_columns_, + InvalidArgument, + "offgraph_kv: invalid physical columns %d/%d", + columns, + declared_columns_); + std::unordered_set sources; + std::unordered_set destinations; + bool relocate = false; + for (const auto& [from, to] : retained_columns) { + ET_CHECK_OR_RETURN_ERROR( + from >= 0 && from < columns_ - 1 && to >= 0 && to < columns - 1 && + sources.insert(from).second && destinations.insert(to).second, + InvalidArgument, + "offgraph_kv: invalid retained column %d->%d", + from, + to); + relocate |= from != to; + } + 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; + if (committed != nullptr) { + *committed = true; + } + return Error::Ok; + } + const auto device = CUDAGuard::create(device_); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + // Resize is an explicit boundary, not a synchronization in every forward. + ET_CHECK_OK_OR_RETURN_ERROR(synchronize(/*all_streams=*/true)); + stream_ = stream; + if (trim_unused) { + CudaAllocator::release_cached_memory(device_); + } + if (columns == columns_ && !relocate) { + return Error::Ok; + } + + 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); + } + if (cudaStreamSynchronize(stream) == cudaSuccess && trim_unused) { + CudaAllocator::release_cached_memory(device_); + } + }; + 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(current.rows / old_columns); + for (const auto& [from, to] : retained_columns) { + for (const auto& [dst, src] : + {std::pair{replacement.k, current.k}, + std::pair{replacement.v, current.v}}) { + const cudaError_t error = cudaMemcpy2DAsync( + static_cast(dst) + slot * to, + slot * columns, + static_cast(src) + slot * from, + slot * old_columns, + slot, + logical_rows, + cudaMemcpyDeviceToDevice, + stream); + if (error != cudaSuccess) { + roll_back(); + return Error::Internal; + } + } + } + } + if (cudaStreamSynchronize(stream) != cudaSuccess) { + 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_++; + if (committed != nullptr) { + *committed = true; + } + if (trim_unused) { + ET_CHECK_OR_RETURN_ERROR( + cudaStreamSynchronize(stream) == cudaSuccess, + Internal, + "offgraph_kv: cannot finish freeing obsolete column storage"); + CudaAllocator::release_cached_memory(device_); + } 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 live_columns=%zu " + "allocated_bytes=%lld column_resize_count=%lld", + old_columns, + columns_, + retained_columns.size(), static_cast(allocated_bytes_), - static_cast(growth_count_)); + static_cast(column_resize_count_)); return Error::Ok; } diff --git a/backends/cuda/runtime/cuda_kv_pool.h b/backends/cuda/runtime/cuda_kv_pool.h index c78f85431bd..02d8fd11493 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -57,7 +58,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,6 +85,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. + // Each pair is a retained old column and its new column. Dummy data is not + // retained. The operation commits only after every replacement copy passes. + runtime::Error resize_columns( + int columns, + const std::vector>& retained_columns, + cudaStream_t stream, + bool trim_unused, + bool* committed = nullptr); + // 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(); @@ -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_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 8d753579de0..809c241d7fa 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2719,6 +2719,386 @@ 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; + cfg.runtime_sequence_columns = true; + 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, GrowthAndSparseIdCompactionPreserveAllKV) { + 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}) { + while (ids.size() < static_cast(sessions)) { + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ids.push_back(*id); + } + std::array, 4> retained; + if (old_columns != 0) { + seed(fake, 4, old_columns); + for (size_t layer = 0; layer < 4; ++layer) { + retained[layer] = read_column( + fake.bound[fake.internal_names[layer]].data, 4, old_columns, 0); + } + } + 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 layer = 0; layer < 4; ++layer) { + EXPECT_EQ( + read_column( + fake.bound[fake.internal_names[layer]].data, + 4, + sessions + 1, + 0), + retained[layer]); + } + } + old_columns = sessions + 1; + } + + // Preserve a nonzero logical ID while compacting it into physical column 0. + const int32_t survivor = ids[5]; + const int rows = static_cast(kv->metrics().flat_capacity); + 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)); + } + } + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + const auto after = kv->metrics(); + EXPECT_EQ(after.physical_columns, 2); + EXPECT_EQ(after.live_sequences, 1); + EXPECT_EQ(after.flat_capacity, before.flat_capacity); + EXPECT_EQ(control->pos(survivor), position); + EXPECT_LT(after.allocated_bytes, before.allocated_bytes); + EXPECT_EQ(after.allocated_bytes * 17, before.allocated_bytes * 2); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + for (size_t layer = 0; layer < 4; ++layer) { + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, rows, 2, 0), + retained[layer]); + } + ASSERT_EQ(step(*cache_ptr, handle, {survivor}, 4), Error::Ok); + std::array cols{}; + ASSERT_EQ( + cudaMemcpy( + cols.data(), + fake.bound["seq_cols"].data, + sizeof(cols), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(cols, (std::array{0, 1, 1, 1})); + 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], 0); + EXPECT_EQ(info[3], position + 1); + for (int row = 0; row < kSegments; ++row) { + EXPECT_EQ(info[row * 5 + 4], 2); + } + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { + 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); + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + std::vector values(rows * 2 * kRow, 1234 + layer); + 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->compact_columns(0), Error::Ok); + 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, 2, 0), + std::vector(rows * kRow, 1234 + layer)); + } + ASSERT_EQ(step(*cache_ptr, handle, {*clone}), Error::Ok); + EXPECT_EQ(control->pos(*clone), 41); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, PendingStepMustFinishBeforeContraction) { + 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})); + EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); + EXPECT_FALSE(control->seq_rm(*id)); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); + EXPECT_FALSE(control->seq_rm(*id)); + ASSERT_EQ(kv->commit_step(1), Error::Ok); + ASSERT_TRUE(control->seq_rm(*id)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->metrics().live_sequences, 0); + EXPECT_EQ(kv->metrics().physical_columns, 2); + control->clear(); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, FixedInfoABIIsRejected) { + 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, ContractionInvalidatesEveryGraphAndBinding) { + 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(); + const auto b = control->seq_new(); + ASSERT_TRUE(a.has_value()); + ASSERT_TRUE(b.has_value()); + ASSERT_EQ(step(*cache_ptr, decode, {*a, *b}), 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; + ASSERT_TRUE(control->seq_rm(*a)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + 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; + bool committed = true; + EXPECT_EQ( + pool.resize_columns( + kDeclaredColumns, + {{0, 0}}, + cudaStreamPerThread, + /*trim_unused=*/true, + &committed), + Error::MemoryAllocationFailed); + EXPECT_FALSE(committed); + 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(), Error::Ok); + pool.forget_handle(&handle); +} + TEST_F(CudaBatchedSequenceCacheTest, BuilderValidatesAndIsRegistered) { auto no_seqs = sequence_config(); no_seqs.max_seqs.reset(); diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index 257e81df5e7..fcce318504b 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -261,6 +261,105 @@ def forward(self, q, k, v, position): return flat + ring +@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, old_info = _plan( + seq_ids, + position, + mapping, + max_write, + 42, + physical_columns - 1, + ) + seq_info = torch.cat( + [old_info, old_info.new_full((42, 1), physical_columns)], dim=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, + runtime_columns=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) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") class LowerBatchedSequencePassTest(unittest.TestCase): CAPACITY = 32 @@ -322,6 +421,29 @@ def test_manifest_is_validated(self) -> None: with self.assertRaises(ValueError): parse_offgraph_kv_manifest(self.manifest(**bad)) + def test_runtime_pitch_manifest_and_side_buffer(self) -> None: + manifest = self.manifest(version=2, runtime_columns=True) + parsed = parse_offgraph_kv_manifest(manifest) + self.assertTrue(parsed["runtime_columns"]) + 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( + buffers[f"{OFFGRAPH_KV_FQN_PREFIX}layer_0_k"], + (1, self.CAPACITY * (self.MAX_SEQS + 1), N_KV_HEADS, HEAD_DIM), + ) + for bad in ( + self.manifest(version=1, runtime_columns=True), + self.manifest(version=2, runtime_columns=False), + self.manifest(version=2), + ): + with self.assertRaises(ValueError): + parse_offgraph_kv_manifest(bad) + def test_declares_column_storage_and_step_buffers(self) -> None: lowered = self._lowered() graph = lowered.graph_module.graph diff --git a/backends/cuda/triton/kernels/sdpa_varlen.py b/backends/cuda/triton/kernels/sdpa_varlen.py index bc3ecea5698..d2bb3b4f253 100644 --- a/backends/cuda/triton/kernels/sdpa_varlen.py +++ b/backends/cuda/triton/kernels/sdpa_varlen.py @@ -24,6 +24,10 @@ * ``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 runtime-column ABI uses ``Int32[S, 5]``. Its last field is the physical +column count, shared by every segment, which sets the K/V row pitch even when +the compiled tensor declares a larger maximum number of columns. + 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 @@ -65,6 +69,7 @@ def _sdpa_varlen_kernel( # noqa: C901 sm_scale, rows_available, num_qb, + INFO_WIDTH: tl.constexpr, NUM_SPLITS: tl.constexpr, IS_CAUSAL: tl.constexpr, CONTEXT_WINDOW: tl.constexpr, @@ -82,10 +87,14 @@ 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 * INFO_WIDTH + 0) + q_len = tl.load(Info_ptr + seg * INFO_WIDTH + 1) + col = tl.load(Info_ptr + seg * INFO_WIDTH + 2) + kv_end = tl.load(Info_ptr + seg * INFO_WIDTH + 3) + if INFO_WIDTH == 5: + columns = tl.load(Info_ptr + seg * INFO_WIDTH + 4).to(tl.int64) + stride_kr = columns * stride_kc + stride_vr = columns * stride_vc if qb * BLOCK_M >= q_len * NUM_GROUPS: return @@ -212,6 +221,7 @@ def _sdpa_varlen_decode_kernel( sm_scale, rows_available, NUM_SEGMENTS: tl.constexpr, + INFO_WIDTH: tl.constexpr, NUM_SPLITS: tl.constexpr, IS_CAUSAL: tl.constexpr, CONTEXT_WINDOW: tl.constexpr, @@ -233,14 +243,18 @@ def _sdpa_varlen_decode_kernel( 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 * INFO_WIDTH) + seg_q_len = tl.load(Info_ptr + seg * INFO_WIDTH + 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 * INFO_WIDTH + 2), col) + kv_end = tl.where(take, tl.load(Info_ptr + seg * INFO_WIDTH + 3), kv_end) + if INFO_WIDTH == 5: + 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) @@ -438,8 +452,12 @@ 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[1] not in (4, 5) + ): + raise ValueError("seq_info must be Int32[S, 4] or runtime-pitch 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 context_window and is_causal: @@ -490,6 +508,7 @@ def sdpa_varlen( # noqa: C901 scale, available, NUM_SEGMENTS=seq_info.shape[0], + INFO_WIDTH=seq_info.shape[1], NUM_SPLITS=splits, IS_CAUSAL=is_causal, CONTEXT_WINDOW=context_window, @@ -528,6 +547,7 @@ def sdpa_varlen( # noqa: C901 scale, available, num_qb, + INFO_WIDTH=seq_info.shape[1], NUM_SPLITS=splits, IS_CAUSAL=is_causal, CONTEXT_WINDOW=context_window, diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 640b48f9d50..0c6654cc4b8 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -144,6 +144,27 @@ 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(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 064292d8ea1..ce23d863b97 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -126,7 +126,12 @@ def export_and_lower( max_cells: int = 65536, kv_layout: str = "cell", max_kv_seqs: int = 4, + runtime_kv_columns: bool = False, ) -> None: + if runtime_kv_columns and not ( + backend == "cuda" and use_offgraph_kv_cache and kv_layout == "sequence" + ): + raise ValueError("runtime KV columns require CUDA off-graph sequence layout") if use_offgraph_kv_cache and use_turboquant: raise ValueError("off-graph KV cache and TurboQuant are mutually exclusive") if backend == "mlx" and use_offgraph_kv_cache: @@ -149,6 +154,7 @@ def export_and_lower( device_sampling=sample, kv_layout=kv_layout, max_kv_seqs=max_kv_seqs, + runtime_kv_columns=runtime_kv_columns, vision_model=vision_model, pos_embed_table=pos_embed_table, max_vision_patches=max_vision_patches, @@ -338,6 +344,7 @@ def batched_sequence_manifest( max_seqs: int, causal: bool = True, context_window: bool = False, + runtime_columns: bool = False, ) -> str: """The batched-sequence lowering manifest: one column per sequence.""" from executorch.backends.cuda.passes.lower_offgraph_kv import ( @@ -349,6 +356,9 @@ def batched_sequence_manifest( manifest["max_seqs"] = max_seqs manifest["max_segments"] = batched_sequence_max_segments(max_seqs) manifest["causal"] = causal + if runtime_columns: + manifest["version"] = 2 + manifest["runtime_columns"] = True if context_window: manifest["context_window"] = True return json.dumps(manifest, sort_keys=True, separators=(",", ":")) @@ -423,6 +433,7 @@ def export_cuda_batching( # noqa: C901 max_vision_patches: int = 16384, kv_layout: str = "cell", max_kv_seqs: int = 4, + runtime_kv_columns: bool = False, ): """Exports the forward methods and writes the artifact. @@ -464,6 +475,8 @@ def export_cuda_batching( # noqa: C901 if kv_layout not in KV_LAYOUTS: raise ValueError(f"kv_layout must be one of {KV_LAYOUTS}, got {kv_layout!r}") sequence_layout = kv_layout == "sequence" + if runtime_kv_columns and (not sequence_layout or dflash_draft is not None): + raise ValueError("runtime KV columns require solo sequence-layout export") if sequence_layout and max_kv_seqs <= 0: raise ValueError("the sequence layout needs max_kv_seqs > 0") has_vision = vision_model is not None and pos_embed_table is not None @@ -509,7 +522,7 @@ def export_cuda_batching( # noqa: C901 raise ValueError("max_step_tokens must be below the model's context") inductor_config.coordinate_descent_tuning = False - inductor_config.aot_inductor.compile_wrapper_opt_level = "O0" + inductor_config.aot_inductor.compile_wrapper_opt_level = "O2" # The PCH path shells out to `openssl sha512` and is flaky; it is only a # compile-time optimization. inductor_config.aot_inductor.precompile_headers = False @@ -518,7 +531,9 @@ def export_cuda_batching( # noqa: C901 single_manifest = enable_offgraph_kv_cache(model, max_step_tokens) manifest = ( - batched_sequence_manifest(single_manifest, max_kv_seqs) + batched_sequence_manifest( + single_manifest, max_kv_seqs, runtime_columns=runtime_kv_columns + ) if sequence_layout else cell_manifest(single_manifest, max_cells) ) @@ -677,6 +692,8 @@ def partitioner(name: str) -> CudaPartitioner: constant_methods["use_sampling"] = False if sequence_layout: constant_methods[MAX_KV_SEQS_METHOD] = max_kv_seqs + if runtime_kv_columns: + constant_methods["get_offgraph_kv_sequence_info_abi"] = 2 else: constant_methods[MAX_CELLS_METHOD] = max_cells if "draft_forward" in programs: @@ -1218,6 +1235,11 @@ def main() -> None: "use, up to this.", ) add_kv_layout_arguments(parser) + parser.add_argument( + "--runtime-kv-columns", + action="store_true", + help="Export the experimental runtime-pitch ABI for CUDA sequence KV storage.", + ) parser.add_argument( "--activation-dtype", default=None, @@ -1358,6 +1380,7 @@ def main() -> None: max_cells=args.max_cells, kv_layout=args.kv_layout, max_kv_seqs=args.max_kv_seqs, + runtime_kv_columns=args.runtime_kv_columns, ) 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..ff3e3a78cf9 --- /dev/null +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -0,0 +1,289 @@ +/* + * 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 +#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) { + nvtxRangePushA(label.c_str()); + } + ~DiagnosticRange() { + nvtxRangePop(); + } + 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()) { + result["method_calls"].push_back( + {{"method", method.name}, {"calls", method.calls}}); + } + 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) { + 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 == "compact") { + require( + executor->compact_kv_columns(request.value("spare_columns", 0)) == + Error::Ok, + "compact physical KV"); + } 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..56602eeb300 100644 --- a/extension/llm/cache/cache.h +++ b/extension/llm/cache/cache.h @@ -178,6 +178,8 @@ struct ET_EXPERIMENTAL CacheConfig { // storage width is fixed when the program is compiled. Unset = no fixed // bound; the capacity they share is the only limit. std::optional max_seqs; + // Requires a batched-sequence program with the runtime-pitch ABI. + bool runtime_sequence_columns = false; }; ET_EXPERIMENTAL inline bool valid(const CacheGeometry& geometry) { From b649b062c27f9834a5e75715e83941aca9399b52 Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Thu, 19 Nov 2026 16:35:13 -0800 Subject: [PATCH 2/8] Address Claude review: inflight recovery, geometric growth, DFlash guard - Revert the unrelated O0 -> O2 change in export_solo.py. - Recover a prepared-but-uncommitted ABI-2 step in the next prepare_step (fence all streams, then clear inflight_) instead of wedging the cache until clear() drops every sequence; add a regression test. - Grow physical columns geometrically and trim the allocator only on the compact path, avoiding one full KV copy per admission. - Reject runtime columns + DFlash in CudaExecutor and in the batched-sequence cache factory. - Gate the seq_clone fence/poison on runtime columns so ABI-1 clone failures are unchanged; refuse seq_rm for a declared sequence in both ABIs. - Fix the lintrunner CMake formatting failure and stale seq_info width comments. - Pool resize comment and lowering .get() redundancy left as-is: resize_columns is only called from ensure_columns, and the .get() keeps LowerOffGraphKVPass usable with manifests not built by the parser. --- backends/cuda/batching/cuda_executor.cpp | 7 +++ backends/cuda/runtime/cuda_kv_cache.cpp | 48 +++++++++++++++---- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 23 +++++++++ backends/cuda/triton/kernels/sdpa_varlen.py | 3 +- examples/models/muse-glimmer/CMakeLists.txt | 12 +++-- .../models/muse-glimmer/export/export_solo.py | 2 +- 6 files changed, 79 insertions(+), 16 deletions(-) diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index 01e1b51862c..6cb975fa8d6 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -378,6 +378,13 @@ Result> CudaExecutor::create( (sequence_layout && sequence_info_abi == 2), InvalidProgram, "CudaExecutor: unsupported sequence-info ABI"); + // Runtime columns have not been qualified with draft (DFlash) programs: + // column moves interact with pending draft owners, and the combination + // is rejected by the factory as well as here. + ET_CHECK_OR_RETURN_ERROR( + !(sequence_info_abi == 2 && geometry.dflash_block_size), + InvalidProgram, + "CudaExecutor: runtime sequence columns do not support DFlash"); std::int64_t max_cells = 0; if (sequence_layout) { ET_CHECK_OR_RETURN_ERROR( diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 5a716ab336c..c5e36418e73 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -982,7 +982,11 @@ class CudaBatchedSequenceCache final : public cache::Cache, if (copy_column(source->second.column, seqs_.at(*id).column, keep) != Error::Ok || pool_.mark_step_done() != Error::Ok) { - if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + // Only the runtime-column path fences here: an ABI-1 clone failure + // previously just returned nullopt, and a device-wide sync plus + // poisoning must not change its failure behaviour. + if (cfg_.runtime_sequence_columns && + pool_.synchronize(/*all_streams=*/true) != Error::Ok) { poisoned_ = true; } seqs_.erase(*id); @@ -993,10 +997,12 @@ class CudaBatchedSequenceCache final : public cache::Cache, bool seq_rm(int32_t seq_id) override { std::lock_guard guard(mutex_); - if (cfg_.runtime_sequence_columns && - (inflight_ || - std::find(step_seq_ids_.begin(), step_seq_ids_.end(), seq_id) != - step_seq_ids_.end())) { + // Refuse while a step is in flight or declared, in both ABIs: removing + // a declared sequence would make the next prepare_step look it up in + // seqs_ and throw. The inflight part only ever applies to ABI 2. + if (inflight_ || + std::find(step_seq_ids_.begin(), step_seq_ids_.end(), seq_id) != + step_seq_ids_.end()) { return false; } return seqs_.erase(seq_id) > 0; @@ -1047,10 +1053,22 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::lock_guard guard(mutex_); ET_CHECK_OK_OR_RETURN_ERROR(error_); ET_CHECK_OR_RETURN_ERROR( - !poisoned_ && (!cfg_.runtime_sequence_columns || !inflight_) && - (!dflash_block_size_ || pending_owners_.empty()), + !poisoned_ && (!dflash_block_size_ || pending_owners_.empty()), InvalidState, "offgraph_kv: uncommitted or failed draft co-batch; clear required"); + if (cfg_.runtime_sequence_columns && inflight_) { + // The previous step was prepared but never committed: the backend + // skips commit on any execute failure, so without recovery one + // failed forward would wedge the cache until clear() dropped every + // live sequence. Fence every stream first -- no forward can still + // be reading or writing the columns -- then treat the step as + // aborted and proceed. Draft programs keep the stricter guard above. + if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + return Error::Internal; + } + inflight_ = false; + } if (!validated_) { const Error valid = pool_.validate(); if (valid != Error::Ok) { @@ -1280,9 +1298,15 @@ class CudaBatchedSequenceCache final : public cache::Cache, Error ensure_columns(bool compact, int spare_columns, cudaStream_t stream) { const int live = static_cast(seqs_.size()); + // Grow geometrically (doubling the live columns) instead of one column + // per admission: each resize is a device-wide sync plus a full KV copy, + // so admitting N sessions one column at a time costs N full copies. + // The declared maximum still caps the width, and compact_columns() + // is the only path that shrinks back down. + const int grown = std::max(live + 1, 2 * (columns_ - 1) + 1); const int target = compact ? std::min(max_seqs_, std::max(1, live + spare_columns)) + 1 - : std::max(columns_, live + 1); + : std::min(max_seqs_ + 1, std::max(columns_, grown)); std::map next; std::unordered_set used; bool relocate = false; @@ -1323,8 +1347,10 @@ class CudaBatchedSequenceCache final : public cache::Cache, } } bool committed = false; + // Trim the allocator only on the compact path: trimming on every + // growth hands back pool memory the next forward must re-allocate. const Error error = pool_.resize_columns( - target, retained, stream, /*trim_unused=*/true, &committed); + target, retained, stream, /*trim_unused=*/compact, &committed); if (error != Error::Ok && !committed) { return error; } @@ -1568,12 +1594,14 @@ std::shared_ptr make_cuda_batched_sequence_kv_cache( slimc10::ScalarType storage_dtype = slimc10::ScalarType::BFloat16; if (!cache::valid(geometry, cfg) || cfg.initial_capacity <= 0 || cfg.initial_capacity > cfg.capacity || + (cfg.runtime_sequence_columns && geometry.dflash_block_size) || !storage_dtype_of(cfg.kv_dtype, storage_dtype)) { ET_LOG(Error, "offgraph_kv: invalid cache geometry or config"); 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, 4 (or 5 with runtime columns)]; all are fixed + // by the program. if (!cfg.max_seqs || !cfg.max_write || *cfg.max_write > cfg.capacity || (geometry.dflash_block_size && (*geometry.dflash_block_size <= 0 || diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 809c241d7fa..7e216d0307a 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2992,6 +2992,29 @@ TEST_F(CudaRuntimeColumnCacheTest, PendingStepMustFinishBeforeContraction) { kv->forget_handle(&handle); } +TEST_F(CudaRuntimeColumnCacheTest, UncommittedStepRecoversOnNextPrepare) { + 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); + EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); + // The next step must recover (after fencing) instead of wedging until + // clear() drops every live sequence. + 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, FixedInfoABIIsRejected) { auto cache_ptr = make(); auto* kv = cache_ptr->as(); diff --git a/backends/cuda/triton/kernels/sdpa_varlen.py b/backends/cuda/triton/kernels/sdpa_varlen.py index d2bb3b4f253..88009e4b230 100644 --- a/backends/cuda/triton/kernels/sdpa_varlen.py +++ b/backends/cuda/triton/kernels/sdpa_varlen.py @@ -407,7 +407,8 @@ def sdpa_varlen( # noqa: C901 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, + seq_info: ``Int32[S, 4]`` (or ``Int32[S, 5]`` with the runtime + pitch in field 4) on the query's device, ``(q_start, q_len, col, kv_end)`` per segment; see the module docstring. scale: softmax scale. is_causal: row ``r`` sees positions up to its own; otherwise every diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 0c6654cc4b8..49fce0c3f71 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -144,19 +144,23 @@ target_include_directories( dflash_timing_test PUBLIC ${_common_include_directories} ) -option(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE "Build isolated CUDA KV diagnostic" OFF) +option(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE "Build isolated CUDA KV diagnostic" + OFF +) if(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE) 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) + 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} + ${_json_include} ) target_link_libraries( muse_glimmer_runtime_kv_probe PRIVATE cuda_batching CUDA::cudart - ${link_libraries} + ${link_libraries} ) if(NOT APPLE AND NOT MSVC) target_link_options( diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py index ce23d863b97..b19c1cfa25c 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -522,7 +522,7 @@ def export_cuda_batching( # noqa: C901 raise ValueError("max_step_tokens must be below the model's context") inductor_config.coordinate_descent_tuning = False - inductor_config.aot_inductor.compile_wrapper_opt_level = "O2" + inductor_config.aot_inductor.compile_wrapper_opt_level = "O0" # The PCH path shells out to `openssl sha512` and is flaky; it is only a # compile-time optimization. inductor_config.aot_inductor.precompile_headers = False From e87a870ebc16f7e5fdac42ac77c132afb8982e9e Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Thu, 19 Nov 2026 23:44:44 -0800 Subject: [PATCH 3/8] Fix runtime-column admission, recovery, and CUDA coverage --- .../tests/test_muse_glimmer_batching_ci.py | 9 + .github/workflows/cuda.yml | 10 +- backends/cuda/batching/cuda_executor.cpp | 46 +++-- backends/cuda/batching/cuda_executor.h | 12 ++ .../cuda/batching/test/test_cuda_executor.cpp | 11 + backends/cuda/passes/lower_offgraph_kv.py | 21 +- backends/cuda/runtime/cuda_kv_cache.cpp | 151 +++++++++----- backends/cuda/runtime/cuda_kv_cache.h | 16 +- backends/cuda/runtime/cuda_kv_pool.cpp | 10 +- backends/cuda/runtime/cuda_kv_pool.h | 5 +- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 165 +++++++++++---- .../test_offgraph_kv_batched_sequence.py | 83 +++++++- backends/cuda/triton/kernels/sdpa_varlen.py | 4 +- .../models/muse-glimmer/export/export_solo.py | 5 +- .../tests/check_runtime_kv_columns.py | 192 ++++++++++++++++++ .../tests/runtime_kv_columns_probe.cpp | 11 + extension/llm/cache/cache.h | 5 +- 17 files changed, 619 insertions(+), 137 deletions(-) create mode 100644 examples/models/muse-glimmer/tests/check_runtime_kv_columns.py diff --git a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py index 5c8fcead860..0f24d7ca2aa 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -23,6 +23,15 @@ 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) + 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 d0bc499aae9..3e8e96435e3 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -694,10 +694,12 @@ jobs: make muse-glimmer-batching-cuda 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 + -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_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" @@ -712,6 +714,10 @@ jobs: examples/models/muse-glimmer/tests/test_dflash_token_sampler.py \ examples/models/muse-glimmer/tests/test_checkpoint_context.py + 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" + # CUDA DFlash executor on a tiny exported target + draft. The native # tests skip without the artifact, so fail if any skipped. export ET_MUSE_DFLASH_TINY_DIR="${RUNNER_TEMP:-/tmp}/muse_glimmer_dflash_tiny" diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index 6cb975fa8d6..c64e72ef411 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -371,20 +371,14 @@ Result> CudaExecutor::create( const bool sequence_layout = declared_seqs.has_value(); ET_ASSIGN_OR_RETURN( sequence_info_abi, - metadata::detail::read_int_method( - *module, "get_offgraph_kv_sequence_info_abi")); + metadata::detail::read_int_method(*module, kSequenceInfoABIMethod)); ET_CHECK_OR_RETURN_ERROR( - sequence_info_abi.value_or(1) == 1 || - (sequence_layout && sequence_info_abi == 2), + detail::valid_sequence_info_abi( + sequence_info_abi.value_or(1), + sequence_layout, + geometry.dflash_block_size.has_value()), InvalidProgram, "CudaExecutor: unsupported sequence-info ABI"); - // Runtime columns have not been qualified with draft (DFlash) programs: - // column moves interact with pending draft owners, and the combination - // is rejected by the factory as well as here. - ET_CHECK_OR_RETURN_ERROR( - !(sequence_info_abi == 2 && geometry.dflash_block_size), - InvalidProgram, - "CudaExecutor: runtime sequence columns do not support DFlash"); std::int64_t max_cells = 0; if (sequence_layout) { ET_CHECK_OR_RETURN_ERROR( @@ -543,7 +537,6 @@ Result> CudaExecutor::create( static_cast(sequence_layout ? max_context_length : max_cells); cfg.kv_dtype = kv_dtype; cfg.max_write = max_step_tokens; - cfg.runtime_sequence_columns = sequence_info_abi == 2; if (sequence_layout) { cfg.max_seqs = static_cast(*declared_seqs); } @@ -554,14 +547,27 @@ Result> CudaExecutor::create( llm_cache::valid(geometry, cfg), InvalidProgram, "CudaExecutor: the program's layout is unusable"); - auto built = llm_cache::CacheFactory::global().build( - backend_id, - sequence_layout ? llm_cache::kind::kBatchedSequence - : llm_cache::kind::kBatchedCell, - geometry, - cfg); - ET_CHECK_OK_OR_RETURN_ERROR(built.error()); - std::shared_ptr cache = built.get(); + std::shared_ptr cache; + if (sequence_info_abi == 2) { + ET_CHECK_OR_RETURN_ERROR( + backend_id == kCudaBackendId, + InvalidProgram, + "CudaExecutor: runtime sequence columns require the CUDA backend"); + cache = make_cuda_batched_sequence_kv_cache(geometry, cfg, true); + ET_CHECK_OR_RETURN_ERROR( + cache != nullptr, + InvalidProgram, + "CudaExecutor: invalid runtime-column cache geometry or config"); + } else { + auto built = llm_cache::CacheFactory::global().build( + backend_id, + sequence_layout ? llm_cache::kind::kBatchedSequence + : llm_cache::kind::kBatchedCell, + geometry, + cfg); + ET_CHECK_OK_OR_RETURN_ERROR(built.error()); + cache = built.get(); + } auto* const ctl = cache->as(); ET_CHECK_OR_RETURN_ERROR( ctl != nullptr && cache->as() != nullptr, diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 48baf7ffa1e..b53ce696f21 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -51,6 +51,16 @@ inline constexpr char kMaxCellsMethod[] = "get_offgraph_kv_max_cells"; // Published instead of the cell count by a program whose KV cache keeps a // private history per sequence. inline constexpr char kMaxSeqsMethod[] = "get_offgraph_kv_max_seqs"; +inline constexpr char kSequenceInfoABIMethod[] = + "get_offgraph_kv_sequence_info_abi"; + +namespace detail { +inline bool +valid_sequence_info_abi(int64_t version, bool sequence_layout, bool draft) { + return version == 1 || (version == 2 && sequence_layout && !draft); +} +} // namespace detail + // Optional: the fewest selected rows forward_others was exported for. Its // selector is padded up to it. Defaults to 1. inline constexpr char kMinSelectedRowsMethod[] = "get_min_prefill_chunk"; @@ -227,6 +237,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // The cache's pool usage, for memory reporting. OffGraphKVMetrics kv_metrics() const; + // An idle boundary serialized with execute. The scratch column is additional + // to spare_columns unused owner columns. ::executorch::runtime::Error compact_kv_columns(int spare_columns = 1); // Every method, narrowest first, with how many forwards it ran. Read it diff --git a/backends/cuda/batching/test/test_cuda_executor.cpp b/backends/cuda/batching/test/test_cuda_executor.cpp index 062861075a7..7576f798855 100644 --- a/backends/cuda/batching/test/test_cuda_executor.cpp +++ b/backends/cuda/batching/test/test_cuda_executor.cpp @@ -39,6 +39,17 @@ namespace batching = ::executorch::extension::llm::batching; using ::executorch::extension::Module; using ::executorch::runtime::Error; +TEST(CudaExecutorMetadataTest, SequenceInfoABIRejectsUnsupportedCombinations) { + EXPECT_TRUE(cb::detail::valid_sequence_info_abi(1, false, false)); + EXPECT_TRUE(cb::detail::valid_sequence_info_abi(1, true, false)); + EXPECT_TRUE(cb::detail::valid_sequence_info_abi(1, true, true)); + EXPECT_TRUE(cb::detail::valid_sequence_info_abi(2, true, false)); + EXPECT_FALSE(cb::detail::valid_sequence_info_abi(2, false, false)); + EXPECT_FALSE(cb::detail::valid_sequence_info_abi(2, true, true)); + EXPECT_FALSE(cb::detail::valid_sequence_info_abi(0, true, false)); + EXPECT_FALSE(cb::detail::valid_sequence_info_abi(3, true, false)); +} + namespace { // Must match export_toy_decoder.py. diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index b71f9e4961b..c3db060a475 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -25,6 +25,7 @@ OFFGRAPH_KV_COMPILE_SPEC = "offgraph_kv_manifest" +OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD = "get_offgraph_kv_sequence_info_abi" # Consumed by the runtime, not by this pass: "input_index:dim" naming # the input whose extent is the number of tokens a step writes. OFFGRAPH_KV_STEP_WIDTH_COMPILE_SPEC = "offgraph_kv_step_width" @@ -149,6 +150,17 @@ 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"], + OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD: manifest["version"], + } + + def ring_attention_mask( position: torch.Tensor, buf_size: int, window: int ) -> torch.Tensor: @@ -312,7 +324,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`` is ``columns`` + for ABI 1 and ``seq_info[0, 4]`` for ABI 2. 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 @@ -322,7 +335,7 @@ def batched_sequence_step( K/V-width entries. ``k``/``v`` are BHSD; the storage is BSHD. ``context_window`` gives every draft block query the same retained context before the block; ordinary attention uses each query's own window. - With ``runtime_columns``, ABI-5 ``seq_info[:, 4]`` supplies the physical + With ``runtime_columns``, 5-wide ABI-2 ``seq_info[:, 4]`` supplies the physical pitch for writes and attention; ``columns`` remains the declared maximum. """ position = position.reshape(-1) @@ -755,7 +768,7 @@ def _lower_batched_sequence( OFFGRAPH_KV_SEQ_INFO_FQN, ( self._manifest["max_segments"], - 5 if self._manifest.get("runtime_columns", False) else 4, + 5 if self._manifest["runtime_columns"] else 4, ), torch.int32, device, @@ -772,7 +785,7 @@ def _lower_batched_sequence( self._manifest["causal"], out_dtype, self._manifest.get("context_window", False), - self._manifest.get("runtime_columns", False), + self._manifest["runtime_columns"], ) return fn, call_args, example_args diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index c5e36418e73..ef25d103cd8 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 @@ -802,9 +803,10 @@ 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]): ABI 2 supplies the physical row pitch +// in a fifth seq_info 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 @@ -813,6 +815,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { // token's column (seq_cols) and one (q_start, q_len, column, length) 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. +// ABI 2 grows owner columns on admission and reserves 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 @@ -829,26 +832,28 @@ class CudaBatchedSequenceCache final : public cache::Cache, CudaBatchedSequenceCache( const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg, - slimc10::ScalarType storage_dtype) + slimc10::ScalarType storage_dtype, + bool runtime_columns) : geometry_(geometry), cfg_(cfg), max_seqs_(*cfg.max_seqs), - columns_(cfg.runtime_sequence_columns ? 2 : *cfg.max_seqs + 1), + runtime_columns_(runtime_columns), max_write_(*cfg.max_write), max_segments_(batched_sequence_max_segments(*cfg.max_seqs)), - info_width_(cfg.runtime_sequence_columns ? 5 : 4), + info_width_(runtime_columns ? 5 : 4), dflash_block_size_(geometry.dflash_block_size), + columns_(runtime_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), - cfg.runtime_sequence_columns ? 5 : 4}}}, + runtime_columns ? 5 : 4}}}, storage_dtype, static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1), *cfg.max_seqs + 1, - cfg.runtime_sequence_columns ? 2 : *cfg.max_seqs + 1) { + runtime_columns ? 2 : *cfg.max_seqs + 1) { for (const cache::LayerGeometry& layer : geometry.layers) { layer_rows_.push_back(rows_of(layer, cfg)); } @@ -878,8 +883,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, // nor invalidates captured graphs. void clear() override { std::lock_guard guard(mutex_); - if ((dflash_block_size_ || cfg_.runtime_sequence_columns) && - pool_.allocated()) { + if ((dflash_block_size_ || runtime_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) { @@ -936,13 +940,24 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::optional seq_new() override { std::lock_guard guard(mutex_); const auto id = free_sequence_id(); - if (!id) { + if (!id || poisoned_ || + (runtime_columns_ && inflight_ && !free_physical_column())) { return std::nullopt; } - const int column = cfg_.runtime_sequence_columns - ? free_physical_column().value_or(-1) - : *id; + const int column = + runtime_columns_ ? free_physical_column().value_or(-1) : *id; seqs_.emplace(*id, Sequence{column, cache::SequenceCache(geometry_, cfg_)}); + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + seqs_.erase(*id); + } + }); + if (runtime_columns_ && + ensure_columns(false, 0, pool_.stream()) != Error::Ok) { + return std::nullopt; + } + admitted = true; return *id; } @@ -953,8 +968,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::lock_guard guard(mutex_); const auto source = seqs_.find(src); const auto id = free_sequence_id(); - if (source == seqs_.end() || !id || !pool_.allocated() || - (cfg_.runtime_sequence_columns && inflight_)) { + if (source == seqs_.end() || !id || !pool_.allocated() || poisoned_ || + (runtime_columns_ && inflight_)) { return std::nullopt; } // The copies below run on this thread's stream, which may not be the @@ -970,13 +985,17 @@ class CudaBatchedSequenceCache final : public cache::Cache, if (keep <= 0 || !plan.rewind(keep)) { return std::nullopt; } - const int column = cfg_.runtime_sequence_columns - ? free_physical_column().value_or(-1) - : *id; + const int column = + runtime_columns_ ? free_physical_column().value_or(-1) : *id; seqs_.emplace(*id, Sequence{column, std::move(plan)}); - if (cfg_.runtime_sequence_columns && + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + seqs_.erase(*id); + } + }); + if (runtime_columns_ && ensure_columns(false, 0, pool_.stream()) != Error::Ok) { - seqs_.erase(*id); return std::nullopt; } if (copy_column(source->second.column, seqs_.at(*id).column, keep) != @@ -985,26 +1004,28 @@ class CudaBatchedSequenceCache final : public cache::Cache, // Only the runtime-column path fences here: an ABI-1 clone failure // previously just returned nullopt, and a device-wide sync plus // poisoning must not change its failure behaviour. - if (cfg_.runtime_sequence_columns && + if (runtime_columns_ && pool_.synchronize(/*all_streams=*/true) != Error::Ok) { poisoned_ = true; } - seqs_.erase(*id); return std::nullopt; } + admitted = true; return *id; } bool seq_rm(int32_t seq_id) override { std::lock_guard guard(mutex_); - // Refuse while a step is in flight or declared, in both ABIs: removing - // a declared sequence would make the next prepare_step look it up in - // seqs_ and throw. The inflight part only ever applies to ABI 2. - if (inflight_ || - std::find(step_seq_ids_.begin(), step_seq_ids_.end(), seq_id) != - step_seq_ids_.end()) { + if (std::find(pending_owners_.begin(), pending_owners_.end(), seq_id) != + pending_owners_.end()) { return false; } + 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. prepare/compact fence an + // abandoned ABI-2 forward before its column can be written or moved. return seqs_.erase(seq_id) > 0; } @@ -1056,13 +1077,14 @@ class CudaBatchedSequenceCache final : public cache::Cache, !poisoned_ && (!dflash_block_size_ || pending_owners_.empty()), InvalidState, "offgraph_kv: uncommitted or failed draft co-batch; clear required"); - if (cfg_.runtime_sequence_columns && inflight_) { + if (runtime_columns_ && inflight_) { // The previous step was prepared but never committed: the backend // skips commit on any execute failure, so without recovery one // failed forward would wedge the cache until clear() dropped every // live sequence. Fence every stream first -- no forward can still // be reading or writing the columns -- then treat the step as - // aborted and proceed. Draft programs keep the stricter guard above. + // reusable and proceed, without rolling back the logical rows already + // claimed by prepare. Draft programs keep the stricter guard above. if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { poisoned_ = true; return Error::Internal; @@ -1115,7 +1137,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, for (const auto& [seq_id, end] : ends) { required = std::max(required, end); } - if (cfg_.runtime_sequence_columns) { + if (runtime_columns_) { ET_CHECK_OK_OR_RETURN_ERROR(ensure_columns(false, 0, stream)); } ET_CHECK_OK_OR_RETURN_ERROR(pool_.prepare( @@ -1130,7 +1152,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, auto* info = reinterpret_cast(cols + max_write_); std::fill(cols, cols + write_length, static_cast(columns_ - 1)); std::fill(info, info + max_segments_ * info_width_, 0); - if (cfg_.runtime_sequence_columns) { + if (runtime_columns_) { for (int index = 0; index < max_segments_; ++index) { info[index * info_width_ + 4] = columns_; } @@ -1169,7 +1191,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, } } step_seq_ids_.clear(); - inflight_ = cfg_.runtime_sequence_columns; + inflight_ = runtime_columns_; return Error::Ok; } @@ -1220,18 +1242,24 @@ class CudaBatchedSequenceCache final : public cache::Cache, Error compact_columns(int spare_columns) override { std::lock_guard guard(mutex_); ET_CHECK_OR_RETURN_ERROR( - cfg_.runtime_sequence_columns, + runtime_columns_, NotSupported, "offgraph_kv: program uses fixed physical columns"); ET_CHECK_OR_RETURN_ERROR( - !poisoned_ && !inflight_ && step_seq_ids_.empty() && - pending_owners_.empty(), + !poisoned_ && pending_owners_.empty(), InvalidState, - "offgraph_kv: compact only between committed steps"); + "offgraph_kv: cannot compact a poisoned cache or pending draft step"); ET_CHECK_OR_RETURN_ERROR( spare_columns >= 0 && spare_columns <= max_seqs_, InvalidArgument, "offgraph_kv: invalid spare columns"); + if (inflight_) { + if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + return Error::Internal; + } + inflight_ = false; + } return ensure_columns(true, spare_columns, pool_.stream()); } @@ -1275,9 +1303,9 @@ class CudaBatchedSequenceCache final : public cache::Cache, } std::optional free_sequence_id() const { - for (int column = 0; column < max_seqs_; ++column) { - if (seqs_.count(column) == 0) { - return column; + for (int id = 0; id < max_seqs_; ++id) { + if (seqs_.count(id) == 0) { + return id; } } return std::nullopt; @@ -1303,19 +1331,21 @@ class CudaBatchedSequenceCache final : public cache::Cache, // so admitting N sessions one column at a time costs N full copies. // The declared maximum still caps the width, and compact_columns() // is the only path that shrinks back down. - const int grown = std::max(live + 1, 2 * (columns_ - 1) + 1); + const int grown = live + 1 <= columns_ + ? columns_ + : static_cast(std::min( + max_seqs_ + 1LL, + std::max(live + 1LL, 2LL * (columns_ - 1) + 1))); const int target = compact ? std::min(max_seqs_, std::max(1, live + spare_columns)) + 1 : std::min(max_seqs_ + 1, std::max(columns_, grown)); std::map next; std::unordered_set used; - bool relocate = false; for (const auto& [id, sequence] : seqs_) { if (compact) { const int column = static_cast(next.size()); next.emplace(id, column); used.insert(column); - relocate |= sequence.column >= 0 && sequence.column != column; } else if (sequence.column >= 0) { ET_CHECK_OR_RETURN_ERROR( sequence.column < target - 1 && used.insert(sequence.column).second, @@ -1339,18 +1369,27 @@ class CudaBatchedSequenceCache final : public cache::Cache, next.emplace(id, column); used.insert(column); } - if (target != columns_ || relocate || compact) { + if (target != columns_ || compact) { std::vector> retained; for (const auto& [id, sequence] : seqs_) { if (sequence.column >= 0) { retained.emplace_back(sequence.column, next.at(id)); } } + int live_rows = 0; + for (const auto& [id, sequence] : seqs_) { + live_rows = std::max(live_rows, sequence.plan.length()); + } bool committed = false; // Trim the allocator only on the compact path: trimming on every // growth hands back pool memory the next forward must re-allocate. const Error error = pool_.resize_columns( - target, retained, stream, /*trim_unused=*/compact, &committed); + target, + retained, + live_rows, + stream, + /*trim_unused=*/compact, + &committed); if (error != Error::Ok && !committed) { return error; } @@ -1500,12 +1539,13 @@ class CudaBatchedSequenceCache final : public cache::Cache, const cache::CacheGeometry geometry_; const cache::CacheConfig cfg_; const int max_seqs_; - int columns_; + const bool runtime_columns_; const int max_write_; const int max_segments_; const int info_width_; - bool inflight_{false}; const std::optional dflash_block_size_; + int columns_; + bool inflight_{false}; std::vector layer_rows_; CudaKVPool pool_; std::map seqs_; @@ -1515,8 +1555,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 or post-commit resize requires a successful clear(). bool poisoned_{false}; Error error_{Error::Ok}; }; @@ -1590,11 +1629,12 @@ std::shared_ptr make_cuda_cell_kv_cache( std::shared_ptr make_cuda_batched_sequence_kv_cache( const cache::CacheGeometry& geometry, - const cache::CacheConfig& cfg) { + const cache::CacheConfig& cfg, + bool runtime_columns) { slimc10::ScalarType storage_dtype = slimc10::ScalarType::BFloat16; if (!cache::valid(geometry, cfg) || cfg.initial_capacity <= 0 || cfg.initial_capacity > cfg.capacity || - (cfg.runtime_sequence_columns && geometry.dflash_block_size) || + (runtime_columns && geometry.dflash_block_size) || !storage_dtype_of(cfg.kv_dtype, storage_dtype)) { ET_LOG(Error, "offgraph_kv: invalid cache geometry or config"); return nullptr; @@ -1613,7 +1653,7 @@ std::shared_ptr make_cuda_batched_sequence_kv_cache( return nullptr; } return std::make_shared( - geometry, cfg, storage_dtype); + geometry, cfg, storage_dtype, runtime_columns); } runtime::Error attach_offgraph_kv_cache( @@ -1663,7 +1703,10 @@ const bool cuda_cache_builders_registered = [] { } builders[] = { {cache::kind::kSingle, make_cuda_sequence_kv_cache}, {cache::kind::kBatchedCell, make_cuda_cell_kv_cache}, - {cache::kind::kBatchedSequence, make_cuda_batched_sequence_kv_cache}, + {cache::kind::kBatchedSequence, + [](const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg) { + return make_cuda_batched_sequence_kv_cache(geometry, cfg); + }}, // The cell layout is the batch layout this backend serves. {cache::kind::kBatched, make_cuda_cell_kv_cache}, }; diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index f10fb75a9a2..98947c1ebd9 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -30,12 +30,14 @@ 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 and step-buffer allocations, excluding 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}; }; @@ -89,7 +91,8 @@ class CudaKVCache { virtual OffGraphKVMetrics metrics() const = 0; // An explicit idle boundary; callers must serialize this with execution. - virtual runtime::Error compact_columns(int) { + // spare_columns counts unused owner columns, excluding the scratch column. + virtual runtime::Error compact_columns(int spare_columns) { return runtime::Error::NotSupported; } }; @@ -217,9 +220,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). runtime_columns selects ABI 2: physical owner columns +// start at one and grow on admission up to cfg.max_seqs; ABI 1 keeps the +// declared width. Both reserve one additional scratch column. std::shared_ptr make_cuda_batched_sequence_kv_cache( const cache::CacheGeometry& geometry, - const cache::CacheConfig& cfg); + const cache::CacheConfig& cfg, + bool runtime_columns = false); } // namespace executorch::backends::cuda diff --git a/backends/cuda/runtime/cuda_kv_pool.cpp b/backends/cuda/runtime/cuda_kv_pool.cpp index 46ff31a183b..d01b0a64b42 100644 --- a/backends/cuda/runtime/cuda_kv_pool.cpp +++ b/backends/cuda/runtime/cuda_kv_pool.cpp @@ -463,6 +463,7 @@ void CudaKVPool::invalidate_bindings() { Error CudaKVPool::resize_columns( int columns, const std::vector>& retained_columns, + int64_t live_rows, cudaStream_t stream, bool trim_unused, bool* committed) { @@ -470,7 +471,8 @@ Error CudaKVPool::resize_columns( *committed = false; } ET_CHECK_OR_RETURN_ERROR( - declared_columns_ > 1 && columns >= 2 && columns <= declared_columns_, + declared_columns_ > 1 && columns >= 2 && columns <= declared_columns_ && + live_rows >= 0, InvalidArgument, "offgraph_kv: invalid physical columns %d/%d", columns, @@ -541,7 +543,11 @@ Error CudaKVPool::resize_columns( 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(current.rows / old_columns); + const size_t logical_rows = + static_cast(std::min(live_rows, current.rows / old_columns)); + if (logical_rows == 0) { + continue; + } for (const auto& [from, to] : retained_columns) { for (const auto& [dst, src] : {std::pair{replacement.k, current.k}, diff --git a/backends/cuda/runtime/cuda_kv_pool.h b/backends/cuda/runtime/cuda_kv_pool.h index 02d8fd11493..4f6a2688923 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -87,10 +87,13 @@ class CudaKVPool final { // Flattened row counts remain multiples of the current physical width. // Each pair is a retained old column and its new column. Dummy data is not - // retained. The operation commits only after every replacement copy passes. + // retained. live_rows is the retained logical prefix, capped by each ring. + // Replacements commit only after all copies pass. committed may be true + // even on error if post-commit allocator trimming fails. runtime::Error resize_columns( int columns, const std::vector>& retained_columns, + int64_t live_rows, cudaStream_t stream, bool trim_unused, bool* committed = nullptr); diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 7e216d0307a..4d9c7281585 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2732,8 +2732,8 @@ class CudaRuntimeColumnCacheTest : public CudaKVCacheTest { static std::shared_ptr make() { auto cfg = config(kCapacity, 4, kMaxWrite); cfg.max_seqs = kMaxSeqs; - cfg.runtime_sequence_columns = true; - return cu::make_cuda_batched_sequence_kv_cache(flat_and_ring(2), cfg); + return cu::make_cuda_batched_sequence_kv_cache( + flat_and_ring(2), cfg, /*runtime_columns=*/true); } static FakeContainer container(int info_width = 5) { @@ -2827,19 +2827,23 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { std::vector ids; int old_columns = 0; for (const int sessions : {1, 2, 4, 8, 16}) { - while (ids.size() < static_cast(sessions)) { - const auto id = control->seq_new(); - ASSERT_TRUE(id.has_value()); - ids.push_back(*id); - } + const int live_rows = ids.empty() ? 0 : control->pos(ids.front()); std::array, 4> retained; if (old_columns != 0) { - seed(fake, 4, old_columns); + seed(fake, live_rows, old_columns); for (size_t layer = 0; layer < 4; ++layer) { retained[layer] = read_column( - fake.bound[fake.internal_names[layer]].data, 4, old_columns, 0); + fake.bound[fake.internal_names[layer]].data, + live_rows, + old_columns, + 0); } } + 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); @@ -2854,7 +2858,7 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { EXPECT_EQ( read_column( fake.bound[fake.internal_names[layer]].data, - 4, + live_rows, sessions + 1, 0), retained[layer]); @@ -2865,7 +2869,7 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { // Preserve a nonzero logical ID while compacting it into physical column 0. const int32_t survivor = ids[5]; - const int rows = static_cast(kv->metrics().flat_capacity); + const int rows = control->pos(survivor); seed(fake, rows, old_columns); std::array, 4> retained; for (size_t layer = 0; layer < 4; ++layer) { @@ -2968,7 +2972,7 @@ TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { kv->forget_handle(&handle); } -TEST_F(CudaRuntimeColumnCacheTest, PendingStepMustFinishBeforeContraction) { +TEST_F(CudaRuntimeColumnCacheTest, DeclaredStepCanCompactOrClose) { auto cache_ptr = make(); auto* control = cache_ptr->as(); auto* kv = cache_ptr->as(); @@ -2978,17 +2982,97 @@ TEST_F(CudaRuntimeColumnCacheTest, PendingStepMustFinishBeforeContraction) { const auto id = control->seq_new(); ASSERT_TRUE(id.has_value()); ASSERT_TRUE(control->declare_step({*id})); - EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); - EXPECT_FALSE(control->seq_rm(*id)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); - EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); - EXPECT_FALSE(control->seq_rm(*id)); ASSERT_EQ(kv->commit_step(1), Error::Ok); + ASSERT_TRUE(control->declare_step({*id})); ASSERT_TRUE(control->seq_rm(*id)); - ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidArgument); EXPECT_EQ(kv->metrics().live_sequences, 0); - EXPECT_EQ(kv->metrics().physical_columns, 2); - control->clear(); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, FailedStepAllowsCloseAndFencesBeforeReuse) { + 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_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); } @@ -3004,7 +3088,7 @@ TEST_F(CudaRuntimeColumnCacheTest, UncommittedStepRecoversOnNextPrepare) { // Simulate a failed forward: prepare runs, commit never does. ASSERT_TRUE(control->declare_step({*id})); ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); - EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); + EXPECT_EQ(kv->compact_columns(0), Error::Ok); // The next step must recover (after fencing) instead of wedging until // clear() drops every live sequence. ASSERT_TRUE(control->declare_step({*id})); @@ -3098,25 +3182,28 @@ TEST_F(CudaKVPoolTest, FailedColumnGrowthKeepsOldStorageAndBindingsUsable) { const auto before_bytes = pool.allocated_bytes(); const int updates = fake.updates; handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; - bool committed = true; - EXPECT_EQ( - pool.resize_columns( - kDeclaredColumns, - {{0, 0}}, - cudaStreamPerThread, - /*trim_unused=*/true, - &committed), - Error::MemoryAllocationFailed); - EXPECT_FALSE(committed); - 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); + for (const bool trim_unused : {false, true}) { + bool committed = true; + EXPECT_EQ( + pool.resize_columns( + kDeclaredColumns, + {{0, 0}}, + /*live_rows=*/1, + cudaStreamPerThread, + trim_unused, + &committed), + Error::MemoryAllocationFailed); + EXPECT_FALSE(committed); + 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(), Error::Ok); pool.forget_handle(&handle); diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index fcce318504b..f0051ff117b 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -23,12 +23,15 @@ batched_sequence_step, CheckOffGraphKVStepWidthPass, LowerOffGraphKVPass, + offgraph_kv_constant_methods, OFFGRAPH_KV_FQN_PREFIX, OFFGRAPH_KV_SEQ_COLS_FQN, OFFGRAPH_KV_SEQ_INFO_FQN, + OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD, parse_offgraph_kv_manifest, ring_physical_capacity, ) +from executorch.backends.cuda.triton.kernels.sdpa_varlen import _num_splits, sdpa_varlen from executorch.exir import EdgeCompileConfig, to_edge from executorch.exir.dialects._ops import ops as exir_ops from executorch.extension.llm.cache.reference_cache import ( @@ -359,6 +362,58 @@ def test_flat_pitch_and_sparse_survivor(self): def test_ring_pitch_and_sparse_survivor(self): self._run(window=2) + 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): @@ -474,9 +529,17 @@ 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, runtime_columns: bool) -> None: torch.manual_seed(21) - lowered = self._lowered() + manifest = self.manifest( + version=2 if runtime_columns else 1, runtime_columns=runtime_columns + ) + metadata = offgraph_kv_constant_methods(manifest) + self.assertEqual( + metadata[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], 2 if runtime_columns else 1 + ) + self.assertEqual(metadata["get_offgraph_kv_max_seqs"], self.MAX_SEQS) + lowered = self._lowered(manifest) runtime = {} for name, value in list(lowered.constants.items()): if name.startswith(OFFGRAPH_KV_FQN_PREFIX): @@ -487,7 +550,7 @@ def test_lowered_program_matches_the_neutral_op(self) -> None: 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) @@ -499,11 +562,25 @@ def test_lowered_program_matches_the_neutral_op(self) -> None: self.MAX_SEGMENTS, self.MAX_SEQS, ) + if runtime_columns: + seq_info = torch.cat( + [ + seq_info, + seq_info.new_full((self.MAX_SEGMENTS, 1), self.MAX_SEQS + 1), + ], + dim=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) + 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( self.manifest(causal=False, context_window=True), diff --git a/backends/cuda/triton/kernels/sdpa_varlen.py b/backends/cuda/triton/kernels/sdpa_varlen.py index 88009e4b230..29b58bca3eb 100644 --- a/backends/cuda/triton/kernels/sdpa_varlen.py +++ b/backends/cuda/triton/kernels/sdpa_varlen.py @@ -406,7 +406,9 @@ 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. + sequence. The head dimension must be contiguous. For 5-wide + seq_info, column/head lanes must also be contiguous and the row + pitch is field 4 times the column stride, not key.stride(0). seq_info: ``Int32[S, 4]`` (or ``Int32[S, 5]`` with the runtime pitch in field 4) on the query's device, ``(q_start, q_len, col, kv_end)`` per segment; see the module docstring. diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py index b19c1cfa25c..c1ad66743da 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -453,6 +453,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 ( @@ -691,9 +692,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 - if runtime_kv_columns: - constant_methods["get_offgraph_kv_sequence_info_abi"] = 2 + 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..9d76f47b62e --- /dev/null +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -0,0 +1,192 @@ +# 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. + +"""Compare actual ABI-2 CUDA allocations and logits with the fixed-column ABI. + +Exports the same tiny flat/ring model twice and drives the native probe through +row growth, wrapped-history cloning, sparse-owner compaction and graph replay. +""" + +import argparse +import json +import subprocess +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(runtime_columns: bool) -> list[dict]: + """Cross row/column resize boundaries with deterministic inputs.""" + requests = [ + {"op": "new"}, + { + "op": "step", + "tokens": list(range(32)), + "seq_ids": [0] * 32, + "select": [31], + "tag": "prefill", + }, + { + "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 stage in range(2): + if stage == 1 and runtime_columns: + requests.append({"op": "compact", "spare_columns": 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-{stage}-{repeat}", + } + ) + requests.extend([{"op": "remove", "seq_id": 1}, {"op": "remove", "seq_id": 2}]) + if runtime_columns: + requests.append({"op": "compact", "spare_columns": 0}) + requests.extend( + [ + {"op": "new"}, + { + "op": "step", + "tokens": [5, 6, 7, 8], + "seq_ids": [0] * 4, + "select": [3], + "tag": "reuse", + }, + ] + ) + for request in requests: + if request["op"] == "step": + request["save_logits"] = True + return requests + + +def run(probe: Path, root: Path, runtime_columns: bool) -> tuple[dict, list[dict]]: + """Export and drive one ABI using the same model weights and queries.""" + artifact = root / ("abi2" if runtime_columns else "abi1") + artifact.mkdir() + 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, + runtime_kv_columns=runtime_columns, + ) + output = artifact / "logits" + output.mkdir() + requests = commands(runtime_columns) + 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, + ) + (artifact / "probe.stderr.log").write_text(completed.stderr) + (artifact / "probe.jsonl").write_text(completed.stdout) + completed.check_returncode() + capture = "CUDA graph: captured and instantiated for 'forward_2" + assert completed.stderr.count(capture) >= (2 if runtime_columns else 1), ( + "forward_2 must capture, replay, and recapture after compaction; " + "see probe.stderr.log" + ) + for failure in ( + "CUDA graph: capture failed for 'forward_2", + "CUDA graph: disabled for 'forward_2", + ): + assert ( + failure not in completed.stderr + ), "eager fallback cannot qualify graph replay" + 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 + + +def main() -> None: + """Require native ABI-2 numerical agreement and memory contraction.""" + parser = argparse.ArgumentParser() + parser.add_argument("--probe", required=True, type=Path) + parser.add_argument("--output-dir", required=True, type=Path) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + fixed, _ = run(args.probe.resolve(), args.output_dir, False) + dynamic, responses = run(args.probe.resolve(), args.output_dir, True) + assert fixed.keys() == dynamic.keys() + for tag in fixed: + np.testing.assert_allclose(dynamic[tag], fixed[tag], atol=5e-2, rtol=0) + np.testing.assert_array_equal(dynamic[tag].argmax(-1), fixed[tag].argmax(-1)) + np.testing.assert_allclose( + dynamic["grow"][0], dynamic["grow"][1], atol=5e-2, rtol=0 + ) + steps = [r for r in responses if r.get("op") == "step"] + assert steps[0]["snapshot"]["physical_columns"] == 2 + assert steps[2]["snapshot"]["physical_columns"] == 5 + assert steps[2]["snapshot"]["declared_columns"] == 9 + compactions = [r["snapshot"] for r in responses if r.get("op") == "compact"] + assert [m["physical_columns"] for m in compactions] == [3, 2] + assert compactions[0]["live_KV_bytes"] < steps[2]["snapshot"]["live_KV_bytes"] + print("ABI-2 native logits, ring cloning, compaction and graph replay 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 index ff3e3a78cf9..6d075b333de 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -12,7 +12,12 @@ #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 @@ -49,10 +54,16 @@ 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; diff --git a/extension/llm/cache/cache.h b/extension/llm/cache/cache.h index 56602eeb300..5f2fe1cb1a8 100644 --- a/extension/llm/cache/cache.h +++ b/extension/llm/cache/cache.h @@ -112,7 +112,8 @@ class ET_EXPERIMENTAL BatchControl : public CacheControl { // cache asks this before it hands out work seq_new would refuse. 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 @@ -178,8 +179,6 @@ struct ET_EXPERIMENTAL CacheConfig { // storage width is fixed when the program is compiled. Unset = no fixed // bound; the capacity they share is the only limit. std::optional max_seqs; - // Requires a batched-sequence program with the runtime-pitch ABI. - bool runtime_sequence_columns = false; }; ET_EXPERIMENTAL inline bool valid(const CacheGeometry& geometry) { From 0f95624691588ae325028668a3d3ea8be1641bba Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Fri, 20 Nov 2026 00:46:04 -0800 Subject: [PATCH 4/8] Expose native KV probe diagnostics and run it before longer CUDA tests --- .github/workflows/cuda.yml | 8 ++++---- .../muse-glimmer/tests/check_runtime_kv_columns.py | 10 +++++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 3e8e96435e3..da09bdbbaac 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -708,16 +708,16 @@ 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 \ examples/models/muse-glimmer/tests/test_dflash_token_sampler.py \ examples/models/muse-glimmer/tests/test_checkpoint_context.py - 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" - # CUDA DFlash executor on a tiny exported target + draft. The native # tests skip without the artifact, so fail if any skipped. export ET_MUSE_DFLASH_TINY_DIR="${RUNNER_TEMP:-/tmp}/muse_glimmer_dflash_tiny" 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 9d76f47b62e..c7ac8a552b3 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -13,6 +13,7 @@ import argparse import json import subprocess +import sys from dataclasses import replace from pathlib import Path @@ -135,9 +136,16 @@ def run(probe: Path, root: Path, runtime_columns: bool) -> tuple[dict, list[dict ) (artifact / "probe.stderr.log").write_text(completed.stderr) (artifact / "probe.jsonl").write_text(completed.stdout) + if completed.returncode: + print(completed.stderr, file=sys.stderr) + print(completed.stdout, file=sys.stderr) completed.check_returncode() capture = "CUDA graph: captured and instantiated for 'forward_2" - assert completed.stderr.count(capture) >= (2 if runtime_columns else 1), ( + enough_captures = completed.stderr.count(capture) >= (2 if runtime_columns else 1) + if not enough_captures: + print(completed.stderr, file=sys.stderr) + print(completed.stdout, file=sys.stderr) + assert enough_captures, ( "forward_2 must capture, replay, and recapture after compaction; " "see probe.stderr.log" ) From e19a789a59ce29a32a7cfcd3c99a28890436f62b Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Fri, 20 Nov 2026 01:17:24 -0800 Subject: [PATCH 5/8] Enable native CUDA logging for graph qualification --- .ci/scripts/tests/test_muse_glimmer_batching_ci.py | 2 ++ .github/workflows/cuda.yml | 10 +++++++--- 2 files changed, 9 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 0f24d7ca2aa..b2e5803423e 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -31,6 +31,8 @@ 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=ON", 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() diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index da09bdbbaac..24920bea8b6 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -691,14 +691,18 @@ 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 reads the native runtime's Info logs. + cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=ON + 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}" \ + 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 \ + --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 From 47a2cd75d677ddcd4e733f35e1396a7a6e227556 Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Fri, 20 Nov 2026 01:45:22 -0800 Subject: [PATCH 6/8] Compare split-decode reference tensors on the same device --- backends/cuda/tests/test_offgraph_kv_batched_sequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index f0051ff117b..88b0e9cd89e 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -128,7 +128,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 From bd49b8559ca0197cb683335423c35cb9b8f4158b Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Sat, 21 Nov 2026 04:07:20 -0800 Subject: [PATCH 7/8] Clarify engine-thread maintenance and strengthen KV qualification --- backends/cuda/batching/cuda_executor.cpp | 25 ++++----- backends/cuda/batching/cuda_executor.h | 10 ++-- backends/cuda/runtime/cuda_backend.cpp | 13 ++++- backends/cuda/runtime/cuda_kv_cache.cpp | 12 +++-- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 53 +++++++++++++------ .../tests/check_runtime_kv_columns.py | 12 ++++- .../tests/runtime_kv_columns_probe.cpp | 9 ++++ 7 files changed, 90 insertions(+), 44 deletions(-) diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index a9f15dd30b4..70f0eada13f 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -694,9 +694,7 @@ Error CudaExecutor::set_input_embedder(InputEmbedder embedder) { bool CudaExecutor::execute_raw( const RawTargetStep& step, const std::function& consume) { - std::unique_lock execution_lock( - execution_mutex_, std::try_to_lock); - if (!execution_lock.owns_lock() || !initialized_ || !consume || + if (raw_executing_ || !initialized_ || !consume || step.tokens.size() > static_cast(std::numeric_limits::max()) || step.positions.size() != step.tokens.size() || @@ -716,12 +714,15 @@ bool CudaExecutor::execute_raw( } } last_cache_activity_ = std::chrono::steady_clock::now(); - struct IdleClock { + raw_executing_ = true; + struct ExecutionScope { + bool& executing; std::chrono::steady_clock::time_point& activity; - ~IdleClock() { + ~ExecutionScope() { + executing = false; activity = std::chrono::steady_clock::now(); } - } idle_clock{last_cache_activity_}; + } execution_scope{raw_executing_, last_cache_activity_}; if (step.embeddings) { return execute_embeddings(step, consume); } @@ -1100,12 +1101,8 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const { } Error CudaExecutor::compact_kv_columns(int spare_columns) { - std::unique_lock execution_lock( - execution_mutex_, std::try_to_lock); ET_CHECK_OR_RETURN_ERROR( - execution_lock.owns_lock(), - InvalidState, - "CudaExecutor: compact between executes"); + !raw_executing_, InvalidState, "CudaExecutor: compact between executes"); return kv_->compact_columns(spare_columns); } @@ -1113,9 +1110,7 @@ void CudaExecutor::on_idle() { if (!runtime_columns_) { return; } - std::unique_lock execution_lock( - execution_mutex_, std::try_to_lock); - if (!execution_lock.owns_lock() || + if (raw_executing_ || std::chrono::steady_clock::now() - last_cache_activity_ < std::chrono::milliseconds(500)) { return; @@ -1127,7 +1122,7 @@ void CudaExecutor::on_idle() { } last_cache_activity_ = std::chrono::steady_clock::now(); const Error error = kv_->compact_columns(/*spare_columns=*/1); - if (error != Error::Ok && error != Error::NotSupported) { + if (error != Error::Ok) { ET_LOG( Error, "CudaExecutor: idle KV compaction failed (%d)", diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 760cd2252b1..1c222528811 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -17,13 +17,14 @@ // 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, session and maintenance calls are confined to the engine +// thread, matching Executor. execute_raw rejects re-entrant execution. #include #include #include #include #include -#include #include #include #include @@ -233,8 +234,9 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // The cache's pool usage, for memory reporting. OffGraphKVMetrics kv_metrics() const; - // An idle boundary serialized with execute. The scratch column is additional - // to spare_columns unused owner columns. + // Engine-thread only, between execute calls. A call from execute_raw's + // consumer is rejected. The scratch column is additional to spare_columns + // unused owner columns; compaction never increases the physical width. ::executorch::runtime::Error compact_kv_columns(int spare_columns = 1); void on_idle() override; @@ -312,7 +314,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // separate generators, so every forward must agree. std::optional device_logits_; bool initialized_ = false; - std::mutex execution_mutex_; + bool raw_executing_ = false; std::chrono::steady_clock::time_point last_cache_activity_ = std::chrono::steady_clock::now(); }; diff --git a/backends/cuda/runtime/cuda_backend.cpp b/backends/cuda/runtime/cuda_backend.cpp index b3c9df8b34c..c1562a021e9 100644 --- a/backends/cuda/runtime/cuda_backend.cpp +++ b/backends/cuda/runtime/cuda_backend.cpp @@ -815,6 +815,15 @@ class ET_EXPERIMENTAL CudaBackend final } #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 @@ -876,7 +885,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 = @@ -906,7 +915,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 { diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 9aeb0fa2350..e03b82fa53a 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -940,8 +940,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::optional seq_new() override { std::lock_guard guard(mutex_); const auto id = free_sequence_id(); - if (!id || poisoned_ || - (runtime_columns_ && inflight_ && !free_physical_column())) { + if (!id || poisoned_ || (runtime_columns_ && inflight_)) { return std::nullopt; } const int column = @@ -1122,7 +1121,10 @@ class CudaBatchedSequenceCache final : public cache::Cache, required = std::max(required, end); } if (runtime_columns_) { - ET_CHECK_OK_OR_RETURN_ERROR(ensure_columns(false, 0, stream)); + ET_CHECK_OR_RETURN_ERROR( + static_cast(seqs_.size()) < columns_, + InvalidState, + "offgraph_kv: admission must provide every owner a column"); } ET_CHECK_OK_OR_RETURN_ERROR(pool_.prepare( std::min(required, cfg_.capacity) * columns_, @@ -1336,7 +1338,9 @@ class CudaBatchedSequenceCache final : public cache::Cache, max_seqs_ + 1LL, std::max(live + 1LL, 2LL * (columns_ - 1) + 1))); const int target = compact - ? std::min(max_seqs_, std::max(1, live + spare_columns)) + 1 + ? std::min( + columns_, + std::min(max_seqs_, std::max(1, live + spare_columns)) + 1) : std::min(max_seqs_ + 1, std::max(columns_, grown)); std::map next; std::unordered_set used; diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 249d0d3a677..16e41e48eb3 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2847,15 +2847,17 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { 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::array, 4> retained; + std::vector, 4>> retained(ids.size()); if (old_columns != 0) { seed(fake, live_rows, old_columns); - for (size_t layer = 0; layer < 4; ++layer) { - retained[layer] = read_column( - fake.bound[fake.internal_names[layer]].data, - live_rows, - old_columns, - 0); + 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)) { @@ -2873,14 +2875,16 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { fake.bound["flat_k"].sizes, std::vector({1, kCapacity * kDeclaredColumns, kHeads, kDim})); if (old_columns != 0) { - for (size_t layer = 0; layer < 4; ++layer) { - EXPECT_EQ( - read_column( - fake.bound[fake.internal_names[layer]].data, - live_rows, - sessions + 1, - 0), - retained[layer]); + 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; @@ -2955,9 +2959,22 @@ TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { 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, 1234 + layer); + 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, @@ -2984,7 +3001,7 @@ TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { const int rows = layer < 2 ? 40 : 33; EXPECT_EQ( read_column(fake.bound[fake.internal_names[layer]].data, rows, 2, 0), - std::vector(rows * kRow, 1234 + layer)); + expected[layer]); } ASSERT_EQ(step(*cache_ptr, handle, {*clone}), Error::Ok); EXPECT_EQ(control->pos(*clone), 41); @@ -3156,6 +3173,8 @@ TEST_F(CudaRuntimeColumnCacheTest, SameWidthCompactionKeepsMappingAndBindings) { void* const pointer = fake.bound["flat_k"].data; const auto count = kv->metrics().column_resize_count; handle.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup; + ASSERT_EQ(kv->compact_columns(kMaxSeqs), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, 3); ASSERT_EQ(kv->compact_columns(0), Error::Ok); EXPECT_EQ(kv->metrics().column_resize_count, count); EXPECT_EQ(fake.bound["flat_k"].data, pointer); 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 2964f5b8659..dee2e556d65 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -36,6 +36,7 @@ def commands(runtime_columns: bool) -> list[dict]: "seq_ids": [0] * 32, "select": [31], "tag": "prefill", + "check_reentrancy": True, }, { "op": "step", @@ -141,7 +142,7 @@ def run(probe: Path, root: Path, runtime_columns: bool) -> tuple[dict, list[dict print(completed.stdout, file=sys.stderr) completed.check_returncode() capture = "CUDA graph: captured and instantiated for 'forward_2" - enough_captures = completed.stderr.count(capture) >= (2 if runtime_columns else 1) + enough_captures = completed.stderr.count(capture) == (2 if runtime_columns else 1) if not enough_captures: print(completed.stderr, file=sys.stderr) print(completed.stdout, file=sys.stderr) @@ -177,7 +178,7 @@ def main() -> None: parser.add_argument("--output-dir", required=True, type=Path) args = parser.parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) - fixed, _ = run(args.probe.resolve(), args.output_dir, False) + fixed, fixed_responses = run(args.probe.resolve(), args.output_dir, False) dynamic, responses = run(args.probe.resolve(), args.output_dir, True) assert fixed.keys() == dynamic.keys() for tag in fixed: @@ -187,6 +188,13 @@ def main() -> None: dynamic["grow"][0], dynamic["grow"][1], atol=5e-2, rtol=0 ) steps = [r for r in responses if r.get("op") == "step"] + fixed_steps = [r for r in fixed_responses if r.get("op") == "step"] + assert len(fixed_steps) == len(steps) + 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"]["physical_columns"] == 2 assert steps[2]["snapshot"]["physical_columns"] == 5 assert steps[2]["snapshot"]["declared_columns"] == 9 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 d9f81136d8a..779dbacbf59 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -155,6 +155,15 @@ Json run_step(cb::CudaExecutor& executor, const Json& request) { 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"); + require( + executor.compact_kv_columns(0) == Error::InvalidState, + "nested compaction must be rejected"); + } const size_t rows = out.selected_indices.size(); if (rows == 0) { return true; From 952486c401a769bf03b2fd1e7b81a98e8bee156c Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Sat, 21 Nov 2026 08:23:47 -0800 Subject: [PATCH 8/8] Keep CUDA KV recovery and graph qualification valid without logging Abort prepared forwards independently of logging, qualify capture and replay through counters, and retain idle compaction headroom across bursts. Add release-path recovery, allocation-free trimming, and native burst regression coverage. Authored with OpenAI Codex assistance. --- .ci/scripts/muse_glimmer_batching_workload.h | 3 + .../muse_glimmer_batching_workload_test.cpp | 6 + .../tests/test_muse_glimmer_batching_ci.py | 2 +- .github/workflows/cuda.yml | 6 +- backends/cuda/CMakeLists.txt | 5 + backends/cuda/batching/cuda_executor.cpp | 7 +- backends/cuda/batching/cuda_executor.h | 3 + backends/cuda/passes/lower_offgraph_kv.py | 6 +- backends/cuda/runtime/cuda_backend.cpp | 8 +- backends/cuda/runtime/cuda_delegate_handle.h | 12 ++ backends/cuda/runtime/cuda_kv_cache.cpp | 30 +-- backends/cuda/runtime/cuda_kv_cache.h | 6 + backends/cuda/runtime/cuda_kv_pool.cpp | 24 ++- backends/cuda/runtime/cuda_kv_pool.h | 3 + .../test/test_cuda_backend_execute.cpp | 183 +++++++++++++++++- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 2 + .../test_offgraph_kv_batched_sequence.py | 27 ++- examples/models/muse-glimmer/CMakeLists.txt | 3 + .../tests/check_runtime_kv_columns.py | 74 +++++-- .../tests/runtime_kv_columns_probe.cpp | 7 +- extension/cuda/cuda_allocator.cpp | 14 +- extension/cuda/test/cuda_allocator_exit.cpp | 32 ++- 22 files changed, 401 insertions(+), 62 deletions(-) diff --git a/.ci/scripts/muse_glimmer_batching_workload.h b/.ci/scripts/muse_glimmer_batching_workload.h index 33f25418cb9..e9ce319d536 100644 --- a/.ci/scripts/muse_glimmer_batching_workload.h +++ b/.ci/scripts/muse_glimmer_batching_workload.h @@ -107,6 +107,9 @@ class EvidenceExecutor final : public batching::Executor { bool initialize() override { return inner_.initialize(); } + void on_idle() override { + inner_.on_idle(); + } std::size_t preferred_batch_tokens() const override { return inner_.preferred_batch_tokens(); } diff --git a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp index 94ba8ed639b..2dee107cb53 100644 --- a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp +++ b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp @@ -35,6 +35,10 @@ void rejected(F action) { class FakeExecutor final : public batching::Executor { public: bool succeeds = true; + int idle_calls = 0; + void on_idle() override { + ++idle_calls; + } std::optional open_session() override { return 1; } @@ -95,6 +99,8 @@ void workload_limits() { void successful_batch_owners() { FakeExecutor inner; ci::EvidenceExecutor executor(inner); + executor.on_idle(); + require(inner.idle_calls == 1); batching::BatchOutput out; require(executor.execute({{input(1), input(1)}}, out)); require(executor.execute({{input(2)}}, out)); diff --git a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py index b2e5803423e..a7922f4c6f4 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -31,7 +31,7 @@ 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=ON", 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): diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 512738df2db..f97d0c652cd 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -695,8 +695,8 @@ jobs: # The normal serving binaries and the opt-in correctness tool share # CudaExecutor; MG preparation tests also run on Linux. - # Capture qualification reads the native runtime's Info logs. - cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=ON + # 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" --preset muse-glimmer-cuda \ @@ -816,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 70f0eada13f..278a612cf6d 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -1100,6 +1100,10 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const { return kv_->metrics(); } +CudaGraphMetrics CudaExecutor::graph_metrics(std::string_view method) const { + return kv_->graph_metrics(method); +} + Error CudaExecutor::compact_kv_columns(int spare_columns) { ET_CHECK_OR_RETURN_ERROR( !raw_executing_, InvalidState, "CudaExecutor: compact between executes"); @@ -1121,7 +1125,8 @@ void CudaExecutor::on_idle() { return; } last_cache_activity_ = std::chrono::steady_clock::now(); - const Error error = kv_->compact_columns(/*spare_columns=*/1); + const Error error = + kv_->compact_columns(static_cast(metrics.live_sequences)); if (error != Error::Ok) { ET_LOG( Error, diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 1c222528811..0ee47f917b6 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -234,6 +235,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // The cache's pool usage, for memory reporting. OffGraphKVMetrics kv_metrics() const; + // Read between executes, on the engine thread. + CudaGraphMetrics graph_metrics(std::string_view method) const; // Engine-thread only, between execute calls. A call from execute_raw's // consumer is rejected. The scratch column is additional to spare_columns // unused owner columns; compaction never increases the physical width. diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index 63d937813d8..d9193a25037 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -85,8 +85,8 @@ def ring_physical_capacity(window: int, max_write: int) -> int: def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 manifest = json.loads(value.decode("utf-8")) - if manifest.get("version") not in (1, 2): - raise ValueError("off-graph KV manifest version must be 1 or 2") + if manifest.get("version") != 1: + raise ValueError("off-graph KV manifest version must be 1") maximum_capacity = manifest.get("maximum_capacity") if not isinstance(maximum_capacity, int) or maximum_capacity <= 0: raise ValueError("off-graph maximum_capacity must be positive") @@ -118,6 +118,8 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 raise ValueError("off-graph context_window must be a bool") if manifest["context_window"] and manifest["causal"]: raise ValueError("off-graph context_window requires non-causal attention") + if runtime_columns and manifest["context_window"]: + raise ValueError("off-graph runtime columns do not support context_window") if layout == "cell": # A cell step packs tokens of several sequences into the shared pool, # so the pool bounds its width, not one sequence's capacity. diff --git a/backends/cuda/runtime/cuda_backend.cpp b/backends/cuda/runtime/cuda_backend.cpp index c1562a021e9..c551cdc0c73 100644 --- a/backends/cuda/runtime/cuda_backend.cpp +++ b/backends/cuda/runtime/cuda_backend.cpp @@ -794,9 +794,11 @@ class ET_EXPERIMENTAL CudaBackend final 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( - handle->kv_cache->abort_step() == Error::Ok, + error == Error::Ok, "offgraph_kv: failed to abort prepared forward"); + (void)error; } }); if (handle->kv_cache != nullptr) { @@ -872,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++) { @@ -895,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 @@ -1316,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'", @@ -1328,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 e03b82fa53a..1279af9d791 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -443,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) { @@ -943,8 +943,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, if (!id || poisoned_ || (runtime_columns_ && inflight_)) { return std::nullopt; } - const int column = - runtime_columns_ ? free_physical_column().value_or(-1) : *id; + const int column = runtime_columns_ ? -1 : *id; seqs_.emplace(*id, Sequence{column, cache::SequenceCache(geometry_, cfg_)}); bool admitted = false; aoti::ScopeGuard rollback([&]() noexcept { @@ -984,8 +983,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, if (keep <= 0 || !plan.rewind(keep)) { return std::nullopt; } - const int column = - runtime_columns_ ? free_physical_column().value_or(-1) : *id; + const int column = runtime_columns_ ? -1 : *id; seqs_.emplace(*id, Sequence{column, std::move(plan)}); bool admitted = false; aoti::ScopeGuard rollback([&]() noexcept { @@ -1071,7 +1069,7 @@ 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_) { @@ -1193,7 +1191,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, ET_CHECK_OR_RETURN_ERROR( !poisoned_, InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); + "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. @@ -1243,6 +1241,11 @@ class CudaBatchedSequenceCache final : public cache::Cache, return metrics; } + CudaGraphMetrics graph_metrics(std::string_view method) const override { + std::lock_guard guard(mutex_); + return pool_.graph_metrics(method); + } + Error compact_columns(int spare_columns) override { std::lock_guard guard(mutex_); ET_CHECK_OR_RETURN_ERROR( @@ -1312,19 +1315,6 @@ class CudaBatchedSequenceCache final : public cache::Cache, return std::nullopt; } - std::optional free_physical_column() const { - for (int column = 0; column < columns_ - 1; ++column) { - bool used = false; - for (const auto& [id, sequence] : seqs_) { - used |= sequence.column == column; - } - if (!used) { - return column; - } - } - return std::nullopt; - } - Error ensure_columns(bool compact, int spare_columns, cudaStream_t stream) { const int live = static_cast(seqs_.size()); // Grow geometrically (doubling the live columns) instead of one column diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index 7c734e1d3b6..092b5f50a49 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -96,6 +96,12 @@ class CudaKVCache { virtual OffGraphKVMetrics metrics() const = 0; + // Successful captures/launches and failed captures for a named method. + // Read between executes under the executor's engine-thread contract. + virtual CudaGraphMetrics graph_metrics(std::string_view) const { + return {}; + } + // An explicit idle boundary; callers must serialize this with execution. // spare_columns counts unused owner columns, excluding the scratch column. virtual runtime::Error compact_columns(int spare_columns) { diff --git a/backends/cuda/runtime/cuda_kv_pool.cpp b/backends/cuda/runtime/cuda_kv_pool.cpp index 3a538d38921..d472d7f56ad 100644 --- a/backends/cuda/runtime/cuda_kv_pool.cpp +++ b/backends/cuda/runtime/cuda_kv_pool.cpp @@ -439,6 +439,19 @@ Error CudaKVPool::grow( 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 @@ -562,13 +575,22 @@ Error CudaKVPool::resize_columns( cudaMemcpyDeviceToDevice, stream); if (error != cudaSuccess) { + ET_LOG( + Error, + "offgraph_kv: column copy failed: %s", + cudaGetErrorString(error)); roll_back(); return Error::Internal; } } } } - if (cudaStreamSynchronize(stream) != cudaSuccess) { + 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; } diff --git a/backends/cuda/runtime/cuda_kv_pool.h b/backends/cuda/runtime/cuda_kv_pool.h index 906a0b137a1..8dcae8a3200 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -110,6 +111,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); 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 16e41e48eb3..ee86b12da31 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -3173,12 +3173,14 @@ TEST_F(CudaRuntimeColumnCacheTest, SameWidthCompactionKeepsMappingAndBindings) { void* const pointer = fake.bound["flat_k"].data; const auto count = kv->metrics().column_resize_count; handle.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup; + handle.cuda_graph_state.warmup_remaining = 0; ASSERT_EQ(kv->compact_columns(kMaxSeqs), Error::Ok); EXPECT_EQ(kv->metrics().physical_columns, 3); ASSERT_EQ(kv->compact_columns(0), Error::Ok); EXPECT_EQ(kv->metrics().column_resize_count, count); EXPECT_EQ(fake.bound["flat_k"].data, pointer); EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Warmup); + EXPECT_EQ(handle.cuda_graph_state.warmup_remaining, 0); EXPECT_EQ(read_column(pointer, 2, 3, 0), before); ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); std::vector> info(2); diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index 7d1067bbadc..9f5b35229dc 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -477,7 +477,7 @@ def test_manifest_is_validated(self) -> None: parse_offgraph_kv_manifest(self.manifest(**bad)) def test_runtime_pitch_manifest_and_side_buffer(self) -> None: - manifest = self.manifest(version=2, runtime_columns=True) + manifest = self.manifest(runtime_columns=True) parsed = parse_offgraph_kv_manifest(manifest) self.assertTrue(parsed["runtime_columns"]) lowered = self._lowered(manifest) @@ -491,16 +491,23 @@ def test_runtime_pitch_manifest_and_side_buffer(self) -> None: buffers[f"{OFFGRAPH_KV_FQN_PREFIX}layer_0_k"], (1, self.CAPACITY * (self.MAX_SEQS + 1), N_KV_HEADS, HEAD_DIM), ) - for version in (1, 2): - for runtime_columns in (False, True): - with self.subTest(version=version, runtime_columns=runtime_columns): - metadata = offgraph_kv_constant_methods( - self.manifest(version=version, runtime_columns=runtime_columns) - ) - self.assertEqual( - metadata[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], - 2 if runtime_columns else 1, + for runtime_columns in (False, True): + with self.subTest(runtime_columns=runtime_columns): + metadata = offgraph_kv_constant_methods( + self.manifest(runtime_columns=runtime_columns) + ) + self.assertEqual( + metadata[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], + 2 if runtime_columns else 1, + ) + with self.assertRaises(ValueError): + parse_offgraph_kv_manifest( + self.manifest(version=2, runtime_columns=runtime_columns) ) + with self.assertRaisesRegex(ValueError, "do not support context_window"): + parse_offgraph_kv_manifest( + self.manifest(runtime_columns=True, causal=False, context_window=True) + ) with self.assertRaises(ValueError): parse_offgraph_kv_manifest( self.manifest(layout="sequence", runtime_columns=True) diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 2b1d32e7100..9a7245a6f57 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -148,6 +148,9 @@ 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() 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 dee2e556d65..d3f554ef5e1 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -84,6 +84,29 @@ def commands(runtime_columns: bool) -> list[dict]: }, ] ) + 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", + } + ) + requests.extend([{"op": "remove", "seq_id": 3}, {"op": "remove", "seq_id": 4}]) + if runtime_columns: + requests.extend([{"op": "idle"}, {"op": "idle"}]) + 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", + } + ) for request in requests: if request["op"] == "step": request["save_logits"] = True @@ -141,24 +164,16 @@ def run(probe: Path, root: Path, runtime_columns: bool) -> tuple[dict, list[dict print(completed.stderr, file=sys.stderr) print(completed.stdout, file=sys.stderr) completed.check_returncode() - capture = "CUDA graph: captured and instantiated for 'forward_2" - enough_captures = completed.stderr.count(capture) == (2 if runtime_columns else 1) - if not enough_captures: - print(completed.stderr, file=sys.stderr) - print(completed.stdout, file=sys.stderr) - assert enough_captures, ( - "forward_2 must capture, replay, and recapture after compaction; " - "see probe.stderr.log" - ) - for failure in ( - "CUDA graph: capture failed for 'forward_2", - "CUDA graph: disabled for 'forward_2", - ): - assert ( - failure not in completed.stderr - ), "eager fallback cannot qualify graph replay" responses = [json.loads(line) for line in completed.stdout.splitlines()] assert responses[0]["ready"] and len(responses) == len(requests) + 1 + graph = next( + method + for method in responses[-1]["snapshot"]["method_calls"] + if method["method"] == "forward_2" + ) + assert graph["captures"] == (2 if runtime_columns else 1), graph + assert graph["replays"] > graph["captures"], graph + assert graph["capture_failures"] == 0, graph logits = {} for request, response in zip(requests, responses[1:], strict=True): assert response["op"] == request["op"] and not response.get("failed") @@ -190,19 +205,42 @@ def main() -> None: steps = [r for r in responses if r.get("op") == "step"] fixed_steps = [r for r in fixed_responses if r.get("op") == "step"] assert len(fixed_steps) == len(steps) - for reference, candidate in zip(fixed_steps, steps, strict=True): + for reference, candidate in zip(fixed_steps[:-2], steps[:-2], strict=True): assert ( candidate["snapshot"]["live_KV_bytes"] < reference["snapshot"]["live_KV_bytes"] ) + for reference, candidate in zip(fixed_steps[-2:], steps[-2:], strict=True): + assert ( + candidate["snapshot"]["live_KV_bytes"] + <= reference["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 compactions = [ r["snapshot"] for r in responses if r.get("op") in ("compact", "idle") ] - assert [m["physical_columns"] for m in compactions] == [3, 2] + assert [m["physical_columns"] for m in compactions] == [3, 2, 7, 7] assert compactions[0]["live_KV_bytes"] < steps[2]["snapshot"]["live_KV_bytes"] + before_compaction = steps[7]["snapshot"] + assert ( + compactions[0]["allocator_used_bytes"] + < before_compaction["allocator_used_bytes"] + ) + assert ( + compactions[0]["allocator_reserved_bytes"] + <= before_compaction["allocator_reserved_bytes"] + ) + assert ( + compactions[-1]["column_resize_count"] == compactions[-2]["column_resize_count"] + ) + assert steps[-2]["snapshot"]["physical_columns"] == 9 + assert steps[-1]["snapshot"]["physical_columns"] == 7 + assert ( + steps[-1]["snapshot"]["column_resize_count"] + == compactions[-1]["column_resize_count"] + ) print("ABI-2 native logits, ring cloning, compaction and graph replay passed") 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 779dbacbf59..2df9871c3af 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -122,8 +122,13 @@ Json snapshot(cb::CudaExecutor& executor) { } 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}}); + {{"method", method.name}, + {"calls", method.calls}, + {"captures", graph.captures}, + {"replays", graph.replays}, + {"capture_failures", graph.capture_failures}}); } return result; } diff --git a/extension/cuda/cuda_allocator.cpp b/extension/cuda/cuda_allocator.cpp index c3837a703ae..6aa0f702fb6 100644 --- a/extension/cuda/cuda_allocator.cpp +++ b/extension/cuda/cuda_allocator.cpp @@ -785,6 +785,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { #if defined(EXECUTORCH_USE_HIP) (void)index; #else + std::pair selected; std::vector> targets; { auto& state = mem_pool_state(); @@ -794,7 +795,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { if (it == state.pools.end()) { return; } - targets.emplace_back(it->first, it->second); + selected = {it->first, it->second}; } else { // A caller asking for everything gets every pool this allocator created, // not whichever device the calling thread happens to be current on, since @@ -805,7 +806,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { // The pools stay in the map. Trimming empties one without invalidating it, so // a later load reuses it rather than paying to create it again. - for (const auto& [device, pool] : targets) { + const auto trim = [](int device, cudaMemPool_t pool) { if (pool != nullptr) { // Only frees the driver has already observed can be released, and a free // still pending gives back nothing rather than less. The backend waits on @@ -842,6 +843,15 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { cudaGetErrorString(graph_err)); (void)cudaGetLastError(); } + }; + if (index >= 0) { + // A column resize trims after committing its new storage. This path must + // not allocate a host snapshot that can throw before pitch reconciliation. + trim(selected.first, selected.second); + } else { + for (const auto& [device, pool] : targets) { + trim(device, pool); + } } #endif } diff --git a/extension/cuda/test/cuda_allocator_exit.cpp b/extension/cuda/test/cuda_allocator_exit.cpp index 6370f3ca445..6a2fa9100b2 100644 --- a/extension/cuda/test/cuda_allocator_exit.cpp +++ b/extension/cuda/test/cuda_allocator_exit.cpp @@ -10,6 +10,7 @@ #include #include +#include using namespace executorch::extension::cuda; @@ -19,9 +20,10 @@ void* rounded = nullptr; executorch::runtime::DeviceAllocator* allocator = nullptr; int frees = 0; int trims = 0; +bool forbid_host_allocation = false; const auto fake_pool = reinterpret_cast(storage + 256); -void fail(const char* message) { +[[noreturn]] void fail(const char* message) { std::fprintf(stderr, "%s\n", message); std::_Exit(1); } @@ -42,6 +44,26 @@ void free_at_exit() { } } // namespace +// A per-device trim is called after the KV pool commits its replacement. It +// must not allocate a snapshot that could throw before pitch reconciliation. +void* operator new(std::size_t size) { + if (forbid_host_allocation) { + fail("per-device trim allocated host memory after storage commit"); + } + if (void* memory = std::malloc(size == 0 ? 1 : size)) { + return memory; + } + fail("host allocation failed"); +} + +void operator delete(void* memory) noexcept { + std::free(memory); +} + +void operator delete(void* memory, std::size_t) noexcept { + std::free(memory); +} + // Stand-ins keep the test independent of GPU packing and driver teardown order. extern "C" { cudaError_t cudaGetDevice(int* device) { @@ -118,5 +140,13 @@ int main() { fail("allocate_async did not create the pool"); } CudaAllocator::deallocate_async(pooled.get(), -1, nullptr); + forbid_host_allocation = true; + CudaAllocator::release_cached_memory(0); + CudaAllocator::release_cached_memory(1); + forbid_host_allocation = false; + if (trims != 1) { + fail("per-device trim did not reach exactly one existing pool"); + } + trims = 0; return 0; }