Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .ci/scripts/muse_glimmer_batching_workload.h
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ class EvidenceExecutor final : public batching::Executor {
bool initialize() override {
return inner_.initialize();
}
void on_idle() override {
inner_.on_idle();
}
std::size_t preferred_batch_tokens() const override {
return inner_.preferred_batch_tokens();
}
Expand Down
6 changes: 6 additions & 0 deletions .ci/scripts/tests/muse_glimmer_batching_workload_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ void rejected(F action) {
class FakeExecutor final : public batching::Executor {
public:
bool succeeds = true;
int idle_calls = 0;
void on_idle() override {
++idle_calls;
}
std::optional<batching::SessionId> open_session() override {
return 1;
}
Expand Down Expand Up @@ -95,6 +99,8 @@ void workload_limits() {
void successful_batch_owners() {
FakeExecutor inner;
ci::EvidenceExecutor executor(inner);
executor.on_idle();
require(inner.idle_calls == 1);
batching::BatchOutput out;
require(executor.execute({{input(1), input(1)}}, out));
require(executor.execute({{input(2)}}, out));
Expand Down
11 changes: 11 additions & 0 deletions .ci/scripts/tests/test_muse_glimmer_batching_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@


class MuseGlimmerBatchingCITest(unittest.TestCase):
def test_runtime_columns_probe_runs_in_cuda_ci(self):
workflow = (ROOT / ".github/workflows/cuda.yml").read_text()
job = workflow.split(" unittest-cuda-muse-glimmer-batching:", 1)[1].split(
" unittest-cuda-quantized-gemm:", 1
)[0]
self.assertIn("-DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON", job)
self.assertIn("muse_glimmer_runtime_kv_probe --parallel", job)
self.assertIn("tests/check_runtime_kv_columns.py", job)
self.assertIn("-DEXECUTORCH_ENABLE_LOGGING=OFF", job)
self.assertIn("cmake --build --preset llm-release-cuda-install", job)

def test_e2e_builds_smoke_before_running_it(self):
script = (SCRIPTS / "test_model_e2e.sh").read_text()
build = script.index("bash .ci/scripts/build_muse_glimmer_batching_smoke.sh")
Expand Down
20 changes: 15 additions & 5 deletions .github/workflows/cuda.yml
Original file line number Diff line number Diff line change
Expand Up @@ -695,13 +695,19 @@ jobs:

# The normal serving binaries and the opt-in correctness tool share
# CudaExecutor; MG preparation tests also run on Linux.
make muse-glimmer-batching-cuda
# Capture qualification uses native counters in the release build.
cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=OFF
cmake --build --preset llm-release-cuda-install
BATCHING_BIN_DIR="${PWD}/cmake-out/examples/models/muse-glimmer-batching"
cmake -S "${PWD}/examples/models/muse-glimmer" -B "${BATCHING_BIN_DIR}" \
-DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON
cmake -S "${PWD}/examples/models/muse-glimmer" --preset muse-glimmer-cuda \
-B "${BATCHING_BIN_DIR}" -DMUSE_GLIMMER_BUILD_BATCHING=ON \
-DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON \
-DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON
bash .ci/scripts/build_muse_glimmer_batching_smoke.sh "${BATCHING_BIN_DIR}"
cmake --build "${BATCHING_BIN_DIR}" \
--target muse_glimmer_batching_test muse_glimmer_cuda_dflash_test --parallel
--target muse_glimmer_batching_runner muse_glimmer_batching_worker \
muse_glimmer_batching_test muse_glimmer_cuda_dflash_test \
muse_glimmer_runtime_kv_probe --parallel
ctest --test-dir "${BATCHING_BIN_DIR}" \
-R '^muse_glimmer_batching$' --output-on-failure --no-tests=error
test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_runner"
Expand All @@ -710,6 +716,10 @@ jobs:

# The batching export on a tiny model, and the CLI's backend dispatch.
pip install gguf
python examples/models/muse-glimmer/tests/check_runtime_kv_columns.py \
--probe "${BATCHING_BIN_DIR}/muse_glimmer_runtime_kv_probe" \
--output-dir "${RUNNER_TEMP:-/tmp}/muse_glimmer_runtime_kv_columns"

python -m pytest -v -o "addopts=" \
examples/models/muse-glimmer/tests/test_cuda_batching_pipeline.py \
examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py \
Expand Down Expand Up @@ -806,7 +816,7 @@ jobs:
backends/cuda/tests/test_merge_ptes.py \
-v -o "addopts="

cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON
cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON -DEXECUTORCH_ENABLE_LOGGING=OFF
cmake --build cmake-out --target test_cuda_allocator test_cuda_allocator_exit test_cuda_mutable_state test_cuda_weight_cache test_cuda_output_copy test_cuda_backend_execute test_cuda_sort_rand test_cuda_current_stream test_cuda_kv_cache test_cuda_guard test_cuda_stream_guard test_step_plan test_cuda_executor -j$(nproc)
ctest --test-dir cmake-out -R test_cuda_allocator --output-on-failure -V
ctest --test-dir cmake-out -R test_cuda_mutable_state --output-on-failure -V
Expand Down
5 changes: 5 additions & 0 deletions backends/cuda/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,11 @@ if(BUILD_TESTING)
runtime/test/test_cuda_backend_execute.cpp EXTRA_LIBS aoti_cuda_backend
)
target_compile_definitions(test_cuda_backend_execute PRIVATE CUDA_AVAILABLE=1)
if(EXECUTORCH_BUILD_EXTENSION_LLM)
target_compile_definitions(
test_cuda_backend_execute PRIVATE EXECUTORCH_BUILD_EXTENSION_LLM
)
endif()
# sort.cu and rand.cu are compiled only under this condition (see
# _aoti_cuda_shim_sources), so the test that calls them is too.
if(NOT EXECUTORCH_BUILD_ROCM AND CMAKE_CUDA_COMPILER)
Expand Down
94 changes: 70 additions & 24 deletions backends/cuda/batching/cuda_executor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,8 @@ CudaExecutor::CudaExecutor(
std::vector<ForwardMethod> methods,
int min_selected_rows,
bool has_sampler,
bool has_argmax)
bool has_argmax,
bool runtime_columns)
: install_guard_(cache),
module_(std::move(module)),
ctl_(cache->as<llm_cache::BatchControl>()),
Expand All @@ -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),
runtime_columns_(runtime_columns) {}

CudaExecutor::~CudaExecutor() {
if (device_params_ != nullptr) {
Expand Down Expand Up @@ -369,6 +371,15 @@ Result<std::unique_ptr<CudaExecutor>> CudaExecutor::create(
declared_seqs,
metadata::detail::read_int_method(*module, kMaxSeqsMethod));
const bool sequence_layout = declared_seqs.has_value();
ET_ASSIGN_OR_RETURN(
sequence_info_abi,
metadata::detail::read_int_method(*module, kSequenceInfoABIMethod));
ET_CHECK_OR_RETURN_ERROR(
sequence_info_abi.value_or(1) == 1 ||
(sequence_info_abi == 2 && sequence_layout &&
!geometry.dflash_block_size.has_value()),
InvalidProgram,
"CudaExecutor: unsupported sequence-info ABI");
Comment thread
Gasoonjia marked this conversation as resolved.
Resolved
std::int64_t max_cells = 0;
if (sequence_layout) {
ET_CHECK_OR_RETURN_ERROR(
Expand Down Expand Up @@ -537,14 +548,13 @@ Result<std::unique_ptr<CudaExecutor>> CudaExecutor::create(
llm_cache::valid(geometry, cfg),
InvalidProgram,
"CudaExecutor: the program's layout is unusable");
auto built = llm_cache::CacheFactory::global().build(
backend_id,
sequence_layout ? llm_cache::kind::kBatchedSequence
: llm_cache::kind::kBatchedCell,
geometry,
cfg);
ET_CHECK_OK_OR_RETURN_ERROR(built.error());
std::shared_ptr<llm_cache::Cache> cache = built.get();
const char* kind = sequence_info_abi == 2
? llm_cache::kind::kBatchedSequenceRuntime
: sequence_layout ? llm_cache::kind::kBatchedSequence
: llm_cache::kind::kBatchedCell;
ET_ASSIGN_OR_RETURN(
cache,
llm_cache::CacheFactory::global().build(backend_id, kind, geometry, cfg));
auto* const ctl = cache->as<llm_cache::BatchControl>();
ET_CHECK_OR_RETURN_ERROR(
ctl != nullptr && cache->as<CudaKVCache>() != nullptr,
Expand Down Expand Up @@ -588,7 +598,8 @@ Result<std::unique_ptr<CudaExecutor>> CudaExecutor::create(
std::move(methods),
min_selected_rows,
has_sampler,
has_argmax));
has_argmax,
sequence_info_abi == 2));
executor->embeddings_method_ = embeddings_method;
return executor;
}
Expand Down Expand Up @@ -640,14 +651,17 @@ bool CudaExecutor::initialize() {
}

std::optional<SessionId> CudaExecutor::open_session() {
last_cache_activity_ = std::chrono::steady_clock::now();
return sessions_.open();
}

void CudaExecutor::close_session(SessionId session) {
last_cache_activity_ = std::chrono::steady_clock::now();
sessions_.close(session);
}

std::optional<SessionId> CudaExecutor::clone(SessionId source, Position upto) {
last_cache_activity_ = std::chrono::steady_clock::now();
return sessions_.clone(source, upto);
}

Expand Down Expand Up @@ -680,7 +694,7 @@ Error CudaExecutor::set_input_embedder(InputEmbedder embedder) {
bool CudaExecutor::execute_raw(
const RawTargetStep& step,
const std::function<bool(const RawTargetOutput&)>& consume) {
if (!initialized_ || raw_executing_ || !consume ||
if (raw_executing_ || !initialized_ || !consume ||
step.tokens.size() >
static_cast<std::size_t>(std::numeric_limits<int>::max()) ||
step.positions.size() != step.tokens.size() ||
Expand All @@ -699,19 +713,16 @@ bool CudaExecutor::execute_raw(
return false;
}
}
struct Reset {
explicit Reset(bool& target) : flag(target) {
flag = true;
}
Reset(const Reset&) = delete;
Reset& operator=(const Reset&) = delete;
Reset(Reset&&) = delete;
Reset& operator=(Reset&&) = delete;
~Reset() {
flag = false;
last_cache_activity_ = std::chrono::steady_clock::now();
raw_executing_ = true;
struct ExecutionScope {
bool& executing;
std::chrono::steady_clock::time_point& activity;
~ExecutionScope() {
executing = false;
activity = std::chrono::steady_clock::now();
}
bool& flag;
} reset(raw_executing_);
} execution_scope{raw_executing_, last_cache_activity_};
if (step.embeddings) {
return execute_embeddings(step, consume);
}
Expand Down Expand Up @@ -1089,6 +1100,41 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const {
return kv_->metrics();
}

CudaGraphMetrics CudaExecutor::graph_metrics(std::string_view method) const {
return kv_->graph_metrics(method);
}

Error CudaExecutor::compact_kv_columns(int spare_columns) {
ET_CHECK_OR_RETURN_ERROR(
!raw_executing_, InvalidState, "CudaExecutor: compact between executes");
return kv_->compact_columns(spare_columns);
}

void CudaExecutor::on_idle() {
if (!runtime_columns_) {
return;
}
if (raw_executing_ ||
std::chrono::steady_clock::now() - last_cache_activity_ <
std::chrono::milliseconds(500)) {
return;
}
const auto metrics = kv_->metrics();
if (metrics.physical_columns <= 2 ||
2 * metrics.live_sequences + 1 >= metrics.physical_columns) {
return;
}
last_cache_activity_ = std::chrono::steady_clock::now();
const Error error =
kv_->compact_columns(static_cast<int>(metrics.live_sequences));
if (error != Error::Ok) {
ET_LOG(
Error,
"CudaExecutor: idle KV compaction failed (%d)",
static_cast<int>(error));
}
}

std::vector<ForwardMethodCalls> CudaExecutor::method_calls() const {
std::vector<ForwardMethodCalls> calls;
calls.reserve(methods_.size() + 1);
Expand Down
23 changes: 21 additions & 2 deletions backends/cuda/batching/cuda_executor.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@
// and optionally one dynamic `forward_others` for anything wider. Each forward
// runs the method with the smallest width that holds it; a static method's
// extra rows are padding.
// All execution, session and maintenance calls are confined to the engine
// thread, matching Executor. execute_raw rejects re-entrant execution.

#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include <executorch/backends/cuda/batching/step_plan.h>
Expand Down Expand Up @@ -51,6 +55,10 @@ inline constexpr char kMaxCellsMethod[] = "get_offgraph_kv_max_cells";
// Published instead of the cell count by a program whose KV cache keeps a
// private history per sequence.
inline constexpr char kMaxSeqsMethod[] = "get_offgraph_kv_max_seqs";
// Optional: seq_info field layout. Defaults to ABI 1 (fixed columns).
inline constexpr char kSequenceInfoABIMethod[] =
"get_offgraph_kv_sequence_info_abi";

// Optional: the fewest selected rows forward_others was exported for. Its
// selector is padded up to it. Defaults to 1.
inline constexpr char kMinSelectedRowsMethod[] = "get_min_prefill_chunk";
Expand Down Expand Up @@ -227,6 +235,13 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor {

// The cache's pool usage, for memory reporting.
OffGraphKVMetrics kv_metrics() const;
// Read between executes, on the engine thread.
CudaGraphMetrics graph_metrics(std::string_view method) const;
// Engine-thread only, between execute calls. A call from execute_raw's
// consumer is rejected. The scratch column is additional to spare_columns
// unused owner columns; compaction never increases the physical width.
::executorch::runtime::Error compact_kv_columns(int spare_columns = 1);
void on_idle() override;

// Every method, narrowest first, with how many forwards it ran. Read it
// between executes, not while one runs.
Expand All @@ -252,7 +267,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor {
std::vector<ForwardMethod> methods,
int min_selected_rows,
bool has_sampler,
bool has_argmax);
bool has_argmax,
bool runtime_columns);

// Draws one token per row of `logits`, rows [0, sessions.size()), on the
// device; returns them in row order.
Expand All @@ -273,7 +289,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_;
Expand All @@ -293,6 +309,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor {
llm_batching::util::SessionTable sessions_;
bool has_sampler_;
bool has_argmax_;
const bool runtime_columns_;
// Device staging for the sampler's params, grown to the widest row count.
void* device_params_ = nullptr;
std::size_t device_params_rows_ = 0;
Expand All @@ -301,6 +318,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor {
std::optional<bool> device_logits_;
bool initialized_ = false;
bool raw_executing_ = false;
std::chrono::steady_clock::time_point last_cache_activity_ =
std::chrono::steady_clock::now();
};

} // namespace executorch::backends::cuda::batching
Loading
Loading