Skip to content
Open
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
43 changes: 43 additions & 0 deletions .ci/scripts/tests/test_muse_glimmer_batching_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import re
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

Expand All @@ -23,6 +25,47 @@


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("make muse-glimmer-batching-cuda", job)

@unittest.skipIf(sys.platform == "win32", "Linux workflow requires POSIX make")
def test_documented_make_target_uses_the_cpu_count(self):
result = subprocess.run(
["make", "-n", "muse-glimmer-batching-cuda"],
cwd=ROOT,
capture_output=True,
text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('--parallel "$(nproc)"', result.stdout)
self.assertNotIn('--parallel ""', result.stdout)

@unittest.skipIf(sys.platform == "win32", "Linux workflow requires POSIX paths")
def test_cache_ci_guard_rejects_skipped_cases(self):
workflow = (ROOT / ".github/workflows/cuda.yml").read_text()
marker = ' if grep -q "SKIPPED" /tmp/test_cuda_kv_cache.log; then'
body = workflow.split(marker, 1)[1].split(" fi", 1)[0]
guard = marker.strip() + body + "fi"
with tempfile.TemporaryDirectory() as directory:
log = Path(directory) / "native.log"
guard = guard.replace("/tmp/test_cuda_kv_cache.log", str(log))
for output, expected in (
("[ PASSED ] 77 tests", 0),
("[ SKIPPED ] case", 1),
):
log.write_text(output)
result = subprocess.run(
["bash", "-c", guard], capture_output=True, text=True
)
self.assertEqual(result.returncode, expected, result.stderr)

def test_e2e_builds_smoke_before_running_it(self):
script = (SCRIPTS / "test_model_e2e.sh").read_text()
build = script.index("bash .ci/scripts/build_muse_glimmer_batching_smoke.sh")
Expand Down
21 changes: 17 additions & 4 deletions .github/workflows/cuda.yml
Original file line number Diff line number Diff line change
Expand Up @@ -697,11 +697,15 @@ jobs:
# CudaExecutor; MG preparation tests also run on Linux.
make muse-glimmer-batching-cuda
BATCHING_BIN_DIR="${PWD}/cmake-out/examples/models/muse-glimmer-batching"
cmake -S "${PWD}/examples/models/muse-glimmer" -B "${BATCHING_BIN_DIR}" \
-DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON
cmake -S "${PWD}/examples/models/muse-glimmer" \
-B "${BATCHING_BIN_DIR}" -DMUSE_GLIMMER_BUILD_BATCHING=ON \
-DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON \
-DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON
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 +714,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 @@ -815,7 +823,12 @@ jobs:
ctest --test-dir cmake-out -R test_cuda_backend_execute --output-on-failure -V
ctest --test-dir cmake-out -R test_cuda_sort_rand --output-on-failure -V
ctest --test-dir cmake-out -R test_cuda_current_stream --output-on-failure -V
ctest --test-dir cmake-out -R test_cuda_kv_cache --output-on-failure -V
ctest --test-dir cmake-out -R '^test_cuda_kv_cache$' --output-on-failure --no-tests=error -V > /tmp/test_cuda_kv_cache.log 2>&1 || { cat /tmp/test_cuda_kv_cache.log; exit 1; }
cat /tmp/test_cuda_kv_cache.log
if grep -q "SKIPPED" /tmp/test_cuda_kv_cache.log; then
echo "::error::test_cuda_kv_cache skipped"
exit 1
fi
ctest --test-dir cmake-out -R test_step_plan --output-on-failure -V
# CudaExecutor end to end on a toy decoder, against its eager greedy
# output. The test skips without the model, so fail if it skipped.
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ muse-glimmer-batching-cuda:
-DMUSE_GLIMMER_BUILD_BATCHING_TESTS=OFF
cmake --build "$(CURDIR)/cmake-out/examples/models/muse-glimmer-batching" \
--target muse_glimmer_batching_runner muse_glimmer_batching_worker \
--parallel "$(nproc)"
--parallel "$$(nproc)"
@echo ""
@echo "Build complete!"
@echo " Runner: $(CURDIR)/cmake-out/examples/models/muse-glimmer-batching/muse_glimmer_batching_runner"
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
4 changes: 4 additions & 0 deletions backends/cuda/batching/cuda_executor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,10 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const {
return kv_->metrics();
}

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

std::vector<ForwardMethodCalls> CudaExecutor::method_calls() const {
std::vector<ForwardMethodCalls> calls;
calls.reserve(methods_.size() + 1);
Expand Down
4 changes: 3 additions & 1 deletion backends/cuda/batching/cuda_executor.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include <executorch/backends/cuda/batching/step_plan.h>
Expand Down Expand Up @@ -227,7 +228,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor {

// The cache's pool usage, for memory reporting.
OffGraphKVMetrics kv_metrics() const;

// Sequence-layout counters; read between executes, on the engine thread.
CudaGraphMetrics graph_metrics(std::string_view method) const;
// Every method, narrowest first, with how many forwards it ran. Read it
// between executes, not while one runs.
std::vector<ForwardMethodCalls> method_calls() const;
Expand Down
24 changes: 20 additions & 4 deletions backends/cuda/passes/lower_offgraph_kv.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from torch.export.graph_signature import InputKind
from torch.fx.experimental.proxy_tensor import make_fx


OFFGRAPH_KV_COMPILE_SPEC = "offgraph_kv_manifest"
# Consumed by the runtime, not by this pass: "input_index:dim" naming
# the input whose extent is the number of tokens a step writes.
Expand Down Expand Up @@ -147,6 +146,16 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901
return manifest


def offgraph_kv_constant_methods(value: bytes) -> dict[str, int]:
"""Runtime sequence metadata derived from the lowering manifest."""
manifest = parse_offgraph_kv_manifest(value)
if manifest["layout"] != "batched-sequence":
return {}
return {
"get_offgraph_kv_max_seqs": manifest["max_seqs"],
}


def ring_attention_mask(
position: torch.Tensor, buf_size: int, window: int
) -> torch.Tensor:
Expand Down Expand Up @@ -310,7 +319,8 @@ def batched_sequence_step(
"""Write this step's K/V into each sequence's column, then attend.

The storage is declared ``[1, rows * columns, H, D]``: row ``r`` of
column ``c`` is slot ``r * columns + c``, so it is ``[rows, columns, H, D]``
column ``c`` is slot ``r * pitch + c``, where ``pitch`` comes from
``seq_info[0, 4]``. It is ``[rows, pitch, H, D]``
and grows by whole rows, as the sequence layout's does. Token ``i`` lands
in column ``seq_cols[i]`` at row ``position % rows`` (a ring layer's rows
wrap; a flat layer's never do). ``seq_info`` names each segment's query
Expand All @@ -321,9 +331,12 @@ def batched_sequence_step(
``context_window`` gives every draft block query the same retained context
before the block; ``symmetric_window`` uses strict per-query distance as in
DFlash. Ordinary attention uses each query's own past-window bound.
Five-field ``seq_info`` supplies the physical pitch for writes and attention;
``columns`` remains the declared maximum.
"""
position = position.reshape(-1)
slots = (position % rows) * columns + seq_cols[: k.shape[2]]
pitch = seq_info[0, 4].to(torch.int64)
slots = (position % rows) * pitch + seq_cols[: k.shape[2]]
_write(k_storage, slots, k)
_write(v_storage, slots, v)
heads, dim = k_storage.shape[2], k_storage.shape[3]
Expand Down Expand Up @@ -750,7 +763,10 @@ def _lower_batched_sequence(
seq_info = self._cell_buffer(
exported_program,
OFFGRAPH_KV_SEQ_INFO_FQN,
(self._manifest["max_segments"], 4),
(
self._manifest["max_segments"],
5,
),
torch.int32,
device,
)
Expand Down
28 changes: 26 additions & 2 deletions backends/cuda/runtime/cuda_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,16 @@ class ET_EXPERIMENTAL CudaBackend final
// the step is driven from here rather than by the runner.
int64_t kv_step_width = 0;
#if defined(EXECUTORCH_BUILD_EXTENSION_LLM)
bool kv_prepared = false;
executorch::backends::aoti::ScopeGuard abort_kv_step([&]() noexcept {
if (kv_prepared) {
const Error error = handle->kv_cache->abort_step();
ET_CHECK_OR_LOG_ERROR(
error == Error::Ok,
"offgraph_kv: failed to abort prepared forward");
(void)error;
}
});
if (handle->kv_cache != nullptr) {
const auto step_width = read_offgraph_kv_step_width(
handle->kv_step_width, Span<EValue*>(args.data(), n_inputs));
Expand All @@ -802,10 +812,20 @@ class ET_EXPERIMENTAL CudaBackend final
ET_CHECK_OK_OR_RETURN_ERROR(step_stream.error());
ET_CHECK_OK_OR_RETURN_ERROR(
handle->kv_cache->prepare_step(kv_step_width, step_stream.get()));
kv_prepared = true;
ET_CHECK_OK_OR_RETURN_ERROR(handle->kv_cache->rebind_for_execute(handle));
}
#endif
ET_CHECK_OK_OR_RETURN_ERROR(mutable_state_rebind_for_execute(handle));
const auto commit_kv_step = [&]() {
const Error error = commit_offgraph_kv_step(handle, kv_step_width);
#if defined(EXECUTORCH_BUILD_EXTENSION_LLM)
if (error == Error::Ok) {
kv_prepared = false;
}
#endif
return error;
};

// ---------------------------------------------------------------
// CUDA graph REPLAY path — skip all tensor setup and just replay
Expand Down Expand Up @@ -854,6 +874,7 @@ class ET_EXPERIMENTAL CudaBackend final
Internal,
"cudaGraphLaunch failed: %s",
cudaGetErrorString(gerr));
++handle->cuda_graph_state.metrics.replays;

// Copy outputs from static buffers into the planned GPU ET buffers (D2D)
for (size_t i = 0; i < n_outputs; i++) {
Expand All @@ -867,7 +888,7 @@ class ET_EXPERIMENTAL CudaBackend final
}
ET_CUDA_CHECK_OR_RETURN_ERROR(cudaStreamSynchronize(cs));

return commit_offgraph_kv_step(handle, kv_step_width);
return commit_kv_step();
}

const bool is_capture_step =
Expand All @@ -877,6 +898,7 @@ class ET_EXPERIMENTAL CudaBackend final
Error error = run_once(
handle, args, n_inputs, n_outputs, is_capture_step, graph_launched);
if (error != Error::Ok && is_capture_step && !graph_launched) {
++handle->cuda_graph_state.metrics.capture_failures;
// A capture records kernels without running them, so until the new graph
// runs, the inputs and any state the program updates are untouched. A
// program that keeps state in host memory, where host code does run
Expand All @@ -897,7 +919,7 @@ class ET_EXPERIMENTAL CudaBackend final
graph_launched);
}
ET_CHECK_OK_OR_RETURN_ERROR(error);
return commit_offgraph_kv_step(handle, kv_step_width);
return commit_kv_step();
}

void destroy(DelegateHandle* handle_) const override {
Expand Down Expand Up @@ -1298,6 +1320,7 @@ class ET_EXPERIMENTAL CudaBackend final
}

handle->cuda_graph_state.phase = CudaGraphPhase::Replay;
++handle->cuda_graph_state.metrics.captures;
ET_LOG(
Info,
"CUDA graph: captured and instantiated for '%s'",
Expand All @@ -1310,6 +1333,7 @@ class ET_EXPERIMENTAL CudaBackend final
Internal,
"cudaGraphLaunch (first replay) failed: %s",
cudaGetErrorString(gerr));
++handle->cuda_graph_state.metrics.replays;
graph_launched = true;
handle->cuda_graph_state.note_graph_allocations();

Expand Down
12 changes: 12 additions & 0 deletions backends/cuda/runtime/cuda_delegate_handle.h
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,18 @@ enum class CudaGraphPhase {
Replay = 2,
};

struct CudaGraphMetrics {
uint64_t captures{0};
uint64_t replays{0};
uint64_t capture_failures{0};
};

// All CUDA graph related state grouped into a single struct.
struct CudaGraphState {
CudaGraphPhase phase = CudaGraphPhase::Disabled;
int warmup_remaining = 0;
// Lifetime counts survive release/recapture; read between executions.
CudaGraphMetrics metrics;

// Captured graph and executable instance
cudaGraph_t graph = nullptr;
Expand Down Expand Up @@ -259,6 +267,7 @@ struct CudaGraphState {
CudaGraphState(CudaGraphState&& other) noexcept
: phase(other.phase),
warmup_remaining(other.warmup_remaining),
metrics(other.metrics),
graph(other.graph),
graph_exec(other.graph_exec),
static_input_ptrs(std::move(other.static_input_ptrs)),
Expand All @@ -269,6 +278,7 @@ struct CudaGraphState {
graph_allocations(std::move(other.graph_allocations)) {
other.graph = nullptr;
other.graph_exec = nullptr;
other.metrics = {};
}

CudaGraphState& operator=(CudaGraphState&& other) noexcept {
Expand All @@ -277,6 +287,7 @@ struct CudaGraphState {

phase = other.phase;
warmup_remaining = other.warmup_remaining;
metrics = other.metrics;
graph = other.graph;
graph_exec = other.graph_exec;
static_input_ptrs = std::move(other.static_input_ptrs);
Expand All @@ -288,6 +299,7 @@ struct CudaGraphState {

other.graph = nullptr;
other.graph_exec = nullptr;
other.metrics = {};
}
return *this;
}
Expand Down
Loading
Loading