Skip to content
Draft
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
6 changes: 4 additions & 2 deletions .github/workflows/cuda.yml
Original file line number Diff line number Diff line change
Expand Up @@ -702,9 +702,11 @@ jobs:
-DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON
bash .ci/scripts/build_muse_glimmer_batching_smoke.sh "${BATCHING_BIN_DIR}"
cmake --build "${BATCHING_BIN_DIR}" \
--target muse_glimmer_batching_test muse_glimmer_cuda_dflash_test --parallel
--target muse_glimmer_batching_test muse_glimmer_cuda_dflash_test \
muse_glimmer_dflash2_pairtree_test muse_glimmer_dflash_mode_test --parallel
ctest --test-dir "${BATCHING_BIN_DIR}" \
-R '^muse_glimmer_batching$' --output-on-failure --no-tests=error
-R '^muse_glimmer_(batching|dflash2_pairtree|dflash_mode)$' \
--output-on-failure --no-tests=error
test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_runner"
test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_worker"
test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_smoke"
Expand Down
38 changes: 35 additions & 3 deletions backends/cuda/batching/cuda_executor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,26 @@ bool CudaExecutor::execute_raw(
return false;
}
}
const auto slices = plan_slices(total, methods_);
if (!step.parents.empty()) {
if (step.embeddings || step.parents.size() != step.tokens.size() ||
slices.size() != 1) {
ET_LOG(Error, "CudaExecutor: a tree step must fit one token forward");
return false;
}
// RoPE reads step.positions, while the cache derives them from parents.
for (int i = 0; i < total; ++i) {
const auto parent = step.parents[i];
const bool placed = parent < 0
? parent == -1 && step.positions[i] == ctl_->pos(step.seq_ids[i])
: parent < i && step.seq_ids[parent] == step.seq_ids[i] &&
step.positions[i] == step.positions[parent] + 1;
if (!placed) {
ET_LOG(Error, "CudaExecutor: tree positions disagree with its parents");
return false;
}
}
}
struct Reset {
explicit Reset(bool& target) : flag(target) {
flag = true;
Expand All @@ -715,7 +735,7 @@ bool CudaExecutor::execute_raw(
if (step.embeddings) {
return execute_embeddings(step, consume);
}
for (const auto& slice : plan_slices(total, methods_)) {
for (const auto& slice : slices) {
const int off = slice.offset;
const int n = slice.length;
const auto& method = methods_[slice.method];
Expand Down Expand Up @@ -743,8 +763,11 @@ bool CudaExecutor::execute_raw(
? slice.width
: std::max<std::size_t>(selected.size(), min_selected_rows_);
selected.resize(rows, selected.empty() ? 0 : selected.back());
if (!ctl_->declare_step(std::vector<std::int32_t>(
step.seq_ids.begin() + off, step.seq_ids.begin() + off + n))) {
const std::vector<std::int32_t> seq_ids(
step.seq_ids.begin() + off, step.seq_ids.begin() + off + n);
if (!(step.parents.empty()
? ctl_->declare_step(seq_ids)
: ctl_->declare_tree_step(seq_ids, step.parents))) {
return false;
}
std::vector<std::int64_t> token_values(
Expand Down Expand Up @@ -800,6 +823,15 @@ bool CudaExecutor::execute_raw(
return true;
}

int CudaExecutor::widest_static_tokens() const {
for (auto it = methods_.rbegin(); it != methods_.rend(); ++it) {
if (it->is_static) {
return it->max_tokens;
}
}
return 0;
}

std::optional<std::vector<Token>> CudaExecutor::argmax_rows(
const ::executorch::aten::Tensor& logits,
std::size_t rows) {
Expand Down
10 changes: 10 additions & 0 deletions backends/cuda/batching/cuda_executor.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ struct RawTargetStep {
// Global token-row indices; -1 discards a result. Repeats and reordering are
// allowed. Callback selected_indices maps rows back into this vector.
std::vector<std::int64_t> logit_indices;
// When set, the step is a token tree: parents[i] is the step index of token
// i's parent, or -1 for its sequence's root
// (BatchControl::declare_tree_step). positions must agree: a root continues
// its sequence, a child sits one past its parent. A tree must fit one forward
// and cannot take embeddings.
std::vector<std::int32_t> parents;
// Host [1, tokens, hidden] decoder inputs. When set, the step runs through
// kEmbeddingsMethod and `tokens` is not read.
::executorch::extension::TensorPtr embeddings;
Expand Down Expand Up @@ -169,6 +175,10 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor {
std::size_t preferred_batch_tokens() const override {
return static_cast<std::size_t>(methods_.back().max_tokens);
}
// The widest static method's step: the most tokens one forward runs with a
// logit row selected for each of them. A wider dynamic forward_others is not
// counted: its selector is bounded separately.
int widest_static_tokens() const;

// Loads every method here, so the delegate that resolves the cache binds on
// the thread that runs it.
Expand Down
31 changes: 29 additions & 2 deletions backends/cuda/runtime/cuda_kv_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache {
}
cache::CellCache::clear();
step_seq_ids_.clear();
step_parents_.clear();
active_owners_.clear();
pending_width_ = 0;
poisoned_ = false;
Expand All @@ -364,9 +365,27 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache {
return false;
}
step_seq_ids_ = seq_ids;
step_parents_.clear();
return true;
}

bool declare_tree_step(
const std::vector<int32_t>& seq_ids,
const std::vector<int32_t>& parents) override {
std::lock_guard<std::recursive_mutex> guard(mutex_);
if (poisoned_ || !cache::CellCache::declare_tree_step(seq_ids, parents)) {
return false;
}
step_seq_ids_ = seq_ids;
step_parents_ = parents;
return true;
}

bool retain_tree(const std::vector<int32_t>& keep) override {
std::lock_guard<std::recursive_mutex> guard(mutex_);
return cache::CellCache::retain_tree(keep);
}

std::optional<int32_t> seq_new() override {
std::lock_guard<std::recursive_mutex> guard(mutex_);
return cache::CellCache::seq_new();
Expand Down Expand Up @@ -468,12 +487,18 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache {
width,
tokens);

// Every declared token continues its sequence, so the positions follow
// from the declaration; nothing is read back from the device.
// Every declared token continues its sequence, or in a tree step sits one
// past its parent, so the positions follow from the declaration; nothing
// is read back from the device.
positions_.resize(tokens);
std::vector<int32_t> next(kMaxSeqs, -1);
for (int i = 0; i < tokens; ++i) {
const int32_t seq_id = step_seq_ids_[i];
if (!step_parents_.empty()) {
positions_[i] = step_parents_[i] < 0 ? cache::CellCache::pos(seq_id)
: positions_[step_parents_[i]] + 1;
continue;
}
if (next[seq_id] < 0) {
next[seq_id] = cache::CellCache::pos(seq_id);
}
Expand Down Expand Up @@ -521,6 +546,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache {
return uploaded;
}
step_seq_ids_.clear();
step_parents_.clear();
return Error::Ok;
}

Expand Down Expand Up @@ -786,6 +812,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache {
std::vector<int> window_layers_;
CudaKVPool pool_;
std::vector<int32_t> step_seq_ids_;
std::vector<int32_t> step_parents_;
std::vector<int32_t> positions_;
std::vector<int32_t> active_owners_;
int pending_width_{0};
Expand Down
74 changes: 74 additions & 0 deletions examples/models/muse-glimmer/BATCHING_SERVING.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,77 @@ that shortlist. Re-export earlier CUDA DFlash2 artifacts to use this ordering.
If the selected DFlash2 score row contains a NaN or infinity, both backends
fail the requests in that execution batch. Other sessions can continue.

### PairTree DFlash2 on CUDA

Serial DFlash2 verifies one chain of N proposals per session. PairTree DFlash2
verifies a bounded tree per greedy session instead: from the same DFlash2
draft call, it keeps the B most likely proposal prefixes, at most N deep, and
the target checks every node in one forward with each node attending only its
own ancestors. The session commits the longest prefix the target's own greedy
tokens follow, plus the target's next token, so the output is the target's
greedy continuation, as with Serial DFlash2. The tree follows the PairTree
reference builder (`dflash2_pairwise_k16`): prefixes are ranked by the retained
unary candidate mass plus the selector's pairwise log-softmax.

Export with `--dflash2-pairtree` to use it. The program then has a second
draft method, `draft_forward_pairtree`, which returns what `draft_forward`
returns plus what PairTree reads: the candidates' unary logits and the
full-vocabulary logsumexp. `draft_forward` itself is the same program as
without the flag, and both methods share the draft's weights, which the
`.ptd` stores once. A round's trees must fit one static target forward,
capped at 256 rows: for every session of a full round to get B nodes, add a
forward size of at least `--max-draft-owners` x (B + 1) tokens. A static
forward returns FP32 logits for every row (256 x the 202,048-token vocabulary
x 4 bytes is about 200 MB) and each added size captures its own CUDA graph, so
add only the sizes you need:

```sh
python -m executorch.examples.models.muse_glimmer.export.export_dflash \
--backend cuda --use-offgraph-kv-cache --activation-dtype bfloat16 \
--target-gguf /path/to/Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf \
--draft-gguf /path/to/Muse-Glimmer-30B-DFlash2-Q4_K_M.gguf \
--forward-sizes 1,2,4,8,16,32,64 --dflash2-pairtree \
--output-dir /path/to/muse-dflash2-pairtree
```

A worker started with `--dflash` on such a program runs PairTree DFlash2 with
a default budget per session and round: B = 31 when it decodes one sequence
at a time (`--max_decode_sequences 1` or `--max_sessions 1`) and B = 15
otherwise. A CUDA round holds at most four sessions (`--max-draft-owners`),
and four trees of 15 nodes verify the 64 rows Serial DFlash2 with 15
proposals does; wider verifies, such as 128 rows at B = 31, cost much more per
row on the 30B export. The default never exceeds the widest static forward.
`--dflash_tree_budget B` (the Python launcher: `--dflash-tree-budget B`) sets
the budget instead, and 0 runs Serial DFlash2; startup fails when B + 1
exceeds the widest static target forward, the program lacks
`draft_forward_pairtree`, or the target uses the sequence KV layout. Rounds
with several sessions share that forward: each session's tree gets at most
`widest / sessions - 1` nodes. `--dflash-n-draft` still sets the depth. The
worker prints the mode, the budget and why to stderr once at startup, and a
refusal's reason with its error; `CudaDFlashStats::tree_budget` reports the
budget too (0 for Serial DFlash2).

To keep Serial DFlash2 on a `--dflash2-pairtree` program, pass
`--dflash_serial_only` (launcher: `--dflash-serial-only`) or a zero tree
budget; the launcher leaves the budget unset unless given. Either way the
worker never loads `draft_forward_pairtree` and runs the same methods, rounds
and KV-cache steps as on the program exported without the flag. Its tokens
are bit-identical to that program's when both were exported with the same
kernel picks, since the export times kernel variants on the device (see
`tests/README.md`). `--dflash_serial_only` refuses a nonzero tree budget. A
program without `draft_forward_pairtree` always runs Serial DFlash2, and only
an explicit nonzero budget makes it fail.

Sampled sessions (temperature > 0) keep Serial DFlash2: each batch drafts its
greedy sessions in tree rounds first and its sampled sessions after them,
with `draft_forward`; the worker logs this once. If the tree builder refuses
one session's candidate table (a non-finite value, for example), that whole
round runs Serial DFlash2, which reports a non-finite selected row as it
always does. `CudaDFlashStats` counts tree cycles (`tree_cycles`) and the
cycles that fell back (`tree_fallback_cycles`, every session of such a
round); for a tree, `proposed` counts its nodes and a bonus is an accepted
path that ends at a leaf.

## Build

On Apple Silicon, run the Make target from the ExecuTorch checkout:
Expand Down Expand Up @@ -422,6 +493,9 @@ and `--max-draft-owners`), then add `--dflash` to the serve command above. The
CUDA verifier accepts 2 to D - 1 proposals for a trained block of size D.
Original DFlash can run static decode drafts in CUDA graphs. DFlash2 uses the
dynamic draft method so the output projection can select the requested prefix.
A program exported with `--dflash2-pairtree` and wide enough `--forward-sizes`
runs PairTree DFlash2 unless `--dflash-serial-only` is given; see
[PairTree DFlash2 on CUDA](#pairtree-dflash2-on-cuda).

ATEM tool intent must start a line outside Markdown code or immediately follow a
tool recipient header. User-directed examples and quoted markers remain content.
Expand Down
43 changes: 36 additions & 7 deletions examples/models/muse-glimmer/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,42 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS)
extension_llm_serving Threads::Threads
)
add_test(NAME muse_glimmer_batching COMMAND muse_glimmer_batching_test)
# Tokenizer include paths contain regex.h; keep GoogleTest and its users on
# the same simple-regex ABI instead of the shadowed POSIX header. Only the
# tests below build it.
add_subdirectory(
${EXECUTORCH_ROOT}/third-party/googletest
${CMAKE_CURRENT_BINARY_DIR}/dflash_googletest EXCLUDE_FROM_ALL
)
target_compile_definitions(gtest PUBLIC GTEST_HAS_POSIX_RE=0)
add_executable(
muse_glimmer_dflash2_pairtree_test tests/dflash2_pairtree_test.cpp
)
target_include_directories(
muse_glimmer_dflash2_pairtree_test PRIVATE ${_common_include_directories}
)
target_link_libraries(
muse_glimmer_dflash2_pairtree_test PRIVATE GTest::gtest_main
)
add_test(NAME muse_glimmer_dflash2_pairtree
COMMAND muse_glimmer_dflash2_pairtree_test
)
set_tests_properties(
muse_glimmer_dflash2_pairtree
PROPERTIES
ENVIRONMENT
"MUSE_GLIMMER_PAIRTREE_FIXTURE=${CMAKE_CURRENT_SOURCE_DIR}/tests/data/pairtree_reference.bin"
)
add_executable(muse_glimmer_dflash_mode_test tests/dflash_mode_test.cpp)
target_include_directories(
muse_glimmer_dflash_mode_test PRIVATE ${_common_include_directories}
)
target_link_libraries(
muse_glimmer_dflash_mode_test PRIVATE GTest::gtest_main
)
add_test(NAME muse_glimmer_dflash_mode
COMMAND muse_glimmer_dflash_mode_test
)
if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "mlx")
add_executable(
muse_glimmer_mlx_dflash_test tests/mlx_dflash_native_test.cpp
Expand All @@ -377,13 +413,6 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS)
endif()
endif()
if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "cuda")
# Tokenizer include paths contain regex.h; keep GoogleTest and its users
# on the same simple-regex ABI instead of the shadowed POSIX header.
add_subdirectory(
${EXECUTORCH_ROOT}/third-party/googletest
${CMAKE_CURRENT_BINARY_DIR}/dflash_googletest EXCLUDE_FROM_ALL
)
target_compile_definitions(gtest PUBLIC GTEST_HAS_POSIX_RE=0)
add_executable(
muse_glimmer_cuda_dflash_test tests/cuda_dflash_executor_test.cpp
tests/cuda_dflash_native_test.cpp
Expand Down
9 changes: 9 additions & 0 deletions examples/models/muse-glimmer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,15 @@ The CUDA batching verifier accepts 2 to D - 1 proposals. Draft proposals are
greedy on both batching backends. Per-request temperature, top-p, and top-k
apply to target sampling.

On CUDA, a DFlash2 export with `--dflash2-pairtree` runs greedy sessions with
PairTree DFlash2, which verifies a tree of up to B proposals per session in one
target forward: B = 31 for one decode sequence and 15 otherwise, or
`--dflash-tree-budget B`. Full rounds need a static forward size of at least
`--max-draft-owners` x (B + 1). Sampled sessions keep Serial DFlash2;
`--dflash-serial-only` or `--dflash-tree-budget 0` runs the export with Serial
DFlash2's methods and steps. See
[PairTree DFlash2](BATCHING_SERVING.md#pairtree-dflash2-on-cuda).

Choose concurrency and prefix-cache limits to fit available memory. Prefix
snapshots are disabled by default; omit `--prefix-cache-entries` to disable them.
If the export stores weights separately, also pass `--data-path` with its data
Expand Down
Loading