From 9dee99d6e69c7efb6cc5a7c8a794cde2d5735aa5 Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 19:20:30 -0800 Subject: [PATCH 1/5] [CUDA] Compact runtime KV columns after sessions close Reclaim closed-owner storage between forwards after a configurable quiet interval, preserving still-open histories and recapturing graphs when columns move. Release observed frees through the existing CUDA allocator trim. Authored with OpenAI Codex assistance. --- .github/workflows/cuda.yml | 2 +- backends/cuda/batching/cuda_executor.cpp | 41 ++++- backends/cuda/batching/cuda_executor.h | 13 +- backends/cuda/runtime/cuda_kv_cache.cpp | 78 ++++++++- backends/cuda/runtime/cuda_kv_cache.h | 11 ++ backends/cuda/runtime/cuda_kv_pool.cpp | 64 ++++--- backends/cuda/runtime/cuda_kv_pool.h | 13 +- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 164 ++++++++++++++++-- .../runtime/cuda_dflash_executor.cpp | 5 + .../runtime/cuda_dflash_executor.h | 1 + .../tests/check_runtime_kv_columns.py | 136 ++++++++++++++- .../tests/runtime_kv_columns_probe.cpp | 22 +++ extension/llm/batching/executor.h | 7 + extension/llm/batching/metrics.cpp | 4 + extension/llm/batching/metrics.h | 1 + extension/llm/batching/runner.cpp | 28 ++- extension/llm/batching/test/runner_test.cpp | 127 ++++++++++++++ 17 files changed, 660 insertions(+), 57 deletions(-) diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index f7055f6c7da..39ef317b558 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -716,7 +716,7 @@ jobs: 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" + --output-dir "${RUNNER_TEMP:-/tmp}/muse_glimmer_runtime_kv_columns" --check-compaction python -m pytest -v -o "addopts=" \ examples/models/muse-glimmer/tests/test_cuda_batching_pipeline.py \ diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index 7e494338418..c22f20bc2b2 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -268,7 +268,8 @@ CudaExecutor::CudaExecutor( std::vector methods, int min_selected_rows, bool has_sampler, - bool has_argmax) + bool has_argmax, + std::chrono::milliseconds column_compaction_delay) : install_guard_(cache), module_(std::move(module)), ctl_(cache->as()), @@ -281,7 +282,8 @@ CudaExecutor::CudaExecutor( min_selected_rows_(min_selected_rows), sessions_(*ctl_, max_sessions, max_session_tokens, vocab_size), has_sampler_(has_sampler), - has_argmax_(has_argmax) {} + has_argmax_(has_argmax), + column_compaction_delay_(column_compaction_delay) {} CudaExecutor::~CudaExecutor() { if (device_params_ != nullptr) { @@ -334,6 +336,10 @@ Result> CudaExecutor::create( const int kv_dtype = config.kv_dtype; const int initial_capacity = config.initial_capacity; const auto& options = config.options; + ET_CHECK_OR_RETURN_ERROR( + config.kv_column_compaction_delay.count() >= 0, + InvalidArgument, + "CudaExecutor: negative compaction delay"); ET_CHECK_OR_RETURN_ERROR( module != nullptr, InvalidArgument, "CudaExecutor: no program"); ET_CHECK_OR_RETURN_ERROR( @@ -588,7 +594,8 @@ Result> CudaExecutor::create( std::move(methods), min_selected_rows, has_sampler, - has_argmax)); + has_argmax, + config.kv_column_compaction_delay)); executor->embeddings_method_ = embeddings_method; return executor; } @@ -1093,6 +1100,34 @@ 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"); + return kv_->compact_columns(spare_columns); +} + +bool CudaExecutor::on_idle() { + if (raw_executing_) { + return true; + } + const auto metrics = kv_->metrics(); + // Below 25% occupancy, retain spare room equal to the live-owner count. + // Time controls when this runs, never which owners can be removed. + if (metrics.physical_columns <= 2 || + 4 * metrics.live_sequences + 1 >= metrics.physical_columns) { + return true; + } + const Error error = kv_->compact_columns( + static_cast(metrics.live_sequences), column_compaction_delay_); + if (error != Error::Ok) { + ET_LOG( + Error, + "CudaExecutor: idle KV compaction failed (%d)", + static_cast(error)); + } + return error == Error::Ok; +} + 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 af8c4167459..0cf044906af 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -18,6 +18,7 @@ // runs the method with the smallest width that holds it; a static method's // extra rows are padding. +#include #include #include #include @@ -88,6 +89,9 @@ struct CudaExecutorConfig { int max_session_tokens = 0; int kv_dtype = static_cast(::executorch::aten::ScalarType::BFloat16); int initial_capacity = -1; + // A quiet interval before reclaiming unused physical columns. This never + // expires an open session; zero allows maintenance at the next idle check. + std::chrono::milliseconds kv_column_compaction_delay{500}; CudaExecutorOptions options; }; @@ -230,6 +234,9 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { OffGraphKVMetrics kv_metrics() const; // Sequence-layout counters; read between executes, on the engine thread. CudaGraphMetrics graph_metrics(std::string_view method) const; + // Explicit compaction preserves every live owner, even inactive sessions. + ::executorch::runtime::Error compact_kv_columns(int spare_columns = 1); + bool on_idle() override; // Every method, narrowest first, with how many forwards it ran. Read it // between executes, not while one runs. std::vector method_calls() const; @@ -254,7 +261,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { std::vector methods, int min_selected_rows, bool has_sampler, - bool has_argmax); + bool has_argmax, + std::chrono::milliseconds column_compaction_delay); // Draws one token per row of `logits`, rows [0, sessions.size()), on the // device; returns them in row order. @@ -275,7 +283,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_; @@ -303,6 +311,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { std::optional device_logits_; bool initialized_ = false; bool raw_executing_ = false; + const std::chrono::milliseconds column_compaction_delay_; }; } // namespace executorch::backends::cuda::batching diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index cb076018fd5..88dc61e2929 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -899,6 +899,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, pending_owners_.clear(); poisoned_ = false; inflight_ = false; + last_activity_ = std::chrono::steady_clock::now(); } bool declare_step(const std::vector& seq_ids) override { @@ -956,6 +957,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, return std::nullopt; } admitted = true; + last_activity_ = std::chrono::steady_clock::now(); return *id; } @@ -1008,6 +1010,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, return std::nullopt; } admitted = true; + last_activity_ = std::chrono::steady_clock::now(); return *id; } @@ -1018,13 +1021,21 @@ class CudaBatchedSequenceCache final : public cache::Cache, step_seq_ids_.clear(); } // Logical removal does not free storage; verbs run between forwards. - return seqs_.erase(seq_id) > 0; + const bool removed = seqs_.erase(seq_id) > 0; + if (removed) { + last_activity_ = std::chrono::steady_clock::now(); + } + return removed; } bool rewind(int32_t seq_id, int position) override { std::lock_guard guard(mutex_); const auto it = seqs_.find(seq_id); - return it != seqs_.end() && it->second.plan.rewind(position); + const bool rewound = it != seqs_.end() && it->second.plan.rewind(position); + if (rewound) { + last_activity_ = std::chrono::steady_clock::now(); + } + return rewound; } int pos(int32_t seq_id) const override { @@ -1182,6 +1193,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, step_seq_ids_.clear(); inflight_ = grow_columns_; prepared = true; + last_activity_ = std::chrono::steady_clock::now(); return Error::Ok; } @@ -1211,6 +1223,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, } } pending_owners_.clear(); + last_activity_ = std::chrono::steady_clock::now(); return Error::Ok; } @@ -1252,6 +1265,53 @@ class CudaBatchedSequenceCache final : public cache::Cache, return pool_.graph_metrics(method); } + Error compact_columns(int spare_columns, std::chrono::milliseconds quiet_for) + override { + std::lock_guard guard(mutex_); + ET_CHECK_OR_RETURN_ERROR( + grow_columns_, NotSupported, "offgraph_kv: fixed column policy"); + ET_CHECK_OR_RETURN_ERROR( + !poisoned_ && !inflight_ && pending_owners_.empty(), + InvalidState, + "offgraph_kv: compact only between committed forwards"); + ET_CHECK_OR_RETURN_ERROR( + spare_columns >= 0 && spare_columns <= max_seqs_, + InvalidArgument, + "offgraph_kv: invalid spare columns"); + ET_CHECK_OR_RETURN_ERROR( + quiet_for.count() >= 0, + InvalidArgument, + "offgraph_kv: negative quiet interval"); + if (std::chrono::duration_cast( + std::chrono::steady_clock::now() - last_activity_) < quiet_for) { + return Error::Ok; + } + const int live = static_cast(seqs_.size()); + const int target = static_cast(std::min( + columns_, + std::min( + max_seqs_, std::max(1, live + int64_t{spare_columns})) + + 1)); + const auto device = CUDAGuard::create(pool_.device()); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + const int old_columns = columns_; + const Error resized = resize_columns(target, cudaStreamPerThread); + last_activity_ = std::chrono::steady_clock::now(); + ET_CHECK_OK_OR_RETURN_ERROR(resized); + if (columns_ < old_columns && pool_.allocated()) { + // The new mappings are committed. Fence old-buffer frees before giving + // unused reservation back; never roll back into the retired addresses. + const Error fenced = pool_.synchronize(/*all_streams=*/false); + if (fenced != Error::Ok) { + poisoned_ = true; + return fenced; + } + ::executorch::extension::cuda::CudaAllocator::release_cached_memory( + pool_.device()); + } + return Error::Ok; + } + protected: void* face(cache::FaceId id) override { return cache::expose(this, id); @@ -1307,10 +1367,14 @@ class CudaBatchedSequenceCache final : public cache::Cache, : static_cast(std::min( max_seqs_ + 1LL, std::max(live + 1LL, 2LL * (columns_ - 1) + 1))); + return resize_columns(target, stream); + } + + Error resize_columns(int target, cudaStream_t stream) { std::map next; std::unordered_set used; for (const auto& [id, sequence] : seqs_) { - if (sequence.column >= 0) { + if (sequence.column >= 0 && sequence.column < target - 1) { ET_CHECK_OR_RETURN_ERROR( sequence.column < target - 1 && used.insert(sequence.column).second, InvalidState, @@ -1334,12 +1398,16 @@ class CudaBatchedSequenceCache final : public cache::Cache, used.insert(column); } if (target != columns_) { + std::vector> retained; int live_rows = 0; for (const auto& [id, sequence] : seqs_) { + if (sequence.column >= 0) { + retained.emplace_back(sequence.column, next.at(id)); + } live_rows = std::max(live_rows, sequence.plan.length()); } ET_CHECK_OK_OR_RETURN_ERROR( - pool_.resize_columns(target, live_rows, stream)); + pool_.resize_columns(target, retained, live_rows, stream)); columns_ = target; } for (auto& [id, sequence] : seqs_) { @@ -1484,6 +1552,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, const std::optional dflash_block_size_; int columns_; bool inflight_{false}; + std::chrono::steady_clock::time_point last_activity_ = + std::chrono::steady_clock::now(); std::vector layer_rows_; CudaKVPool pool_; std::map seqs_; diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index 139a1db7313..225cec9bd9c 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include #include @@ -102,6 +103,16 @@ class CudaKVCache { virtual CudaGraphMetrics graph_metrics(std::string_view) const { return {}; } + + // Reclaim only columns without live owners, between forwards. Live owners + // retain their histories even if they have not run recently. + // quiet_for is measured from mutations of the cache itself, including raw + // owner operations. Zero explicitly bypasses the quiet interval. + virtual runtime::Error compact_columns( + int /*spare_columns*/, + std::chrono::milliseconds /*quiet_for*/ = std::chrono::milliseconds{0}) { + 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 30fcc255182..edc2b5e4c56 100644 --- a/backends/cuda/runtime/cuda_kv_pool.cpp +++ b/backends/cuda/runtime/cuda_kv_pool.cpp @@ -476,15 +476,29 @@ void CudaKVPool::invalidate_bindings() { Error CudaKVPool::resize_columns( int columns, + const std::vector>& retained_columns, int64_t live_rows, cudaStream_t stream) { ET_CHECK_OR_RETURN_ERROR( - declared_columns_ > 1 && columns >= columns_ && - columns <= declared_columns_ && live_rows >= 0, + declared_columns_ > 1 && columns >= 2 && columns <= declared_columns_ && + live_rows >= 0, 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, @@ -497,7 +511,7 @@ Error CudaKVPool::resize_columns( columns_ = columns; return Error::Ok; } - if (columns == columns_) { + if (columns == columns_ && !relocate) { return Error::Ok; } const auto device = CUDAGuard::create(device_); @@ -539,29 +553,30 @@ Error CudaKVPool::resize_columns( if (logical_rows == 0) { continue; } - for (const auto& [dst, src] : - {std::pair{replacement.k, current.k}, - std::pair{replacement.v, current.v}}) { - const cudaError_t error = cudaMemcpy2DAsync( - dst, - slot * columns, - src, - slot * old_columns, - slot * (old_columns - 1), - logical_rows, - cudaMemcpyDeviceToDevice, - stream); - if (error != cudaSuccess) { - ET_LOG( - Error, - "offgraph_kv: column copy failed: %s", - cudaGetErrorString(error)); - roll_back(); - return Error::Internal; + 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) { + ET_LOG( + Error, + "offgraph_kv: column copy failed: %s", + cudaGetErrorString(error)); + roll_back(); + return Error::Internal; + } } } } - const cudaError_t synchronize_error = cudaStreamSynchronize(stream); if (synchronize_error != cudaSuccess) { ET_LOG( @@ -583,10 +598,11 @@ Error CudaKVPool::resize_columns( column_resize_count_++; ET_LOG( Info, - "offgraph_kv: resized columns=%d->%d " + "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(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 dcf3debca17..fc8c431e64f 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -87,11 +87,14 @@ class CudaKVPool final { prepare(int64_t required_rows, int64_t live_rows, cudaStream_t stream); // Flattened row counts remain multiples of the current physical width. - // Copies the old owner columns in place; the scratch column is not retained. - // live_rows is the logical prefix, capped by each ring. Growth commits only - // after all copies pass; smaller widths are rejected. - runtime::Error - resize_columns(int columns, int64_t live_rows, cudaStream_t stream); + // Each pair is a retained old column and its new column. Dummy data is not + // retained. live_rows is the retained logical prefix, capped by each ring. + // Growth or contraction commits only after all retained copies pass. + runtime::Error resize_columns( + int columns, + const std::vector>& retained_columns, + int64_t live_rows, + cudaStream_t stream); // Records where the step's work ends on its stream, for the next step to // follow if it runs on another. diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 1e6287f0e51..b7d6ca49fa5 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2856,7 +2856,7 @@ class CudaRuntimeColumnCacheTest : public CudaKVCacheTest { } // namespace -TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdsPreserveAllKV) { +TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { auto cache_ptr = make(); ASSERT_NE(cache_ptr, nullptr); auto* control = cache_ptr->as(); @@ -2911,7 +2911,7 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdsPreserveAllKV) { old_columns = sessions + 1; } - // Closing other owners preserves the survivor and the allocated width. + // Preserve a nonzero logical ID while compacting it into physical column 0. const int32_t survivor = ids[5]; const int rows = control->pos(survivor); seed(fake, rows, old_columns); @@ -2927,19 +2927,21 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdsPreserveAllKV) { ASSERT_TRUE(control->seq_rm(id)); } } + ASSERT_EQ(kv->compact_columns(0), Error::Ok); const auto after = kv->metrics(); - EXPECT_EQ(after.physical_columns, old_columns); + 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_EQ(after.allocated_bytes, before.allocated_bytes); - ASSERT_EQ(step(*cache_ptr, handle, {survivor}, 4), Error::Ok); + 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, old_columns, 5), + 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( @@ -2948,7 +2950,7 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdsPreserveAllKV) { sizeof(cols), cudaMemcpyDeviceToHost), cudaSuccess); - EXPECT_EQ(cols, (std::array{5, 16, 16, 16})); + EXPECT_EQ(cols, (std::array{0, 1, 1, 1})); std::vector info(kSegments * 5); ASSERT_EQ( cudaMemcpy( @@ -2957,15 +2959,15 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdsPreserveAllKV) { info.size() * sizeof(int32_t), cudaMemcpyDeviceToHost), cudaSuccess); - EXPECT_EQ(info[2], 5); + EXPECT_EQ(info[2], 0); EXPECT_EQ(info[3], position + 1); for (int row = 0; row < kSegments; ++row) { - EXPECT_EQ(info[row * 5 + 4], old_columns); + EXPECT_EQ(info[row * 5 + 4], 2); } kv->forget_handle(&handle); } -TEST_F(CudaRuntimeColumnCacheTest, CloneCopiesWrappedRingHistoryAfterGrowth) { +TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { auto cache_ptr = make(); auto* control = cache_ptr->as(); auto* kv = cache_ptr->as(); @@ -3013,12 +3015,13 @@ TEST_F(CudaRuntimeColumnCacheTest, CloneCopiesWrappedRingHistoryAfterGrowth) { 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, 3, 1), + read_column(fake.bound[fake.internal_names[layer]].data, rows, 2, 0), expected[layer]); } ASSERT_EQ(step(*cache_ptr, handle, {*clone}), Error::Ok); @@ -3206,6 +3209,53 @@ TEST_F(CudaRuntimeColumnCacheTest, OwnerReuseKeepsMappingAndBindings) { kv->forget_handle(&handle); } +TEST_F(CudaRuntimeColumnCacheTest, SameWidthCompactionKeepsMappingAndBindings) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto first = control->seq_new(); + const auto second = control->seq_new(); + ASSERT_TRUE(first.has_value()); + ASSERT_TRUE(second.has_value()); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + ASSERT_TRUE(control->seq_rm(*first)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->metrics().physical_columns, 2); + EXPECT_EQ(control->seq_new(), first); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + ASSERT_EQ(kv->metrics().physical_columns, 3); + seed(fake, 2, 3); + const auto before = read_column(fake.bound["flat_k"].data, 2, 3, 0); + 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); + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + info.size() * sizeof(info[0]), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ( + info, + (std::vector>{{0, 1, 1, 2, 3}, {1, 1, 0, 3, 3}})); + kv->forget_handle(&handle); +} + TEST_F(CudaRuntimeColumnCacheTest, RegistryGrowsColumnsByDefault) { auto cfg = config(kCapacity, 4, kMaxWrite); cfg.max_seqs = kMaxSeqs; @@ -3309,6 +3359,95 @@ TEST_F(CudaRuntimeColumnCacheTest, ColumnGrowthFollowsPendingHistoryWrites) { ASSERT_EQ(cudaStreamDestroy(stream), cudaSuccess); } +TEST_F( + CudaRuntimeColumnCacheTest, + CompactionReturnsUnusedReservationToTheDriver) { + auto geometry = flat_and_ring(32); + for (auto& layer : geometry.layers) { + layer.n_kv_heads = 4; + layer.head_dim = 64; + } + // The burst exceeds CUDA pool backing granularity, so retained tiny + // buffers cannot pin every freed page as they can for a 1K-row pool. + constexpr int kRows = 8192; + auto cfg = config(kRows, kRows, 16); + cfg.max_seqs = 16; + auto ptr = cu::make_cuda_batched_sequence_kv_cache(geometry, cfg); + auto* control = ptr->as(); + auto* kv = ptr->as(); + auto fake = container(); + for (size_t index = 0; index < 4; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, (index < 2 ? kRows : 47) * 17, 4, 64}); + } + declare(fake, fake.fqns[4], slimc10::ScalarType::Long, {16}); + declare(fake, fake.fqns[5], slimc10::ScalarType::Int, {32, 5}); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector owners; + for (int i = 0; i < 16; ++i) { + const auto owner = control->seq_new(); + ASSERT_TRUE(owner.has_value()); + owners.push_back(*owner); + } + ASSERT_EQ(step(*ptr, handle, owners), Error::Ok); + ASSERT_EQ(cudaStreamSynchronize(cudaStreamPerThread), cudaSuccess); + int device = 0; + ASSERT_EQ(cudaGetDevice(&device), cudaSuccess); + const auto pool = + ::executorch::extension::cuda::CudaAllocator::pool_for_device(device); + if (pool == nullptr) { + kv->forget_handle(&handle); + GTEST_SKIP() << "CUDA allocator pools are unavailable"; + } + uint64_t before = 0, after = 0; + ASSERT_EQ( + cudaMemPoolGetAttribute(pool, cudaMemPoolAttrReservedMemCurrent, &before), + cudaSuccess); + const auto live_before = kv->metrics().allocated_bytes; + for (size_t i = 0; i + 1 < owners.size(); ++i) { + ASSERT_TRUE(control->seq_rm(owners[i])); + } + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ( + cudaMemPoolGetAttribute(pool, cudaMemPoolAttrReservedMemCurrent, &after), + cudaSuccess); + EXPECT_LT(after, before); + EXPECT_GE(before - after, 8 * 1024 * 1024); + EXPECT_LT(kv->metrics().allocated_bytes, live_before); + EXPECT_EQ(kv->metrics().physical_columns, 2); + EXPECT_EQ(control->pos(owners.back()), 1); + ASSERT_EQ(step(*ptr, handle, {owners.back()}), Error::Ok); + EXPECT_EQ(control->pos(owners.back()), 2); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, CompactionRejectsAnInflightForward) { + auto ptr = make(); + auto* control = ptr->as(); + auto* kv = 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_EQ(kv->compact_columns(0), Error::InvalidState); + ASSERT_EQ(kv->commit_step(1), Error::Ok); + EXPECT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(control->pos(*id), 1); + EXPECT_EQ(kv->compact_columns(-1), Error::InvalidArgument); + EXPECT_EQ( + kv->compact_columns(0, std::chrono::milliseconds{-1}), + Error::InvalidArgument); + EXPECT_EQ(kv->compact_columns(kMaxSeqs + 1), Error::InvalidArgument); + kv->forget_handle(&handle); +} + TEST_F(CudaRuntimeColumnCacheTest, GrowthInvalidatesEveryGraphAndBinding) { auto cache_ptr = make(); auto* control = cache_ptr->as(); @@ -3386,6 +3525,7 @@ TEST_F(CudaKVPoolTest, FailedColumnGrowthKeepsOldStorageAndBindingsUsable) { EXPECT_EQ( pool.resize_columns( kDeclaredColumns, + {{0, 0}}, /*live_rows=*/1, cudaStreamPerThread), Error::MemoryAllocationFailed); diff --git a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp index d5cc5776d99..c95ff165ea4 100644 --- a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp +++ b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp @@ -791,6 +791,11 @@ bool MuseGlimmerCudaDFlashExecutor::initialize() { return true; } +bool MuseGlimmerCudaDFlashExecutor::on_idle() { + // Draft columns remain fixed; only target owner storage is compacted. + return target_->on_idle(); +} + std::optional MuseGlimmerCudaDFlashExecutor::open_session() { if (failed_ || sessions_.size() >= static_cast(max_sessions_) || next_session_ == std::numeric_limits::max()) { diff --git a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h index 57627bc15c5..5ea440fbf26 100644 --- a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h +++ b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h @@ -195,6 +195,7 @@ class MuseGlimmerCudaDFlashExecutor final : public batching::Executor { ~MuseGlimmerCudaDFlashExecutor() override; std::size_t preferred_batch_tokens() const override; bool initialize() override; + bool on_idle() override; std::optional open_session() override; void close_session(batching::SessionId session) override; std::optional clone( 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 8ff1ed981dc..1f515aa3ec6 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -117,14 +117,21 @@ def commands() -> list[dict]: return requests -def run(probe: Path, artifact: Path, preallocate: bool) -> tuple[dict, list[dict]]: - output = artifact / ("preallocated" if preallocate else "growing") +def run( + probe: Path, + artifact: Path, + preallocate: bool, + custom_requests=None, + compaction_delay_ms=500, + label=None, +) -> tuple[dict, list[dict]]: + output = artifact / (label or ("preallocated" if preallocate else "growing")) output.mkdir(exist_ok=True) prefix = [] if preallocate: prefix.extend({"op": "new"} for _ in range(8)) prefix.extend({"op": "remove", "seq_id": owner} for owner in range(8)) - requests = prefix + commands() + requests = prefix + (commands() if custom_requests is None else custom_requests) completed = subprocess.run( [ str(probe), @@ -134,6 +141,7 @@ def run(probe: Path, artifact: Path, preallocate: bool) -> tuple[dict, list[dict "--max_sessions=8", "--max_context=64", "--initial_kv_capacity=4", + f"--kv_compaction_delay_ms={compaction_delay_ms}", ], input="".join(json.dumps(r) + "\n" for r in requests), text=True, @@ -161,10 +169,129 @@ def run(probe: Path, artifact: Path, preallocate: bool) -> tuple[dict, list[dict return logits, responses[1 + len(prefix) :] +def check_compaction(probe: Path, artifact: Path) -> None: + # A clone holds a wrapped history while every other owner is explicitly + # closed. Exercise both manual compaction and automatic idle policy. + requests = [ + {"op": "new"}, + { + "op": "step", + "tokens": list(range(32)), + "seq_ids": [0] * 32, + "select": [31], + "tag": "compact-prefill", + }, + { + "op": "step", + "tokens": list(range(32, 48)), + "seq_ids": [0] * 16, + "select": [15], + "tag": "compact-wrap", + }, + {"op": "clone", "seq_id": 0, "upto": 48}, + ] + requests.extend({"op": "new"} for _ in range(6)) + requests.append( + { + "op": "step", + "tokens": [13] * 8, + "seq_ids": list(range(8)), + "select": list(range(8)), + "tag": "compact-burst", + } + ) + requests.append({"op": "idle", "tag": "all-open"}) + requests.extend({"op": "remove", "seq_id": i} for i in (0, 2, 3, 4, 5, 6, 7)) + requests.append({"op": "compact", "spare_columns": 0, "tag": "manual"}) + for repeat in range(5): + requests.append( + { + "op": "step", + "tokens": [20 + repeat], + "seq_ids": [1], + "select": [0], + "tag": f"compact-before-{repeat}", + } + ) + requests.extend({"op": "new"} for _ in range(7)) + requests.append( + { + "op": "step", + "tokens": [14] * 7, + "seq_ids": [0, 2, 3, 4, 5, 6, 7], + "select": list(range(7)), + "tag": "compact-regrow", + } + ) + requests.extend({"op": "remove", "seq_id": i} for i in (0, 2, 3, 4, 5, 6, 7)) + requests.append({"op": "idle", "tag": "idle-before"}) + requests.append({"op": "wait", "milliseconds": 600}) + requests.append({"op": "idle", "tag": "idle-shrink"}) + for repeat in range(5): + requests.append( + { + "op": "step", + "tokens": [30 + repeat], + "seq_ids": [1], + "select": [0], + "tag": f"compact-after-{repeat}", + } + ) + for request in requests: + if request["op"] == "step": + request["save_logits"] = True + reference_requests = [ + {"op": "metrics"} if r["op"] in ("compact", "idle") else r for r in requests + ] + fixed, _ = run(probe, artifact, True, reference_requests, label="compact-fixed") + for delay, before, expected, label in ( + (0, 3, 3, "compact-immediate"), + (500, 9, 3, "compact-expiring"), + (60000, 9, 9, "compact-delayed"), + ): + actual, trace = run(probe, artifact, False, requests, delay, label) + assert fixed.keys() == actual.keys() + for tag in fixed: + assert np.isfinite(fixed[tag]).all() and np.isfinite(actual[tag]).all(), tag + np.testing.assert_array_equal(actual[tag], fixed[tag], err_msg=tag) + snapshots = { + r.get("tag"): response["snapshot"] + for r, response in zip(requests, trace, strict=True) + if "tag" in r + } + assert snapshots["all-open"]["live_sequences"] == 8 + assert snapshots["all-open"]["physical_columns"] == 9 + assert snapshots["manual"]["live_sequences"] == 1 + assert snapshots["manual"]["physical_columns"] == 2 + assert snapshots["idle-before"]["physical_columns"] == before + assert snapshots["idle-shrink"]["live_sequences"] == 1 + assert snapshots["idle-shrink"]["physical_columns"] == expected + assert ( + snapshots["manual"]["live_KV_bytes"] + < snapshots["all-open"]["live_KV_bytes"] + ) + if expected == 3: + assert ( + snapshots["idle-shrink"]["live_KV_bytes"] + < snapshots["compact-regrow"]["live_KV_bytes"] + ) + graph = next( + m + for m in trace[-1]["snapshot"]["method_calls"] + if m["method"] == "forward_1" + ) + assert graph["captures"] >= 2 and graph["replays"] > graph["captures"], graph + assert graph["capture_failures"] == 0, graph + print( + "Native compaction, open-owner retention, idle delay, identical logits and graph recapture passed" + ) + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--probe", required=True, type=Path) parser.add_argument("--output-dir", required=True, type=Path) + parser.add_argument("--check-compaction", action="store_true") args = parser.parse_args() artifact = args.output_dir.resolve() artifact.mkdir(parents=True, exist_ok=True) @@ -231,6 +358,9 @@ def main() -> None: "Native column growth, identical logits, ring cloning and graph recapture passed" ) + if args.check_compaction: + check_compaction(args.probe.resolve(), artifact) + 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 ab4826a94b6..044558a1d0b 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -42,6 +43,11 @@ namespace cb = executorch::backends::cuda::batching; using executorch::runtime::Error; using Json = nlohmann::json; +DEFINE_int64( + kv_compaction_delay_ms, + 500, + "Quiet interval before column compaction"); + namespace { void require(bool condition, const char* message) { @@ -180,6 +186,8 @@ int main(int argc, char** argv) { config.max_sessions = FLAGS_max_sessions; config.max_session_tokens = FLAGS_max_context; config.initial_capacity = FLAGS_initial_kv_capacity; + config.kv_column_compaction_delay = + std::chrono::milliseconds(FLAGS_kv_compaction_delay_ms); config.options.cuda_graph_for_static_methods = true; auto created = cb::CudaExecutor::create(config); require(created.ok(), "create actual CUDA executor"); @@ -211,6 +219,20 @@ int main(int argc, char** argv) { 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)) == + executorch::runtime::Error::Ok, + "compact physical columns"); + } else if (op == "wait") { + const int milliseconds = request.at("milliseconds").get(); + require( + milliseconds >= 0 && milliseconds <= 1000, + "bounded diagnostic wait"); + std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); + } else if (op == "idle") { + result["maintained"] = executor->on_idle(); + require(result["maintained"].get(), "idle maintenance"); } else if (op == "step") { result = run_step(*executor, request); } else if (op != "metrics") { diff --git a/extension/llm/batching/executor.h b/extension/llm/batching/executor.h index 5a8641f4dbf..8eb74bdcbd0 100644 --- a/extension/llm/batching/executor.h +++ b/extension/llm/batching/executor.h @@ -86,6 +86,13 @@ class ET_EXPERIMENTAL Executor { return 0; } + // Engine-thread maintenance between batches, outside the Runner's control + // mutex. A false result pauses retries until another batch or owner closure; + // it must preserve every still-open session. + virtual bool on_idle() { + return true; + } + // A session to route tasks to. nullopt = at capacity. Every successful id // must be unique for the lifetime of the consuming Runner, even after close. virtual std::optional open_session() = 0; diff --git a/extension/llm/batching/metrics.cpp b/extension/llm/batching/metrics.cpp index 365e2e1bb79..21eca18774e 100644 --- a/extension/llm/batching/metrics.cpp +++ b/extension/llm/batching/metrics.cpp @@ -83,6 +83,10 @@ std::string format_report(const EngineMetrics& m) { os << " init " << detail::ms(m.init_us) << " ms executor setup, before the wall above\n"; } + if (m.idle_maintenance_failures > 0) { + os << " maintenance " << m.idle_maintenance_failures + << " idle failures\n"; + } os << " generations " << m.generations_completed << " of " << m.generations_started << ": " << m.finished_stop_token << " stop, " << m.finished_token_limit << " limit, " << m.finished_cancelled diff --git a/extension/llm/batching/metrics.h b/extension/llm/batching/metrics.h index d9c5a025249..697ab5c039c 100644 --- a/extension/llm/batching/metrics.h +++ b/extension/llm/batching/metrics.h @@ -248,6 +248,7 @@ struct ET_EXPERIMENTAL EngineMetrics { // no two points to measure between. Outside wall_us(), which starts at the // first step -- folding it in would hide one-time setup inside the run. std::int64_t init_us = 0; + std::uint64_t idle_maintenance_failures = 0; double wall_us() const { return stamped(t_first_step) && stamped(t_last_step) diff --git a/extension/llm/batching/runner.cpp b/extension/llm/batching/runner.cpp index bb504fec540..4ef4058108b 100644 --- a/extension/llm/batching/runner.cpp +++ b/extension/llm/batching/runner.cpp @@ -458,7 +458,7 @@ class RunnerImpl : public std::enable_shared_from_this { AcceptsCommand>; void run_(); - void process_pending_commands_(); + bool process_pending_commands_(); void process_command_(OpenCommand command); void process_command_(CloseCommand command); void process_command_(CloneCommand command); @@ -790,12 +790,31 @@ void RunnerImpl::run_() { lifecycle_.store(Lifecycle::Stopping, std::memory_order_release); } + bool idle_maintenance_enabled = true; while (is_running_()) { - process_pending_commands_(); + if (process_pending_commands_()) { + idle_maintenance_enabled = true; + } reap_cancelled_(); if (execute_one_batch_()) { + idle_maintenance_enabled = true; continue; // more work may be ready } + if (idle_maintenance_enabled) { + bool maintained = false; +#if ET_HAS_EXCEPTIONS + try { +#endif + maintained = executor_.on_idle(); +#if ET_HAS_EXCEPTIONS + } catch (...) { + } +#endif + if (!maintained) { + ++metrics_.idle_maintenance_failures; + idle_maintenance_enabled = false; + } + } std::unique_lock lock(control_mutex_); engine_cv_.wait_for(lock, std::chrono::milliseconds(20), [this] { return lifecycle_.load(std::memory_order_relaxed) != Lifecycle::Running || @@ -855,13 +874,15 @@ void RunnerImpl::reap_cancelled_() { } } -void RunnerImpl::process_pending_commands_() { +bool RunnerImpl::process_pending_commands_() { std::vector commands; { std::lock_guard lock(control_mutex_); commands.swap(inbox_); } + bool closed_owner = false; for (auto& command : commands) { + closed_owner |= std::holds_alternative(command); std::visit( Overloaded{ [this](OpenCommand& open) { process_command_(std::move(open)); }, @@ -873,6 +894,7 @@ void RunnerImpl::process_pending_commands_() { }}, command); } + return closed_owner; } void RunnerImpl::process_command_(OpenCommand command) { diff --git a/extension/llm/batching/test/runner_test.cpp b/extension/llm/batching/test/runner_test.cpp index d85118ba689..287aad49340 100644 --- a/extension/llm/batching/test/runner_test.cpp +++ b/extension/llm/batching/test/runner_test.cpp @@ -379,6 +379,133 @@ TEST(GenerationHandleTest, DefaultHandleIsInvalid) { handle.wait(); } +TEST(RunnerMaintenanceTest, IdleHookRunsBetweenBatchesOnTheEngineThread) { + class IdleExecutor : public FakeExecutor { + public: + bool on_idle() override { + EXPECT_FALSE(in_execute()); + EXPECT_NE(std::this_thread::get_id(), caller); + ++idle_calls; + return true; + } + const std::thread::id caller = std::this_thread::get_id(); + std::atomic idle_calls{0}; + } executor; + Fixture fixture(executor); + Session session = open(fixture.runner); + executor.hold(); + auto updates = std::make_shared(); + auto handle = generate(session, tokens(1), config(1), updates); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + while (!executor.in_execute() && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + EXPECT_TRUE(executor.in_execute()); + const int idle_calls = executor.idle_calls.load(); + std::this_thread::sleep_for(std::chrono::milliseconds(40)); + EXPECT_EQ(executor.idle_calls.load(), idle_calls); + executor.release(); + ASSERT_TRUE(updates->wait()); + handle.wait(); + while (executor.idle_calls.load() == idle_calls && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + EXPECT_GT(executor.idle_calls.load(), idle_calls); +} + +TEST(RunnerMaintenanceTest, FailedIdleHookWaitsForAnotherBatchBeforeRetrying) { + executorch::runtime::runtime_init(); + class IdleExecutor : public FakeExecutor { + public: + bool on_idle() override { + ++idle_calls; + return false; + } + std::atomic idle_calls{0}; + } executor; + Fixture fixture(executor); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + while (executor.idle_calls.load() == 0 && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + ASSERT_EQ(executor.idle_calls.load(), 1); + std::this_thread::sleep_for(std::chrono::milliseconds(60)); + EXPECT_EQ(executor.idle_calls.load(), 1); + + Session session = open(fixture.runner); + auto updates = std::make_shared(); + auto handle = generate(session, tokens(1), config(1), updates); + ASSERT_TRUE(updates->wait()); + handle.wait(); + EXPECT_EQ(handle.finish_reason(), FinishReason::NewTokenLimit); + while (executor.idle_calls.load() < 2 && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + EXPECT_EQ(executor.idle_calls.load(), 2); + std::this_thread::sleep_for(std::chrono::milliseconds(60)); + EXPECT_EQ(executor.idle_calls.load(), 2); + fixture.runner.shutdown(); + EXPECT_EQ(fixture.runner.metrics().idle_maintenance_failures, 2u); +} + +TEST( + RunnerMaintenanceTest, + OwnerClosureRearmsFailedMaintenanceWithoutAForward) { + class IdleExecutor : public FakeExecutor { + public: + bool on_idle() override { + ++idle_calls; + return false; + } + std::atomic idle_calls{0}; + } executor; + Fixture fixture(executor); + Session session = open(fixture.runner); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + while (executor.idle_calls.load() == 0 && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + ASSERT_EQ(executor.idle_calls.load(), 1); + session = Session{}; + while (executor.idle_calls.load() < 2 && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + EXPECT_EQ(executor.idle_calls.load(), 2); + fixture.runner.shutdown(); + EXPECT_EQ(fixture.runner.metrics().idle_maintenance_failures, 2u); +} + +#if ET_HAS_EXCEPTIONS +TEST(RunnerMaintenanceTest, ThrowingIdleHookIsReportedAndSuspended) { + executorch::runtime::runtime_init(); + class IdleExecutor : public FakeExecutor { + public: + bool on_idle() override { + ++idle_calls; + throw std::runtime_error("idle maintenance failed"); + } + std::atomic idle_calls{0}; + } executor; + Fixture fixture(executor); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + while (executor.idle_calls.load() == 0 && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + ASSERT_EQ(executor.idle_calls.load(), 1); + std::this_thread::sleep_for(std::chrono::milliseconds(60)); + EXPECT_EQ(executor.idle_calls.load(), 1); + fixture.runner.shutdown(); + EXPECT_EQ(fixture.runner.metrics().idle_maintenance_failures, 1u); +} +#endif + TEST(GenerationHandleTest, MoveTransfersValidity) { FakeExecutor executor; Fixture fixture(executor); From ed01352898b415ca963320c2583f296788c7b2a5 Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 21:12:33 -0800 Subject: [PATCH 2/5] Fix idle compaction forwarding, bounded trimming and rollback coverage --- .ci/scripts/muse_glimmer_batching_workload.h | 3 + .../muse_glimmer_batching_workload_test.cpp | 11 ++ .github/workflows/cuda.yml | 2 +- backends/cuda/batching/cuda_executor.cpp | 12 +- backends/cuda/batching/cuda_executor.h | 16 +- backends/cuda/runtime/cuda_kv_cache.cpp | 29 +++- backends/cuda/runtime/cuda_kv_pool.cpp | 30 +++- backends/cuda/runtime/cuda_kv_pool.h | 1 + .../cuda/runtime/test/test_cuda_allocator.cpp | 9 ++ .../cuda/runtime/test/test_cuda_kv_cache.cpp | 129 +++++++++++++++ .../runtime/cuda_dflash_executor.cpp | 2 +- .../tests/check_runtime_kv_columns.py | 26 ++- .../tests/runtime_kv_columns_probe.cpp | 153 +++++++++++++++++- extension/cuda/cuda_allocator.cpp | 27 ++-- extension/cuda/cuda_allocator.h | 5 +- extension/llm/batching/executor.h | 10 +- extension/llm/batching/runner.cpp | 16 +- extension/llm/batching/test/runner_test.cpp | 68 +++++++- 18 files changed, 502 insertions(+), 47 deletions(-) diff --git a/.ci/scripts/muse_glimmer_batching_workload.h b/.ci/scripts/muse_glimmer_batching_workload.h index 33f25418cb9..ee17658f64c 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(); } + bool on_idle() override { + return 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..81a37765fd7 100644 --- a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp +++ b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp @@ -35,6 +35,11 @@ void rejected(F action) { class FakeExecutor final : public batching::Executor { public: bool succeeds = true; + int idle_calls = 0; + bool on_idle() override { + ++idle_calls; + return succeeds; + } std::optional open_session() override { return 1; } @@ -96,6 +101,12 @@ void successful_batch_owners() { FakeExecutor inner; ci::EvidenceExecutor executor(inner); batching::BatchOutput out; + require(executor.on_idle()); + require(inner.idle_calls == 1); + inner.succeeds = false; + require(!executor.on_idle()); + require(inner.idle_calls == 2); + inner.succeeds = true; require(executor.execute({{input(1), input(1)}}, out)); require(executor.execute({{input(2)}}, out)); require(executor.evidence().max_sessions == 1); diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 39ef317b558..f7055f6c7da 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -716,7 +716,7 @@ jobs: 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" --check-compaction + --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 \ diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index c22f20bc2b2..7a48ea3ef82 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -269,7 +269,7 @@ CudaExecutor::CudaExecutor( int min_selected_rows, bool has_sampler, bool has_argmax, - std::chrono::milliseconds column_compaction_delay) + std::optional column_compaction_delay) : install_guard_(cache), module_(std::move(module)), ctl_(cache->as()), @@ -337,7 +337,8 @@ Result> CudaExecutor::create( const int initial_capacity = config.initial_capacity; const auto& options = config.options; ET_CHECK_OR_RETURN_ERROR( - config.kv_column_compaction_delay.count() >= 0, + !config.kv_column_compaction_delay || + config.kv_column_compaction_delay->count() >= 0, InvalidArgument, "CudaExecutor: negative compaction delay"); ET_CHECK_OR_RETURN_ERROR( @@ -1107,7 +1108,7 @@ Error CudaExecutor::compact_kv_columns(int spare_columns) { } bool CudaExecutor::on_idle() { - if (raw_executing_) { + if (!column_compaction_delay_ || raw_executing_) { return true; } const auto metrics = kv_->metrics(); @@ -1118,7 +1119,10 @@ bool CudaExecutor::on_idle() { return true; } const Error error = kv_->compact_columns( - static_cast(metrics.live_sequences), column_compaction_delay_); + static_cast(metrics.live_sequences), *column_compaction_delay_); + if (error == Error::NotSupported) { + return true; // Fixed physical columns need no idle maintenance. + } if (error != Error::Ok) { ET_LOG( Error, diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 0cf044906af..ca1fb5baacc 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -89,9 +89,12 @@ struct CudaExecutorConfig { int max_session_tokens = 0; int kv_dtype = static_cast(::executorch::aten::ScalarType::BFloat16); int initial_capacity = -1; - // A quiet interval before reclaiming unused physical columns. This never - // expires an open session; zero allows maintenance at the next idle check. - std::chrono::milliseconds kv_column_compaction_delay{500}; + // Idle compaction starts below 25% physical-column occupancy and keeps + // spare columns equal to the live-owner count. Open sessions never expire. + // nullopt disables automatic compaction; zero permits the next idle check. + // A later burst can regrow columns and recapture CUDA graphs. + std::optional kv_column_compaction_delay{ + std::chrono::milliseconds{500}}; CudaExecutorOptions options; }; @@ -234,7 +237,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { OffGraphKVMetrics kv_metrics() const; // Sequence-layout counters; read between executes, on the engine thread. CudaGraphMetrics graph_metrics(std::string_view method) const; - // Explicit compaction preserves every live owner, even inactive sessions. + // Call on the engine thread between executes, never concurrently with the + // Runner. Explicit compaction preserves inactive but still-open owners. ::executorch::runtime::Error compact_kv_columns(int spare_columns = 1); bool on_idle() override; // Every method, narrowest first, with how many forwards it ran. Read it @@ -262,7 +266,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { int min_selected_rows, bool has_sampler, bool has_argmax, - std::chrono::milliseconds column_compaction_delay); + std::optional column_compaction_delay); // Draws one token per row of `logits`, rows [0, sessions.size()), on the // device; returns them in row order. @@ -311,7 +315,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { std::optional device_logits_; bool initialized_ = false; bool raw_executing_ = false; - const std::chrono::milliseconds column_compaction_delay_; + const std::optional column_compaction_delay_; }; } // namespace executorch::backends::cuda::batching diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 88dc61e2929..b951c447fe0 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -1295,6 +1295,19 @@ class CudaBatchedSequenceCache final : public cache::Cache, const auto device = CUDAGuard::create(pool_.device()); ET_CHECK_OK_OR_RETURN_ERROR(device.error()); const int old_columns = columns_; +#if !defined(EXECUTORCH_USE_HIP) + const int64_t old_bytes = pool_.allocated_bytes(); + uint64_t reserved_before = 0; + const auto allocator_pool = + ::executorch::extension::cuda::CudaAllocator::pool_for_device( + pool_.device()); + const bool can_trim = pool_.allocated() && target < old_columns && + allocator_pool != nullptr && + cudaMemPoolGetAttribute( + allocator_pool, + cudaMemPoolAttrReservedMemCurrent, + &reserved_before) == cudaSuccess; +#endif const Error resized = resize_columns(target, cudaStreamPerThread); last_activity_ = std::chrono::steady_clock::now(); ET_CHECK_OK_OR_RETURN_ERROR(resized); @@ -1306,8 +1319,18 @@ class CudaBatchedSequenceCache final : public cache::Cache, poisoned_ = true; return fenced; } - ::executorch::extension::cuda::CudaAllocator::release_cached_memory( - pool_.device()); +#if !defined(EXECUTORCH_USE_HIP) + if (can_trim) { + // Bound this device-wide trim by the KV storage just retired. Preserve + // the pre-existing unused reservation of other users of the shared + // pool. + const uint64_t released = old_bytes - pool_.allocated_bytes(); + const uint64_t keep = + reserved_before > released ? reserved_before - released : 0; + ::executorch::extension::cuda::CudaAllocator::release_cached_memory( + pool_.device(), keep, /*trim_graph_memory=*/false); + } +#endif } return Error::Ok; } @@ -1376,7 +1399,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, for (const auto& [id, sequence] : seqs_) { if (sequence.column >= 0 && sequence.column < target - 1) { ET_CHECK_OR_RETURN_ERROR( - sequence.column < target - 1 && used.insert(sequence.column).second, + used.insert(sequence.column).second, InvalidState, "offgraph_kv: invalid physical owner mapping"); next.emplace(id, sequence.column); diff --git a/backends/cuda/runtime/cuda_kv_pool.cpp b/backends/cuda/runtime/cuda_kv_pool.cpp index edc2b5e4c56..ecc5aea82e8 100644 --- a/backends/cuda/runtime/cuda_kv_pool.cpp +++ b/backends/cuda/runtime/cuda_kv_pool.cpp @@ -488,7 +488,6 @@ Error CudaKVPool::resize_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 && @@ -497,7 +496,6 @@ Error CudaKVPool::resize_columns( "offgraph_kv: invalid retained column %d->%d", from, to); - relocate |= from != to; } for (const Layer& layer : layers_) { ET_CHECK_OR_RETURN_ERROR( @@ -511,9 +509,27 @@ Error CudaKVPool::resize_columns( columns_ = columns; return Error::Ok; } - if (columns == columns_ && !relocate) { + if (columns == columns_) { return Error::Ok; } + // Group adjacent source/destination owners so growth pays one 2D copy + // per layer instead of one per owner. Sorting also handles sparse IDs. + auto ordered = retained_columns; + std::sort(ordered.begin(), ordered.end()); + struct Run { + int from; + int to; + int count; + }; + std::vector runs; + for (const auto& [from, to] : ordered) { + if (!runs.empty() && runs.back().from + runs.back().count == from && + runs.back().to + runs.back().count == to) { + ++runs.back().count; + } else { + runs.push_back({from, to, 1}); + } + } const auto device = CUDAGuard::create(device_); ET_CHECK_OK_OR_RETURN_ERROR(device.error()); // Fence the pool's previous work, including another thread's PTDS, without @@ -553,16 +569,16 @@ Error CudaKVPool::resize_columns( if (logical_rows == 0) { continue; } - for (const auto& [from, to] : retained_columns) { + for (const auto& run : runs) { 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, + static_cast(dst) + slot * run.to, slot * columns, - static_cast(src) + slot * from, + static_cast(src) + slot * run.from, slot * old_columns, - slot, + slot * run.count, logical_rows, cudaMemcpyDeviceToDevice, stream); diff --git a/backends/cuda/runtime/cuda_kv_pool.h b/backends/cuda/runtime/cuda_kv_pool.h index fc8c431e64f..22313005c41 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -90,6 +90,7 @@ class CudaKVPool final { // Each pair is a retained old column and its new column. Dummy data is not // retained. live_rows is the retained logical prefix, capped by each ring. // Growth or contraction commits only after all retained copies pass. + // Equal widths are a no-op; relocation is only needed during contraction. runtime::Error resize_columns( int columns, const std::vector>& retained_columns, diff --git a/backends/cuda/runtime/test/test_cuda_allocator.cpp b/backends/cuda/runtime/test/test_cuda_allocator.cpp index 70a26ec2c5b..2c9577268f9 100644 --- a/backends/cuda/runtime/test/test_cuda_allocator.cpp +++ b/backends/cuda/runtime/test/test_cuda_allocator.cpp @@ -922,6 +922,15 @@ TEST_F(CudaAllocatorPoolTest, ReleaseCachedMemoryReturnsGraphMemory) { ASSERT_EQ(cudaGraphExecDestroy(graph_exec), cudaSuccess); ASSERT_EQ(cudaGraphDestroy(graph), cudaSuccess); + const size_t before = reserved; + CudaAllocator::release_cached_memory(0, 0, /*trim_graph_memory=*/false); + ASSERT_EQ( + cudaDeviceGetGraphMemAttribute( + 0, cudaGraphMemAttrReservedMemCurrent, &reserved), + cudaSuccess); + EXPECT_EQ(reserved, before) + << "pool-only maintenance keeps graph reservation"; + CudaAllocator::release_cached_memory(0); ASSERT_EQ( diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index b7d6ca49fa5..2337f5a15ac 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2927,6 +2927,8 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { ASSERT_TRUE(control->seq_rm(id)); } } + EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); + EXPECT_EQ(kv->metrics().allocated_bytes, before.allocated_bytes); ASSERT_EQ(kv->compact_columns(0), Error::Ok); const auto after = kv->metrics(); EXPECT_EQ(after.physical_columns, 2); @@ -3403,6 +3405,7 @@ TEST_F( kv->forget_handle(&handle); GTEST_SKIP() << "CUDA allocator pools are unavailable"; } + ::executorch::extension::cuda::CudaAllocator::release_cached_memory(device); uint64_t before = 0, after = 0; ASSERT_EQ( cudaMemPoolGetAttribute(pool, cudaMemPoolAttrReservedMemCurrent, &before), @@ -3418,6 +3421,7 @@ TEST_F( EXPECT_LT(after, before); EXPECT_GE(before - after, 8 * 1024 * 1024); EXPECT_LT(kv->metrics().allocated_bytes, live_before); + EXPECT_GE(after, before - (live_before - kv->metrics().allocated_bytes)); EXPECT_EQ(kv->metrics().physical_columns, 2); EXPECT_EQ(control->pos(owners.back()), 1); ASSERT_EQ(step(*ptr, handle, {owners.back()}), Error::Ok); @@ -3655,6 +3659,131 @@ TEST_F(CudaRuntimeColumnCacheTest, FailedAdmissionKeepsLiveOwnersUsable) { kv->forget_handle(&handle); } +TEST_F(CudaRuntimeColumnCacheTest, FailedContractionPreservesSparseOwners) { + constexpr int kLargeDim = 1 << 21; + auto cfg = config(/*capacity=*/2, /*initial=*/2, /*max_write=*/1); + cfg.max_seqs = 8; + cache::CacheGeometry geometry; + geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, 1, kLargeDim}}; + auto ptr = cu::make_cuda_batched_sequence_kv_cache(geometry, cfg); + ASSERT_NE(ptr, nullptr); + auto* control = ptr->as(); + auto* kv = ptr->as(); + FakeContainer fake; + fake.internal_names = {"flat_k", "flat_v", "seq_cols", "seq_info"}; + fake.fqns = { + "__et_offgraph_kv_layer_0_k", + "__et_offgraph_kv_layer_0_v", + "__et_offgraph_kv_seq_cols", + "__et_offgraph_kv_seq_info"}; + for (int index = 0; index < 2; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, 18, 1, kLargeDim}); + } + declare(fake, fake.fqns[2], slimc10::ScalarType::Long, {1}); + declare(fake, fake.fqns[3], slimc10::ScalarType::Int, {16, 5}); + auto handle = make_handle(fake); + auto noted = kv->note_handle(&handle); + ASSERT_TRUE(noted.ok()) << static_cast(noted.error()); + ASSERT_TRUE(noted.get()); + std::vector owners; + for (int index = 0; index < 8; ++index) { + auto owner = control->seq_new(); + ASSERT_TRUE(owner.has_value()); + owners.push_back(*owner); + } + for (const auto owner : owners) { + ASSERT_EQ(step(*ptr, handle, {owner}), Error::Ok); + } + auto* old_k = static_cast(fake.bound["flat_k"].data); + auto* old_v = static_cast(fake.bound["flat_v"].data); + const auto history = iota_rows(1); + for (const int index : {5, 7}) { + for (auto* base : {old_k, old_v}) { + ASSERT_EQ( + cudaMemcpy( + base + index * size_t{kLargeDim}, + history.data(), + history.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + } + } + for (int index = 0; index < 8; ++index) { + if (index != 5 && index != 7) { + ASSERT_TRUE(control->seq_rm(owners[index])); + } + } + int device = 0; + ASSERT_EQ(cudaGetDevice(&device), cudaSuccess); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + ::executorch::extension::cuda::CudaAllocator::release_cached_memory(device); + size_t free_bytes = 0, total_bytes = 0; + ASSERT_EQ(cudaMemGetInfo(&free_bytes, &total_bytes), cudaSuccess); + constexpr size_t kMargin = 32 * 1024 * 1024; + if (free_bytes <= 8 * kMargin) { + kv->forget_handle(&handle); + GTEST_SKIP() + << "Insufficient free memory for a controlled contraction failure"; + } + void* reservation = nullptr; + if (cudaMalloc(&reservation, free_bytes - kMargin) != cudaSuccess) { + (void)cudaGetLastError(); + kv->forget_handle(&handle); + GTEST_SKIP() << "Cannot reserve free memory for a controlled failure"; + } + auto release = [](void* data) { (void)cudaFree(data); }; + std::unique_ptr held(reservation, release); + const auto before = kv->metrics(); + const int updates = fake.updates; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + EXPECT_EQ(kv->compact_columns(0), Error::MemoryAllocationFailed); + EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); + EXPECT_EQ(kv->metrics().column_resize_count, before.column_resize_count); + EXPECT_EQ(kv->metrics().allocated_bytes, before.allocated_bytes); + EXPECT_EQ(kv->metrics().live_sequences, 2); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(fake.updates, updates); + EXPECT_EQ(fake.bound["flat_k"].data, old_k); + EXPECT_EQ(fake.bound["flat_v"].data, old_v); + for (const int index : {5, 7}) { + EXPECT_EQ(control->pos(owners[index]), 1); + EXPECT_EQ(read_rows(old_k + index * size_t{kLargeDim}, 1), history); + EXPECT_EQ(read_rows(old_v + index * size_t{kLargeDim}, 1), history); + } + for (const int index : {5, 7}) { + ASSERT_EQ(step(*ptr, handle, {owners[index]}), Error::Ok); + std::array info{}; + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + sizeof(info), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(info, (std::array{0, 1, index, 2, 9})); + } + held.reset(); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, 3); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + auto* compacted = static_cast(fake.bound["flat_k"].data); + EXPECT_EQ(read_rows(compacted, 1), history); + EXPECT_EQ(read_rows(compacted + kLargeDim, 1), history); + ASSERT_TRUE(control->rewind(owners[5], 1)); + ASSERT_TRUE(control->rewind(owners[7], 1)); + for (const int index : {5, 7}) { + ASSERT_EQ(step(*ptr, handle, {owners[index]}), Error::Ok); + } + EXPECT_EQ(control->pos(owners[5]), 2); + EXPECT_EQ(control->pos(owners[7]), 2); + kv->forget_handle(&handle); +} + TEST_F(CudaBatchedSequenceCacheTest, BuilderValidatesAndIsRegistered) { auto no_seqs = sequence_config(); no_seqs.max_seqs.reset(); diff --git a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp index c95ff165ea4..448feb433a7 100644 --- a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp +++ b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp @@ -793,7 +793,7 @@ bool MuseGlimmerCudaDFlashExecutor::initialize() { bool MuseGlimmerCudaDFlashExecutor::on_idle() { // Draft columns remain fixed; only target owner storage is compacted. - return target_->on_idle(); + return !failed_ && target_->on_idle(); } std::optional MuseGlimmerCudaDFlashExecutor::open_session() { 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 1f515aa3ec6..9f3397ad2a0 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -287,11 +287,31 @@ def check_compaction(probe: Path, artifact: Path) -> None: ) +def check_runner(probe: Path, artifact: Path) -> None: + # Exercise actual Runner polling/close re-arm through the CI decorator, + # rather than only manually calling the cache maintenance hook. + runner_traces = [] + for delay, label in ((-1, "runner-disabled"), (500, "runner-compact")): + _, trace = run( + probe, + artifact, + False, + [{"op": "runner"}], + delay, + label, + ) + runner_traces.append(trace[0]) + assert runner_traces[0]["idle_columns"] == 9 + assert runner_traces[1]["idle_columns"] == 3 + assert runner_traces[0]["outputs"] == runner_traces[1]["outputs"] + assert all(row["snapshot"]["live_sequences"] == 0 for row in runner_traces) + print("Runner-driven idle compaction, open history and regrowth passed") + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--probe", required=True, type=Path) parser.add_argument("--output-dir", required=True, type=Path) - parser.add_argument("--check-compaction", action="store_true") args = parser.parse_args() artifact = args.output_dir.resolve() artifact.mkdir(parents=True, exist_ok=True) @@ -358,8 +378,8 @@ def main() -> None: "Native column growth, identical logits, ring cloning and graph recapture passed" ) - if args.check_compaction: - check_compaction(args.probe.resolve(), artifact) + check_compaction(args.probe.resolve(), artifact) + check_runner(args.probe.resolve(), artifact) if __name__ == "__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 044558a1d0b..036d21c68e9 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -9,9 +9,12 @@ // A serialized correctness transport over the actual CUDA batching executor. // Raw cache IDs are never mixed with ServingRuntime or SessionTable IDs. #include +#include +#include #include #include #include +#include "../../../../.ci/scripts/muse_glimmer_batching_workload.h" #include #include @@ -21,6 +24,8 @@ #include #include #include +#include +#include #include #include #include @@ -40,13 +45,14 @@ DEFINE_int32(max_context, 64, "Logical model context"); DEFINE_int32(initial_kv_capacity, 4, "Initial logical rows per column"); namespace cb = executorch::backends::cuda::batching; +namespace batching = executorch::extension::llm::batching; using executorch::runtime::Error; using Json = nlohmann::json; DEFINE_int64( kv_compaction_delay_ms, 500, - "Quiet interval before column compaction"); + "Quiet interval before column compaction; -1 disables automatic compaction"); namespace { @@ -165,6 +171,143 @@ Json run_step(cb::CudaExecutor& executor, const Json& request) { return {{"logits", outputs}}; } +// Read cache metrics only on the engine thread, after the actual CI decorator +// forwards idle maintenance. The caller observes a synchronized test snapshot. +class RunnerObserver final : public batching::Executor { + public: + explicit RunnerObserver(cb::CudaExecutor& executor) + : target_(executor), evidence_(executor) {} + bool initialize() override { + return evidence_.initialize(); + } + std::size_t preferred_batch_tokens() const override { + return evidence_.preferred_batch_tokens(); + } + std::optional open_session() override { + return evidence_.open_session(); + } + void close_session(batching::SessionId id) override { + evidence_.close_session(id); + } + void set_sampling( + batching::SessionId id, + const batching::SamplingParams& params, + std::optional seed) override { + evidence_.set_sampling(id, params, seed); + } + bool execute(const batching::BatchInput& input, batching::BatchOutput& out) + override { + return evidence_.execute(input, out); + } + bool on_idle() override { + const bool ok = evidence_.on_idle(); + const auto metrics = target_.kv_metrics(); + std::lock_guard lock(mutex_); + columns_ = metrics.physical_columns; + owners_ = metrics.live_sequences; + ++idle_calls_; + return ok; + } + bool wait_for(int columns, int owners) { + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (std::chrono::steady_clock::now() < deadline) { + { + std::lock_guard lock(mutex_); + if (columns_ == columns && owners_ == owners && idle_calls_ > 0) { + return true; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + return false; + } + + private: + cb::CudaExecutor& target_; + muse_glimmer_ci::EvidenceExecutor evidence_; + std::mutex mutex_; + int64_t columns_ = 0; + int64_t owners_ = 0; + int idle_calls_ = 0; +}; + +Json check_runner(cb::CudaExecutor& executor) { + require(executor.kv_metrics().live_sequences == 0, "fresh Runner cache"); + RunnerObserver observer(executor); + batching::Runner runner( + observer, batching::DecodeFirstScheduler::create(32, 8, 16)); + std::vector sessions; + auto open = [&] { + auto future = runner.open_session_async(); + require( + future.wait_for(std::chrono::seconds(10)) == std::future_status::ready, + "Runner admission timeout"); + auto session = future.get(); + require(session.has_value(), "Runner admission failed"); + sessions.push_back(std::move(*session)); + }; + for (int i = 0; i < 8; ++i) { + open(); + } + Json output = Json::array(); + auto generate = [&](const std::vector& indices, int salt) { + auto tokens = std::make_shared>>( + indices.size()); + std::vector handles; + batching::GenConfig config; + config.max_new_tokens = 3; + config.seed = 0; + for (size_t i = 0; i < indices.size(); ++i) { + handles.push_back(sessions[indices[i]].generate_async( + std::vector{ + 1, 2, 3, static_cast(salt)}, + config, + [tokens, i](const batching::GenerationUpdate& update) { + (*tokens)[i].insert( + (*tokens)[i].end(), update.tokens.begin(), update.tokens.end()); + })); + } + for (auto& handle : handles) { + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!handle.done() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + require(handle.done(), "Runner generation timeout"); + handle.wait(); + require( + handle.finish_reason() == batching::FinishReason::NewTokenLimit, + "Runner generation failed"); + } + for (const auto& row : *tokens) { + require(row.size() == 3, "Runner token budget"); + } + output.push_back(*tokens); + }; + generate({0, 1, 2, 3, 4, 5, 6, 7}, 4); + require(observer.wait_for(9, 8), "Runner burst physical width"); + const auto survivor_position = sessions[7].position(); + for (size_t i = 0; i < 7; ++i) { + sessions[i] = batching::Session{}; + } + const int idle_columns = FLAGS_kv_compaction_delay_ms == -1 ? 9 : 3; + require( + observer.wait_for(idle_columns, 1), + "Runner quiet compaction through CI wrapper"); + require( + sessions[7].position() == survivor_position, + "inactive open history retained"); + generate({7}, 5); + for (int i = 0; i < 7; ++i) { + open(); + } + generate({7, 8, 9, 10, 11, 12, 13, 14}, 6); + require(observer.wait_for(9, 8), "Runner regrowth physical width"); + runner.shutdown(); + return {{"outputs", output}, {"idle_columns", idle_columns}}; +} + } // namespace int main(int argc, char** argv) { @@ -186,8 +329,10 @@ int main(int argc, char** argv) { config.max_sessions = FLAGS_max_sessions; config.max_session_tokens = FLAGS_max_context; config.initial_capacity = FLAGS_initial_kv_capacity; - config.kv_column_compaction_delay = - std::chrono::milliseconds(FLAGS_kv_compaction_delay_ms); + config.kv_column_compaction_delay = FLAGS_kv_compaction_delay_ms == -1 + ? std::nullopt + : std::make_optional( + std::chrono::milliseconds(FLAGS_kv_compaction_delay_ms)); config.options.cuda_graph_for_static_methods = true; auto created = cb::CudaExecutor::create(config); require(created.ok(), "create actual CUDA executor"); @@ -233,6 +378,8 @@ int main(int argc, char** argv) { } else if (op == "idle") { result["maintained"] = executor->on_idle(); require(result["maintained"].get(), "idle maintenance"); + } else if (op == "runner") { + result = check_runner(*executor); } else if (op == "step") { result = run_step(*executor, request); } else if (op != "metrics") { diff --git a/extension/cuda/cuda_allocator.cpp b/extension/cuda/cuda_allocator.cpp index c3837a703ae..c2109d58486 100644 --- a/extension/cuda/cuda_allocator.cpp +++ b/extension/cuda/cuda_allocator.cpp @@ -781,9 +781,14 @@ cudaMemPool_t CudaAllocator::pool_for_device(DeviceIndex index) { } #endif // !EXECUTORCH_USE_HIP -void CudaAllocator::release_cached_memory(DeviceIndex index) { +void CudaAllocator::release_cached_memory( + DeviceIndex index, + size_t min_bytes_to_keep, + bool trim_graph_memory) { #if defined(EXECUTORCH_USE_HIP) (void)index; + (void)min_bytes_to_keep; + (void)trim_graph_memory; #else std::vector> targets; { @@ -812,7 +817,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { // its stream during teardown for that reason, before dropping it. This // cannot wait on anything itself: it holds no stream, and a caller // reaching it directly is responsible for having synchronized. - const cudaError_t err = cudaMemPoolTrimTo(pool, 0); + const cudaError_t err = cudaMemPoolTrimTo(pool, min_bytes_to_keep); if (err != cudaSuccess) { ET_LOG( Error, @@ -833,14 +838,16 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { // unused graph memory cached by every user of the device, so another // library in this process pays to map its own graph allocations again. // Nothing breaks, since only unused blocks go. - const cudaError_t graph_err = cudaDeviceGraphMemTrim(device); - if (graph_err != cudaSuccess) { - ET_LOG( - Error, - "cudaDeviceGraphMemTrim failed for device %d: %s.", - device, - cudaGetErrorString(graph_err)); - (void)cudaGetLastError(); + if (trim_graph_memory) { + const cudaError_t graph_err = cudaDeviceGraphMemTrim(device); + if (graph_err != cudaSuccess) { + ET_LOG( + Error, + "cudaDeviceGraphMemTrim failed for device %d: %s.", + device, + cudaGetErrorString(graph_err)); + (void)cudaGetLastError(); + } } } #endif diff --git a/extension/cuda/cuda_allocator.h b/extension/cuda/cuda_allocator.h index 2c55785076a..5864ec56cd9 100644 --- a/extension/cuda/cuda_allocator.h +++ b/extension/cuda/cuda_allocator.h @@ -151,8 +151,11 @@ class EXECUTORCH_EXTENSION_CUDA_API CudaAllocator final * on the device it ran on, so releasing only the current device would * leave that memory held. */ + // min_bytes_to_keep bounds trimming of the shared pool's total reservation. static void release_cached_memory( - executorch::runtime::etensor::DeviceIndex index); + executorch::runtime::etensor::DeviceIndex index, + size_t min_bytes_to_keep = 0, + bool trim_graph_memory = true); #if !defined(EXECUTORCH_USE_HIP) /** diff --git a/extension/llm/batching/executor.h b/extension/llm/batching/executor.h index 8eb74bdcbd0..8cc3af2179b 100644 --- a/extension/llm/batching/executor.h +++ b/extension/llm/batching/executor.h @@ -86,9 +86,13 @@ class ET_EXPERIMENTAL Executor { return 0; } - // Engine-thread maintenance between batches, outside the Runner's control - // mutex. A false result pauses retries until another batch or owner closure; - // it must preserve every still-open session. + // Engine-thread maintenance when no batch or queued command is ready, + // outside the Runner's control mutex. While idle, Runner polls every 20 ms. + // true includes no work, unsupported maintenance, and work not yet due; + // a backend can defer until its own quiet interval without sleeping here. + // false reports failure and pauses retries until another completed batch or + // a command closes an owner (including admission rollback). Preserve every + // still-open session. Executor decorators must forward this hook. virtual bool on_idle() { return true; } diff --git a/extension/llm/batching/runner.cpp b/extension/llm/batching/runner.cpp index 4ef4058108b..ed4cdd41533 100644 --- a/extension/llm/batching/runner.cpp +++ b/extension/llm/batching/runner.cpp @@ -564,6 +564,7 @@ class RunnerImpl : public std::enable_shared_from_this { std::unordered_map sessions_; // Kept after records close to enforce executor IDs are lifetime-unique. std::unordered_set issued_session_ids_; + bool owner_closed_ = false; TaskId next_tid_ = 1; EngineMetrics metrics_; @@ -800,7 +801,12 @@ void RunnerImpl::run_() { idle_maintenance_enabled = true; continue; // more work may be ready } - if (idle_maintenance_enabled) { + bool idle_now = false; + { + std::lock_guard lock(control_mutex_); + idle_now = is_running_() && inbox_.empty(); + } + if (idle_maintenance_enabled && idle_now) { bool maintained = false; #if ET_HAS_EXCEPTIONS try { @@ -880,9 +886,8 @@ bool RunnerImpl::process_pending_commands_() { std::lock_guard lock(control_mutex_); commands.swap(inbox_); } - bool closed_owner = false; + owner_closed_ = false; for (auto& command : commands) { - closed_owner |= std::holds_alternative(command); std::visit( Overloaded{ [this](OpenCommand& open) { process_command_(std::move(open)); }, @@ -894,7 +899,7 @@ bool RunnerImpl::process_pending_commands_() { }}, command); } - return closed_owner; + return owner_closed_; } void RunnerImpl::process_command_(OpenCommand command) { @@ -928,6 +933,7 @@ void RunnerImpl::process_command_(OpenCommand command) { if (!published) { if (newly_issued) { executor_.close_session(*sid); + owner_closed_ = true; } command.ack->set_value(std::nullopt); } @@ -945,6 +951,7 @@ void RunnerImpl::process_command_(CloseCommand command) { /*on_engine_thread=*/true); } executor_.close_session(command.session); + owner_closed_ = true; } void RunnerImpl::process_command_(CloneCommand command) { @@ -996,6 +1003,7 @@ void RunnerImpl::process_command_(CloneCommand command) { } if (owned) { executor_.close_session(*sid); + owner_closed_ = true; } command.ack->set_value(std::nullopt); } diff --git a/extension/llm/batching/test/runner_test.cpp b/extension/llm/batching/test/runner_test.cpp index 287aad49340..8abc565dd31 100644 --- a/extension/llm/batching/test/runner_test.cpp +++ b/extension/llm/batching/test/runner_test.cpp @@ -388,14 +388,26 @@ TEST(RunnerMaintenanceTest, IdleHookRunsBetweenBatchesOnTheEngineThread) { ++idle_calls; return true; } + bool execute( + const executorch::extension::llm::batching::BatchInput& batch, + executorch::extension::llm::batching::BatchOutput& output) override { + if (++execute_calls == 1) { + idle_before_first = idle_calls.load(); + } else if (execute_calls == 2) { + EXPECT_EQ(idle_calls.load(), idle_before_first); + } + return FakeExecutor::execute(batch, output); + } const std::thread::id caller = std::this_thread::get_id(); std::atomic idle_calls{0}; + int execute_calls = 0; + int idle_before_first = 0; } executor; Fixture fixture(executor); Session session = open(fixture.runner); executor.hold(); auto updates = std::make_shared(); - auto handle = generate(session, tokens(1), config(1), updates); + auto handle = generate(session, tokens(1), config(2), updates); const auto deadline = std::chrono::steady_clock::now() + kTimeout; while (!executor.in_execute() && std::chrono::steady_clock::now() < deadline) { @@ -408,6 +420,7 @@ TEST(RunnerMaintenanceTest, IdleHookRunsBetweenBatchesOnTheEngineThread) { executor.release(); ASSERT_TRUE(updates->wait()); handle.wait(); + EXPECT_EQ(executor.execute_calls, 2); while (executor.idle_calls.load() == idle_calls && std::chrono::steady_clock::now() < deadline) { std::this_thread::yield(); @@ -415,6 +428,59 @@ TEST(RunnerMaintenanceTest, IdleHookRunsBetweenBatchesOnTheEngineThread) { EXPECT_GT(executor.idle_calls.load(), idle_calls); } +TEST(RunnerMaintenanceTest, QueuedOpenRunsBeforeIdleMaintenance) { + class IdleExecutor : public FakeExecutor { + public: + bool on_idle() override { + if (expect_open.load() && open_count() < 3) { + ++before_open; + } + ++idle_calls; + return true; + } + std::atomic expect_open{false}; + std::atomic before_open{0}; + std::atomic idle_calls{0}; + } executor; + std::promise>> pending; + auto callback_future = pending.get_future(); + Fixture fixture(executor); + Session first = open(fixture.runner); + Session cancelled = open(fixture.runner); + executor.hold(); + auto updates = std::make_shared(); + auto running = generate(first, tokens(1), config(1), updates); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + while (!executor.in_execute() && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + if (!executor.in_execute()) { + executor.release(); + FAIL() << "execute gate was not reached"; + } + // Queue a generation while the engine is busy, then cancel it before its + // StartCommand is handled. Its terminal callback enqueues an open from the + // engine thread while process_pending_commands_ is draining its old inbox. + auto handle = cancelled.generate_async( + tokens(1), config(1), [&](const GenerationUpdate& update) { + if (update.finish_reason == FinishReason::Cancelled) { + executor.expect_open = true; + pending.set_value(fixture.runner.open_session_async()); + } + }); + handle.cancel(); + executor.release(); + ASSERT_EQ(callback_future.wait_for(kTimeout), std::future_status::ready); + auto future = callback_future.get(); + ASSERT_EQ(future.wait_for(kTimeout), std::future_status::ready); + auto session = future.get(); + ASSERT_TRUE(session.has_value()); + running.wait(); + handle.wait(); + EXPECT_EQ(executor.before_open.load(), 0); +} + TEST(RunnerMaintenanceTest, FailedIdleHookWaitsForAnotherBatchBeforeRetrying) { executorch::runtime::runtime_init(); class IdleExecutor : public FakeExecutor { From f021e5382fdd2d057a7ffc6565026bf862c1a0fe Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 22:00:47 -0800 Subject: [PATCH 3/5] [CUDA] Expose idle compaction policy and qualify its boundaries --- .../muse_glimmer_batching_workload_test.cpp | 3 + backends/cuda/batching/cuda_executor.cpp | 6 +- backends/cuda/batching/cuda_executor.h | 5 +- backends/cuda/runtime/cuda_kv_cache.h | 2 +- .../cuda/runtime/test/test_cuda_allocator.cpp | 7 +++ .../cuda/runtime/test/test_cuda_kv_cache.cpp | 53 +++++++++++++---- .../muse-glimmer/runtime/backend_factory.cpp | 2 + .../muse-glimmer/runtime/backend_factory.h | 5 ++ .../runtime/cuda_dflash_executor.cpp | 3 +- .../runtime/runners/batching_bootstrap.cpp | 12 ++++ .../tests/check_runtime_kv_columns.py | 13 ++++ .../tests/runtime_kv_columns_probe.cpp | 59 ++++++++++++++++++- extension/cuda/cuda_allocator.h | 10 +++- extension/llm/batching/runner.cpp | 47 +++++++++------ 14 files changed, 185 insertions(+), 42 deletions(-) diff --git a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp index 81a37765fd7..dcacdd3d5f0 100644 --- a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp +++ b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp @@ -106,11 +106,14 @@ void successful_batch_owners() { inner.succeeds = false; require(!executor.on_idle()); require(inner.idle_calls == 2); + // Virtual forwarding consumes this setting before it is reassigned. + // cppcheck-suppress redundantAssignment inner.succeeds = true; require(executor.execute({{input(1), input(1)}}, out)); require(executor.execute({{input(2)}}, out)); require(executor.evidence().max_sessions == 1); rejected([&] { ci::check_batching(executor.evidence()); }); + // cppcheck-suppress redundantAssignment inner.succeeds = false; require(!executor.execute({{input(1), input(2)}}, out)); require(executor.evidence().multi_session_steps == 0); diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index 7a48ea3ef82..d6258e56d0e 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -314,7 +314,8 @@ Result> CudaExecutor::create( int max_session_tokens, int kv_dtype, int initial_capacity, - CudaExecutorOptions options) { + CudaExecutorOptions options, + std::optional column_compaction_delay) { ET_CHECK_OR_RETURN_ERROR( max_session_tokens > 0, InvalidArgument, @@ -325,6 +326,7 @@ Result> CudaExecutor::create( config.kv_dtype = kv_dtype; config.initial_capacity = initial_capacity; config.options = std::move(options); + config.kv_column_compaction_delay = column_compaction_delay; return create(std::move(module), config); } @@ -1104,7 +1106,7 @@ CudaGraphMetrics CudaExecutor::graph_metrics(std::string_view method) const { 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); + return kv_->compact_columns(spare_columns, std::chrono::milliseconds{0}); } bool CudaExecutor::on_idle() { diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index ca1fb5baacc..2999897ad30 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -165,13 +165,16 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // reserves `max_session_tokens` cells; together they must fit the program's // max_cells. `kv_dtype` is the ET ScalarType K/V is stored in; a negative // `initial_capacity` starts the pools at the cache's default. + // `column_compaction_delay` controls idle maintenance; nullopt disables it. static ::executorch::runtime::Result> create( std::unique_ptr<::executorch::extension::Module> module, int max_sessions, int max_session_tokens, int kv_dtype, int initial_capacity = -1, - CudaExecutorOptions options = {}); + CudaExecutorOptions options = {}, + std::optional column_compaction_delay = + std::chrono::milliseconds{500}); // The widest method's step. A wider batch runs as several forwards. std::size_t preferred_batch_tokens() const override { diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index 225cec9bd9c..08c363f5a19 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -110,7 +110,7 @@ class CudaKVCache { // owner operations. Zero explicitly bypasses the quiet interval. virtual runtime::Error compact_columns( int /*spare_columns*/, - std::chrono::milliseconds /*quiet_for*/ = std::chrono::milliseconds{0}) { + std::chrono::milliseconds /*quiet_for*/) { return runtime::Error::NotSupported; } }; diff --git a/backends/cuda/runtime/test/test_cuda_allocator.cpp b/backends/cuda/runtime/test/test_cuda_allocator.cpp index 2c9577268f9..8ae2a85cec0 100644 --- a/backends/cuda/runtime/test/test_cuda_allocator.cpp +++ b/backends/cuda/runtime/test/test_cuda_allocator.cpp @@ -819,6 +819,13 @@ TEST_F(CudaAllocatorPoolTest, ReleaseCachedMemoryReturnsPoolMemory) { ASSERT_GT(reserved_bytes(owned), 0u) << "the pool should hold the freed block for reuse"; + const auto before_trim = reserved_bytes(owned); + constexpr size_t kKeepBytes = 4u << 20; + CudaAllocator::release_cached_memory( + 0, kKeepBytes, /*trim_graph_memory=*/false); + EXPECT_GE(reserved_bytes(owned), kKeepBytes); + EXPECT_LE(reserved_bytes(owned), before_trim); + CudaAllocator::release_cached_memory(0); EXPECT_EQ(reserved_bytes(owned), 0u) diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 2337f5a15ac..a104fa40504 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -2929,7 +2929,7 @@ TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { } EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); EXPECT_EQ(kv->metrics().allocated_bytes, before.allocated_bytes); - ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->compact_columns(0, std::chrono::milliseconds{0}), Error::Ok); const auto after = kv->metrics(); EXPECT_EQ(after.physical_columns, 2); EXPECT_EQ(after.live_sequences, 1); @@ -3017,7 +3017,7 @@ TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { 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->compact_columns(0, std::chrono::milliseconds{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) { @@ -3224,7 +3224,7 @@ TEST_F(CudaRuntimeColumnCacheTest, SameWidthCompactionKeepsMappingAndBindings) { ASSERT_TRUE(second.has_value()); ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); ASSERT_TRUE(control->seq_rm(*first)); - ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->compact_columns(0, std::chrono::milliseconds{0}), Error::Ok); ASSERT_EQ(kv->metrics().physical_columns, 2); EXPECT_EQ(control->seq_new(), first); ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); @@ -3235,9 +3235,10 @@ TEST_F(CudaRuntimeColumnCacheTest, SameWidthCompactionKeepsMappingAndBindings) { 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); + ASSERT_EQ( + kv->compact_columns(kMaxSeqs, std::chrono::milliseconds{0}), Error::Ok); EXPECT_EQ(kv->metrics().physical_columns, 3); - ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->compact_columns(0, std::chrono::milliseconds{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); @@ -3406,6 +3407,15 @@ TEST_F( GTEST_SKIP() << "CUDA allocator pools are unavailable"; } ::executorch::extension::cuda::CudaAllocator::release_cached_memory(device); + // Seed unused reservation from another user of the shared pool. An + // unbounded trim would reclaim it and must fail the reservation floor below. + constexpr size_t kUnrelatedBytes = 32u << 20; + auto unrelated = ::executorch::extension::cuda::CudaAllocator::allocate_async( + kUnrelatedBytes, device, cudaStreamPerThread); + ASSERT_TRUE(unrelated.ok()); + ::executorch::extension::cuda::CudaAllocator::deallocate_async( + unrelated.get(), device, cudaStreamPerThread); + ASSERT_EQ(cudaStreamSynchronize(cudaStreamPerThread), cudaSuccess); uint64_t before = 0, after = 0; ASSERT_EQ( cudaMemPoolGetAttribute(pool, cudaMemPoolAttrReservedMemCurrent, &before), @@ -3414,7 +3424,7 @@ TEST_F( for (size_t i = 0; i + 1 < owners.size(); ++i) { ASSERT_TRUE(control->seq_rm(owners[i])); } - ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->compact_columns(0, std::chrono::milliseconds{0}), Error::Ok); ASSERT_EQ( cudaMemPoolGetAttribute(pool, cudaMemPoolAttrReservedMemCurrent, &after), cudaSuccess); @@ -3422,6 +3432,17 @@ TEST_F( EXPECT_GE(before - after, 8 * 1024 * 1024); EXPECT_LT(kv->metrics().allocated_bytes, live_before); EXPECT_GE(after, before - (live_before - kv->metrics().allocated_bytes)); + EXPECT_GE(after, kUnrelatedBytes + kv->metrics().allocated_bytes); + ::executorch::extension::cuda::CudaAllocator::release_cached_memory( + device, 0, /*trim_graph_memory=*/false); + uint64_t unbounded = 0; + ASSERT_EQ( + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &unbounded), + cudaSuccess); + EXPECT_LT(unbounded, after) + << "the bounded trim must retain more than a zero-floor trim"; + EXPECT_LT(unbounded, kUnrelatedBytes + kv->metrics().allocated_bytes); EXPECT_EQ(kv->metrics().physical_columns, 2); EXPECT_EQ(control->pos(owners.back()), 1); ASSERT_EQ(step(*ptr, handle, {owners.back()}), Error::Ok); @@ -3440,15 +3461,21 @@ TEST_F(CudaRuntimeColumnCacheTest, CompactionRejectsAnInflightForward) { ASSERT_TRUE(id.has_value()); 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, std::chrono::milliseconds{0}), + Error::InvalidState); ASSERT_EQ(kv->commit_step(1), Error::Ok); - EXPECT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->compact_columns(0, std::chrono::milliseconds{0}), Error::Ok); EXPECT_EQ(control->pos(*id), 1); - EXPECT_EQ(kv->compact_columns(-1), Error::InvalidArgument); + EXPECT_EQ( + kv->compact_columns(-1, std::chrono::milliseconds{0}), + Error::InvalidArgument); EXPECT_EQ( kv->compact_columns(0, std::chrono::milliseconds{-1}), Error::InvalidArgument); - EXPECT_EQ(kv->compact_columns(kMaxSeqs + 1), Error::InvalidArgument); + EXPECT_EQ( + kv->compact_columns(kMaxSeqs + 1, std::chrono::milliseconds{0}), + Error::InvalidArgument); kv->forget_handle(&handle); } @@ -3740,7 +3767,9 @@ TEST_F(CudaRuntimeColumnCacheTest, FailedContractionPreservesSparseOwners) { const auto before = kv->metrics(); const int updates = fake.updates; handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; - EXPECT_EQ(kv->compact_columns(0), Error::MemoryAllocationFailed); + EXPECT_EQ( + kv->compact_columns(0, std::chrono::milliseconds{0}), + Error::MemoryAllocationFailed); EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); EXPECT_EQ(kv->metrics().column_resize_count, before.column_resize_count); EXPECT_EQ(kv->metrics().allocated_bytes, before.allocated_bytes); @@ -3768,7 +3797,7 @@ TEST_F(CudaRuntimeColumnCacheTest, FailedContractionPreservesSparseOwners) { EXPECT_EQ(info, (std::array{0, 1, index, 2, 9})); } held.reset(); - ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->compact_columns(0, std::chrono::milliseconds{0}), Error::Ok); EXPECT_EQ(kv->metrics().physical_columns, 3); ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); auto* compacted = static_cast(fake.bound["flat_k"].data); diff --git a/examples/models/muse-glimmer/runtime/backend_factory.cpp b/examples/models/muse-glimmer/runtime/backend_factory.cpp index e94b58e31fa..6ac46bd3e05 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.cpp +++ b/examples/models/muse-glimmer/runtime/backend_factory.cpp @@ -46,6 +46,8 @@ runtime::Result create_muse_glimmer_backend( } executor_config.max_sessions = config.max_sessions; executor_config.max_session_tokens = config.max_session_tokens; + executor_config.kv_column_compaction_delay = + config.kv_column_compaction_delay; ET_ASSIGN_OR_RETURN(executor, cb::CudaExecutor::create(executor_config)); const auto vocab = executor->vocab_size(); const auto session_tokens = executor->max_session_tokens(); diff --git a/examples/models/muse-glimmer/runtime/backend_factory.h b/examples/models/muse-glimmer/runtime/backend_factory.h index cb908851cc5..e1622daad58 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.h +++ b/examples/models/muse-glimmer/runtime/backend_factory.h @@ -9,6 +9,8 @@ #include #include +#include +#include namespace executorch::extension::llm { @@ -24,6 +26,9 @@ struct MuseGlimmerBackendConfig { batching::Token bos_id = 200000; bool use_dflash = false; int dflash_n_draft = 0; // zero uses the exported maximum minus one + // CUDA target column compaction; nullopt disables it. Open sessions persist. + std::optional kv_column_compaction_delay{ + std::chrono::milliseconds{500}}; }; struct MuseGlimmerBackend { diff --git a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp index 448feb433a7..e77858f03fd 100644 --- a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp +++ b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp @@ -551,6 +551,7 @@ Result MuseGlimmerCudaDFlashExecutor::create( } target_config.max_sessions = config.max_sessions; target_config.max_session_tokens = config.max_session_tokens; + target_config.kv_column_compaction_delay = config.kv_column_compaction_delay; for (int n = 1; n <= df::kOwnerLimit; ++n) { target_config.options.additional_cuda_graph_methods.push_back( df::kStaticForwardPrefix + std::to_string(n)); @@ -793,7 +794,7 @@ bool MuseGlimmerCudaDFlashExecutor::initialize() { bool MuseGlimmerCudaDFlashExecutor::on_idle() { // Draft columns remain fixed; only target owner storage is compacted. - return !failed_ && target_->on_idle(); + return failed_ || target_->on_idle(); } std::optional MuseGlimmerCudaDFlashExecutor::open_session() { diff --git a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp index 7e8ce57d739..50c66038ccd 100644 --- a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp +++ b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp @@ -26,6 +26,10 @@ DEFINE_string(backend, "cuda", "Executor backend"); DEFINE_string(backend, "mlx", "Executor backend"); #endif DEFINE_int32(max_sessions, 4, "Maximum logical sessions"); +DEFINE_int64( + kv_column_compaction_delay_ms, + 500, + "CUDA column compaction quiet interval; -1 disables, 0 allows the next idle check"); DEFINE_int32( max_session_tokens, 0, @@ -67,6 +71,10 @@ DEFINE_uint64(eos_id, 200001, "Additional EOS token ID (never eom)"); namespace executorch::extension::llm { std::unique_ptr create_muse_glimmer_batching_runtime() { + if (FLAGS_kv_column_compaction_delay_ms < -1) { + throw std::invalid_argument( + "--kv_column_compaction_delay_ms must be -1 or nonnegative"); + } const bool every_prompt_end = FLAGS_prefix_checkpoint_prompt_end == "every"; if (!every_prompt_end && FLAGS_prefix_checkpoint_prompt_end != "initial") { throw std::invalid_argument( @@ -133,6 +141,10 @@ create_muse_glimmer_batching_runtime() { backend.bos_id = FLAGS_bos_id; backend.use_dflash = FLAGS_dflash; backend.dflash_n_draft = FLAGS_dflash_n_draft; + backend.kv_column_compaction_delay = FLAGS_kv_column_compaction_delay_ms == -1 + ? std::nullopt + : std::make_optional( + std::chrono::milliseconds{FLAGS_kv_column_compaction_delay_ms}); auto created = create_muse_glimmer_backend(backend); if (!created.ok()) throw std::runtime_error( 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 9f3397ad2a0..fc88e055069 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -308,6 +308,18 @@ def check_runner(probe: Path, artifact: Path) -> None: print("Runner-driven idle compaction, open history and regrowth passed") +def check_policy(probe: Path, artifact: Path) -> None: + for delay, expected in ((-1, 9), (0, 3), (500, 3)): + _, trace = run( + probe, artifact, False, [{"op": "policy"}], delay, f"policy-{delay}" + ) + measured = trace[0] + assert measured["threshold_columns"] == 9, measured + assert measured["below_threshold_columns"] == expected, measured + assert measured["snapshot"]["live_sequences"] == 0, measured + print("CudaExecutor disabled policy and 25 percent threshold passed") + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--probe", required=True, type=Path) @@ -380,6 +392,7 @@ def main() -> None: check_compaction(args.probe.resolve(), artifact) check_runner(args.probe.resolve(), artifact) + check_policy(args.probe.resolve(), artifact) if __name__ == "__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 036d21c68e9..5f95e554959 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -214,7 +214,8 @@ class RunnerObserver final : public batching::Executor { while (std::chrono::steady_clock::now() < deadline) { { std::lock_guard lock(mutex_); - if (columns_ == columns && owners_ == owners && idle_calls_ > 0) { + if ((columns < 0 || columns_ == columns) && owners_ == owners && + idle_calls_ > 0) { return true; } } @@ -222,6 +223,10 @@ class RunnerObserver final : public batching::Executor { } return false; } + int64_t physical_columns() { + std::lock_guard lock(mutex_); + return columns_; + } private: cb::CudaExecutor& target_; @@ -261,7 +266,7 @@ Json check_runner(cb::CudaExecutor& executor) { for (size_t i = 0; i < indices.size(); ++i) { handles.push_back(sessions[indices[i]].generate_async( std::vector{ - 1, 2, 3, static_cast(salt)}, + 1, 2, 3, static_cast(salt + indices[i])}, config, [tokens, i](const batching::GenerationUpdate& update) { (*tokens)[i].insert( @@ -291,10 +296,15 @@ Json check_runner(cb::CudaExecutor& executor) { for (size_t i = 0; i < 7; ++i) { sessions[i] = batching::Session{}; } + require(observer.wait_for(-1, 1), "Runner closed-owner processing"); + // Check past the default quiet interval in both runs. An ignored nullopt + // must not pass merely because the first idle poll occurred before 500 ms. + std::this_thread::sleep_for(std::chrono::milliseconds(600)); const int idle_columns = FLAGS_kv_compaction_delay_ms == -1 ? 9 : 3; require( observer.wait_for(idle_columns, 1), "Runner quiet compaction through CI wrapper"); + const auto observed_idle_columns = observer.physical_columns(); require( sessions[7].position() == survivor_position, "inactive open history retained"); @@ -305,7 +315,48 @@ Json check_runner(cb::CudaExecutor& executor) { generate({7, 8, 9, 10, 11, 12, 13, 14}, 6); require(observer.wait_for(9, 8), "Runner regrowth physical width"); runner.shutdown(); - return {{"outputs", output}, {"idle_columns", idle_columns}}; + return {{"outputs", output}, {"idle_columns", observed_idle_columns}}; +} + +Json check_policy(cb::CudaExecutor& executor) { + require(executor.kv_metrics().live_sequences == 0, "fresh policy cache"); + require( + FLAGS_kv_compaction_delay_ms == -1 || FLAGS_kv_compaction_delay_ms == 0 || + FLAGS_kv_compaction_delay_ms == 500, + "bounded policy test delay"); + auto& control = executor.cache_control(); + std::vector ids; + for (int i = 0; i < 8; ++i) { + auto id = control.seq_new(); + require(id.has_value(), "policy owner admission"); + ids.push_back(*id); + } + run_step( + executor, + {{"tokens", {1, 2, 3, 4, 5, 6, 7, 8}}, + {"seq_ids", ids}, + {"select", {0, 1, 2, 3, 4, 5, 6, 7}}}); + for (int i = 0; i < 6; ++i) { + require(control.seq_rm(ids[i]), "policy owner closure"); + } + std::this_thread::sleep_for(std::chrono::milliseconds(600)); + require(executor.on_idle(), "policy at threshold"); + const auto threshold_columns = executor.kv_metrics().physical_columns; + require(threshold_columns == 9, "25 percent occupancy must not compact"); + require(control.seq_rm(ids[6]), "policy below-threshold closure"); + std::this_thread::sleep_for(std::chrono::milliseconds(600)); + require(executor.on_idle(), "policy below threshold"); + const auto below_columns = executor.kv_metrics().physical_columns; + require( + below_columns == (FLAGS_kv_compaction_delay_ms == -1 ? 9 : 3), + "policy disable and below-threshold width"); + require(control.pos(ids[7]) == 1, "policy inactive owner history"); + run_step(executor, {{"tokens", {9}}, {"seq_ids", {ids[7]}}, {"select", {0}}}); + require(control.pos(ids[7]) == 2, "policy survivor continuation"); + require(control.seq_rm(ids[7]), "policy final owner closure"); + return { + {"threshold_columns", threshold_columns}, + {"below_threshold_columns", below_columns}}; } } // namespace @@ -380,6 +431,8 @@ int main(int argc, char** argv) { require(result["maintained"].get(), "idle maintenance"); } else if (op == "runner") { result = check_runner(*executor); + } else if (op == "policy") { + result = check_policy(*executor); } else if (op == "step") { result = run_step(*executor, request); } else if (op != "metrics") { diff --git a/extension/cuda/cuda_allocator.h b/extension/cuda/cuda_allocator.h index 5864ec56cd9..c1a5bd01e88 100644 --- a/extension/cuda/cuda_allocator.h +++ b/extension/cuda/cuda_allocator.h @@ -133,8 +133,8 @@ class EXECUTORCH_EXTENSION_CUDA_API CudaAllocator final * All delegates using this allocator share its pools and retention threshold. * Trimming may release any delegate's cached blocks, making its next * allocation slower. Live allocations and the device default pool are - * unaffected. Unused graph memory is trimmed device-wide only on devices - * this allocator has a pool entry for. + * unaffected. When trim_graph_memory is true, unused graph memory is trimmed + * device-wide only on devices this allocator has a pool entry for. * * Call after device work has finished. This function does not synchronize; * only frees already observed by the driver can be released. The CUDA @@ -150,8 +150,12 @@ class EXECUTORCH_EXTENSION_CUDA_API CudaAllocator final * class: a delegate is often torn down from a thread that is not current * on the device it ran on, so releasing only the current device would * leave that memory held. + * @param min_bytes_to_keep Minimum total reservation to retain in each + * selected shared pool. A negative index applies this floor separately + * to every selected device. Live allocations can exceed the floor. + * @param trim_graph_memory Whether to also trim device-wide unused CUDA + * graph memory. Use false for routine pool-only maintenance. */ - // min_bytes_to_keep bounds trimming of the shared pool's total reservation. static void release_cached_memory( executorch::runtime::etensor::DeviceIndex index, size_t min_bytes_to_keep = 0, diff --git a/extension/llm/batching/runner.cpp b/extension/llm/batching/runner.cpp index ed4cdd41533..ca71b70edec 100644 --- a/extension/llm/batching/runner.cpp +++ b/extension/llm/batching/runner.cpp @@ -459,9 +459,9 @@ class RunnerImpl : public std::enable_shared_from_this { void run_(); bool process_pending_commands_(); - void process_command_(OpenCommand command); - void process_command_(CloseCommand command); - void process_command_(CloneCommand command); + bool process_command_(OpenCommand command); + bool process_command_(CloseCommand command); + bool process_command_(CloneCommand command); void process_command_(StartCommand command); void process_command_(AcceptsCommand command); std::optional retire_session_(SessionId session); @@ -564,7 +564,6 @@ class RunnerImpl : public std::enable_shared_from_this { std::unordered_map sessions_; // Kept after records close to enforce executor IDs are lifetime-unique. std::unordered_set issued_session_ids_; - bool owner_closed_ = false; TaskId next_tid_ = 1; EngineMetrics metrics_; @@ -886,23 +885,33 @@ bool RunnerImpl::process_pending_commands_() { std::lock_guard lock(control_mutex_); commands.swap(inbox_); } - owner_closed_ = false; + bool closed_owner = false; for (auto& command : commands) { - std::visit( + closed_owner |= std::visit( Overloaded{ - [this](OpenCommand& open) { process_command_(std::move(open)); }, - [this](CloseCommand& close) { process_command_(std::move(close)); }, - [this](CloneCommand& clone) { process_command_(std::move(clone)); }, - [this](StartCommand& start) { process_command_(std::move(start)); }, + [this](OpenCommand& open) { + return process_command_(std::move(open)); + }, + [this](CloseCommand& close) { + return process_command_(std::move(close)); + }, + [this](CloneCommand& clone) { + return process_command_(std::move(clone)); + }, + [this](StartCommand& start) { + process_command_(std::move(start)); + return false; + }, [this](AcceptsCommand& accepts) { process_command_(std::move(accepts)); + return false; }}, command); } - return owner_closed_; + return closed_owner; } -void RunnerImpl::process_command_(OpenCommand command) { +bool RunnerImpl::process_command_(OpenCommand command) { const bool running = is_running_(); auto sid = running ? executor_.open_session() : std::nullopt; if (running && !sid) { @@ -933,16 +942,16 @@ void RunnerImpl::process_command_(OpenCommand command) { if (!published) { if (newly_issued) { executor_.close_session(*sid); - owner_closed_ = true; } command.ack->set_value(std::nullopt); } + return newly_issued && !published; } -void RunnerImpl::process_command_(CloseCommand command) { +bool RunnerImpl::process_command_(CloseCommand command) { auto retired = retire_session_(command.session); if (!retired) { - return; + return false; } if (retired->active_generation) { complete_generation_( @@ -951,17 +960,17 @@ void RunnerImpl::process_command_(CloseCommand command) { /*on_engine_thread=*/true); } executor_.close_session(command.session); - owner_closed_ = true; + return true; } -void RunnerImpl::process_command_(CloneCommand command) { +bool RunnerImpl::process_command_(CloneCommand command) { const auto source = sessions_.find(command.source); // A later CloseCommand may already have cleared the public open flag. FIFO // admission still gives this clone access until that command retires source. if (!is_running_() || source == sessions_.end() || source->second.poisoned || command.upto < 0 || command.upto > source->second.position()) { command.ack->set_value(std::nullopt); - return; + return false; } std::optional sid; @@ -1003,10 +1012,10 @@ void RunnerImpl::process_command_(CloneCommand command) { } if (owned) { executor_.close_session(*sid); - owner_closed_ = true; } command.ack->set_value(std::nullopt); } + return owned && !published; } void RunnerImpl::process_command_(StartCommand command) { From 25dcc93ab9fc9b0dd8ef4a204ee1fe74c323e741 Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 23:25:06 -0800 Subject: [PATCH 4/5] [CUDA] Verify sparse-owner and DFlash target compaction --- .github/workflows/cuda.yml | 3 + backends/cuda/batching/cuda_executor.h | 2 +- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 41 ++++-- .../tests/cuda_dflash_native_test.cpp | 133 +++++++++++++++++- .../tests/export_cuda_dflash_tiny.py | 8 +- 5 files changed, 173 insertions(+), 14 deletions(-) diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index f7055f6c7da..457ebb66340 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -729,6 +729,9 @@ jobs: export ET_MUSE_DFLASH_TINY_DIR="${RUNNER_TEMP:-/tmp}/muse_glimmer_dflash_tiny" python examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py \ --output-dir "${ET_MUSE_DFLASH_TINY_DIR}" + export ET_MUSE_DFLASH_SEQUENCE_TINY_DIR="${RUNNER_TEMP:-/tmp}/muse_glimmer_dflash_sequence_tiny" + python examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py \ + --output-dir "${ET_MUSE_DFLASH_SEQUENCE_TINY_DIR}" --kv-layout sequence ctest --test-dir "${BATCHING_BIN_DIR}" -R '^muse_glimmer_cuda_dflash$' \ --output-on-failure --no-tests=error -V > /tmp/muse_glimmer_cuda_dflash.log 2>&1 \ || { cat /tmp/muse_glimmer_cuda_dflash.log; exit 1; } diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 2999897ad30..3d3ebb5ecd1 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -89,7 +89,7 @@ struct CudaExecutorConfig { int max_session_tokens = 0; int kv_dtype = static_cast(::executorch::aten::ScalarType::BFloat16); int initial_capacity = -1; - // Idle compaction starts below 25% physical-column occupancy and keeps + // Idle compaction starts below 25% occupancy of non-scratch columns and keeps // spare columns equal to the live-owner count. Open sessions never expire. // nullopt disables automatic compaction; zero permits the next idle check. // A later burst can regrow columns and recapture CUDA graphs. diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index a104fa40504..a59032c59a9 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -3727,14 +3727,22 @@ TEST_F(CudaRuntimeColumnCacheTest, FailedContractionPreservesSparseOwners) { } auto* old_k = static_cast(fake.bound["flat_k"].data); auto* old_v = static_cast(fake.bound["flat_v"].data); - const auto history = iota_rows(1); + std::array, 8> history_k, history_v; for (const int index : {5, 7}) { - for (auto* base : {old_k, old_v}) { + history_k[index] = iota_rows(1); + history_v[index] = iota_rows(1); + for (size_t element = 0; element < history_k[index].size(); ++element) { + history_k[index][element] += 100 * index; + history_v[index][element] += 1000 * index; + } + for (const auto& [base, history] : + {std::pair{old_k, &history_k[index]}, + std::pair{old_v, &history_v[index]}}) { ASSERT_EQ( cudaMemcpy( base + index * size_t{kLargeDim}, - history.data(), - history.size() * sizeof(uint16_t), + history->data(), + history->size() * sizeof(uint16_t), cudaMemcpyHostToDevice), cudaSuccess); } @@ -3781,8 +3789,10 @@ TEST_F(CudaRuntimeColumnCacheTest, FailedContractionPreservesSparseOwners) { EXPECT_EQ(fake.bound["flat_v"].data, old_v); for (const int index : {5, 7}) { EXPECT_EQ(control->pos(owners[index]), 1); - EXPECT_EQ(read_rows(old_k + index * size_t{kLargeDim}, 1), history); - EXPECT_EQ(read_rows(old_v + index * size_t{kLargeDim}, 1), history); + EXPECT_EQ( + read_rows(old_k + index * size_t{kLargeDim}, 1), history_k[index]); + EXPECT_EQ( + read_rows(old_v + index * size_t{kLargeDim}, 1), history_v[index]); } for (const int index : {5, 7}) { ASSERT_EQ(step(*ptr, handle, {owners[index]}), Error::Ok); @@ -3800,13 +3810,26 @@ TEST_F(CudaRuntimeColumnCacheTest, FailedContractionPreservesSparseOwners) { ASSERT_EQ(kv->compact_columns(0, std::chrono::milliseconds{0}), Error::Ok); EXPECT_EQ(kv->metrics().physical_columns, 3); ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); - auto* compacted = static_cast(fake.bound["flat_k"].data); - EXPECT_EQ(read_rows(compacted, 1), history); - EXPECT_EQ(read_rows(compacted + kLargeDim, 1), history); + auto* compacted_k = static_cast(fake.bound["flat_k"].data); + auto* compacted_v = static_cast(fake.bound["flat_v"].data); + for (const int index : {5, 7}) { + const size_t column = index == 5 ? 0 : 1; + EXPECT_EQ(read_rows(compacted_k + column * kLargeDim, 1), history_k[index]); + EXPECT_EQ(read_rows(compacted_v + column * kLargeDim, 1), history_v[index]); + } ASSERT_TRUE(control->rewind(owners[5], 1)); ASSERT_TRUE(control->rewind(owners[7], 1)); for (const int index : {5, 7}) { ASSERT_EQ(step(*ptr, handle, {owners[index]}), Error::Ok); + std::array info{}; + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + sizeof(info), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(info, (std::array{0, 1, index == 5 ? 0 : 1, 2, 3})); } EXPECT_EQ(control->pos(owners[5]), 2); EXPECT_EQ(control->pos(owners[7]), 2); diff --git a/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp b/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp index 05deebd100a..b21582def1e 100644 --- a/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp +++ b/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp @@ -13,7 +13,9 @@ #include #include +#include #include +#include #include #include #include @@ -47,7 +49,7 @@ struct CudaDFlashTestPeer { 4, 96, static_cast(aten::ScalarType::BFloat16), - /*initial_capacity=*/-1, + /*initial_capacity=*/512, std::move(options)); EXPECT_EQ(target.error(), rt::Error::Ok); if (!target.ok()) { @@ -80,9 +82,25 @@ struct CudaDFlashTestPeer { config.capacity = 512; config.max_write = 96; config.kv_dtype = static_cast(aten::ScalarType::BFloat16); + auto sequence_count = + detail::read_int_method(program, cuda_dflash_detail::kMaxSeqs); + if (!sequence_count.ok()) { + return nullptr; + } + if (*sequence_count) { + auto capacity = + detail::read_int_method(program, cuda_dflash_detail::kSeqCapacity); + if (!capacity.ok() || !*capacity) { + return nullptr; + } + config.capacity = static_cast(**capacity); + config.max_seqs = static_cast(**sequence_count); + config.initial_capacity = + std::min(config.initial_capacity, config.capacity); + } auto draft = c::CacheFactory::global().build( executorch::backends::cuda::kCudaBackendId, - c::kind::kBatchedCell, + *sequence_count ? c::kind::kBatchedSequence : c::kind::kBatchedCell, geometry, config); EXPECT_EQ(draft.error(), rt::Error::Ok); @@ -128,6 +146,12 @@ struct CudaDFlashTestPeer { static bool rewind(DFlash& executor, b::SessionId sid, int position) { return executor.rewind(executor.sessions_.at(sid), position); } + static auto target_metrics(DFlash& executor) { + return executor.target_->kv_metrics(); + } + static rt::Error compact_target(DFlash& executor) { + return executor.target_->compact_kv_columns(0); + } static bool poisoned(DFlash& executor, b::SessionId sid) { return executor.sessions_.at(sid).poisoned; } @@ -194,6 +218,7 @@ class FixtureModule final : public Module { } std::array rejected{15, 15, 15, 15}; bool fail_target_sampler = false; + bool require_finite_logits = false; rt::Result> execute( const std::string& name, const std::vector& inputs) override { @@ -220,6 +245,21 @@ class FixtureModule final : public Module { return actual; } target_output_ = !draft; + if (require_finite_logits) { + const auto& logits = actual.get()[0].toTensor(); + std::vector values(logits.numel()); + if (cudaMemcpy( + values.data(), + logits.const_data_ptr(), + values.size() * sizeof(float), + cudaMemcpyDeviceToHost) != cudaSuccess || + !std::all_of(values.begin(), values.end(), [](float value) { + return std::isfinite(value); + })) { + ADD_FAILURE() << "Nonfinite or unreadable native DFlash logits"; + return rt::Error::Internal; + } + } if (!deterministic_) { return actual; } @@ -747,6 +787,95 @@ TEST_F(CudaDFlashNative, UnmodifiedOldArtifactRunsSoloAndFourOwnerDecode) { EXPECT_EQ(executor_->stats().failed_batches, 0); } +TEST_F( + CudaDFlashNative, + SequenceTargetCompactionPreservesSpeculativeContinuation) { + const char* sequence_dir = std::getenv("ET_MUSE_DFLASH_SEQUENCE_TINY_DIR"); + if (!sequence_dir || !*sequence_dir) { + GTEST_SKIP() + << "Set ET_MUSE_DFLASH_SEQUENCE_TINY_DIR to a tiny export with " + "--kv-layout sequence"; + } + dir_ = sequence_dir; + auto run = [&](bool compact) { + std::vector emitted; + executor_.reset(); + create(/*deterministic=*/false); + if (!executor_) { + return emitted; + } + fixture_->require_finite_logits = true; + std::array owners; + b::BatchInput batch; + for (int owner = 0; owner < 4; ++owner) { + owners[owner] = open(); + Tokens prompt(owner + 3); + std::iota(prompt.begin(), prompt.end(), 1 + 17 * owner); + batch.inputs.push_back(input(owners[owner], 0, std::move(prompt))); + } + b::BatchOutput out; + // Exercise four-owner speculation, then prime the survivor's static path + // before its target KV column moves from column 3 to column 0. + for (int round = 0; round < 3; ++round) { + if (!executor_->execute(batch, out)) { + ADD_FAILURE() << "Native DFlash step failed before compaction"; + return emitted; + } + batch.inputs.clear(); + for (int owner = round < 1 ? 0 : 3; owner < 4; ++owner) { + const int output_index = round < 2 ? owner : 0; + if (!out.outputs[output_index] || + out.outputs[output_index]->tokens.empty()) { + ADD_FAILURE() << "No DFlash output before compaction"; + return emitted; + } + Peer::check( + *executor_, + owners[owner], + Peer::frontier(*executor_, owners[owner])); + batch.inputs.push_back(input( + owners[owner], + Peer::frontier(*executor_, owners[owner]), + {out.outputs[output_index]->tokens.back()})); + } + if (round == 1) { + for (int owner = 0; owner < 3; ++owner) { + executor_->close_session(owners[owner]); + } + } + } + const auto before = Peer::target_metrics(*executor_); + EXPECT_EQ(before.physical_columns, 5); + if (compact) { + EXPECT_EQ(Peer::compact_target(*executor_), rt::Error::Ok); + const auto after = Peer::target_metrics(*executor_); + EXPECT_EQ(after.physical_columns, 2); + EXPECT_EQ(after.column_resize_count, before.column_resize_count + 1); + } + for (int round = 0; round < 2; ++round) { + const auto start = batch.inputs[0].position; + if (!executor_->execute(batch, out) || !out.outputs[0] || + out.outputs[0]->tokens.empty()) { + ADD_FAILURE() << "Native DFlash continuation failed"; + return emitted; + } + emitted.push_back(out.outputs[0]->tokens); + Peer::check(*executor_, owners[3], start + out.outputs[0]->tokens.size()); + batch.inputs = {input( + owners[3], + Peer::frontier(*executor_, owners[3]), + {out.outputs[0]->tokens.back()})}; + } + EXPECT_GT(executor_->stats().static_draft_forwards, 0); + EXPECT_EQ(executor_->stats().failed_batches, 0); + return emitted; + }; + const auto reference = run(false); + const auto compacted = run(true); + ASSERT_EQ(reference.size(), 2); + EXPECT_EQ(compacted, reference); +} + // The production adapter captures draft_forward_{N} in CUDA graphs; on real // outputs those replays must decode exactly as the eager static drafts do. TEST_F(CudaDFlashNative, CapturedStaticDraftsMatchEager) { diff --git a/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py b/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py index 78a42b4930b..33d2350fa4f 100644 --- a/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py +++ b/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py @@ -30,7 +30,7 @@ from executorch.examples.models.muse_glimmer.tests.test_pipeline import TINY_CONFIG -def export(output_dir: Path) -> None: +def export(output_dir: Path, kv_layout: str = "cell") -> None: torch.manual_seed(123) config = replace(TINY_CONFIG, dim=64, n_layers=2, head_dim=16, max_seq_len=128) target = MuseGlimmerModel(config).to(torch.bfloat16).eval() @@ -59,6 +59,8 @@ def export(output_dir: Path) -> None: forward_sizes=(1, 2, 4, 8, 16), dflash_draft=draft.to(torch.bfloat16).eval(), max_draft_owners=4, + kv_layout=kv_layout, + max_kv_seqs=4, ) print(f"Wrote {output_dir}/model.pte and aoti_cuda_blob.ptd") @@ -66,7 +68,9 @@ def export(output_dir: Path) -> None: def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--output-dir", required=True, type=Path) - export(parser.parse_args().output_dir) + parser.add_argument("--kv-layout", choices=("cell", "sequence"), default="cell") + args = parser.parse_args() + export(args.output_dir, args.kv_layout) if __name__ == "__main__": From 6d9ecfd1d29273b9f5b6d84160d5b5a542a67c9d Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Tue, 24 Nov 2026 00:02:15 -0800 Subject: [PATCH 5/5] Strengthen DFlash continuation checks after KV column compaction --- backends/cuda/batching/cuda_executor.cpp | 2 +- backends/cuda/batching/cuda_executor.h | 3 +- .../tests/cuda_dflash_native_test.cpp | 57 +++++++++++++++---- .../tests/export_cuda_dflash_tiny.py | 8 +++ 4 files changed, 56 insertions(+), 14 deletions(-) diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index d6258e56d0e..2acdf26e1d5 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -1114,7 +1114,7 @@ bool CudaExecutor::on_idle() { return true; } const auto metrics = kv_->metrics(); - // Below 25% occupancy, retain spare room equal to the live-owner count. + // Below 25% non-scratch occupancy, retain spare room equal to the live count. // Time controls when this runs, never which owners can be removed. if (metrics.physical_columns <= 2 || 4 * metrics.live_sequences + 1 >= metrics.physical_columns) { diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 3d3ebb5ecd1..6eb268c0f47 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -90,7 +90,8 @@ struct CudaExecutorConfig { int kv_dtype = static_cast(::executorch::aten::ScalarType::BFloat16); int initial_capacity = -1; // Idle compaction starts below 25% occupancy of non-scratch columns and keeps - // spare columns equal to the live-owner count. Open sessions never expire. + // spare columns equal to the live-owner count, retaining at least one + // non-scratch column when none are live. Open sessions never expire. // nullopt disables automatic compaction; zero permits the next idle check. // A later burst can regrow columns and recapture CUDA graphs. std::optional kv_column_compaction_delay{ diff --git a/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp b/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp index b21582def1e..92e3c3fb84c 100644 --- a/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp +++ b/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp @@ -35,6 +35,8 @@ using executorch::extension::TensorPtr; namespace executorch::extension::llm { // Tiny artifacts cannot pass Muse's special-token vocabulary check. Keep the // production factory unchanged and construct only the validated tiny geometry. +// Explicitly clamp initial KV storage too: the production defaults do not yet +// clamp the 512-token initial capacity for exports with smaller context limits. struct CudaDFlashTestPeer { static std::unique_ptr create(std::unique_ptr module, int proposals, bool draft_graphs) { @@ -219,6 +221,7 @@ class FixtureModule final : public Module { std::array rejected{15, 15, 15, 15}; bool fail_target_sampler = false; bool require_finite_logits = false; + std::vector> observed_logits; rt::Result> execute( const std::string& name, const std::vector& inputs) override { @@ -247,18 +250,25 @@ class FixtureModule final : public Module { target_output_ = !draft; if (require_finite_logits) { const auto& logits = actual.get()[0].toTensor(); + if (logits.scalar_type() != aten::ScalarType::Float) { + ADD_FAILURE() << "This tiny fixture requires Float logits"; + return rt::Error::Internal; + } std::vector values(logits.numel()); - if (cudaMemcpy( + if (cudaMemcpyAsync( values.data(), logits.const_data_ptr(), values.size() * sizeof(float), - cudaMemcpyDeviceToHost) != cudaSuccess || + cudaMemcpyDeviceToHost, + stream) != cudaSuccess || + cudaStreamSynchronize(stream) != cudaSuccess || !std::all_of(values.begin(), values.end(), [](float value) { return std::isfinite(value); })) { ADD_FAILURE() << "Nonfinite or unreadable native DFlash logits"; return rt::Error::Internal; } + observed_logits.push_back(std::move(values)); } if (!deterministic_) { return actual; @@ -797,12 +807,17 @@ TEST_F( "--kv-layout sequence"; } dir_ = sequence_dir; - auto run = [&](bool compact) { + struct Continuation { std::vector emitted; + std::vector> logits; + std::uint64_t static_draft_forwards = 0; + }; + auto run = [&](bool compact) { + Continuation result; executor_.reset(); create(/*deterministic=*/false); if (!executor_) { - return emitted; + return result; } fixture_->require_finite_logits = true; std::array owners; @@ -819,7 +834,7 @@ TEST_F( for (int round = 0; round < 3; ++round) { if (!executor_->execute(batch, out)) { ADD_FAILURE() << "Native DFlash step failed before compaction"; - return emitted; + return result; } batch.inputs.clear(); for (int owner = round < 1 ? 0 : 3; owner < 4; ++owner) { @@ -827,7 +842,7 @@ TEST_F( if (!out.outputs[output_index] || out.outputs[output_index]->tokens.empty()) { ADD_FAILURE() << "No DFlash output before compaction"; - return emitted; + return result; } Peer::check( *executor_, @@ -845,6 +860,8 @@ TEST_F( } } const auto before = Peer::target_metrics(*executor_); + const auto stats_before = executor_->stats(); + fixture_->observed_logits.clear(); EXPECT_EQ(before.physical_columns, 5); if (compact) { EXPECT_EQ(Peer::compact_target(*executor_), rt::Error::Ok); @@ -857,23 +874,39 @@ TEST_F( if (!executor_->execute(batch, out) || !out.outputs[0] || out.outputs[0]->tokens.empty()) { ADD_FAILURE() << "Native DFlash continuation failed"; - return emitted; + return result; } - emitted.push_back(out.outputs[0]->tokens); + result.emitted.push_back(out.outputs[0]->tokens); Peer::check(*executor_, owners[3], start + out.outputs[0]->tokens.size()); batch.inputs = {input( owners[3], Peer::frontier(*executor_, owners[3]), {out.outputs[0]->tokens.back()})}; } - EXPECT_GT(executor_->stats().static_draft_forwards, 0); + result.static_draft_forwards = executor_->stats().static_draft_forwards - + stats_before.static_draft_forwards; + EXPECT_GT(result.static_draft_forwards, 0); EXPECT_EQ(executor_->stats().failed_batches, 0); - return emitted; + result.logits = std::move(fixture_->observed_logits); + return result; }; const auto reference = run(false); const auto compacted = run(true); - ASSERT_EQ(reference.size(), 2); - EXPECT_EQ(compacted, reference); + ASSERT_EQ(reference.emitted.size(), 2); + EXPECT_EQ(compacted.emitted, reference.emitted); + EXPECT_EQ(compacted.static_draft_forwards, reference.static_draft_forwards); + ASSERT_FALSE(reference.logits.empty()); + ASSERT_EQ(compacted.logits.size(), reference.logits.size()); + for (std::size_t i = 0; i < reference.logits.size(); ++i) { + ASSERT_EQ(compacted.logits[i].size(), reference.logits[i].size()); + EXPECT_EQ( + std::memcmp( + compacted.logits[i].data(), + reference.logits[i].data(), + reference.logits[i].size() * sizeof(float)), + 0) + << "Continuation logits differ at forward " << i; + } } // The production adapter captures draft_forward_{N} in CUDA graphs; on real diff --git a/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py b/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py index 33d2350fa4f..2c457225343 100644 --- a/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py +++ b/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py @@ -9,6 +9,14 @@ python examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py --output-dir DIR ET_MUSE_DFLASH_TINY_DIR=DIR ctest -R muse_glimmer_cuda_dflash +For the sequence-layout continuation case, also export a second fixture: + + python examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py --output-dir SEQ_DIR --kv-layout sequence + ET_MUSE_DFLASH_TINY_DIR=DIR ET_MUSE_DFLASH_SEQUENCE_TINY_DIR=SEQ_DIR ctest -R muse_glimmer_cuda_dflash + +The native suite requires the cell fixture variable for setup, including when +running only the sequence-layout case. + The geometry is the native test's contract: vocabulary 256, two tapped target layers of width 64 (128 hidden columns), DFlash block 16, 32-token steps, and four draft owners.