From 4eb93db4da129f282ae69df70909ffdfc726b02c Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Thu, 3 Dec 2026 10:14:33 -0800 Subject: [PATCH 1/3] [CUDA] Support PairTree DFlash2 for Muse Glimmer In PairTree DFlash2 mode, the CUDA DFlash executor verifies greedy sessions' DFlash2 candidates as one PairTree per session instead of one chain. Their rounds draft with draft_forward_pairtree, which the executor loads only in that mode; its candidate table comes back to the host, the trees of every session in the round run in one target forward, and each session commits the longest path its target's greedy tokens follow plus the next token, keeping that path's KV and hidden rows. The output is the target's greedy continuation, as with Serial DFlash2. In Serial DFlash2 mode, chosen by --dflash_serial_only, a zero budget or a program without the method, the executor neither loads nor runs that method. A round's trees share the widest static target forward, at most 256 rows: each of S sessions gets at most widest / S - 1 nodes and its context's room. Before it resolves the mode, the executor checks what the program offers: draft_forward_pairtree with draft_forward's inputs and outputs plus the candidate logits, tree steps on the target cache, and the row argmax method; a method that does not match counts as missing, so the default falls back to Serial DFlash2 and an explicit budget is refused. The executor returns the mode and why, or the resolver's refusal, as the factory's note, and reports the budget in CudaDFlashStats. Sampled sessions share the rounds: a round with a greedy session drafts all of its sessions in one draft_forward_pairtree call and verifies them in one target forward, each sampled session as the unbranched chain Serial DFlash2 would verify, with its full rows, accepted by Serial DFlash2's rule at the same positional draws and committed as that chain; greedy sessions share the rows the chains leave. A round of sampled sessions only runs Serial DFlash2 with draft_forward. A round in which the builder refuses a table runs Serial DFlash2 as a whole. CudaDFlashStats counts greedy tree and fallback cycles. The CUDA CI job also builds and runs the CPU-only PairTree builder and mode-resolution tests. The tiny test fixtures keep their shapes; the PairTree fixtures are exported in a wider one (static forwards of 1, 4 and 32 tokens, 40-token steps, 1024 cells), each with a plain twin in the same process, so each pair shares its kernel picks; the exporter fails unless every common method is the same compiled library. Serial-only and a zero budget on a PairTree export must be bit-identical to Serial DFlash2 on its twin, on a random and a controlled pair, at 1, 4 and 16 sessions with sampled sessions, a second turn, a rewind and a replaced session: the same tokens, both caches' cells, frontiers and committed hidden rows after every execution, the same stats and target forwards, and the PairTree method never loaded; PairTree mode on the same script must differ. The compiled draft_forward_pairtree must return draft_forward's ids and scores bit for bit. On a PairTree export of the controlled fixture whose tables the builder refuses, every round must fall back to Serial DFlash2 with its tokens and no failed batch, and a NaN row must fail only its batch. Mixed batches of 2, 4 and 16 sessions must take one draft call and one target forward per round, decode greedy sessions as the target does, and emit serial-only's sampled tokens; four-owner exports cover rounds with several sampled chains in several orders and short trees. Packed greedy PairTree sessions decode as Serial DFlash2 and target-only decoding do, up to the random fixture's near-ties, and on the controlled fixture trees accept tokens Serial DFlash2 rejects. Hand-built trees check the committed path tokens, hidden rows and cells with the argmax split over several calls; other cases cover the default budgets and startup notes, one session per round near the context limit, a shared 8-row forward, and refused artifacts and budgets. One target tree step matches each node's path run alone and continues its retained path like the linear sequence; with siblings visible through the cell cache's test hook, that comparison fails. Authored with AI assistance (Claude, via Metamate). --- .github/workflows/cuda.yml | 6 +- examples/models/muse-glimmer/runtime/BUCK | 2 + .../muse-glimmer/runtime/backend_factory.cpp | 2 +- .../runtime/cuda_dflash_executor.cpp | 474 +++++- .../runtime/cuda_dflash_executor.h | 52 +- examples/models/muse-glimmer/tests/BUCK | 1 + examples/models/muse-glimmer/tests/README.md | 79 + .../tests/cuda_dflash_native_test.cpp | 1298 ++++++++++++++++- .../tests/export_cuda_dflash_tiny.py | 192 ++- 9 files changed, 2063 insertions(+), 43 deletions(-) diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 99f838fcb3a..0778fc6b13f 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -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" diff --git a/examples/models/muse-glimmer/runtime/BUCK b/examples/models/muse-glimmer/runtime/BUCK index 27809063b5c..523c846cba6 100644 --- a/examples/models/muse-glimmer/runtime/BUCK +++ b/examples/models/muse-glimmer/runtime/BUCK @@ -25,6 +25,8 @@ fbcode_target( "//executorch/runtime/backend:interface", ], exported_deps = [ + ":dflash2_pairtree", + ":dflash_mode", ":muse_glimmer_batching_preparation", "fbsource//third-party/nlohmann-json:nlohmann-json", "//executorch/backends/cuda/batching:cuda_executor", diff --git a/examples/models/muse-glimmer/runtime/backend_factory.cpp b/examples/models/muse-glimmer/runtime/backend_factory.cpp index da12721f21f..2314eb34890 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.cpp +++ b/examples/models/muse-glimmer/runtime/backend_factory.cpp @@ -54,7 +54,7 @@ runtime::Result create_muse_glimmer_backend( InvalidArgument, "Muse Glimmer CUDA: dflash_n_draft requires DFlash"); if (config.use_dflash) { - return MuseGlimmerCudaDFlashExecutor::create(config); + return MuseGlimmerCudaDFlashExecutor::create(config, note); } cb::CudaExecutorConfig executor_config; executor_config.model_path = config.model_path; diff --git a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp index 2bbebadccf3..c7e705dabae 100644 --- a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp +++ b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp @@ -539,7 +539,8 @@ Result> make_cuda_preparation( } Result MuseGlimmerCudaDFlashExecutor::create( - const MuseGlimmerBackendConfig& config) { + const MuseGlimmerBackendConfig& config, + std::string* note) { ET_CHECK_OR_RETURN_ERROR( config.backend == "cuda" && config.use_dflash && !config.model_path.empty() && config.max_sessions > 0 && @@ -694,6 +695,87 @@ Result MuseGlimmerCudaDFlashExecutor::create( InvalidProgram, "DFlash draft packed tensor ABI mismatch"); } + // PairTree DFlash2 drafts with kDFlash2PairTreeMethod, which takes + // draft_forward's inputs and returns its outputs plus the candidates' + // logits; it verifies a tree's nodes and their roots in one static forward + // on the cell KV layout and picks the target's tokens with the row argmax + // method. A program short of any of it serves Serial DFlash2 only. + const auto same = [](const auto& a, const auto& b) { + return a.ok() && b.ok() && a->scalar_type() == b->scalar_type() && + std::equal( + a->sizes().begin(), + a->sizes().end(), + b->sizes().begin(), + b->sizes().end()); + }; + bool pairtree_method = top_k && names.count(kDFlash2PairTreeMethod); + if (pairtree_method) { + const auto tree = module.method_meta(kDFlash2PairTreeMethod); + pairtree_method = tree.ok() && + tree->num_inputs() == draft_meta.num_inputs() && + tree->num_outputs() == 3; + for (std::size_t i = 0; pairtree_method && i < tree->num_inputs(); ++i) { + pairtree_method = + same(tree->input_tensor_meta(i), draft_meta.input_tensor_meta(i)); + } + for (std::size_t i = 0; pairtree_method && i < 2; ++i) { + pairtree_method = + same(tree->output_tensor_meta(i), draft_meta.output_tensor_meta(i)); + } + if (pairtree_method) { + const auto extras = tree->output_tensor_meta(2); + pairtree_method = extras.ok() && + extras->scalar_type() == aten::ScalarType::Float && + extras->sizes().size() == 3 && extras->sizes()[0] == max_owners && + extras->sizes()[1] == block - 1 && extras->sizes()[2] == top_k + 1; + } + } + std::size_t argmax_rows = 0; + if (names.count(cb::kArgmaxMethod)) { + const auto argmax = module.method_meta(cb::kArgmaxMethod); + const auto logits = argmax.ok() + ? argmax->input_tensor_meta(0) + : Result(argmax.error()); + if (logits.ok() && logits->sizes().size() == 2 && logits->sizes()[0] > 0) { + argmax_rows = static_cast(logits->sizes()[0]); + } + } + const int tree_rows = + std::min(pairtree::kMaxRows, target->widest_static_tokens()); + DFlashTreeCapability capability; + capability.pairtree_method = pairtree_method; + capability.tree_verify = + target->cache_control().supports_tree_steps() && argmax_rows > 0; + capability.max_budget = tree_rows - 1; + const auto mode = resolve_dflash_mode( + {config.dflash_tree_budget, + config.dflash_serial_only, + DFlashBackendKind::kCuda, + config.max_decode_sequences}, + capability); + if (mode.error != Error::Ok) { + const bool too_wide = !config.dflash_serial_only && + capability.pairtree_method && capability.tree_verify && + config.dflash_tree_budget.value_or(0) > capability.max_budget; + const auto refusal = std::string("CUDA DFlash: ") + mode.reason + + (too_wide ? " (a tree verify takes at most " + + std::to_string(tree_rows) + " rows: the root and B nodes)" + : std::string()); + ET_LOG(Error, "%s", refusal.c_str()); + if (note) { + *note = refusal; + } + return mode.error; + } + const int tree_budget = mode.tree_budget; + std::string chosen; + if (top_k) { + chosen = (tree_budget ? "CUDA DFlash: PairTree DFlash2, tree budget " + + std::to_string(tree_budget) + : std::string("CUDA DFlash: Serial DFlash2")) + + " (" + mode.reason + ")"; + ET_LOG(Info, "%s", chosen.c_str()); + } ET_ASSIGN_OR_RETURN(geometry, draft_geometry(module, block)); const int temporary = max_owners * block; // A history column holds its context and, while drafting, its own block. @@ -756,6 +838,16 @@ Result MuseGlimmerCudaDFlashExecutor::create( hidden_width, static_cast(top_k))); executor->embeddings_ = std::move(embeddings); + executor->stats_.tree_budget = tree_budget; + if (tree_budget) { + executor->tree_budget_ = tree_budget; + executor->tree_rows_ = tree_rows; + executor->tree_owners_ = std::min(max_owners, tree_rows / 2); + executor->argmax_rows_ = argmax_rows; + } + if (note) { + *note = std::move(chosen); + } return MuseGlimmerBackend{std::move(executor), std::move(spec)}; } @@ -777,6 +869,12 @@ bool MuseGlimmerCudaDFlashExecutor::initialize() { df::kForward, ::executorch::backends::cuda::kCudaBackendId, draft_install_) != Error::Ok || + (tree_budget_ && + batching::load_method_with_cache( + module, + kDFlash2PairTreeMethod, + ::executorch::backends::cuda::kCudaBackendId, + draft_install_) != Error::Ok) || (selector_top_k_ && module.load_method(df::kDFlash2Sample) != Error::Ok) || module.load_method(df::kVerify) != Error::Ok || @@ -1183,7 +1281,8 @@ MuseGlimmerCudaDFlashExecutor::DraftStatus MuseGlimmerCudaDFlashExecutor::draft( const std::vector& owners, const std::vector& anchors, int context_limit, - std::vector>* proposals) { + std::vector>* proposals, + TreeRound* tree) { if (owners.size() != anchors.size() || owners.empty() || owners.size() > static_cast(max_owners_)) { return DraftStatus::Failed; @@ -1218,10 +1317,10 @@ MuseGlimmerCudaDFlashExecutor::DraftStatus MuseGlimmerCudaDFlashExecutor::draft( const int c = static_cast(plan->hidden.size() / row_bytes_); // Original DFlash has a captured method for decode contexts that fit one // block per owner. - const bool use_static = proposals && static_drafts_[owners.size()] && + const bool use_static = !tree && proposals && static_drafts_[owners.size()] && std::all_of(plan->counts.begin(), plan->counts.end(), [this](int n) { - return n <= block_; - }); + return n <= block_; + }); if (use_static && !df::pad_to_static( *plan, static_cast(owners.size()), block_, row_bytes_)) { @@ -1241,7 +1340,7 @@ MuseGlimmerCudaDFlashExecutor::DraftStatus MuseGlimmerCudaDFlashExecutor::draft( auto order = make_tensor_ptr({kv_rows}, std::move(plan->kv_order)); const std::string method = use_static ? df::kStaticForwardPrefix + std::to_string(owners.size()) - : std::string(df::kForward); + : std::string(tree ? kDFlash2PairTreeMethod : df::kForward); std::vector inputs{*tokens, *hidden, *positions, *order}; const int steps = proposals ? proposals_ : 1; ::executorch::extension::TensorPtr selector; @@ -1250,7 +1349,8 @@ MuseGlimmerCudaDFlashExecutor::DraftStatus MuseGlimmerCudaDFlashExecutor::draft( inputs.emplace_back(*selector); } auto result = target_->module().execute(method, inputs); - if (!result.ok() || result->size() != (selector_top_k_ ? 2 : 1) || + if (!result.ok() || + result->size() != (selector_top_k_ ? 2u : 1u) + (tree ? 1 : 0) || !result->at(0).isTensor()) { return DraftStatus::Failed; } @@ -1289,6 +1389,57 @@ MuseGlimmerCudaDFlashExecutor::DraftStatus MuseGlimmerCudaDFlashExecutor::draft( scores.device_type() != aten::DeviceType::CUDA) { return DraftStatus::Failed; } + if (tree) { + if (!result->at(2).isTensor()) { + return DraftStatus::Failed; + } + const auto extras = result->at(2).toTensor(); + if (!dense(extras) || extras.scalar_type() != aten::ScalarType::Float || + extras.dim() != 3 || extras.size(0) != first.size(0) || + extras.size(1) != steps || extras.size(2) != selector_top_k_ + 1) { + return DraftStatus::Failed; + } + std::vector ids(first.numel()); + std::vector table(scores.numel()), unary(extras.numel()); + if (!copy_host(ids.data(), first, first.nbytes()) || + !copy_host(table.data(), scores, scores.nbytes()) || + !copy_host(unary.data(), extras, extras.nbytes())) { + return DraftStatus::Failed; + } + const auto k = static_cast(selector_top_k_); + tree->trees.clear(); + for (std::size_t i = 0; i < owners.size(); ++i) { + if (tree->sampled[i]) { + tree->trees.emplace_back(); // its chain follows the Serial pick + continue; + } + const std::size_t row = i * steps; + auto nodes = pairtree::build( + {ids.data() + row * k, + table.data() + row * k * k, + unary.data() + row * (k + 1), + steps, + selector_top_k_}, + tree->budgets[i]); + if (!nodes || nodes->empty()) { + // A round is verified one way: the whole round falls back to + // Serial DFlash2, which reports a non-finite score on its own + // path as it always does. + tree->trees.clear(); + break; + } + tree->trees.push_back(std::move(*nodes)); + } + const auto sampling = static_cast( + std::count(tree->sampled.begin(), tree->sampled.end(), 1)); + if (!tree->trees.empty() && sampling == 0) { + stats_.warmed_context_tokens += c; + return DraftStatus::Ok; + } + if (tree->trees.empty()) { + stats_.tree_fallback_cycles += owners.size() - sampling; + } + } auto sampled = target_->module().execute(df::kDFlash2Sample, {first, scores}); if (!sampled.ok() || sampled->size() != 1 || !sampled->at(0).isTensor()) { @@ -1349,6 +1500,20 @@ MuseGlimmerCudaDFlashExecutor::DraftStatus MuseGlimmerCudaDFlashExecutor::draft( picked.begin() + offset, picked.begin() + offset + proposals_); } } + if (tree && !tree->trees.empty()) { + // A sampled owner of a tree round verifies the chain Serial DFlash2 would. + // kDFlash2Sample also picked chains for the greedy owners; they go unused. + for (std::size_t i = 0; i < owners.size(); ++i) { + if (!tree->sampled[i]) { + continue; + } + auto& chain = tree->trees[i]; + for (int j = 0; j < proposals_; ++j) { + chain.push_back( + {static_cast((*proposals)[i][j]), j - 1, j + 1, 0.0}); + } + } + } stats_.warmed_context_tokens += c; return DraftStatus::Ok; } @@ -1363,7 +1528,13 @@ MuseGlimmerCudaDFlashExecutor::speculate( std::vector owners; std::vector anchors; std::vector indices; + std::vector sampled; int context = 0; + // With a tree budget, a round holding a greedy session is one PairTree + // round: its sampled sessions' Serial DFlash2 chains share its target + // forward, each taking its full proposals_ + 1 rows; every greedy session + // needs a root and a node. A round of sampled sessions only is Serial. + int greedy = 0, chain_rows = 0; while (cursor < batch.inputs.size()) { const auto& input = batch.inputs[cursor]; auto& state = sessions_.at(input.sid); @@ -1382,11 +1553,21 @@ MuseGlimmerCudaDFlashExecutor::speculate( if (rows > static_cast(fresh_context_)) { return DraftStatus::Failed; } + const bool samples = state.sampling->temperature != 0.0f; + const bool tree_round = tree_budget_ > 0 && (greedy > 0 || !samples); + const int round_rows = + chain_rows + (samples ? proposals_ + 1 : 0) + 2 * (greedy + !samples); if (owners.size() == static_cast(max_owners_) || - rows > static_cast(fresh_context_ - context)) { + rows > static_cast(fresh_context_ - context) || + (tree_round && + (owners.size() == static_cast(tree_owners_) || + round_rows > tree_rows_))) { break; } context += static_cast(rows); + greedy += !samples; + chain_rows += samples ? proposals_ + 1 : 0; + sampled.push_back(samples); owners.push_back(input.sid); anchors.push_back( pending_decode ? (*std::get( @@ -1398,10 +1579,36 @@ MuseGlimmerCudaDFlashExecutor::speculate( continue; } std::vector> proposals; - const auto status = draft(owners, anchors, fresh_context_, &proposals); + std::optional tree; + if (tree_budget_ > 0 && greedy > 0) { + // Each greedy owner's tree fits its share of the rows the sampled + // owners' chains leave, and its context. + tree.emplace(); + tree->sampled = sampled; + for (std::size_t i = 0; i < owners.size(); ++i) { + tree->budgets.push_back( + sampled[i] + ? 0 + : pairtree::round_budget( + tree_budget_, + tree_rows_ - chain_rows, + greedy, + max_context_ - sessions_.at(owners[i]).frontier - 1)); + } + } + const auto status = draft( + owners, anchors, fresh_context_, &proposals, tree ? &*tree : nullptr); if (status != DraftStatus::Ok) { return status; } + if (tree && !tree->trees.empty()) { + const auto verified = verify_tree( + owners, anchors, indices, tree->trees, tree->sampled, out); + if (verified != DraftStatus::Ok) { + return verified; + } + continue; + } RawStep verification; std::vector candidates; std::vector starts; @@ -1473,6 +1680,255 @@ MuseGlimmerCudaDFlashExecutor::speculate( return DraftStatus::Ok; } +MuseGlimmerCudaDFlashExecutor::DraftStatus +MuseGlimmerCudaDFlashExecutor::verify_tree( + const std::vector& owners, + const std::vector& anchors, + const std::vector& indices, + const std::vector>& trees, + const std::vector& sampled, + batching::BatchOutput& out) { + // Each owner's anchor roots its tree; node i sits at step row base + 1 + i. + // Owners keep Serial DFlash2's order, so with full trees every owner's rows + // sit where Serial DFlash2 would verify its chain. + const int width = proposals_ + 1; + RawStep step; + std::vector bases, starts; + std::vector chains; + std::vector chain_tokens; + for (std::size_t i = 0; i < owners.size(); ++i) { + const auto& state = sessions_.at(owners[i]); + const int base = static_cast(step.tokens.size()); + bases.push_back(base); + starts.push_back(state.frontier); + step.tokens.push_back(anchors[i]); + step.positions.push_back(state.frontier); + step.parents.push_back(-1); + for (const auto& node : trees[i]) { + step.tokens.push_back(node.token); + step.positions.push_back(state.frontier + node.depth); + step.parents.push_back(base + 1 + node.parent); + } + step.seq_ids.resize(step.tokens.size(), state.target_id); + if (sampled[i]) { + if (trees[i].size() != static_cast(proposals_)) { + return DraftStatus::Failed; + } + chains.push_back(i); + chain_tokens.insert( + chain_tokens.end(), step.tokens.begin() + base, step.tokens.end()); + } + } + const auto rows = step.tokens.size(); + step.logit_indices.resize(rows); + std::iota(step.logit_indices.begin(), step.logit_indices.end(), 0); + if (rows > static_cast(tree_rows_) || + !verification_hidden_.begin(rows, row_bytes_)) { + return DraftStatus::Failed; + } + std::vector predictions(rows, -1), verdicts; + ++stats_.target_verify_calls; + const bool ok = + target_->execute_raw(step, [&](const cb::RawTargetOutput& output) { + ++stats_.target_verify_forwards; + if (output.offset != 0 || output.length != static_cast(rows) || + output.selected_indices.size() != rows || !output.taps || + output.taps->dim() != 3 || + output.taps->scalar_type() != aten::ScalarType::BFloat16 || + output.taps->size(2) != hidden_width_ || + !verification_hidden_.capture(*output.taps, 0, rows) || + output.logits.device_type() != aten::DeviceType::CUDA || + output.logits.scalar_type() != aten::ScalarType::Float) { + return false; + } + if (verification_hidden_.on_device()) { + stats_.hidden_rows_d2d += rows; + stats_.hidden_bytes_d2d += rows * row_bytes_; + } + // Logits row r is step row r: the chains are moved and read by it. + for (std::size_t r = 0; r < rows; ++r) { + if (output.selected_indices[r] != r) { + return false; + } + } + const auto vocab = target_->vocab_size(); + auto* logits = static_cast(output.logits.mutable_data_ptr()); + const aten::Device cuda( + aten::DeviceType::CUDA, output.logits.device_index()); + // sample_argmax is torch.argmax over float logits, as Serial DFlash2's + // dflash_verify_argmax is: a tie goes to the lowest token id. + for (std::size_t first = 0; first < rows; first += argmax_rows_) { + const auto count = std::min(argmax_rows_, rows - first); + auto view = make_tensor_ptr( + {static_cast(count), vocab}, + logits + first * static_cast(vocab), + aten::ScalarType::Float, + cuda); + auto tokens = target_->argmax_rows(*view, count); + if (!tokens) { + return false; + } + std::copy( + tokens->begin(), tokens->end(), predictions.begin() + first); + } + if (chains.empty()) { + return true; + } + // Serial DFlash2's sampled acceptance, with the same inputs and + // positional draws as its linear verify, over the chains' logits moved + // to the front once every row is read. A chain only moves to lower + // rows, row by row, so no row is overwritten before it moves. + const auto stream = + ::executorch::extension::cuda::getCallerStream().value_or( + cudaStreamPerThread); + const auto row_floats = static_cast(vocab); + for (std::size_t c = 0; c < chains.size(); ++c) { + const auto from = static_cast(bases[chains[c]]); + for (std::size_t r = 0; from != c * width && r < width; ++r) { + if (cudaMemcpyAsync( + logits + (c * width + r) * row_floats, + logits + (from + r) * row_floats, + row_floats * sizeof(float), + cudaMemcpyDeviceToDevice, + stream) != cudaSuccess) { + return false; + } + } + } + const auto count = static_cast(chains.size()); + std::vector params; + params.reserve(count * (width + 3)); + for (const auto i : chains) { + const auto row = verify_params( + sessions_.at(owners[i]), + static_cast(starts[i] + 1)); + params.insert(params.end(), row.begin(), row.end()); + } + auto staged = verify_inputs_.upload( + {{chain_tokens.data(), chain_tokens.size() * sizeof(std::int64_t)}, + {params.data(), params.size() * sizeof(float)}}, + stream); + if (!staged) { + return false; + } + auto result = target_->module().execute( + df::kVerify, + {make_tensor_ptr( + {count, width, vocab}, logits, aten::ScalarType::Float, cuda), + make_tensor_ptr( + {count, width}, (*staged)[0], aten::ScalarType::Long, cuda), + make_tensor_ptr( + {count, width + 3}, + (*staged)[1], + aten::ScalarType::Float, + cuda)}); + if (!result.ok() || result->size() != 1 || !result->at(0).isTensor()) { + return false; + } + const auto& verdict = result->at(0).toTensor(); + verdicts.resize(2 * count); + return verdict.scalar_type() == aten::ScalarType::Long && + verdict.numel() == 2 * count && + copy_host( + verdicts.data(), + verdict, + verdicts.size() * sizeof(std::int64_t)); + }); + if (!ok) { + return DraftStatus::Failed; + } + // Commit each greedy owner's anchor and accepted path, and each sampled + // owner's anchor and accepted prefix; every other node's KV goes. + std::vector walks(owners.size()); + std::vector> bursts(owners.size()); + std::vector keep; + for (std::size_t c = 0; c < chains.size(); ++c) { + const auto i = chains[c]; + std::vector proposals; + for (const auto& node : trees[i]) { + proposals.push_back(static_cast(node.token)); + } + bursts[i] = df::make_burst( + proposals, verdicts[2 * c], verdicts[2 * c + 1], target_->vocab_size()); + if (!bursts[i]) { + return DraftStatus::Failed; + } + walks[i].path.resize(bursts[i]->accepted); + std::iota(walks[i].path.begin(), walks[i].path.end(), 0); + } + for (std::size_t i = 0; i < owners.size(); ++i) { + const int base = bases[i]; + if (!sampled[i]) { + walks[i] = pairtree::walk( + trees[i], + std::vector( + predictions.begin() + base, + predictions.begin() + base + 1 + trees[i].size())); + } + const auto& walk = walks[i]; + auto& hidden = sessions_.at(owners[i]).hidden; + // The path's rows are copied one by one, each possibly still queued when + // the next is appended, so the vector must not reallocate meanwhile. + hidden.reserve(hidden.size() + (walk.path.size() + 1) * row_bytes_); + keep.push_back(base); + bool copied = verification_hidden_.copy_rows(hidden, base, 1); + for (const int node : walk.path) { + keep.push_back(base + 1 + node); + copied = + copied && verification_hidden_.copy_rows(hidden, base + 1 + node, 1); + } + if (!copied) { + // Earlier owners' D2H copies are still queued into their hidden rows. + (void)verification_hidden_.fence(); + return DraftStatus::Failed; + } + if (verification_hidden_.on_device()) { + stats_.hidden_rows_d2h += walk.path.size() + 1; + stats_.hidden_bytes_d2h += (walk.path.size() + 1) * row_bytes_; + } + } + if (!verification_hidden_.fence() || + !target_->cache_control().retain_tree(keep)) { + return DraftStatus::Failed; + } + for (std::size_t i = 0; i < owners.size(); ++i) { + auto& state = sessions_.at(owners[i]); + const auto& walk = walks[i]; + const auto& nodes = trees[i]; + const int committed = starts[i] + static_cast(walk.path.size()) + 1; + if (target_->cache_control().pos(state.target_id) != committed) { + return DraftStatus::Failed; + } + state.frontier = committed; + auto& tokens = out.outputs[indices[i]]->tokens; + ++stats_.cycles; + if (sampled[i]) { + const auto& burst = *bursts[i]; + tokens.insert(tokens.end(), burst.tokens.begin(), burst.tokens.end()); + stats_.proposed += proposals_; + stats_.accepted += burst.accepted; + stats_.bonuses += burst.bonus; + stats_.rejected += !burst.bonus; + continue; + } + for (const int node : walk.path) { + tokens.push_back(static_cast(nodes[node].token)); + } + tokens.push_back(static_cast(walk.token)); + const int last = walk.path.empty() ? -1 : walk.path.back(); + const bool leaf = std::none_of( + nodes.begin(), nodes.end(), [last](const pairtree::Node& node) { + return node.parent == last; + }); + ++stats_.tree_cycles; + stats_.proposed += nodes.size(); + stats_.accepted += walk.path.size(); + stats_.bonuses += leaf; + stats_.rejected += !leaf; + } + return DraftStatus::Ok; +} + bool MuseGlimmerCudaDFlashExecutor::fail_batch( const batching::BatchInput& batch, batching::BatchOutput& out, diff --git a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h index 0684d5d958d..cc3c35b0e3a 100644 --- a/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h +++ b/examples/models/muse-glimmer/runtime/cuda_dflash_executor.h @@ -9,6 +9,8 @@ #include #include +#include +#include #include #include @@ -175,6 +177,17 @@ struct CudaDFlashStats { std::uint64_t rejected = 0; // cycles ended by a rejection, not tokens std::uint64_t bonuses = 0; std::uint64_t failed_batches = 0; + // PairTree DFlash2: greedy per-owner cycles verified as a tree, and greedy + // cycles that fell back to Serial DFlash2 instead, whether or not their round + // then verified: every greedy session of a round in which the tree builder + // refused one session's candidate table. Sampled sessions always verify a + // Serial DFlash2 chain, in a tree round or not, and count in neither. For a + // tree, `proposed` counts its nodes and a bonus is an accepted path that + // ends at a leaf. + std::uint64_t tree_cycles = 0; + std::uint64_t tree_fallback_cycles = 0; + // The PairTree DFlash2 budget chosen at startup; 0 = Serial DFlash2. + std::uint64_t tree_budget = 0; }; // Image and text prompts feed target hidden states into the same draft cache. @@ -182,10 +195,17 @@ struct CudaDFlashStats { // DFlash2 uses one dynamic draft method for every proposal count, including // the full block minus its anchor. The worker samples that prefix on device. // Both use greedy proposals and the session's target sampling policy. +// PairTree DFlash2 (resolve_dflash_mode) verifies greedy sessions' DFlash2 +// candidates as one bounded tree per session instead of a single chain, in +// one target forward, drafting them with kDFlash2PairTreeMethod. Sampled +// sessions share those rounds with their Serial DFlash2 chains. Serial +// DFlash2 never loads that method. class MuseGlimmerCudaDFlashExecutor final : public batching::Executor { public: + // `note` as in create_muse_glimmer_backend. static runtime::Result create( - const MuseGlimmerBackendConfig& config); + const MuseGlimmerBackendConfig& config, + std::string* note = nullptr); MuseGlimmerCudaDFlashExecutor(const MuseGlimmerCudaDFlashExecutor&) = delete; MuseGlimmerCudaDFlashExecutor& operator=( const MuseGlimmerCudaDFlashExecutor&) = delete; @@ -259,15 +279,36 @@ class MuseGlimmerCudaDFlashExecutor final : public batching::Executor { const; bool drain(batching::SessionId owner); enum class DraftStatus { Ok, NonFiniteScore, Failed }; + // A PairTree DFlash2 round: per owner, whether it samples and its greedy + // node budget in; a tree per owner out, which for a sampled owner is its + // Serial DFlash2 chain. No trees means the round fell back to Serial + // DFlash2 proposals. + struct TreeRound { + std::vector sampled; + std::vector budgets; + std::vector> trees; + }; DraftStatus draft( const std::vector& owners, const std::vector& anchors, int context_limit, - std::vector>* proposals); + std::vector>* proposals, + TreeRound* tree = nullptr); DraftStatus speculate( const batching::BatchInput& batch, batching::BatchOutput& out, bool pending_decode); + // Verifies one tree per owner in a single target forward and commits each + // greedy owner's longest accepted path plus the target's next token. A + // sampled owner's tree is its Serial DFlash2 chain, accepted and committed + // by Serial DFlash2's rule. + DraftStatus verify_tree( + const std::vector& owners, + const std::vector& anchors, + const std::vector& indices, + const std::vector>& trees, + const std::vector& sampled, + batching::BatchOutput& out); bool fail_batch( const batching::BatchInput& batch, batching::BatchOutput& out, @@ -283,6 +324,13 @@ class MuseGlimmerCudaDFlashExecutor final : public batching::Executor { max_context_, hidden_width_, selector_top_k_; batching::Token mask_; std::size_t row_bytes_; + // PairTree DFlash2: the per-owner node budget (0 = Serial DFlash2), the + // verify rows one forward takes, the owners one round may hold and the rows + // one sample_argmax call takes. + int tree_budget_ = 0; + int tree_rows_ = 0; + int tree_owners_ = 0; + std::size_t argmax_rows_ = 0; batching::SessionId next_session_ = 1; std::unordered_map sessions_; // Null for a text-only program. diff --git a/examples/models/muse-glimmer/tests/BUCK b/examples/models/muse-glimmer/tests/BUCK index 06236d1881e..1d30d1c188d 100644 --- a/examples/models/muse-glimmer/tests/BUCK +++ b/examples/models/muse-glimmer/tests/BUCK @@ -53,6 +53,7 @@ fbcode_target( deps = [ "//executorch/examples/models/muse-glimmer/runtime:cuda_dflash_executor", "//executorch/extension/cuda:caller_stream", + "//executorch/extension/llm/cache/test:cell_cache_test_peer", "//executorch/extension/llm/runner:stats", "//executorch/extension/tensor:tensor", "//executorch/kernels/portable:generated_lib", diff --git a/examples/models/muse-glimmer/tests/README.md b/examples/models/muse-glimmer/tests/README.md index 78989f09ba3..0d3867965ca 100644 --- a/examples/models/muse-glimmer/tests/README.md +++ b/examples/models/muse-glimmer/tests/README.md @@ -67,6 +67,85 @@ emitted tokens and cache positions, then reverses the packed order for the next round. A CUDA numerical test compares the lowered draft's tiled top-k IDs and all conditional scores with eager execution across one to four sessions. +The third fixture, `pairtree/`, is the quantized DFlash2 export again with +`draft_forward_pairtree` (`--dflash2-pairtree`) in a shape for trees: static +target forwards of 1, 4 and 32 tokens, 40-token steps and 1024 cells, enough +for 16 sessions. `pairtree/plain/` is the same wide export without the +method; `pairtree/controlled/` is the controlled fixture exported like +`pairtree/` (without its NaN row), and `pairtree/controlled_plain/` is that +export without the method. `pairtree/controlled_refused/` is the controlled +fixture with the method in its own shape, NaN row included, and candidate +logits raised above the full vocabulary's logsumexp, so the tree builder +refuses every table. Two packed greedy sessions must decode exactly as +Serial DFlash2 and target-only execution do at tree budgets 1, 4 and 15, and +on the controlled fixture trees must accept the target's tokens that the draft +ranks below its first choice, which Serial DFlash2 rejects. Hand-built trees of +the target's own continuation, with a decoy sibling and nephew at every depth, +must commit each session's whole path, the target's hidden rows of that path +(compared with a linear forward) and its cells, with the argmax split over +several calls; decoding then continues exactly. Further cases cover one +session per round near the context limit, two sessions sharing an 8-row +forward, and mixed batches of 2, 4 and 16 sessions, every other one sampled, +and on `pairtree/four/` and `pairtree/four_controlled/` (four draft owners, a +64-token forward) rounds of one greedy and several sampled sessions in +several orders, at the default budget and at 3 (where the random fixture's +sampled sessions after a short tree may follow rounding): +each round takes one draft call and one target forward, greedy sessions +decode the target's greedy tokens, and sampled sessions emit serial-only's +tokens. One target tree step must give +every node the logits of its own path run alone, up to BF16 rounding, and the +retained path must continue like the linear sequence. As a negative control, +the cell cache's test hook lets tree nodes attend their siblings, and that +comparison must then fail. Batches of sampled sessions only must run Serial +DFlash2 exactly, and +artifacts without `draft_forward_pairtree`, or budgets wider than the widest +static forward, must be refused at startup. Without a budget, the PairTree +exports must run PairTree DFlash2 at 15 nodes, or 31 for one decode sequence, +and the plain ones Serial DFlash2. On the same inputs and draft cache, the +compiled `draft_forward_pairtree` must return `draft_forward`'s candidate ids +and scores bit for bit. On `pairtree/controlled_refused/`, every round must +fall back from PairTree DFlash2 to Serial DFlash2: healthy sessions emit +Serial DFlash2's tokens with no failed batch, and a round with the NaN row +fails only its batch, as Serial DFlash2 does. + +`--dflash-serial-only` and a zero tree budget must run a PairTree export bit +for bit like the plain export. For the random pair and the controlled pair, +1, 4 and 16 sessions, every third one sampled, decode; then one session is +closed and replaced, every other one takes a second turn, and then one is +resubmitted from at least three tokens back (a rewind). Both runs on the PairTree +export and Serial DFlash2 on the plain one must emit the same tokens and, +after every execution, leave the same cells in both caches (positions and +owners), the same frontier, pending token and committed hidden rows (BF16 +bits) in each session. They must also report identical `CudaDFlashStats` and +target forward calls, and must never load `draft_forward_pairtree`. On the +controlled pair, PairTree DFlash2 on the same script must verify trees and +leave different states, so the comparison tells the modes apart. + +This needs both exports of a pair to run the same kernels. Their common +methods trace to identical graphs, but the export picks kernel variants by +timing: Triton autotune configs of the quantized GEMM and attention kernels +and the split-K launch parameters of `backends/cuda/autotune/launch_params.py` +are timed on the device, and both caches live only in the Python process. +Inductor's own autotune results are kept in its on-disk cache. The exporter +therefore writes each pair in one process, where the second export reuses the +first one's picks, and fails with "pair not pinned" unless every common method +is the same compiled library (`check_pinned`); two separate export processes +can pick differently and produce different, equally valid, rounding. Exports +that cannot share a process (the 30B ones) keep Inductor's and Triton's picks +when they share `TORCHINDUCTOR_CACHE_DIR` and `TRITON_CACHE_DIR` with +`TRITON_CACHE_AUTOTUNING=1`, but the split-K picks are not saved across +processes. The `.ptd` of a pair is byte for byte the same, since the backend +stores every weight once. + +These tests compare the branch with itself. Before the change landed, its +Serial DFlash2 path was also compared with the executor it replaced, as a +local check: the same script ran through the batching executor built from +the parent commit and through this one (serial-only and with a zero budget) +on the same tiny `.pte` files, which both load, and their tokens, per-session +frontiers, pending tokens, cache positions and committed hidden rows after +every execution, both caches' free cells and extents, stats and target +forward calls matched. + ## PairTree DFlash2 builder `dflash2_pairtree_test` checks the tree builder and greedy walk on the CPU 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 bcafa9843b8..44dcbfbccd2 100644 --- a/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp +++ b/examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp @@ -9,15 +9,24 @@ #include #include #include +#include +#include #include #include #include #include +#include #include +#include +#include #include #include +#include +#include #include +#include +#include #include namespace llm = executorch::extension::llm; @@ -142,6 +151,141 @@ struct CudaDFlashTestPeer { verify_params(DFlash& executor, b::SessionId sid, b::Position first) { return executor.verify_params(executor.sessions_.at(sid), first); } + // PairTree round limits: verify rows per forward, sessions per round, and + // rows per sample_argmax call. + static void set_tree_round( + DFlash& executor, + int rows, + int owners, + std::size_t argmax_rows) { + executor.tree_rows_ = rows; + executor.tree_owners_ = owners; + executor.argmax_rows_ = argmax_rows; + } + static bool verify_tree( + DFlash& executor, + const std::vector& owners, + const std::vector& anchors, + const std::vector>& trees, + b::BatchOutput& out) { + std::vector indices(owners.size()); + std::iota(indices.begin(), indices.end(), 0); + return executor.verify_tree( + owners, + anchors, + indices, + trees, + std::vector(owners.size(), 0), + out) == DFlash::DraftStatus::Ok; + } + static void set_pending(DFlash& executor, b::SessionId sid, b::Token token) { + executor.sessions_.at(sid).pending = token; + } + static int tree_budget(const DFlash& executor) { + return executor.tree_budget_; + } + // One session's next draft through `method`, its candidate ids and scores + // copied to the host; the draft cache is rewound so the draft can rerun. + static std::pair, std::vector> + draft_outputs(DFlash& executor, b::SessionId sid, const char* method) { + namespace df = cuda_dflash_detail; + auto& state = executor.sessions_.at(sid); + const int start = executor.draft_ctl_->pos(state.draft_id); + auto plan = df::pack_draft( + {{state.draft_id, + start, + *state.pending, + &state.hidden, + static_cast(state.hidden.size() / executor.row_bytes_)}}, + executor.block_, + executor.mask_, + executor.fresh_context_, + executor.max_context_, + executor.row_bytes_); + EXPECT_TRUE(plan && executor.draft_ctl_->declare_step(plan->ids)); + if (!plan) { + return {}; + } + const int rows = + static_cast(plan->hidden.size() / executor.row_bytes_); + const int kv_rows = rows + executor.block_; + auto tokens = executorch::extension::make_tensor_ptr( + {1, executor.block_}, plan->tokens); + auto hidden = executorch::extension::make_tensor_ptr( + {1, rows, executor.hidden_width_}, + plan->hidden, + aten::ScalarType::BFloat16); + auto positions = + executorch::extension::make_tensor_ptr({kv_rows}, plan->positions); + auto order = + executorch::extension::make_tensor_ptr({kv_rows}, plan->kv_order); + auto selector = executorch::extension::make_tensor_ptr( + {executor.proposals_}, std::vector(executor.proposals_)); + auto result = executor.target_->module().execute( + method, {*tokens, *hidden, *positions, *order, *selector}); + EXPECT_TRUE(result.ok() && result->size() >= 2); + std::pair, std::vector> outputs; + if (result.ok() && result->size() >= 2) { + const auto ids = result->at(0).toTensor(); + const auto scores = result->at(1).toTensor(); + outputs.first.resize(ids.numel()); + outputs.second.resize(scores.numel()); + EXPECT_EQ( + cudaMemcpy( + outputs.first.data(), + ids.const_data_ptr(), + ids.nbytes(), + cudaMemcpyDefault), + cudaSuccess); + EXPECT_EQ( + cudaMemcpy( + outputs.second.data(), + scores.const_data_ptr(), + scores.nbytes(), + cudaMemcpyDefault), + cudaSuccess); + } + EXPECT_TRUE(executor.draft_ctl_->rewind(state.draft_id, start)); + return outputs; + } + static bool loaded(DFlash& executor, const char* method) { + return executor.target_->module().is_method_loaded(method); + } + static std::vector method_calls(DFlash& executor) { + return executor.target_->method_calls(); + } + // What an execution leaves behind: both caches' cell tables and every + // session's frontier, pending token, cache positions and committed hidden + // rows, in session order. + static std::string state(DFlash& executor) { + std::string bytes; + auto append = [&bytes](const auto& value) { + bytes.append(reinterpret_cast(&value), sizeof(value)); + }; + for (auto* control : + {&executor.target_->cache_control(), executor.draft_ctl_}) { + const auto* table = dynamic_cast(control); + EXPECT_NE(table, nullptr); + if (table) { + cache::CellCacheTestPeer::append_table(*table, bytes); + } + } + std::map sessions; + for (const auto& [sid, state] : executor.sessions_) { + sessions[sid] = &state; + } + for (const auto& [sid, state] : sessions) { + append(sid); + append(state->frontier); + append(state->pending.value_or(-1)); + append(executor.target_->cache_control().pos(state->target_id)); + append(executor.draft_ctl_->pos(state->draft_id)); + bytes.append( + reinterpret_cast(state->hidden.data()), + state->hidden.size()); + } + return bytes; + } }; } // namespace executorch::extension::llm using Peer = llm::CudaDFlashTestPeer; @@ -357,19 +501,309 @@ class CudaDFlashNative : public ::testing::Test { std::unique_ptr executor_; }; +// A zero tree budget runs Serial DFlash2 on every export; nullopt picks the +// mode from the export (resolve_dflash_mode). rt::Result create_dflash2_fixture( const std::string& dir, std::optional n_draft, - int max_sessions = 2) { + int max_sessions = 2, + std::optional tree_budget = 0, + bool serial_only = false, + int max_decode_sequences = 4, + std::string* note = nullptr) { llm::MuseGlimmerBackendConfig config; config.backend = "cuda"; config.model_path = dir + "/model.pte"; config.data_path = dir + "/aoti_cuda_blob.ptd"; config.use_dflash = n_draft.has_value(); config.dflash_n_draft = n_draft.value_or(0); + config.dflash_tree_budget = tree_budget; + config.dflash_serial_only = serial_only; + config.max_decode_sequences = max_decode_sequences; config.max_sessions = max_sessions; config.max_session_tokens = 48; - return llm::create_muse_glimmer_backend(config); + return llm::create_muse_glimmer_backend(config, note); +} + +struct Generation { + std::vector tokens; + llm::CudaDFlashStats stats; +}; + +const std::vector kPrompts{{1, 7, 2}, {5, 2, 9, 11, 6, 4}}; + +struct Run { + std::optional n_draft; // nullopt = target-only + std::optional tree_budget = 0; + // Per prompt; greedy when empty. + std::vector sampling; + std::vector prompts = kPrompts; + std::size_t length = 20; + std::function configure; + bool serial_only = false; +}; + +// Packed sessions decode `run.length` tokens each. +void generate(const std::string& dir, const Run& run, Generation& result) { + auto backend = create_dflash2_fixture( + dir, + run.n_draft, + static_cast(run.prompts.size()), + run.tree_budget, + run.serial_only); + ASSERT_TRUE(backend.ok()); + auto& executor = *backend.get().executor; + ASSERT_TRUE(executor.initialize()); + if (run.configure) { + run.configure(static_cast(executor)); + } + std::map index; + b::BatchInput batch; + for (std::size_t i = 0; i < run.prompts.size(); ++i) { + auto owner = executor.open_session(); + ASSERT_TRUE(owner); + index[*owner] = i; + executor.set_sampling( + *owner, + run.sampling.empty() ? b::SamplingParams{} : run.sampling[i], + 42 + i); + batch.inputs.push_back(input(*owner, 0, run.prompts[i])); + } + result.tokens.assign(run.prompts.size(), {}); + while (!batch.inputs.empty()) { + b::BatchOutput out; + ASSERT_TRUE(executor.execute(batch, out)); + ASSERT_EQ(out.outputs.size(), batch.inputs.size()); + b::BatchInput next; + for (std::size_t i = 0; i < out.outputs.size(); ++i) { + const auto owner = batch.inputs[i].sid; + const auto prompt = index.at(owner); + ASSERT_TRUE(out.outputs[i]); + const auto& tokens = out.outputs[i]->tokens; + ASSERT_FALSE(tokens.empty()); + auto& sequence = result.tokens[prompt]; + sequence.insert(sequence.end(), tokens.begin(), tokens.end()); + if (sequence.size() < run.length) { + next.inputs.push_back(input( + owner, + run.prompts[prompt].size() + sequence.size() - 1, + {sequence.back()})); + } else { + sequence.resize(run.length); + } + } + batch = std::move(next); + } + if (run.n_draft) { + result.stats = static_cast(executor).stats(); + EXPECT_EQ(result.stats.failed_batches, 0u); + } +} + +// Tree and linear steps can run different static forwards, whose BF16 +// activations round differently. +bool close(float actual, float expected) { + return std::abs(actual - expected) <= 0.02f + 0.02f * std::abs(expected); +} + +int not_close( + const std::vector& actual, + const std::vector& expected) { + int count = 0; + for (std::size_t i = 0; i < actual.size(); ++i) { + count += !close(actual[i], expected[i]); + } + return count; +} + +float max_difference(const std::vector& a, const std::vector& b) { + float result = 0; + for (std::size_t i = 0; i < a.size(); ++i) { + result = std::max(result, std::abs(a[i] - b[i])); + } + return result; +} + +std::int64_t argmax(const std::vector& row) { + return std::max_element(row.begin(), row.end()) - row.begin(); +} + +// Whether `actual`'s argmax is a maximum of `expected` too, up to rounding: a +// near-tie may resolve either way. +bool same_argmax( + const std::vector& actual, + const std::vector& expected) { + return close( + expected[argmax(actual)], + *std::max_element(expected.begin(), expected.end())); +} + +// The target's taps for every position of `tokens`, one linear forward. +std::vector> linear_taps( + const std::string& dir, + const Tokens& tokens) { + cb::CudaExecutorConfig config; + config.model_path = dir + "/model.pte"; + config.data_files = {dir + "/aoti_cuda_blob.ptd"}; + config.max_session_tokens = 48; + auto created = cb::CudaExecutor::create(config); + std::vector> rows(tokens.size()); + if (!created.ok() || !created.get()->initialize()) { + ADD_FAILURE() << "could not load " << dir; + return {}; + } + auto& target = *created.get(); + const auto seq = target.cache_control().seq_new(); + cb::RawTargetStep step; + step.tokens.assign(tokens.begin(), tokens.end()); + for (std::size_t i = 0; i < tokens.size(); ++i) { + step.positions.push_back(i); + } + step.seq_ids.assign(tokens.size(), *seq); + step.logit_indices = {static_cast(tokens.size()) - 1}; + const bool ok = + target.execute_raw(step, [&](const cb::RawTargetOutput& output) { + if (!output.taps || + output.taps->scalar_type() != aten::ScalarType::BFloat16) { + return false; + } + const auto width = static_cast(output.taps->size(2)); + std::vector bits(output.length * width); + if (cudaMemcpy( + bits.data(), + output.taps->const_data_ptr(), + bits.size() * 2, + cudaMemcpyDefault) != cudaSuccess) { + return false; + } + for (int row = 0; row < output.length; ++row) { + auto& values = rows[output.offset + row]; + for (std::size_t column = 0; column < width; ++column) { + const std::uint32_t word = bits[row * width + column] << 16; + float value; + std::memcpy(&value, &word, sizeof(value)); + values.push_back(value); + } + } + return true; + }); + EXPECT_TRUE(ok); + return rows; +} + +// Logits of the step's selected rows, in logit_indices order. +std::vector> step_logits( + cb::CudaExecutor& target, + const cb::RawTargetStep& step) { + std::vector> rows(step.logit_indices.size()); + const bool ok = + target.execute_raw(step, [&](const cb::RawTargetOutput& output) { + if (output.logits.scalar_type() != aten::ScalarType::Float) { + return false; + } + const auto vocab = static_cast(target.vocab_size()); + const auto* logits = + static_cast(output.logits.const_data_ptr()); + const auto stream = + executorch::extension::cuda::getCallerStream().value_or( + cudaStreamPerThread); + for (std::size_t row = 0; row < output.selected_indices.size(); ++row) { + auto& values = rows[output.selected_indices[row]]; + values.resize(vocab); + if (cudaMemcpyAsync( + values.data(), + logits + row * vocab, + vocab * sizeof(float), + cudaMemcpyDefault, + stream) != cudaSuccess) { + return false; + } + } + return cudaStreamSynchronize(stream) == cudaSuccess; + }); + EXPECT_TRUE(ok); + return rows; +} + +// Greedy decoding, checked token by token against target-only forwards over +// the prompt and the session's own earlier tokens (teacher forcing). Each +// token must be the target's argmax, or score within a few BF16 ulps of it: +// the random fixture's target can score two tokens that close, and forwards of +// different widths round them differently. Returns the near-ties taken. +int expect_greedy( + const std::string& dir, + const std::vector& prompts, + const std::vector& actual) { + cb::CudaExecutorConfig config; + config.model_path = dir + "/model.pte"; + config.data_files = {dir + "/aoti_cuda_blob.ptd"}; + config.max_session_tokens = 48; + auto created = cb::CudaExecutor::create(config); + if (!created.ok() || !created.get()->initialize()) { + ADD_FAILURE() << "could not load " << dir; + return 0; + } + auto& target = *created.get(); + const auto seq = target.cache_control().seq_new(); + int near_ties = 0; + for (std::size_t i = 0; i < actual.size(); ++i) { + Tokens context = prompts[i]; + for (std::size_t j = 0; j < actual[i].size(); ++j) { + EXPECT_TRUE(target.cache_control().rewind(*seq, 0)); + cb::RawTargetStep step; + step.tokens.assign(context.begin(), context.end()); + for (std::size_t k = 0; k < context.size(); ++k) { + step.positions.push_back(k); + } + step.seq_ids.assign(context.size(), *seq); + step.logit_indices = {static_cast(context.size()) - 1}; + const auto logits = step_logits(target, step); + if (logits.size() != 1 || logits[0].empty()) { + ADD_FAILURE() << "target-only forward failed"; + return near_ties; + } + const auto& row = logits[0]; + const auto best = argmax(row); + const auto token = actual[i][j]; + if (static_cast(best) != token) { + // Four ulps of a BF16 value at the best logit's scale. + const float ulp = std::ldexp( + 1.0f, std::ilogb(std::max(std::abs(row[best]), 1e-30f)) - 7); + std::printf( + "session %zu token %zu: near-tie, %llu scores %g, argmax %lld %g\n", + i, + j, + static_cast(token), + row[token], + static_cast(best), + row[best]); + EXPECT_LE(row[best] - row[token], 4 * ulp) + << "session " << i << " token " << j << " is not the target's"; + ++near_ties; + } + context.push_back(token); + } + } + return near_ties; +} + +std::vector bf16_row( + const std::vector& bytes, + std::size_t row, + std::size_t width) { + std::vector values(width); + for (std::size_t column = 0; column < width; ++column) { + std::uint16_t bits; + std::memcpy(&bits, bytes.data() + (row * width + column) * 2, 2); + const std::uint32_t word = static_cast(bits) << 16; + std::memcpy(&values[column], &word, sizeof(float)); + } + return values; +} + +const char* pairtree_fixture() { + const char* dir = std::getenv("ET_MUSE_DFLASH2_TINY_DIR"); + return dir && *dir ? dir : nullptr; } // Exercise the production factory (including metadata validation) and the real @@ -486,6 +920,866 @@ TEST(CudaDFlash2Native, PackedOwnersCommitDifferentAcceptedPrefixes) { EXPECT_EQ(second.bonuses - first.bonuses, 1u); } +// PairTree DFlash2 keeps greedy decoding exact: two packed sessions match +// Serial DFlash2 and target-only decoding. +TEST(CudaDFlash2Native, PairTreeMatchesSerialAndTargetOnly) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = std::string(pairtree_fixture()) + "/pairtree"; + Generation target, serial; + ASSERT_NO_FATAL_FAILURE(generate(dir, {std::nullopt}, target)); + ASSERT_NO_FATAL_FAILURE(generate(dir, {0}, serial)); + EXPECT_EQ(serial.tokens, target.tokens); + EXPECT_EQ(serial.stats.tree_cycles, 0u); + EXPECT_EQ(serial.stats.tree_fallback_cycles, 0u); + for (const int budget : {1, 4, 15}) { + SCOPED_TRACE(::testing::Message() << "dflash_tree_budget=" << budget); + Generation tree; + ASSERT_NO_FATAL_FAILURE(generate(dir, {0, budget}, tree)); + EXPECT_LE(expect_greedy(dir, kPrompts, tree.tokens), 2); + EXPECT_GT(tree.stats.tree_cycles, 0u); + EXPECT_EQ(tree.stats.tree_cycles, tree.stats.cycles); + EXPECT_EQ(tree.stats.tree_fallback_cycles, 0u); + EXPECT_LE(tree.stats.proposed, tree.stats.cycles * budget); + EXPECT_EQ(tree.stats.bonuses + tree.stats.rejected, tree.stats.cycles); + EXPECT_EQ( + tree.stats.target_verify_forwards, tree.stats.target_verify_calls); + } +} + +// One target tree step against the same paths run one by one: every node's +// logits match its own path's, the retained path continues like the linear +// sequence, and with siblings visible (the cell cache's test hook) the +// comparison fails. +TEST(CudaDFlash2Native, TreeStepMatchesEachPathRunAlone) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = std::string(pairtree_fixture()) + "/pairtree"; + cb::CudaExecutorConfig config; + config.model_path = dir + "/model.pte"; + config.data_files = {dir + "/aoti_cuda_blob.ptd"}; + config.max_session_tokens = 48; + auto created = cb::CudaExecutor::create(config); + ASSERT_TRUE(created.ok()); + auto& target = *created.get(); + ASSERT_TRUE(target.initialize()); + ASSERT_TRUE(target.cache_control().supports_tree_steps()); + auto& control = target.cache_control(); + const auto seq = control.seq_new(); + ASSERT_TRUE(seq); + const auto run = [&](const std::vector& tokens, + std::int64_t start, + std::vector parents, + std::vector positions) { + cb::RawTargetStep step; + step.tokens = tokens; + step.positions = std::move(positions); + step.seq_ids.assign(tokens.size(), *seq); + step.parents = std::move(parents); + if (step.positions.empty()) { + for (std::size_t i = 0; i < tokens.size(); ++i) { + step.positions.push_back(start + i); + } + } + step.logit_indices.resize(tokens.size()); + std::iota(step.logit_indices.begin(), step.logit_indices.end(), 0); + return step_logits(target, step); + }; + constexpr int kStart = 5; + ASSERT_EQ(run({1, 7, 2, 5, 9}, 0, {}, {}).size(), 5u); + // Root 11 with three children; every depth has siblings. + const std::vector parents{ + -1, 0, 0, 0, 1, 1, 2, 4, 4, 5, 7, 3, 6, 10, 8, 9}; + std::vector tokens{11}, positions{kStart}; + std::vector> paths{{11}}; + for (std::size_t i = 1; i < parents.size(); ++i) { + tokens.push_back(100 + i); + positions.push_back(positions[parents[i]] + 1); + paths.push_back(paths[parents[i]]); + paths.back().push_back(tokens.back()); + } + std::vector> expected; + for (const auto& path : paths) { + ASSERT_TRUE(control.rewind(*seq, kStart)); + expected.push_back(run(path, kStart, {}, {}).back()); + } + ASSERT_TRUE(control.rewind(*seq, kStart)); + const auto compare = [&](bool leak) { + c::CellCacheTestPeer::set_tree_siblings_visible( + static_cast(control), leak); + const auto actual = run(tokens, kStart, parents, positions); + c::CellCacheTestPeer::set_tree_siblings_visible( + static_cast(control), false); + float difference = 0; + int differing = 0, mismatched = 0; + for (std::size_t i = 0; i < actual.size(); ++i) { + difference = std::max(difference, max_difference(actual[i], expected[i])); + differing += not_close(actual[i], expected[i]); + mismatched += !same_argmax(actual[i], expected[i]); + } + std::printf( + "tree step, siblings %s: max |logit difference| %g, %d logits beyond " + "rounding, %d argmax mismatches\n", + leak ? "visible" : "hidden", + difference, + differing, + mismatched); + return std::pair{differing, mismatched}; + }; + const auto [exact, exact_mismatched] = compare(false); + EXPECT_EQ(exact, 0); + EXPECT_EQ(exact_mismatched, 0); + // Keep root -> 101 -> 104 -> 107 -> 110 -> 113, then continue linearly. + const std::vector keep{0, 1, 4, 7, 10, 13}; + ASSERT_TRUE(control.retain_tree(keep)); + ASSERT_EQ(control.pos(*seq), kStart + 6); + const auto continued = run({99}, kStart + 6, {}, {}).back(); + ASSERT_TRUE(control.rewind(*seq, kStart)); + auto linear = paths[13]; + linear.push_back(99); + const auto reference = run(linear, kStart, {}, {}).back(); + EXPECT_TRUE(same_argmax(continued, reference)); + EXPECT_EQ(not_close(continued, reference), 0); + + ASSERT_TRUE(control.rewind(*seq, kStart)); + const auto [leaked, leaked_mismatched] = compare(true); + EXPECT_GT(leaked, 0); + ASSERT_TRUE(control.retain_tree({0})); +} + +// Sampled sessions run Serial DFlash2 in rounds of their own, so a greedy +// session sharing their batch still gets trees. +TEST(CudaDFlash2Native, SampledOnlyBatchesRunSerialDFlash2) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = std::string(pairtree_fixture()) + "/pairtree"; + const b::SamplingParams sampled{0.8f, 0.9f, 7}; + Generation serial, tree; + ASSERT_NO_FATAL_FAILURE(generate(dir, {0, 0, {sampled, sampled}}, serial)); + ASSERT_NO_FATAL_FAILURE(generate(dir, {0, 15, {sampled, sampled}}, tree)); + EXPECT_EQ(tree.tokens, serial.tokens); + EXPECT_GT(tree.stats.cycles, 0u); + EXPECT_EQ(tree.stats.tree_cycles, 0u); + EXPECT_EQ(tree.stats.tree_fallback_cycles, 0u); + auto tree_stats = tree.stats; + tree_stats.tree_budget = serial.stats.tree_budget; + EXPECT_EQ(std::memcmp(&tree_stats, &serial.stats, sizeof(tree_stats)), 0); +} + +// A round with greedy and sampled sessions is one PairTree round: one draft +// call, one target forward. Each sampled session verifies the chain Serial +// DFlash2 would, at the rows Serial DFlash2 would (full trees keep its row +// layout), by its acceptance rule and positional draws, so its tokens are +// serial-only's whenever its logits are bit-identical; here they are. Greedy +// sessions still decode the target's greedy tokens, up to the random +// fixture's near-ties. +TEST(CudaDFlash2Native, MixedBatchesShareOneRound) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string root = pairtree_fixture(); + const b::SamplingParams sampled{0.8f, 0.9f, 7}; + for (const auto& [fixture, sessions] : + {std::pair{std::string("/pairtree"), 2}, + std::pair{std::string("/pairtree"), 4}, + std::pair{std::string("/pairtree"), 16}, + std::pair{std::string("/pairtree/controlled"), 2}, + std::pair{std::string("/pairtree/controlled"), 4}, + std::pair{std::string("/pairtree/controlled"), 16}}) { + const std::string dir = root + fixture; + SCOPED_TRACE(dir + ", " + std::to_string(sessions) + " sessions"); + std::vector prompts; + std::vector sampling; + for (int i = 0; i < sessions; ++i) { + prompts.push_back( + fixture == "/pairtree" + ? Tokens{static_cast(1 + (17 * i) % 200), 7, 2} + : Tokens{1, static_cast(7 + i % 2)}); + sampling.push_back(i % 2 ? sampled : b::SamplingParams{}); + } + Generation serial, tree, target; + ASSERT_NO_FATAL_FAILURE(generate( + dir, {0, std::nullopt, sampling, prompts, 20, {}, true}, serial)); + ASSERT_NO_FATAL_FAILURE( + generate(dir, {0, std::nullopt, sampling, prompts}, tree)); + ASSERT_NO_FATAL_FAILURE( + generate(dir, {std::nullopt, 0, {}, prompts}, target)); + std::vector greedy_prompts, greedy_tokens; + for (int i = 0; i < sessions; ++i) { + if (i % 2) { + EXPECT_EQ(tree.tokens[i], serial.tokens[i]) << "sampled session " << i; + } else { + greedy_prompts.push_back(prompts[i]); + greedy_tokens.push_back(tree.tokens[i]); + } + } + EXPECT_LE( + expect_greedy(dir, greedy_prompts, greedy_tokens), + fixture == "/pairtree" ? sessions : 0); + EXPECT_GT(tree.stats.tree_cycles, 0u); + EXPECT_LT(tree.stats.tree_cycles, tree.stats.cycles); + EXPECT_EQ(tree.stats.tree_fallback_cycles, 0u); + EXPECT_EQ(tree.stats.failed_batches, 0u); + // Two owners a round: each pair verifies in one forward of one call. + EXPECT_EQ( + tree.stats.target_verify_forwards, tree.stats.target_verify_calls); + if (sessions == 2) { + EXPECT_EQ(tree.stats.draft_forwards, tree.stats.target_verify_calls); + } + } +} + +// Four owners a round: several sampled chains share the forward, chains move +// to the front from behind a greedy tree, and a short tree (budget 3) shifts +// the chains' rows and cells off Serial DFlash2's. Every execute is one round: +// one draft call and one target forward. Sampled sessions emit serial-only's +// tokens, except after a short tree on the random fixture, whose near-uniform +// draws follow the rounding that shift causes; there only how many sessions +// still match is reported. +TEST(CudaDFlash2Native, MixedRoundsHoldSeveralChains) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string root = pairtree_fixture(); + const b::SamplingParams sampled{0.8f, 0.9f, 7}; + for (const std::string fixture : + {"/pairtree/four", "/pairtree/four_controlled"}) { + const std::string dir = root + fixture; + const bool random = fixture == "/pairtree/four"; + for (const std::string order : {"GSSS", "SGSS", "SSG"}) { + for (const std::optional budget : + {std::optional(), std::optional(3)}) { + SCOPED_TRACE( + dir + ", " + order + ", budget " + + (budget ? std::to_string(*budget) : "default")); + std::vector prompts; + std::vector sampling; + for (std::size_t i = 0; i < order.size(); ++i) { + prompts.push_back( + random ? Tokens{static_cast(1 + 17 * i), 7, 2} + : Tokens{1, static_cast(7 + i % 2)}); + sampling.push_back(order[i] == 'S' ? sampled : b::SamplingParams{}); + } + Generation serial, tree; + ASSERT_NO_FATAL_FAILURE(generate( + dir, {0, std::nullopt, sampling, prompts, 20, {}, true}, serial)); + ASSERT_NO_FATAL_FAILURE( + generate(dir, {0, budget, sampling, prompts}, tree)); + const bool exact = !(random && budget); + std::vector greedy_prompts, greedy_tokens; + int chains = 0, equal = 0; + for (std::size_t i = 0; i < order.size(); ++i) { + if (order[i] == 'S') { + ++chains; + equal += tree.tokens[i] == serial.tokens[i]; + if (exact) { + EXPECT_EQ(tree.tokens[i], serial.tokens[i]) + << "sampled session " << i; + } + } else { + greedy_prompts.push_back(prompts[i]); + greedy_tokens.push_back(tree.tokens[i]); + } + } + EXPECT_LE( + expect_greedy(dir, greedy_prompts, greedy_tokens), random ? 2 : 0); + EXPECT_GT(tree.stats.tree_cycles, 0u); + EXPECT_EQ(tree.stats.tree_fallback_cycles, 0u); + EXPECT_EQ(tree.stats.failed_batches, 0u); + EXPECT_EQ( + tree.stats.target_verify_forwards, tree.stats.target_verify_calls); + EXPECT_EQ(tree.stats.draft_forwards, tree.stats.target_verify_calls); + EXPECT_LE(tree.stats.target_verify_calls, tree.stats.executions); + EXPECT_EQ(tree.stats.tree_budget, budget.value_or(15)); + if (!exact) { + std::printf( + "%s %s, budget %d: %d/%d sampled sessions as serial-only\n", + fixture.c_str(), + order.c_str(), + *budget, + equal, + chains); + } + } + } + } +} + +// The controlled fixture's draft proposes the target's own tokens as low-ranked +// siblings, so trees accept longer paths than Serial DFlash2 does, across the +// target's sliding window. +TEST(CudaDFlash2Native, PairTreeAcceptsSiblingsSerialDFlash2Rejects) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = + std::string(pairtree_fixture()) + "/pairtree/controlled"; + const std::vector prompts{{1, 7}, {2, 3, 8}}; + Generation target, serial, tree; + ASSERT_NO_FATAL_FAILURE( + generate(dir, {std::nullopt, 0, {}, prompts}, target)); + ASSERT_NO_FATAL_FAILURE(generate(dir, {3, 0, {}, prompts}, serial)); + ASSERT_NO_FATAL_FAILURE(generate(dir, {3, 15, {}, prompts}, tree)); + EXPECT_EQ(serial.tokens, target.tokens); + EXPECT_EQ(tree.tokens, target.tokens); + std::printf( + "controlled: serial %llu/%llu accepted in %llu cycles, tree %llu/%llu in " + "%llu cycles\n", + static_cast(serial.stats.accepted), + static_cast(serial.stats.proposed), + static_cast(serial.stats.cycles), + static_cast(tree.stats.accepted), + static_cast(tree.stats.proposed), + static_cast(tree.stats.cycles)); + EXPECT_EQ(tree.stats.tree_cycles, tree.stats.cycles); + EXPECT_GT(tree.stats.accepted, serial.stats.accepted); + EXPECT_LT(tree.stats.cycles, serial.stats.cycles); + EXPECT_GT(tree.stats.proposed, tree.stats.accepted); +} + +// Trees built by hand from the target's own continuation, with a decoy sibling +// and nephew at every depth: verify_tree must commit each session's whole path, +// its rows of target hidden state and its cells, splitting the argmax over +// several sample_argmax calls, and decoding must then continue exactly. +TEST(CudaDFlash2Native, VerifyTreeCommitsPathTokensRowsAndCells) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = std::string(pairtree_fixture()) + "/pairtree"; + Generation target; + ASSERT_NO_FATAL_FAILURE(generate(dir, {std::nullopt}, target)); + std::vector>> taps; + for (std::size_t i = 0; i < kPrompts.size(); ++i) { + Tokens sequence = kPrompts[i]; + sequence.insert( + sequence.end(), target.tokens[i].begin(), target.tokens[i].end()); + taps.push_back(linear_taps(dir, sequence)); + ASSERT_EQ(taps.back().size(), sequence.size()); + } + auto backend = create_dflash2_fixture(dir, 0, 2, 15); + ASSERT_TRUE(backend.ok()); + auto& executor = static_cast(*backend.get().executor); + ASSERT_TRUE(executor.initialize()); + std::vector owners; + b::BatchInput batch; + for (const auto& prompt : kPrompts) { + owners.push_back(*executor.open_session()); + executor.set_sampling(owners.back(), {}, 0); + batch.inputs.push_back(input(owners.back(), 0, prompt)); + } + b::BatchOutput first; + ASSERT_TRUE(executor.execute(batch, first)); + std::vector emitted; + for (std::size_t i = 0; i < owners.size(); ++i) { + ASSERT_TRUE(first.outputs[i]); + emitted.push_back(first.outputs[i]->tokens); + } + const std::array depths{5, 3}; + std::vector> trees; + std::vector anchors; + std::vector starts; + for (std::size_t i = 0; i < owners.size(); ++i) { + const auto& expected = target.tokens[i]; + const std::size_t done = emitted[i].size(); + ASSERT_LE(done + depths[i] + 1, expected.size()); + ASSERT_TRUE( + std::equal(emitted[i].begin(), emitted[i].end(), expected.begin())); + anchors.push_back(emitted[i].back()); + starts.push_back(static_cast(kPrompts[i].size() + done - 1)); + std::vector nodes; + int parent = -1; + for (int depth = 1; depth <= depths[i]; ++depth) { + const auto want = static_cast(expected[done - 1 + depth]); + nodes.push_back({(want + 7) % 200000, parent, depth, 0}); + nodes.push_back( + {(want + 11) % 200000, + static_cast(nodes.size()) - 1, + depth + 1, + 0}); + nodes.push_back({want, parent, depth, 0}); + parent = static_cast(nodes.size()) - 1; + } + trees.push_back(std::move(nodes)); + } + Peer::set_tree_round(executor, 32, 2, 3); + const auto before = executor.stats(); + b::BatchOutput out; + for (const auto owner : owners) { + out.outputs.push_back(b::Output{owner, {}}); + } + ASSERT_TRUE(Peer::verify_tree(executor, owners, anchors, trees, out)); + const auto after = executor.stats(); + EXPECT_EQ(after.tree_cycles - before.tree_cycles, 2u); + EXPECT_EQ(after.accepted - before.accepted, 8u); + for (std::size_t i = 0; i < owners.size(); ++i) { + SCOPED_TRACE(i); + const auto& expected = target.tokens[i]; + const std::size_t done = emitted[i].size(); + ASSERT_TRUE(out.outputs[i]); + EXPECT_EQ( + out.outputs[i]->tokens, + Tokens( + expected.begin() + done, expected.begin() + done + depths[i] + 1)); + Peer::check(executor, owners[i], starts[i] + depths[i] + 1); + const auto& hidden = Peer::hidden(executor, owners[i]); + const std::size_t width = taps[i][0].size(); + const std::size_t rows = hidden.size() / (2 * width); + ASSERT_GE(rows, static_cast(depths[i] + 1)); + for (int row = 0; row <= depths[i]; ++row) { + const auto actual = bf16_row(hidden, rows - (depths[i] + 1) + row, width); + EXPECT_EQ(not_close(actual, taps[i][starts[i] + row]), 0) + << "hidden row for position " << starts[i] + row; + } + Peer::set_pending(executor, owners[i], out.outputs[i]->tokens.back()); + emitted[i].insert( + emitted[i].end(), + out.outputs[i]->tokens.begin(), + out.outputs[i]->tokens.end()); + } + // Decode the rest and compare with target-only decoding. + Peer::set_tree_round(executor, 32, 2, 64); + while (true) { + b::BatchInput next; + for (std::size_t i = 0; i < owners.size(); ++i) { + if (emitted[i].size() < target.tokens[i].size()) { + next.inputs.push_back(input( + owners[i], + kPrompts[i].size() + emitted[i].size() - 1, + {emitted[i].back()})); + } + } + if (next.inputs.empty()) { + break; + } + b::BatchOutput decoded; + ASSERT_TRUE(executor.execute(next, decoded)); + for (std::size_t i = 0; i < next.inputs.size(); ++i) { + const auto index = next.inputs[i].sid == owners[0] ? 0 : 1; + ASSERT_TRUE(decoded.outputs[i]); + emitted[index].insert( + emitted[index].end(), + decoded.outputs[i]->tokens.begin(), + decoded.outputs[i]->tokens.end()); + } + } + for (std::size_t i = 0; i < owners.size(); ++i) { + emitted[i].resize(target.tokens[i].size()); + } + EXPECT_LE(expect_greedy(dir, kPrompts, emitted), 2); +} + +// One session per round with the largest budget, so its tree is capped by the +// context left near the end; and two sessions sharing an 8-row forward. +TEST(CudaDFlash2Native, PairTreeBudgetsShrinkToTheForwardAndTheContext) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = std::string(pairtree_fixture()) + "/pairtree"; + Generation target, single, shared; + ASSERT_NO_FATAL_FAILURE( + generate(dir, {std::nullopt, 0, {}, kPrompts, 30}, target)); + ASSERT_NO_FATAL_FAILURE(generate( + dir, + {0, + 31, + {}, + kPrompts, + 30, + [](DFlash& executor) { Peer::set_tree_round(executor, 32, 1, 64); }}, + single)); + EXPECT_LE(expect_greedy(dir, kPrompts, single.tokens), 2); + EXPECT_GT(single.stats.tree_cycles, 0u); + EXPECT_EQ(single.stats.target_verify_calls, single.stats.tree_cycles); + EXPECT_LE(single.stats.proposed, single.stats.cycles * 31); + ASSERT_NO_FATAL_FAILURE(generate( + dir, + {0, + 15, + {}, + kPrompts, + 30, + [](DFlash& executor) { Peer::set_tree_round(executor, 8, 2, 64); }}, + shared)); + EXPECT_LE(expect_greedy(dir, kPrompts, shared.tokens), 2); + EXPECT_GT(shared.stats.tree_cycles, 0u); + // Every round's roots and nodes fit its 8-row forward. + EXPECT_LE( + shared.stats.proposed + shared.stats.tree_cycles, + 8 * shared.stats.target_verify_calls); + EXPECT_LE( + single.stats.proposed + single.stats.tree_cycles, + 32 * single.stats.target_verify_calls); +} + +TEST(CudaDFlash2Native, PairTreeNeedsItsExportAndAWideEnoughForward) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = pairtree_fixture(); + // The plain DFlash2 export has no candidate logits; it still runs serially. + EXPECT_EQ( + create_dflash2_fixture(dir, 0, 2, 4).error(), rt::Error::InvalidProgram); + EXPECT_EQ(create_dflash2_fixture(dir, 0, 2, 0).error(), rt::Error::Ok); + // The widest static target forward takes 32 tokens: one root and 31 nodes. + EXPECT_EQ( + create_dflash2_fixture(dir + "/pairtree", 0, 2, 32).error(), + rt::Error::InvalidArgument); + EXPECT_EQ( + create_dflash2_fixture(dir + "/pairtree", 0, 2, 31).error(), + rt::Error::Ok); + EXPECT_EQ( + create_dflash2_fixture(dir + "/pairtree", std::nullopt, 2, 4).error(), + rt::Error::InvalidArgument); +} + +// A --dflash2-pairtree export runs PairTree DFlash2 unless asked not to; +// Serial DFlash2 never loads draft_forward_pairtree. +TEST(CudaDFlash2Native, PairTreeIsTheDefaultOnItsExport) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string plain = pairtree_fixture(); + const std::string pairtree = plain + "/pairtree"; + const auto method = llm::kDFlash2PairTreeMethod; + for (const auto& [dir, serial_only, decodes, budget, says] : + {std::tuple{pairtree, false, 4, 15, "PairTree DFlash2, tree budget 15"}, + std::tuple{pairtree, false, 1, 31, "PairTree DFlash2, tree budget 31"}, + std::tuple{pairtree, true, 4, 0, "Serial DFlash2 (serial-only"}, + std::tuple{plain, false, 1, 0, "--dflash2-pairtree"}}) { + std::string note; + auto backend = create_dflash2_fixture( + dir, 0, 2, std::nullopt, serial_only, decodes, ¬e); + ASSERT_TRUE(backend.ok()); + EXPECT_NE(note.find(says), std::string::npos) << note; + auto& executor = static_cast(*backend.get().executor); + ASSERT_TRUE(executor.initialize()); + EXPECT_EQ(Peer::tree_budget(executor), budget); + EXPECT_EQ(executor.stats().tree_budget, static_cast(budget)); + EXPECT_EQ(Peer::loaded(executor, method), budget > 0); + } + std::string note; + EXPECT_EQ( + create_dflash2_fixture(pairtree, 0, 2, 15, true, 4, ¬e).error(), + rt::Error::InvalidArgument); + EXPECT_NE(note.find("dflash_serial_only"), std::string::npos) << note; + EXPECT_EQ( + create_dflash2_fixture(plain, 0, 2, 15, false, 4, ¬e).error(), + rt::Error::InvalidProgram); + EXPECT_NE(note.find("--dflash2-pairtree"), std::string::npos) << note; + EXPECT_EQ( + create_dflash2_fixture(pairtree, 0, 2, 0, true).error(), rt::Error::Ok); +} + +struct Script { + std::vector tokens; // per session, every turn + std::vector states; // Peer::state after every execution + llm::CudaDFlashStats stats; + std::vector calls; + bool pairtree_loaded = false; +}; + +// `sessions` sessions, every third one sampled, decode at least 10 tokens. +// Then the first is closed and a new session opened (its cells are reused), +// every other session takes a second turn, and the open sessions decode at +// least 6 more tokens. Last, the first open one is resubmitted from at least +// three tokens back and the open sessions decode at least 4 more. +void run_script( + const std::string& dir, + int sessions, + std::optional tree_budget, + bool serial_only, + Script& result) { + auto backend = + create_dflash2_fixture(dir, 0, sessions, tree_budget, serial_only); + ASSERT_TRUE(backend.ok()); + auto& executor = static_cast(*backend.get().executor); + ASSERT_TRUE(executor.initialize()); + struct Slot { + b::SessionId sid; + Tokens history; // prompts and outputs + std::size_t fed = 0; // history tokens in the session's context + std::size_t goal = 0; // history size to stop at + }; + constexpr std::size_t kRoom = 44; // below max_session_tokens + auto prompt = [](int seed) { + Tokens tokens; + for (int k = 0; k < 2 + seed % 5; ++k) { + tokens.push_back(1 + (17 * seed + 5 * k) % 1000); + } + return tokens; + }; + std::vector slots; + auto open = [&](int seed) { + auto owner = executor.open_session(); + ASSERT_TRUE(owner); + const b::SamplingParams sampled{0.8f, 0.9f, 7}; + executor.set_sampling( + *owner, seed % 3 == 2 ? sampled : b::SamplingParams{}, 42 + seed); + slots.push_back({*owner, prompt(seed)}); + }; + auto decode = [&](std::size_t tokens) { + for (auto& slot : slots) { + slot.goal = std::min(kRoom, slot.history.size() + tokens); + } + for (;;) { + b::BatchInput batch; + std::vector fed; + for (auto& slot : slots) { + if (slot.history.size() < slot.goal) { + batch.inputs.push_back(input( + slot.sid, + static_cast(slot.fed), + Tokens(slot.history.begin() + slot.fed, slot.history.end()))); + slot.fed = slot.history.size(); + fed.push_back(&slot); + } + } + if (fed.empty()) { + return; + } + b::BatchOutput out; + ASSERT_TRUE(executor.execute(batch, out)); + ASSERT_EQ(out.outputs.size(), fed.size()); + for (std::size_t i = 0; i < fed.size(); ++i) { + ASSERT_TRUE(out.outputs[i]); + const auto& tokens = out.outputs[i]->tokens; + ASSERT_FALSE(tokens.empty()); + fed[i]->history.insert( + fed[i]->history.end(), tokens.begin(), tokens.end()); + // The last output is fed with the next input. + fed[i]->fed = fed[i]->history.size() - 1; + } + result.states.push_back(Peer::state(executor)); + } + }; + for (int i = 0; i < sessions; ++i) { + ASSERT_NO_FATAL_FAILURE(open(i)); + } + ASSERT_NO_FATAL_FAILURE(decode(10)); + result.tokens.push_back(slots.front().history); + executor.close_session(slots.front().sid); + slots.erase(slots.begin()); + ASSERT_NO_FATAL_FAILURE(open(sessions)); + for (std::size_t i = 1; i < slots.size(); i += 2) { + auto& history = slots[i].history; + if (history.size() + 4 < kRoom) { + history.insert(history.end(), {3, 5, 8, 13}); + } + } + ASSERT_NO_FATAL_FAILURE(decode(6)); + // A rewind: one session continues from an earlier position. + auto& history = slots.front().history; + history.resize(std::min(history.size() - 3, kRoom - 8)); + slots.front().fed = history.size() - 1; + history.insert(history.end(), {21, 34}); + ASSERT_NO_FATAL_FAILURE(decode(4)); + for (const auto& slot : slots) { + result.tokens.push_back(slot.history); + } + result.stats = executor.stats(); + result.calls = Peer::method_calls(executor); + result.pairtree_loaded = Peer::loaded(executor, llm::kDFlash2PairTreeMethod); +} + +// The PairTree export shares every program but draft_forward_pairtree with +// the plain one, and the fixture exports both in one process, so their +// kernels match (the exporter checks it). Serial-only and a zero budget on it +// must then be bit-identical to Serial DFlash2 on the plain export: tokens, +// committed hidden rows, both caches' cells after every execution, the stats +// and the target forwards called. PairTree DFlash2 must not be. +TEST(CudaDFlash2Native, SerialOnlyRunsThePairTreeExportAsThePlainOne) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string root = pairtree_fixture(); + // The random fixture accepts almost nothing; the controlled one accepts + // most proposals. + for (const auto& [plain, pairtree, sessions] : + {std::tuple{root + "/pairtree/plain", root + "/pairtree", 1}, + std::tuple{root + "/pairtree/plain", root + "/pairtree", 4}, + std::tuple{root + "/pairtree/plain", root + "/pairtree", 16}, + std::tuple{ + root + "/pairtree/controlled_plain", + root + "/pairtree/controlled", + 1}, + std::tuple{ + root + "/pairtree/controlled_plain", + root + "/pairtree/controlled", + 4}, + std::tuple{ + root + "/pairtree/controlled_plain", + root + "/pairtree/controlled", + 16}}) { + SCOPED_TRACE(pairtree + ", " + std::to_string(sessions) + " sessions"); + Script expected; + ASSERT_NO_FATAL_FAILURE( + run_script(plain, sessions, std::nullopt, false, expected)); + EXPECT_EQ(expected.stats.tree_budget, 0u); + for (const auto& [budget, serial_only] : + {std::pair{std::optional{}, true}, + std::pair{std::optional{0}, false}}) { + Script actual; + ASSERT_NO_FATAL_FAILURE( + run_script(pairtree, sessions, budget, serial_only, actual)); + EXPECT_EQ(actual.tokens, expected.tokens); + ASSERT_EQ(actual.states.size(), expected.states.size()); + for (std::size_t i = 0; i < actual.states.size(); ++i) { + ASSERT_EQ(actual.states[i], expected.states[i]) << "execution " << i; + } + static_assert(sizeof(llm::CudaDFlashStats) % sizeof(std::uint64_t) == 0); + EXPECT_EQ( + std::memcmp(&actual.stats, &expected.stats, sizeof(actual.stats)), 0); + ASSERT_EQ(actual.calls.size(), expected.calls.size()); + for (std::size_t i = 0; i < actual.calls.size(); ++i) { + EXPECT_EQ(actual.calls[i].name, expected.calls[i].name); + EXPECT_EQ(actual.calls[i].calls, expected.calls[i].calls); + } + EXPECT_FALSE(actual.pairtree_loaded); + } + EXPECT_EQ(expected.stats.tree_cycles, 0u); + if (pairtree.find("controlled") != std::string::npos) { + EXPECT_GT(expected.stats.accepted, 0u); + // The comparison tells the modes apart. + Script tree; + ASSERT_NO_FATAL_FAILURE( + run_script(pairtree, sessions, std::nullopt, false, tree)); + EXPECT_GT(tree.stats.tree_cycles, 0u); + EXPECT_TRUE(tree.pairtree_loaded); + EXPECT_NE(tree.states, expected.states); + } + std::printf( + "serial-only, %s, %d sessions: %zu executions, %llu cycles, %llu " + "accepted\n", + pairtree.c_str(), + sessions, + expected.states.size(), + static_cast(expected.stats.cycles), + static_cast(expected.stats.accepted)); + } +} + +// The compiled draft_forward_pairtree returns draft_forward's candidate ids +// and scores, bit for bit, on the same inputs and draft cache. +TEST(CudaDFlash2Native, PairTreeDraftMethodExtendsDraftForward) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + for (const char* fixture : {"/pairtree", "/pairtree/controlled"}) { + SCOPED_TRACE(fixture); + auto backend = create_dflash2_fixture( + std::string(pairtree_fixture()) + fixture, 0, 2, 1); + ASSERT_TRUE(backend.ok()); + auto& executor = static_cast(*backend.get().executor); + ASSERT_TRUE(executor.initialize()); + const auto sid = executor.open_session(); + ASSERT_TRUE(sid); + executor.set_sampling(*sid, {}, 0); + b::BatchOutput out; + ASSERT_TRUE(executor.execute({{input(*sid, 0, {1, 7, 2, 7})}}, out)); + ASSERT_TRUE(Peer::pending(executor, *sid)); + const auto plain = Peer::draft_outputs(executor, *sid, "draft_forward"); + const auto tree = + Peer::draft_outputs(executor, *sid, llm::kDFlash2PairTreeMethod); + ASSERT_FALSE(plain.first.empty()); + EXPECT_EQ(tree.first, plain.first); + ASSERT_EQ(tree.second.size(), plain.second.size()); + EXPECT_EQ( + std::memcmp( + tree.second.data(), + plain.second.data(), + plain.second.size() * sizeof(float)), + 0); + } +} + +// When the tree builder refuses a round's candidate tables, the round runs +// Serial DFlash2 from draft_forward_pairtree's outputs: the same tokens as +// Serial DFlash2 on finite tables, and only its batch fails on a NaN score, +// as Serial DFlash2 does. The fixture overstates every candidate's logit, so +// the builder refuses every table. +TEST(CudaDFlash2Native, RefusedTreeTablesFallBackToSerialDFlash2) { + if (!pairtree_fixture()) { + GTEST_SKIP() << "Set ET_MUSE_DFLASH2_TINY_DIR to the --dflash2 fixture"; + } + rt::runtime_init(); + const std::string dir = + std::string(pairtree_fixture()) + "/pairtree/controlled_refused"; + Generation serial, tree; + const std::vector prompts{{1, 7}, {2, 8}}; + ASSERT_NO_FATAL_FAILURE(generate(dir, {3, 0, {}, prompts, 16}, serial)); + ASSERT_NO_FATAL_FAILURE(generate(dir, {3, 3, {}, prompts, 16}, tree)); + EXPECT_EQ(tree.tokens, serial.tokens); + EXPECT_EQ(tree.stats.failed_batches, 0u); + EXPECT_EQ(tree.stats.tree_cycles, 0u); + EXPECT_GT(tree.stats.tree_fallback_cycles, 0u); + EXPECT_EQ(tree.stats.tree_fallback_cycles, tree.stats.cycles); + EXPECT_EQ(tree.stats.accepted, serial.stats.accepted); + EXPECT_GT(serial.stats.accepted, 0u); + // A sampled session's chain (4 rows) leaves no node for a greedy session + // in this export's 4-row forward, so the two take separate rounds; the + // greedy one falls back, and the sampled one counts as neither. + const b::SamplingParams sampled{0.8f, 0.9f, 7}; + Generation mixed_serial, mixed; + ASSERT_NO_FATAL_FAILURE( + generate(dir, {3, 0, {{}, sampled}, prompts, 16}, mixed_serial)); + ASSERT_NO_FATAL_FAILURE( + generate(dir, {3, 3, {{}, sampled}, prompts, 16}, mixed)); + EXPECT_EQ(mixed.tokens, mixed_serial.tokens); + EXPECT_EQ(mixed.stats.failed_batches, 0u); + EXPECT_EQ(mixed.stats.tree_cycles, 0u); + EXPECT_GT(mixed.stats.tree_fallback_cycles, 0u); + EXPECT_LT(mixed.stats.tree_fallback_cycles, mixed.stats.cycles); + for (const int budget : {0, 3}) { + SCOPED_TRACE(budget); + auto backend = create_dflash2_fixture(dir, 3, 4, budget); + ASSERT_TRUE(backend.ok()); + auto& executor = static_cast(*backend.get().executor); + ASSERT_TRUE(executor.initialize()); + const auto healthy = executor.open_session(); + const auto bad = executor.open_session(); + ASSERT_TRUE(healthy && bad); + executor.set_sampling(*healthy, {}, 0); + executor.set_sampling(*bad, {}, 0); + b::BatchOutput out; + EXPECT_FALSE(executor.execute( + {{input(*healthy, 0, {2, 8}), input(*bad, 0, {2, 9})}}, out)); + ASSERT_EQ(out.outputs.size(), 2u); + EXPECT_FALSE(out.outputs[0]); + EXPECT_FALSE(out.outputs[1]); + EXPECT_TRUE(Peer::poisoned(executor, *bad)); + const auto stats = executor.stats(); + EXPECT_EQ(stats.failed_batches, 1u); + EXPECT_EQ(stats.tree_cycles, 0u); + EXPECT_EQ(stats.tree_fallback_cycles, budget ? 2u : 0u); + executor.close_session(*healthy); + executor.close_session(*bad); + const auto fresh = executor.open_session(); + ASSERT_TRUE(fresh); + executor.set_sampling(*fresh, {}, 0); + ASSERT_TRUE(executor.execute({{input(*fresh, 0, {1, 7})}}, out)); + ASSERT_TRUE(out.outputs.at(0)); + const auto& tokens = out.outputs[0]->tokens; + EXPECT_FALSE(tokens.empty()); + EXPECT_TRUE(std::all_of( + tokens.begin(), tokens.end(), [](b::Token t) { return t == 7; })); + } +} + TEST(CudaDFlash2Native, NonFiniteScoreFailsOnlyTheScheduledBatch) { const char* dir = std::getenv("ET_MUSE_DFLASH2_TINY_DIR"); if (!dir || !*dir) { 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 bd859abba79..ba6c46266de 100644 --- a/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py +++ b/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py @@ -11,12 +11,29 @@ The original fixture has vocabulary 256, 128 tapped hidden columns, a 16-token block, 32-token steps, and four owners. With `--dflash2`, export a quantized -GGUF with the full vocabulary and a controlled model under `controlled/` -for testing per-owner acceptance. Use `--dflash2 controlled` to export just -the latter fixture. +GGUF with the full vocabulary (static target forwards of 1 and 4 tokens) and a +controlled model under `controlled/` for testing per-owner acceptance. Under +`pairtree/`, both are exported again with `draft_forward_pairtree` and a wider +shape for trees: static forwards of 1, 4 and 32 tokens, 40-token steps and +1024 cells (the controlled one in `pairtree/controlled/`, without its NaN +row). `pairtree/controlled_refused/` is the controlled fixture with +`draft_forward_pairtree` in its own shape, NaN row included, whose candidate +logits are overstated so that PairTree DFlash2 refuses every finite table +too. `pairtree/four/` and `pairtree/four_controlled/` are the two wide +PairTree exports again with four draft owners per round, a 64-token static +forward and a 96-token context. Use `--dflash2 controlled` or +`--dflash2 pairtree` to export just one of these. + +`pairtree/plain/` and `pairtree/controlled_plain/` are the two wide PairTree +exports without `draft_forward_pairtree`. Each pair is exported in one +process, so it also shares the in-process autotune picks (Triton configs and +split-K launch parameters); the exporter checks that every common method is +the same compiled library, and Serial DFlash2 must then produce bit-identical +results on both. """ import argparse +import unittest.mock from dataclasses import replace from pathlib import Path @@ -65,8 +82,21 @@ def export(output_dir: Path) -> None: print(f"Wrote {output_dir}/model.pte and aoti_cuda_blob.ptd") -def export_dflash2(output_dir: Path) -> None: - """Export the quantized GGUF fixture through the CUDA batching exporter.""" +def export_dflash2( + output_dir: Path, + pairtree: bool = False, + wide: bool | None = None, + owners: int = 2, +) -> None: + """Export the quantized GGUF fixture through the CUDA batching exporter. + + ``pairtree`` adds draft_forward_pairtree and nothing else. A ``wide`` + export, the default with ``pairtree``, has a 32-token static forward for + two sessions' trees of up to 15 nodes and a cell pool for 16 sessions of + 48 tokens; with four draft ``owners``, a 64-token one for four and a + 96-token context. + """ + wide = pairtree if wide is None else wide from executorch.examples.models.muse_glimmer.loaders.dflash_loader import ( load_dflash_gguf, ) @@ -75,9 +105,12 @@ def export_dflash2(output_dir: Path) -> None: ) torch.manual_seed(73) + output_dir.mkdir(parents=True, exist_ok=True) checkpoint = output_dir / "draft.gguf" write_dflash_gguf(checkpoint) - draft, dc = load_dflash_gguf(str(checkpoint), backend="cuda", max_seq_len=64) + draft, dc = load_dflash_gguf( + str(checkpoint), backend="cuda", max_seq_len=96 if owners > 2 else 64 + ) config = replace( TINY_CONFIG, dim=dc.dim, @@ -88,7 +121,7 @@ def export_dflash2(output_dir: Path) -> None: ffn_dim_multiplier=1.0, vocab_size=dc.vocab_size, global_attn_cfg="[16,0]", - max_seq_len=48, + max_seq_len=96 if owners > 2 else 48, ) target = MuseGlimmerModel(config).to(torch.bfloat16).eval() target.activation_dtype = torch.bfloat16 @@ -96,16 +129,38 @@ def export_dflash2(output_dir: Path) -> None: target, config, str(output_dir), - max_step_tokens=32, - max_cells=512, - forward_sizes=(1, 4), + # A step must be wider than the widest static forward. + max_step_tokens=(72 if owners > 2 else 40) if wide else 32, + max_cells=1024 if wide else 512, + forward_sizes=( + ((1, 4, 32, 64) if owners > 2 else (1, 4, 32)) if wide else (1, 4) + ), dflash_draft=draft, - max_draft_owners=2, + max_draft_owners=owners, + dflash_pairtree=pairtree, ) -def export_controlled_dflash2(output_dir: Path) -> None: - """Export distinct acceptance lengths for sessions anchored at tokens 7 and 8.""" +def export_controlled_dflash2( + output_dir: Path, + pairtree: bool = False, + wide: bool | None = None, + refuse_trees: bool = False, + owners: int = 2, +) -> None: + """Export distinct acceptance lengths for sessions anchored at tokens 7 and 8. + + A ``wide`` export, the default with ``pairtree``, has a 32-token static + forward, room for 16 sessions, and only finite scores: PairTree DFlash2 + refuses a table with a non-finite score in any row, not only in the + walked ones. ``pairtree`` adds draft_forward_pairtree and nothing else. + With four draft ``owners``, a wide export adds a 64-token static + forward and has a 96-token context. ``refuse_trees`` raises the + candidates' logits above the full vocabulary's logsumexp, so PairTree + DFlash2 refuses every table; Serial + DFlash2 runs on the same, shifted, candidates. + """ + wide = pairtree if wide is None else wide from executorch.examples.models.muse_glimmer.tests.dflash_controlled_fixture import ( initialize_controlled_weights, RejectByAnchor, @@ -119,7 +174,7 @@ def export_controlled_dflash2(output_dir: Path) -> None: n_kv_heads=1, head_dim=16, vocab_size=200096, - max_seq_len=48, + max_seq_len=96 if owners > 2 else 48, global_attn_cfg="[4,0]", output_multiplier=1.0, output_soft_cap_temp=64.0, @@ -150,19 +205,81 @@ def export_controlled_dflash2(output_dir: Path) -> None: with torch.no_grad(): # Anchor 9 selects a non-finite predecessor row. Anchors 7 and 8 stay healthy. target.embed_tokens.weight[9, 2] = 2 - draft.candidate_selector.predecessor_codebook.weight[9, 0] = float("nan") + if not wide: + draft.candidate_selector.predecessor_codebook.weight[9, 0] = float("nan") draft.candidate_selector = RejectByAnchor(draft.candidate_selector) output_dir.mkdir(parents=True, exist_ok=True) - export_cuda_batching( - target.to(torch.bfloat16), - config, - str(output_dir), - max_step_tokens=32, - max_cells=512, - forward_sizes=(1, 4), - dflash_draft=draft.to(torch.bfloat16), - max_draft_owners=2, + from executorch.examples.models.muse_glimmer.source_transformations import ( + cuda as cuda_transformations, + ) + + top_candidates = cuda_transformations.dflash2_top_candidates + + def overstated_top_candidates(logits, k): + values, ids = top_candidates(logits, k) + return values + 30.0, ids + + with unittest.mock.patch.object( + cuda_transformations, + "dflash2_top_candidates", + overstated_top_candidates if refuse_trees else top_candidates, + ): + export_cuda_batching( + target.to(torch.bfloat16), + config, + str(output_dir), + # A step must be wider than the widest static forward. + max_step_tokens=(72 if owners > 2 else 40) if wide else 32, + max_cells=1024 if wide else 512, + forward_sizes=( + ((1, 4, 32, 64) if owners > 2 else (1, 4, 32)) if wide else (1, 4) + ), + dflash_draft=draft.to(torch.bfloat16), + max_draft_owners=owners, + dflash_pairtree=pairtree, + ) + + +def compiled_libraries(pte: Path) -> dict[str, list[str]]: + """Each CUDA method's compiled libraries, by their content-hash keys.""" + from executorch.backends.cuda.cuda_weight_collector import decode_cuda_aoti_metadata + from executorch.exir._serialize._program import deserialize_pte_binary + + program = deserialize_pte_binary(pte.read_bytes()).program + return { + plan.name: [ + variant.so_blob_key + for delegate in plan.delegates + for variant in decode_cuda_aoti_metadata( + bytes(program.backend_delegate_data[delegate.processed.index].data) + ).variants + ] + for plan in program.execution_plan + if plan.delegates + } + + +def check_pinned(plain: Path, pairtree: Path) -> None: + """Raise unless `pairtree` adds only draft_forward_pairtree to `plain`. + + Serial DFlash2 is bit-identical on the two only when every common method + is the same compiled library, which two export processes need not pick. + """ + from executorch.examples.models.muse_glimmer.export.export_dflash import ( + DFLASH2_PAIRTREE_METHOD, + ) + + expected = compiled_libraries(plain / "model.pte") + actual = compiled_libraries(pairtree / "model.pte") + differ = sorted( + name + for name in set(expected) | set(actual) + if name != DFLASH2_PAIRTREE_METHOD and expected.get(name) != actual.get(name) ) + if differ or DFLASH2_PAIRTREE_METHOD not in actual: + raise RuntimeError( + f"pair not pinned: {plain} and {pairtree} differ in {differ}" + ) def main() -> None: @@ -172,14 +289,35 @@ def main() -> None: "--dflash2", nargs="?", const="all", - choices=("all", "controlled"), - help="Export both DFlash2 fixtures (default for this flag), or only controlled/", + choices=("all", "controlled", "pairtree"), + help="Export every DFlash2 fixture (default for this flag), or only " + "controlled/ or pairtree/", ) args = parser.parse_args() if args.dflash2: if args.dflash2 == "all": export_dflash2(args.output_dir) - export_controlled_dflash2(args.output_dir / "controlled") + if args.dflash2 in ("all", "controlled"): + export_controlled_dflash2(args.output_dir / "controlled") + if args.dflash2 in ("all", "pairtree"): + output_dir = args.output_dir / "pairtree" + export_dflash2(output_dir, pairtree=True) + export_dflash2(output_dir / "plain", wide=True) + export_controlled_dflash2(output_dir / "controlled", pairtree=True) + export_controlled_dflash2(output_dir / "controlled_plain", wide=True) + export_controlled_dflash2( + output_dir / "controlled_refused", + pairtree=True, + wide=False, + refuse_trees=True, + ) + check_pinned(output_dir / "plain", output_dir) + check_pinned(output_dir / "controlled_plain", output_dir / "controlled") + # Four draft owners per round: several sampled chains per round. + export_dflash2(output_dir / "four", pairtree=True, owners=4) + export_controlled_dflash2( + output_dir / "four_controlled", pairtree=True, owners=4 + ) else: export(args.output_dir) From bf17cf94befcb90a41fb0430b40c6f6f3adc20f3 Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Tue, 1 Dec 2026 07:55:17 -0800 Subject: [PATCH 2/3] [MLX] Support PairTree DFlash2 for Muse Glimmer Run PairTree DFlash2 tree verification on the MLX backend with the same options as CUDA: a `--dflash2-pairtree` export runs it at B=15 unless `--dflash_tree_budget` or `--dflash_serial_only` says otherwise. A round verifies greedy sessions' trees and sampled sessions' Serial DFlash2 chains in one target forward; each session accepts by its own rule, and a refused candidate table runs the round as Serial DFlash2. Serial-only and Serial DFlash2 never load `draft_forward_pairtree` and run as on a plain export; PairTree mode loads only `draft_forward_pairtree`, so the draft's constants are materialized once. The default MLX batched target cache now takes tree steps: a step's tokens are stored after each session's history, attend through an explicit mask (history within each layer's window by tree position, plus in-step ancestors), and `retain_tree` compacts the accepted path next to the history. Sequences may interleave in a tree step, and a pending tree is settled row by row before other verbs, with the shared tree_step.h rules. The MLX export adds `draft_forward_pairtree` with `--dflash2-pairtree`, and the launcher, factory and export no longer restrict PairTree DFlash2 to CUDA. Review order: MLXSequenceCache.h, MLXBatchedCache.h, mlx_executor.cpp, tests, then the relaxed shared checks. On an Apple M5 Max, PairTree B=15 decodes 1.12x faster than Serial DFlash2 over the 160-prompt MT-Bench/GSM8K/HumanEval set with one session, and 1.14x to 1.19x with two to four sessions, some sampled; B=31 is slower there (0.91x) because a 32-row MLX verify costs about 1.4x a 16-row one. Hence the MLX default B=15; CUDA's single-session default is B=31. Authored with AI assistance (Metamate). --- backends/mlx/runtime/MLXBatchedCache.h | 211 ++++++++- backends/mlx/runtime/MLXSequenceCache.h | 278 ++++++++++- backends/mlx/test/mlx_batch_control_test.cpp | 443 ++++++++++++++++++ .../models/muse-glimmer/BATCHING_SERVING.md | 53 +++ examples/models/muse-glimmer/README.md | 3 + .../muse-glimmer/export/export_dflash.py | 67 ++- .../muse-glimmer/runtime/backend_factory.cpp | 7 +- .../muse-glimmer/runtime/backend_factory.h | 2 +- .../muse-glimmer/runtime/mlx_executor.cpp | 404 ++++++++++++++-- .../muse-glimmer/runtime/mlx_executor.h | 23 +- .../runtime/runners/batching_bootstrap.cpp | 2 +- .../muse-glimmer/serving/serve_batching.py | 6 +- examples/models/muse-glimmer/tests/README.md | 16 +- .../tests/export_mlx_dflash_fixture.py | 68 ++- .../tests/mlx_dflash_native_test.cpp | 426 ++++++++++++++++- .../muse-glimmer/tests/test_mlx_offgraph.py | 52 ++ .../muse-glimmer/tests/test_serve_batching.py | 9 +- 17 files changed, 1971 insertions(+), 99 deletions(-) diff --git a/backends/mlx/runtime/MLXBatchedCache.h b/backends/mlx/runtime/MLXBatchedCache.h index dee6ffa374d..f338d2cf87b 100644 --- a/backends/mlx/runtime/MLXBatchedCache.h +++ b/backends/mlx/runtime/MLXBatchedCache.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,7 @@ #include "MLXSequenceCache.h" #include +#include namespace executorch { namespace backends { @@ -60,6 +62,7 @@ class MLXBatchedCache : public cache::Cache, } bool declare_step(const std::vector& seq_ids) override { + resolve_tree(); if (seq_ids.empty() || seq_ids.size() > static_cast(std::numeric_limits::max())) { return false; @@ -111,6 +114,60 @@ class MLXBatchedCache : public cache::Cache, return true; } + bool supports_tree_steps() const override { + return !geometry_.dflash_block_size.has_value(); + } + + // Each sequence's tokens form one tree rooted at the first of them; the + // sequences may interleave. + bool declare_tree_step( + const std::vector& seq_ids, + const std::vector& parents) override { + if (!supports_tree_steps() || parents.size() != seq_ids.size()) { + return false; + } + // A malformed tree shape leaves a pending tree pending. + std::set seen; + for (size_t i = 0; i < parents.size(); ++i) { + const bool first = seen.insert(seq_ids[i]).second; + if (parents[i] < -1 || parents[i] >= static_cast(i) || + (parents[i] >= 0 && seq_ids[parents[i]] != seq_ids[i]) || + (parents[i] < 0) != first) { + return false; + } + } + if (!declare_step(seq_ids)) { + return false; + } + step_parents_ = parents; + return true; + } + + bool retain_tree(const std::vector& keep) override { + if (!tree_) { + return false; + } + const auto kept = cache::kept_paths(tree_->parents, keep); + if (!kept) { + return false; + } + std::vector> local; + for (const TreeRow& row : tree_->rows) { + local.push_back(row.local(*kept)); + // The step's forward must be complete before any row changes. + if (!complete(row) || + !rows_.at(row.seq_id).can_retain_tree(row.base, local.back())) { + return false; + } + } + for (size_t i = 0; i < tree_->rows.size(); ++i) { + const TreeRow& row = tree_->rows[i]; + rows_.at(row.seq_id).retain_tree(row.base, local[i]); + } + invalidate_step(); + return true; + } + std::optional max_seqs() const override { return std::nullopt; } @@ -125,6 +182,7 @@ class MLXBatchedCache : public cache::Cache, std::optional seq_clone(int32_t src, std::optional upto) override { + resolve_tree(); auto it = rows_.find(src); if (it == rows_.end() || it->second.length() == 0) { return std::nullopt; @@ -148,6 +206,7 @@ class MLXBatchedCache : public cache::Cache, } bool seq_rm(int32_t seq_id) override { + resolve_tree(); if (rows_.erase(seq_id) == 0) { return false; } @@ -162,6 +221,7 @@ class MLXBatchedCache : public cache::Cache, } bool rewind(int32_t seq_id, int position) override { + resolve_tree(); if (!can_rewind(seq_id, position) || !rows_.at(seq_id).rewind(position)) { return false; } @@ -171,7 +231,23 @@ class MLXBatchedCache : public cache::Cache, int pos(int32_t seq_id) const override { auto it = rows_.find(seq_id); - return it == rows_.end() ? 0 : it->second.length(); + if (it == rows_.end()) { + return 0; + } + if (tree_) { + // As the next verb will leave it. A tree is pending once its forward + // has run on every layer (CellCache: once its first layer placed it); + // then that is its root and unbranched chain, before that nothing of + // it, since resolution drops an unfinished step. + for (const TreeRow& row : tree_->rows) { + if (row.seq_id == seq_id && complete(row)) { + const auto kept = cache::kept_paths( + tree_->parents, cache::unbranched_paths(tree_->parents)); + return row.base + static_cast(row.local(*kept).size()); + } + } + } + return it->second.length(); } Tensor attend( @@ -183,6 +259,9 @@ class MLXBatchedCache : public cache::Cache, float scale, StreamOrDevice s) override { validate_step(positions, q, k, v); + if (!step_parents_.empty()) { + return attend_tree(layer, positions, q, k, v, scale, s); + } const auto query_spans = make_query_spans(layer, q.shape(2)); const auto& queries = query_spans.empty() ? spans_ : query_spans; @@ -245,6 +324,120 @@ class MLXBatchedCache : public cache::Cache, int group_at; }; + // One sequence of a placed tree step: its length before the step and its + // step indices, in step order. + struct TreeRow { + int32_t seq_id; + int base; + std::vector steps; + // The positions within `steps` of the kept step indices. + std::vector local(const std::vector& kept) const { + std::vector result; + for (size_t j = 0; j < steps.size(); ++j) { + if (kept[steps[j]]) { + result.push_back(static_cast(j)); + } + } + return result; + } + }; + // A placed tree step, until retain_tree resolves it. + struct Tree { + std::vector rows; + std::vector parents; + }; + + bool complete(const TreeRow& row) const { + return rows_.at(row.seq_id).length() == + row.base + static_cast(row.steps.size()); + } + + // Settles a pending tree before another verb, row by row: each tree keeps + // its root and the single path below it, up to the first branch. A row that + // cannot keep it drops its tree, and an unfinished forward is dropped. + void resolve_tree() { + if (!tree_) { + return; + } + const auto kept = cache::kept_paths( + tree_->parents, cache::unbranched_paths(tree_->parents)); + using sequence::detail::require; + for (const TreeRow& row : tree_->rows) { + auto& sequence = rows_.at(row.seq_id); + if (!complete(row)) { + require(sequence.abandon_forward(), "tree: cannot drop the forward"); + } else if (!sequence.retain_tree(row.base, row.local(*kept))) { + require( + sequence.retain_tree(row.base, {}), "tree: cannot drop the tree"); + } + } + invalidate_step(); + } + + Tensor attend_tree( + int layer, + const std::vector& positions, + const Tensor& q, + const Tensor& k, + const Tensor& v, + float scale, + StreamOrDevice s) { + if (q.shape(2) != step_length()) { + throw std::invalid_argument("attend: a tree step queries every token"); + } + if (!placed_) { + Tree tree{{}, step_parents_}; + for (const auto& group : groups_) { + const int32_t seq_id = spans_[group.front()].seq_id; + TreeRow row{seq_id, rows_.at(seq_id).length(), {}}; + for (size_t index : group) { + const Span& span = spans_[index]; + for (int j = 0; j < span.q_len; ++j) { + row.steps.push_back(span.at + j); + } + } + tree.rows.push_back(std::move(row)); + } + tree_ = std::move(tree); + step_pos_ = positions; + declared_ = false; + placed_ = true; + } + std::vector outs; + outs.reserve(groups_.size()); + std::vector local(step_parents_.size(), -1); + for (size_t g = 0; g < groups_.size(); ++g) { + const TreeRow& row = tree_->rows[g]; + std::vector parents; + parents.reserve(row.steps.size()); + for (size_t j = 0; j < row.steps.size(); ++j) { + local[row.steps[j]] = static_cast(j); + const int32_t parent = step_parents_[row.steps[j]]; + parents.push_back(parent < 0 ? -1 : local[parent]); + } + outs.push_back(rows_.at(row.seq_id) + .attend_tree( + layer, + parents, + gather(q, groups_[g], spans_, s), + gather(k, groups_[g], spans_, s), + gather(v, groups_[g], spans_, s), + scale, + s)); + } + if (groups_.size() != spans_.size()) { + std::vector ordered; + ordered.reserve(spans_.size()); + for (const Span& span : spans_) { + ordered.push_back( + tokens(outs[span.group], span.group_at, span.q_len, s)); + } + return ::mlx::core::concatenate(ordered, 2, s); + } + return outs.size() == 1 ? std::move(outs.front()) + : ::mlx::core::concatenate(outs, 2, s); + } + static Tensor tokens(const Tensor& t, int off, int len, StreamOrDevice s) { if (off == 0 && len == t.shape(2)) { return t; @@ -351,6 +544,18 @@ class MLXBatchedCache : public cache::Cache, } bool check_positions(const std::vector& positions) const { + if (!step_parents_.empty()) { + for (const Span& span : spans_) { + const int base = rows_.at(span.seq_id).length(); + for (int i = span.at; i < span.at + span.q_len; ++i) { + const int32_t parent = step_parents_[i]; + if (positions[i] != (parent < 0 ? base : positions[parent] + 1)) { + return false; + } + } + } + return true; + } std::map ends; size_t at = 0; for (const Span& span : spans_) { @@ -398,6 +603,8 @@ class MLXBatchedCache : public cache::Cache, spans_.clear(); groups_.clear(); step_pos_.clear(); + step_parents_.clear(); + tree_.reset(); declared_ = false; placed_ = false; } @@ -408,6 +615,8 @@ class MLXBatchedCache : public cache::Cache, std::vector spans_; std::vector> groups_; std::vector step_pos_; + std::vector step_parents_; + std::optional tree_; bool declared_ = false; bool placed_ = false; }; diff --git a/backends/mlx/runtime/MLXSequenceCache.h b/backends/mlx/runtime/MLXSequenceCache.h index fc0719824df..8e02bd3a301 100644 --- a/backends/mlx/runtime/MLXSequenceCache.h +++ b/backends/mlx/runtime/MLXSequenceCache.h @@ -118,6 +118,32 @@ class AttentionLayer { const UpdateInfo& update, StreamOrDevice s, std::optional& mask) = 0; + + // Token-tree steps, see MLXSequenceCache::attend_tree. tree_window() is + // nullopt when unsupported, zero for full history, else the causal window. + virtual std::optional tree_window() const { + return std::nullopt; + } + virtual int tree_history_begin(int /*position*/) const { + throw std::logic_error("sequence: tree steps are unsupported"); + } + // Attends over [tree_history_begin(position), position + tokens). + virtual Tensor update_and_attend_tree( + int /*position*/, + const Tensor& /*q*/, + const KV& /*incoming*/, + float /*scale*/, + const UpdateInfo& /*update*/, + const Tensor& /*mask*/, + StreamOrDevice /*s*/) { + throw std::logic_error("sequence: tree steps are unsupported"); + } + virtual void retain_tree( + int /*position*/, + const std::vector& /*keep*/, + StreamOrDevice /*s*/) { + throw std::logic_error("sequence: tree steps are unsupported"); + } }; // Immutable shared factory for attention layers. Invoke the hook on the owner @@ -326,6 +352,35 @@ class Storage { ::mlx::core::concatenate({segments.head->v, segments.tail->v}, 2, s)}; } + // Moves position + keep[i] to position + i and ends at position + + // keep.size(). + void compact( + int position, + const std::vector& keep, + int required_begin, + StreamOrDevice s) { + const int n = static_cast(keep.size()); + bool moved = false; + for (int i = 0; i < n; ++i) { + detail::require( + keep[i] >= i && (i == 0 || keep[i] > keep[i - 1]) && + int64_t{position} + keep[i] < length_, + "storage: invalid compaction"); + moved = moved || keep[i] != i; + } + if (moved) { + const KV kv = *read(position, position + keep.back() + 1, s); + const ::mlx::core::array index( + keep.data(), ::mlx::core::Shape{n}, ::mlx::core::int32); + update( + position, + KV{::mlx::core::take(kv.k, index, 2, s), + ::mlx::core::take(kv.v, index, 2, s)}, + s); + } + rewind(position + n, required_begin); + } + private: int growth_target(int current, int needed) const { detail::require( @@ -494,6 +549,10 @@ class KVAttentionPolicy : public AttentionLayerFactory { StreamOrDevice s, std::optional& mask) const = 0; + virtual std::optional tree_window() const { + return std::nullopt; + } + protected: explicit KVAttentionPolicy(bool causal, bool history_updates = false) : is_causal(causal), allows_history_updates(history_updates) {} @@ -516,6 +575,9 @@ class Full final : public KVAttentionPolicy { int64_t required_slots(int capacity, int /*max_write*/) const override { return capacity; } + std::optional tree_window() const override { + return 0; + } Tensor update_and_attend( Storage& storage, int position, @@ -554,6 +616,9 @@ class SWA final : public KVAttentionPolicy { int64_t required_slots(int capacity, int max_write) const override { return std::min(capacity, int64_t{window_} + max_write - 1); } + std::optional tree_window() const override { + return window_; + } Tensor update_and_attend( Storage& storage, int position, @@ -788,6 +853,49 @@ class KVAttentionLayer final : public AttentionLayer { storage_ = std::move(staged); return output; } + std::optional tree_window() const override { + return policy_->tree_window(); + } + int tree_history_begin(int position) const override { + return policy_->required_history_begin(position); + } + Tensor update_and_attend_tree( + int position, + const Tensor& q, + const KV& incoming, + float scale, + const UpdateInfo& update, + const Tensor& mask, + StreamOrDevice s) override { + require(tree_window().has_value(), "sequence: tree steps are unsupported"); + Storage staged = storage_; + staged.update(position, incoming, s); + const KV kv = *staged.read(tree_history_begin(position), update.end, s); + Tensor output = ::mlx::core::fast::scaled_dot_product_attention( + q, + detail::cast_if_needed(kv.k, q.dtype(), s), + detail::cast_if_needed(kv.v, q.dtype(), s), + scale, + -1, + "", + mask, + std::nullopt, + false, + s); + require( + staged.length() == std::max(length(), update.end), + "sequence: tree step changed persistent growth"); + storage_ = std::move(staged); + return output; + } + void retain_tree(int position, const std::vector& keep, StreamOrDevice s) + override { + const int end = position + static_cast(keep.size()); + Storage staged = storage_; + staged.compact( + position, keep, end == 0 ? 0 : policy_->required_history_begin(end), s); + storage_ = std::move(staged); + } std::shared_ptr policy_; Storage storage_; @@ -976,6 +1084,7 @@ class MLXSequenceCache final : public cache::Cache, layer.attention->clear(); } cached_mask_.reset(); + tree_masks_.reset(); reset_forward(0); } @@ -1012,6 +1121,100 @@ class MLXSequenceCache final : public cache::Cache, l, positions.front(), q, incoming, update, scale, s); } + // One layer of a token-tree step appended at length(). parents[i] is token + // i's parent within the step, or -1 for a root. A token sits one position + // past its parent and sees its history window and its in-step ancestors, + // never its siblings. K/V are stored densely in step order until + // retain_tree moves the kept tokens, strictly increasing step indices, to + // follow the history and drops the rest. + Tensor attend_tree( + int layer, + const std::vector& parents, + const Tensor& q, + const Tensor& k, + const Tensor& v, + float scale, + StreamOrDevice s) { + using sequence::detail::require; + const size_t l = checked_layer(layer); + require( + k.ndim() > 2 && !parents.empty() && + parents.size() == static_cast(k.shape(2)), + "sequence: expected one parent per incoming K/V token"); + for (size_t i = 0; i < parents.size(); ++i) { + require( + parents[i] >= -1 && parents[i] < static_cast(i), + "sequence: a tree parent must precede its child"); + } + require( + layers_[l].attention->tree_window().has_value(), + "sequence: tree steps are unsupported"); + const sequence::KV incoming{k, v}; + const auto update = + layers_[l].attention->validate(length_, length_, q, incoming, scale); + require(!update.overwrite, "sequence: a tree step must append"); + const Tensor mask = tree_mask(l, length_, parents, s); + return attend_validated(l, length_, q, incoming, update, scale, s, &mask); + } + + // Drops what an unfinished append-only (tree) forward already wrote, back + // to length(). + bool abandon_forward() { + if (!pending_end_) { + return true; + } + for (const auto& layer : layers_) { + if (layer.visited && !layer.attention->can_rewind(length_)) { + return false; + } + } + for (auto& layer : layers_) { + if (layer.visited) { + layer.attention->rewind(length_); + } + } + tree_masks_.reset(); + reset_forward(length_); + return true; + } + + bool can_retain_tree(int position, const std::vector& keep) const { + if (pending_end_ || position < 0 || position > length_ || + !can_rewind(position) || + !can_rewind(position + static_cast(keep.size()))) { + return false; + } + for (size_t i = 0; i < keep.size(); ++i) { + if (keep[i] < 0 || keep[i] >= length_ - position || + (i > 0 && keep[i] <= keep[i - 1])) { + return false; + } + } + return true; + } + + bool retain_tree( + int position, + const std::vector& keep, + StreamOrDevice s = {}) { + if (!can_retain_tree(position, keep)) { + return false; + } + // Staged copies, so a failure leaves every layer as it was. + std::vector> staged; + staged.reserve(layers_.size()); + for (const auto& layer : layers_) { + staged.push_back(layer.attention->clone(length_)); + staged.back()->retain_tree(position, keep, s); + } + for (size_t l = 0; l < layers_.size(); ++l) { + layers_[l].attention = std::move(staged[l]); + } + tree_masks_.reset(); + reset_forward(position + static_cast(keep.size())); + return true; + } + protected: void* face(cache::FaceId id) override { return cache::expose(this, id); @@ -1048,6 +1251,59 @@ class MLXSequenceCache final : public cache::Cache, } } + // Visibility for one tree step and window, shared by every layer using it: + // a history column test on the device, then the [T, T] ancestor block. + Tensor tree_mask( + size_t l, + int position, + const std::vector& parents, + StreamOrDevice s) { + using namespace ::mlx::core; + const Stream stream = to_stream(s); + const int window = *layers_[l].attention->tree_window(); + const int begin = layers_[l].attention->tree_history_begin(position); + if (!tree_masks_ || tree_masks_->position != position || + tree_masks_->parents != parents) { + tree_masks_ = TreeMasks{position, parents, {}}; + } + for (const auto& entry : tree_masks_->masks) { + if (entry.window == window && entry.begin == begin && + entry.stream == stream) { + return entry.mask; + } + } + const int T = static_cast(parents.size()); + const int history = position - begin; + std::vector depth(T, 0); + std::vector first(T, 0); + std::vector ancestors(static_cast(T) * T, 0); + for (int i = 0; i < T; ++i) { + depth[i] = parents[i] < 0 ? 0 : depth[parents[i]] + 1; + // Window rule by tree position: key >= position + depth - window + 1. + const int oldest = window ? position + depth[i] - window + 1 : begin; + first[i] = std::max(0, oldest - begin); + for (int a = i; a >= 0; a = parents[a]) { + ancestors[static_cast(i) * T + a] = + position + depth[a] >= oldest; + } + } + Tensor mask = array(ancestors.data(), Shape{T, T}, bool_); + if (history > 0) { + check_allocation_bounded({T, history + T}, bool_, "tree mask"); + mask = concatenate( + {greater_equal( + reshape(arange(history, int32, stream), {1, history}, stream), + reshape(array(first.data(), Shape{T}, int32), {T, 1}, stream), + stream), + mask}, + 1, + stream); + } + tree_masks_->masks.push_back( + {window, begin, stream, reshape(mask, {1, 1, T, history + T}, stream)}); + return tree_masks_->masks.back().mask; + } + Tensor attend_validated( size_t l, int position, @@ -1055,7 +1311,8 @@ class MLXSequenceCache final : public cache::Cache, const sequence::KV& incoming, const sequence::AttentionLayer::UpdateInfo& update, float scale, - StreamOrDevice s) { + StreamOrDevice s, + const Tensor* tree_mask = nullptr) { using sequence::detail::require; auto& layer = layers_[l]; require( @@ -1070,8 +1327,11 @@ class MLXSequenceCache final : public cache::Cache, !pending_end_ || *pending_end_ == update.end, "sequence: unequal persistent ends"); } - Tensor output = layer.attention->update_and_attend( - position, q, incoming, scale, update, s, cached_mask_); + Tensor output = tree_mask + ? layer.attention->update_and_attend_tree( + position, q, incoming, scale, update, *tree_mask, s) + : layer.attention->update_and_attend( + position, q, incoming, scale, update, s, cached_mask_); if (!update.overwrite) { pending_end_ = update.end; layer.visited = true; @@ -1089,9 +1349,21 @@ class MLXSequenceCache final : public cache::Cache, return static_cast(layer); } + struct TreeMasks { + struct Entry { + int window, begin; + ::mlx::core::Stream stream; + Tensor mask; + }; + int position; + std::vector parents; + std::vector masks; + }; + int capacity_; std::vector layers_; std::optional cached_mask_; + std::optional tree_masks_; size_t visited_count_ = 0; int length_ = 0; std::optional pending_end_; diff --git a/backends/mlx/test/mlx_batch_control_test.cpp b/backends/mlx/test/mlx_batch_control_test.cpp index 409cf30edb8..6507634e7fb 100644 --- a/backends/mlx/test/mlx_batch_control_test.cpp +++ b/backends/mlx/test/mlx_batch_control_test.cpp @@ -1261,6 +1261,449 @@ TEST_P(MLXBatchedCacheTest, RetainedBoundaryAndOlderSnapshot) { EXPECT_TRUE(batch_->seq_rm(*snapshot)); } +// Token-tree steps: every token computes what the plain chain of its +// root-to-token path computes, on every layer, and retain_tree keeps exactly +// that path for the following steps. +class MLXTreeStepTest : public MLXBatchedCacheTest { + protected: + array rows(const array& t, const std::vector& index) { + std::vector parts; + for (int i : index) { + parts.push_back(span(t, i, 1)); + } + return ::mlx::core::concatenate(parts, 2); + } + + // One forward over every layer, each with its own Q/K/V. + std::vector forward( + MLXCache& c, + const std::vector& positions, + const std::vector& q, + const std::vector& k, + const std::vector& v) { + std::vector out; + for (size_t l = 0; l < q.size(); ++l) { + out.push_back(c.attend( + static_cast(l), positions, q[l], k[l], v[l], kScale, s)); + } + return out; + } + + std::vector pick( + const std::vector& t, + const std::vector& index) { + std::vector out; + for (const auto& x : t) { + out.push_back(rows(x, index)); + } + return out; + } + + std::vector layers_randn(int layers, int T) { + std::vector out; + for (int l = 0; l < layers; ++l) { + out.push_back(randn(T)); + } + return out; + } + + // Two rounds of one tree per owner; history_a is long enough to wrap rings. + void check_tree_matches_paths(const CacheArgs& args, int history_a) { + ASSERT_NO_FATAL_FAILURE(create_cache(args)); + const int L = static_cast(args.geometry.layers.size()); + const int32_t a = *batch_->seq_new(); + const int32_t b = *batch_->seq_new(); + const std::vector owners{a, b}; + // Each owner's committed tokens, as indices into `tokens`, in order. + struct Token { + std::vector q, k, v; + }; + std::vector> committed(2); + auto token = [&](const std::vector& q, + const std::vector& k, + const std::vector& v, + int i) { + Token t; + for (int l = 0; l < L; ++l) { + t.q.push_back(span(q[l], i, 1)); + t.k.push_back(span(k[l], i, 1)); + t.v.push_back(span(v[l], i, 1)); + } + return t; + }; + const std::vector history{history_a, 3}; + for (int o = 0; o < 2; ++o) { + const int T = history[o]; + auto q = layers_randn(L, T), k = layers_randn(L, T), + v = layers_randn(L, T); + std::vector positions(T); + std::iota(positions.begin(), positions.end(), 0); + for (int i = 0; i < T; ++i) { + committed[o].push_back(token(q, k, v, i)); + } + ASSERT_TRUE(batch_->declare_step(std::vector(T, owners[o]))); + forward(*attention_, positions, q, k, v); + } + // A solo cache holding `owner`'s committed tokens, then `extra`. + auto replay = [&](size_t owner, const std::vector& extra) { + auto solo = + std::make_unique(args.geometry, args.config); + std::vector all = committed[owner]; + all.insert(all.end(), extra.begin(), extra.end()); + std::vector out; + for (size_t i = 0; i < all.size(); ++i) { + out = forward( + *solo, {static_cast(i)}, all[i].q, all[i].k, all[i].v); + } + return out; + }; + const std::vector> local{ + {-1, 0, 0, 1, 1, 2, 4}, {-1, 0, 1, 0}}; + const std::vector> kept{{0, 2, 5}, {0, 3}}; + for (int round = 0; round < 2; ++round) { + std::vector seq_ids, parents, positions; + std::vector> paths; + std::vector bases; + for (size_t o = 0; o < owners.size(); ++o) { + const int base = static_cast(seq_ids.size()); + bases.push_back(base); + const int length = static_cast(committed[o].size()); + for (size_t i = 0; i < local[o].size(); ++i) { + const int32_t parent = local[o][i]; + std::vector path = + parent < 0 ? std::vector{} : paths[base + parent]; + path.push_back(base + static_cast(i)); + paths.push_back(path); + seq_ids.push_back(owners[o]); + parents.push_back(parent < 0 ? -1 : base + parent); + positions.push_back(length + static_cast(path.size()) - 1); + } + } + const int T = static_cast(seq_ids.size()); + auto q = layers_randn(L, T), k = layers_randn(L, T), + v = layers_randn(L, T); + ASSERT_TRUE(batch_->declare_tree_step(seq_ids, parents)); + const auto out = forward(*attention_, positions, q, k, v); + for (int i = 0; i < T; ++i) { + const size_t owner = seq_ids[i] == a ? 0 : 1; + std::vector chain; + for (int p : paths[i]) { + chain.push_back(token(q, k, v, p)); + } + const auto want = replay(owner, chain); + for (int l = 0; l < L; ++l) { + EXPECT_TRUE(allclose(span(out[l], i, 1), want[l], 1e-2f)) + << "round " << round << " token " << i << " layer " << l; + } + } + // A kept set that is not one root-to-node path per owner is refused, + // leaving the tree for a valid resolution. + EXPECT_FALSE(batch_->retain_tree({0, 1, 2})); + EXPECT_FALSE(batch_->retain_tree({1})); + std::vector keep; + for (size_t o = 0; o < 2; ++o) { + for (int i : kept[o]) { + keep.push_back(bases[o] + i); + committed[o].push_back(token(q, k, v, bases[o] + i)); + } + } + ASSERT_TRUE(batch_->retain_tree(keep)); + EXPECT_FALSE(batch_->retain_tree(keep)); + for (size_t o = 0; o < 2; ++o) { + EXPECT_EQ( + batch_->pos(owners[o]), static_cast(committed[o].size())); + } + } + // An ordinary decode step continues each kept path. + auto q = layers_randn(L, 2), k = layers_randn(L, 2), v = layers_randn(L, 2); + ASSERT_TRUE(batch_->declare_step({a, b})); + const auto next = + forward(*attention_, {batch_->pos(a), batch_->pos(b)}, q, k, v); + for (size_t o = 0; o < 2; ++o) { + const auto want = replay(o, {token(q, k, v, static_cast(o))}); + for (int l = 0; l < L; ++l) { + EXPECT_TRUE( + allclose(span(next[l], static_cast(o), 1), want[l], 1e-2f)) + << "owner " << o << " layer " << l; + } + } + } +}; + +TEST_P(MLXTreeStepTest, FullHistoryTreeMatchesPaths) { + check_tree_matches_paths(flat_config(64, 1, H, D, kHalf), 5); +} + +// A window of 3 hides history from deeper tree tokens, by tree position. Ten +// history tokens and two rounds wrap the 14-slot ring and move kept tokens +// across the wrap. +TEST_P(MLXTreeStepTest, WindowedTreeMatchesPaths) { + check_tree_matches_paths(ring_config(64, 3, 12, H, D, kHalf), 10); +} + +// Full and windowed layers in one forward share the step and its masks. +TEST_P(MLXTreeStepTest, MixedLayersTreeMatchesPaths) { + auto args = flat_config(64, 3, H, D, kHalf); + args.geometry.layers[1].policy = {cache::LayerPolicy::Kind::Ring, 3}; + args.config.max_write = 12; + check_tree_matches_paths(args, 10); +} + +// Another verb settles an unretained tree: each tree keeps its root and the +// single path below it, so the next step never attends a sibling. +TEST_P(MLXTreeStepTest, ImplicitResolutionDropsBranches) { + const auto args = flat_config(64, 1, H, D, kHalf); + ASSERT_NO_FATAL_FAILURE(create_cache(args)); + const int32_t a = *batch_->seq_new(); + const int32_t b = *batch_->seq_new(); + array hq = randn(6), hk = randn(6), hv = randn(6); + step({a, a, a, b, b, b}, {0, 1, 2, 0, 1, 2}, hq, hk, hv); + // a: root with two siblings. b: root -> child -> two grandchildren. + array q = randn(7), k = randn(7), v = randn(7); + ASSERT_TRUE(batch_->declare_tree_step( + {a, a, a, b, b, b, b}, {-1, 0, 0, -1, 3, 4, 4})); + attention_->attend(0, {3, 4, 4, 3, 4, 5, 5}, q, k, v, kScale, s); + // A pending tree reports its sequences as resolution will leave them. + EXPECT_EQ(batch_->pos(a), 4); + EXPECT_EQ(batch_->pos(b), 5); + array q1 = randn(2), k1 = randn(2), v1 = randn(2); + ASSERT_TRUE(batch_->declare_step({a, b})); + EXPECT_EQ(batch_->pos(a), 4); + EXPECT_EQ(batch_->pos(b), 5); + EXPECT_FALSE(batch_->retain_tree({0})); + array next = attention_->attend(0, {4, 5}, q1, k1, v1, kScale, s); + const std::vector> kept{{0}, {3, 4}}; + for (int o = 0; o < 2; ++o) { + auto solo = make_cache(args); + alone( + solo, + {0, 1, 2}, + span(hq, 3 * o, 3), + span(hk, 3 * o, 3), + span(hv, 3 * o, 3)); + std::vector p(kept[o].size()); + std::iota(p.begin(), p.end(), 3); + alone(solo, p, rows(q, kept[o]), rows(k, kept[o]), rows(v, kept[o])); + const int at = 3 + static_cast(kept[o].size()); + EXPECT_TRUE(allclose( + span(next, o, 1), + alone(solo, {at}, span(q1, o, 1), span(k1, o, 1), span(v1, o, 1)), + 1e-2f)) + << "owner " << o; + } + // Retaining no node of a tree drops all of it. + ASSERT_TRUE(batch_->declare_tree_step({a, a, b}, {-1, 0, -1})); + attention_->attend(0, {5, 6, 6}, randn(3), randn(3), randn(3), kScale, s); + ASSERT_TRUE(batch_->retain_tree({2})); + EXPECT_EQ(batch_->pos(a), 5); + EXPECT_EQ(batch_->pos(b), 7); +} + +// A per-sequence cache treats a tree as pending once its forward has run on +// every layer, where CellCache does from its first placed layer; pos() +// matches each cache's next verb, and resolution drops an unfinished step. +TEST_P(MLXTreeStepTest, PendingTreePositionFollowsTheForward) { + if (GetParam() == cache::kind::kBatchedCell) { + GTEST_SKIP() << "cells are placed at the first layer"; + } + ASSERT_NO_FATAL_FAILURE(create_cache(flat_config(64, 2, H, D, kHalf))); + const int32_t a = *batch_->seq_new(); + ASSERT_TRUE(batch_->declare_tree_step({a, a, a}, {-1, 0, 1})); + attention_->attend(0, {0, 1, 2}, randn(3), randn(3), randn(3), kScale, s); + EXPECT_EQ(batch_->pos(a), 0); + attention_->attend(1, {0, 1, 2}, randn(3), randn(3), randn(3), kScale, s); + EXPECT_EQ(batch_->pos(a), 3); + ASSERT_TRUE(batch_->retain_tree({0, 1})); + EXPECT_EQ(batch_->pos(a), 2); +} + +// Sequences may interleave in a tree step: every token matches its +// root-to-node path run alone, and the kept paths follow each history. +TEST_P(MLXTreeStepTest, InterleavedTreesMatchPaths) { + const auto args = flat_config(64, 1, H, D, kHalf); + ASSERT_NO_FATAL_FAILURE(create_cache(args)); + const int32_t a = *batch_->seq_new(); + const int32_t b = *batch_->seq_new(); + array hq = randn(6), hk = randn(6), hv = randn(6); + step({a, a, a, b, b, b}, {0, 1, 2, 0, 1, 2}, hq, hk, hv); + // a: root 0 with children 2 and 4. b: root 1 with child 3, grandchild 5. + const std::vector seq_ids{a, b, a, b, a, b}; + const std::vector parents{-1, -1, 0, 1, 0, 3}; + array q = randn(6), k = randn(6), v = randn(6); + ASSERT_TRUE(batch_->declare_tree_step(seq_ids, parents)); + array out = attention_->attend(0, {3, 3, 4, 4, 4, 5}, q, k, v, kScale, s); + auto solo = [&](int owner, const std::vector& path) { + auto c = make_cache(args); + alone( + c, + {0, 1, 2}, + span(hq, 3 * owner, 3), + span(hk, 3 * owner, 3), + span(hv, 3 * owner, 3)); + std::vector p(path.size()); + std::iota(p.begin(), p.end(), 3); + return alone(c, p, rows(q, path), rows(k, path), rows(v, path)); + }; + const std::vector> paths{ + {0}, {1}, {0, 2}, {1, 3}, {0, 4}, {1, 3, 5}}; + for (int i = 0; i < 6; ++i) { + const auto& path = paths[i]; + const array want = solo(seq_ids[i] == a ? 0 : 1, path); + EXPECT_TRUE(allclose( + span(out, i, 1), + span(want, static_cast(path.size()) - 1, 1), + 1e-2f)) + << "token " << i; + } + ASSERT_TRUE(batch_->retain_tree({0, 4, 1, 3})); + EXPECT_EQ(batch_->pos(a), 5); + EXPECT_EQ(batch_->pos(b), 5); + array q1 = randn(2), k1 = randn(2), v1 = randn(2); + ASSERT_TRUE(batch_->declare_step({b, a})); + array next = attention_->attend(0, {5, 5}, q1, k1, v1, kScale, s); + const std::vector> kept{{0, 4}, {1, 3}}; + for (int o = 0; o < 2; ++o) { + auto c = make_cache(args); + alone( + c, + {0, 1, 2}, + span(hq, 3 * o, 3), + span(hk, 3 * o, 3), + span(hv, 3 * o, 3)); + alone(c, {3, 4}, rows(q, kept[o]), rows(k, kept[o]), rows(v, kept[o])); + const int row = o == 0 ? 1 : 0; + EXPECT_TRUE(allclose( + span(next, row, 1), + alone(c, {5}, span(q1, row, 1), span(k1, row, 1), span(v1, row, 1)), + 1e-2f)) + << "owner " << o; + } +} + +// seq_clone, seq_rm and rewind settle a pending tree as declare_step does. +TEST_P(MLXTreeStepTest, EveryVerbResolvesThePendingTree) { + ASSERT_NO_FATAL_FAILURE(create_cache(flat_config(64, 1, H, D, kHalf))); + const int32_t a = *batch_->seq_new(); + const int32_t b = *batch_->seq_new(); + step({a, a, b, b}, {0, 1, 0, 1}, randn(4), randn(4), randn(4)); + // a: root with two children; b: a chain of three. + auto pending = [&] { + const int pa = batch_->pos(a), pb = batch_->pos(b); + ASSERT_TRUE( + batch_->declare_tree_step({a, a, a, b, b, b}, {-1, 0, 0, -1, 3, 4})); + attention_->attend( + 0, + {pa, pa + 1, pa + 1, pb, pb + 1, pb + 2}, + randn(6), + randn(6), + randn(6), + kScale, + s); + }; + ASSERT_NO_FATAL_FAILURE(pending()); + const auto clone = batch_->seq_clone(b, std::nullopt); + ASSERT_TRUE(clone); + EXPECT_FALSE(batch_->retain_tree({0})); + EXPECT_EQ(batch_->pos(a), 3); + EXPECT_EQ(batch_->pos(b), 5); + EXPECT_EQ(batch_->pos(*clone), 5); + ASSERT_TRUE(batch_->seq_rm(*clone)); + + ASSERT_NO_FATAL_FAILURE(pending()); + const int32_t c = *batch_->seq_new(); + step({c}, {0}, randn(1), randn(1), randn(1)); + EXPECT_EQ(batch_->pos(a), 4); + EXPECT_EQ(batch_->pos(b), 8); + ASSERT_NO_FATAL_FAILURE(pending()); + ASSERT_TRUE(batch_->seq_rm(c)); + EXPECT_FALSE(batch_->retain_tree({0})); + EXPECT_EQ(batch_->pos(a), 5); + EXPECT_EQ(batch_->pos(b), 11); + + ASSERT_NO_FATAL_FAILURE(pending()); + ASSERT_TRUE(batch_->rewind(a, 5)); + EXPECT_FALSE(batch_->retain_tree({0})); + EXPECT_EQ(batch_->pos(a), 5); + EXPECT_EQ(batch_->pos(b), 14); +} + +// A tree step whose forward stopped before its last layer is dropped: the +// sequence continues from its history alone. +TEST_P(MLXTreeStepTest, UnfinishedTreeForwardIsDropped) { + if (GetParam() == cache::kind::kBatchedCell) { + GTEST_SKIP() << "cells are placed at the first layer"; + } + const auto args = flat_config(64, 2, H, D, kHalf); + ASSERT_NO_FATAL_FAILURE(create_cache(args)); + const int32_t a = *batch_->seq_new(); + const int L = 2; + auto hq = layers_randn(L, 3), hk = layers_randn(L, 3), + hv = layers_randn(L, 3); + ASSERT_TRUE(batch_->declare_step({a, a, a})); + forward(*attention_, {0, 1, 2}, hq, hk, hv); + ASSERT_TRUE(batch_->declare_tree_step({a, a, a}, {-1, 0, 0})); + attention_->attend(0, {3, 4, 4}, randn(3), randn(3), randn(3), kScale, s); + auto q = layers_randn(L, 1), k = layers_randn(L, 1), v = layers_randn(L, 1); + ASSERT_TRUE(batch_->declare_step({a})); + EXPECT_EQ(batch_->pos(a), 3); + const auto next = forward(*attention_, {3}, q, k, v); + auto solo = std::make_unique(args.geometry, args.config); + forward(*solo, {0, 1, 2}, hq, hk, hv); + const auto want = forward(*solo, {3}, q, k, v); + for (int l = 0; l < L; ++l) { + EXPECT_TRUE(allclose(next[l], want[l], 1e-2f)) << "layer " << l; + } + EXPECT_EQ(batch_->pos(a), 4); +} + +TEST_P(MLXTreeStepTest, MalformedTreesAreRefused) { + ASSERT_NO_FATAL_FAILURE(create_cache(flat_config(64, 1, H, D, kHalf))); + const int32_t a = *batch_->seq_new(); + const int32_t b = *batch_->seq_new(); + EXPECT_FALSE(batch_->retain_tree({})); + EXPECT_FALSE(batch_->declare_tree_step({a, a}, {-1, 1})); + EXPECT_FALSE(batch_->declare_tree_step({a, b}, {-1, 0})); + EXPECT_FALSE(batch_->declare_tree_step({a, a}, {-1})); + EXPECT_FALSE(batch_->declare_tree_step({a, a}, {-1, -1})); + EXPECT_FALSE(batch_->declare_tree_step({a, b, a}, {-1, 0, -1})); + // An ordinary step resolves no tree. + step({a}, {0}, randn(1), randn(1), randn(1)); + EXPECT_FALSE(batch_->retain_tree({0})); + // Repeated keep indices are refused and leave the tree pending. + ASSERT_TRUE(batch_->declare_tree_step({a, a, a}, {-1, 0, 0})); + attention_->attend(0, {1, 2, 2}, randn(3), randn(3), randn(3), kScale, s); + EXPECT_FALSE(batch_->retain_tree({0, 0})); + EXPECT_FALSE(batch_->retain_tree({0, 2, 2})); + EXPECT_EQ(batch_->pos(a), 2); + // A malformed tree step resolves nothing either. + EXPECT_FALSE(batch_->declare_tree_step({a, a}, {-1})); + EXPECT_FALSE(batch_->declare_tree_step({a, b}, {-1, 0})); + EXPECT_FALSE(batch_->declare_tree_step({a, a}, {-1, -1})); + EXPECT_FALSE(batch_->declare_tree_step({a, b, a}, {-1, 0, -1})); + ASSERT_TRUE(batch_->retain_tree({0, 2})); + EXPECT_EQ(batch_->pos(a), 3); + // Discarding a whole tree returns the sequence to its anchor. + ASSERT_TRUE(batch_->declare_tree_step({a, a, a}, {-1, 0, 0})); + attention_->attend(0, {3, 4, 4}, randn(3), randn(3), randn(3), kScale, s); + ASSERT_TRUE(batch_->retain_tree({})); + EXPECT_EQ(batch_->pos(a), 3); +} + +INSTANTIATE_TEST_SUITE_P( + CacheKinds, + MLXTreeStepTest, + ::testing::Values( + cache::kind::kBatched, + cache::kind::kBatchedSequence, + cache::kind::kBatchedCell), + [](const ::testing::TestParamInfo& info) { + if (info.param == cache::kind::kBatchedCell) { + return "BatchedCell"; + } + return info.param == cache::kind::kBatched ? "Batched" + : "BatchedSequence"; + }); + INSTANTIATE_TEST_SUITE_P( CacheKinds, MLXBatchedCacheTest, diff --git a/examples/models/muse-glimmer/BATCHING_SERVING.md b/examples/models/muse-glimmer/BATCHING_SERVING.md index 7514e072e7f..f57958320a7 100644 --- a/examples/models/muse-glimmer/BATCHING_SERVING.md +++ b/examples/models/muse-glimmer/BATCHING_SERVING.md @@ -187,6 +187,59 @@ every greedy session of such a round); sampled sessions count in neither; for a tree, `proposed` counts its nodes and a bonus is an accepted path that ends at a leaf. +### PairTree DFlash2 on MLX + +The MLX export takes the same flag: `--backend mlx --use-offgraph-kv-cache +--dflash2-pairtree` adds `draft_forward_pairtree`, and the `.pte` stores the +draft's weights once (about 0.1 MB more for the 30B export). A worker started +with `--dflash` on it runs PairTree DFlash2 at B = 15, or at +`--dflash_tree_budget B`; `--dflash_serial_only` and budget 0 behave as on +CUDA, and the worker prints the mode the same way. Serial-only on the 30B +export matched Serial DFlash2 on a separately exported plain program bit for +bit. The MLX target forward is dynamic, so no forward sizes are needed; a +round's trees and chains share at most 256 rows and the exported prefill +width. + +MLX rounds mix greedy and sampled sessions as CUDA's do: a round with a greedy +session drafts every session with one `draft_forward_pairtree` call and +verifies them in one target forward. Each sampled session's chain takes its +full `proposals + 1` rows, greedy sessions share the rows the chains leave, and +a round of sampled sessions only runs Serial DFlash2. Owners keep Serial +DFlash2's order. On MLX each session attends separately, and moving a sampled +session ahead of the greedy ones changed none of its tokens on the tiny +fixtures or the 30B export. + +In PairTree mode the MLX worker runs every draft call, tree or not, through +`draft_forward_pairtree`, which drafts as `draft_forward` does, and never loads +`draft_forward`: each MLX method materializes its own constants, and the two +draft methods reference 3.5 GB each on the 30B export. Draft calls outside tree +rounds, such as rounds of sampled sessions only, then also compute the unused +logsumexp. Serial DFlash2 and serial-only load only `draft_forward`, so they +run exactly as on a plain export. A `draft_forward_pairtree` whose inputs or +outputs do not match `draft_forward` counts as absent: the default runs Serial +DFlash2, and an explicit budget fails. The MLX executor keeps no +`CudaDFlashStats` counterpart. + +The default MLX target cache keeps one history per session. A tree step stores +its tokens after that history and attends with an explicit mask: each token +sees its history, within a sliding layer's window counted from its own tree +position, and its ancestors in the step. After the forward, the accepted path +moves next to the history and the other branches are dropped. Sessions may +interleave in a tree step, as in the cell cache. The cell layout +(`batched-cell`) runs the shared cell-cache tree step. + +The default budget follows the target's verify cost per row. For the 17 GB +Muse Glimmer 30B target with the DFlash2 Q4_K_M draft, one session: + +| backend | hardware | verify cost, 32 vs 16 rows | default B | +|---|---|---|---| +| MLX | Apple M5 Max | about 1.4x | 15 | +| CUDA | RTX 5090 | about 1.0x | 31 | + +B = 15 verifies as many rows as Serial DFlash2's 15 proposals, so on the +M5 Max its acceptance gain is not spent on a wider verify; B = 31 accepts more +but its wider verify costs more than it gains there. + ## Build On Apple Silicon, run the Make target from the ExecuTorch checkout: diff --git a/examples/models/muse-glimmer/README.md b/examples/models/muse-glimmer/README.md index e0559da3fcd..bbb2927891b 100644 --- a/examples/models/muse-glimmer/README.md +++ b/examples/models/muse-glimmer/README.md @@ -335,6 +335,9 @@ chains in the same rounds; `--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). +On MLX, a `--backend mlx --dflash2-pairtree` export runs PairTree DFlash2 +the same way, with B = 15 by default; see +[PairTree DFlash2 on MLX](BATCHING_SERVING.md#pairtree-dflash2-on-mlx). Choose concurrency and prefix-cache limits to fit available memory. Prefix snapshots are disabled by default; omit `--prefix-cache-entries` to disable them. diff --git a/examples/models/muse-glimmer/export/export_dflash.py b/examples/models/muse-glimmer/export/export_dflash.py index bd8679ae733..da8ff3da2d7 100644 --- a/examples/models/muse-glimmer/export/export_dflash.py +++ b/examples/models/muse-glimmer/export/export_dflash.py @@ -225,10 +225,8 @@ def export_dflash( mmproj loader and vision export contract to add ``vision_encoder``. """ validate_dflash_export_options(backend, use_offgraph_kv_cache) - if pairtree and not (backend == "cuda" and use_offgraph_kv_cache): - raise ValueError( - "--dflash2-pairtree requires --backend cuda --use-offgraph-kv-cache" - ) + if pairtree and not use_offgraph_kv_cache: + raise ValueError("--dflash2-pairtree requires --use-offgraph-kv-cache") # On CUDA only the cell layout takes tree steps; --kv-layout is CUDA's. if pairtree and backend == "cuda" and kv_layout != "cell": raise ValueError("--dflash2-pairtree on CUDA requires --kv-layout cell") @@ -358,6 +356,7 @@ def export_dflash( activation_dtype, max_vision_patches, **({"use_offgraph_kv_cache": True} if use_offgraph_kv_cache else {}), + **({"pairtree": True} if pairtree else {}), ) @@ -613,11 +612,13 @@ def _export_dflash_mlx( activation_dtype: torch.dtype, max_vision_patches: int, use_offgraph_kv_cache: bool = False, + pairtree: bool = False, ) -> None: """Export the MLX DFlash contract. Always ``embed_text`` + ``target_forward_from_embeddings`` + ``draft_forward``, - with ``vision_encoder`` appended when a vision tower is present. + with ``vision_encoder`` appended when a vision tower is present and + ``draft_forward_pairtree`` with ``pairtree``. """ import executorch.backends.mlx.custom_kernel_ops.gguf.patterns # noqa: F401 import executorch.backends.mlx.patterns # noqa: F401 @@ -776,25 +777,43 @@ def _export_dflash_mlx( else None ), ) + draft_inputs = ( + ( + torch.zeros((sample_owners, exported_block_size), dtype=torch.long), + torch.randn(1, 2, n_target * dim, dtype=activation_dtype), + draft_input_pos, + ) + + draft_extra + + proposal_inputs + ) + draft_dynamic_shapes = ( + ( + {0: owner_dim, 1: block_dim}, + {1: new_ctx_dim}, + draft_shapes, + ) + + ((draft_shapes,) if use_offgraph_kv_cache else ()) + + proposal_shapes + ) with common.BoundMethodForward(combined, combined.draft_forward), torch.no_grad(): draft_ep = export( - combined, - ( - torch.zeros((sample_owners, exported_block_size), dtype=torch.long), - torch.randn(1, 2, n_target * dim, dtype=activation_dtype), - draft_input_pos, - ) - + draft_extra - + proposal_inputs, - dynamic_shapes=( - {0: owner_dim, 1: block_dim}, - {1: new_ctx_dim}, - draft_shapes, - ) - + ((draft_shapes,) if use_offgraph_kv_cache else ()) - + proposal_shapes, - strict=True, + combined, draft_inputs, dynamic_shapes=draft_dynamic_shapes, strict=True ) + pairtree_ep = None + if pairtree: + print("=" * 60) + print(f"Exporting {DFLASH2_PAIRTREE_METHOD}...") + print("=" * 60) + with ( + common.BoundMethodForward(combined, combined.draft_forward_pairtree), + torch.no_grad(), + ): + pairtree_ep = export( + combined, + draft_inputs, + dynamic_shapes=draft_dynamic_shapes, + strict=True, + ) mutable_buffer_metadata = common.mutable_buffer_metadata(combined) del combined, target_model, draft_model @@ -815,6 +834,8 @@ def _export_dflash_mlx( "embed_text": embed_text_ep, "draft_forward": draft_ep, } + if pairtree_ep is not None: + methods[DFLASH2_PAIRTREE_METHOD] = pairtree_ep if vision_ep is not None: methods["vision_encoder"] = vision_ep partitioner = {name: [MLXPartitioner()] for name in methods} @@ -877,7 +898,7 @@ def _export_dflash_mlx( constant_methods=constant_methods, ) - del target_from_embeddings_ep, embed_text_ep, draft_ep, vision_ep + del target_from_embeddings_ep, embed_text_ep, draft_ep, pairtree_ep, vision_ep gc.collect() et_program = et_prog.to_executorch( @@ -1285,7 +1306,7 @@ def main() -> None: action="store_true", help="Also export draft_forward_pairtree, which adds the DFlash2 " "candidates' unary logits and logsumexp for PairTree DFlash2; " - "draft_forward is unchanged. A tree of B nodes for each of " + "draft_forward is unchanged. On CUDA, a tree of B nodes for each of " "--max-draft-owners sessions needs a static forward of at least " "owners * (B + 1) tokens in --forward-sizes.", ) diff --git a/examples/models/muse-glimmer/runtime/backend_factory.cpp b/examples/models/muse-glimmer/runtime/backend_factory.cpp index 2314eb34890..ffd266409d5 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.cpp +++ b/examples/models/muse-glimmer/runtime/backend_factory.cpp @@ -23,10 +23,9 @@ runtime::Result create_muse_glimmer_backend( const MuseGlimmerBackendConfig& config, std::string* note) { const char* refusal = nullptr; - if (config.dflash_tree_budget.value_or(0) && - !(config.backend == "cuda" && config.use_dflash)) { + if (config.dflash_tree_budget.value_or(0) && !config.use_dflash) { refusal = - "Muse Glimmer: PairTree DFlash2 (dflash_tree_budget) requires CUDA DFlash"; + "Muse Glimmer: PairTree DFlash2 (dflash_tree_budget) requires DFlash"; } else if (config.dflash_serial_only && !config.use_dflash) { refusal = "Muse Glimmer: dflash_serial_only requires DFlash"; } @@ -39,7 +38,7 @@ runtime::Result create_muse_glimmer_backend( } #if defined(EXECUTORCH_BUILD_MLX) if (config.backend == "mlx") { - return MuseGlimmerMLXExecutor::create(config); + return MuseGlimmerMLXExecutor::create(config, note); } #endif #if defined(EXECUTORCH_BUILD_CUDA) diff --git a/examples/models/muse-glimmer/runtime/backend_factory.h b/examples/models/muse-glimmer/runtime/backend_factory.h index 1b0b310c6ff..e07c22d58e2 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.h +++ b/examples/models/muse-glimmer/runtime/backend_factory.h @@ -27,7 +27,7 @@ struct MuseGlimmerBackendConfig { batching::Token bos_id = 200000; bool use_dflash = false; int dflash_n_draft = 0; // zero uses the exported maximum minus one - // PairTree DFlash2 node budget per session and round (CUDA); zero runs + // PairTree DFlash2 node budget per session and round; zero runs // Serial DFlash2, and nullopt picks the mode (resolve_dflash_mode). std::optional dflash_tree_budget; // Serial DFlash2 even on a --dflash2-pairtree program. diff --git a/examples/models/muse-glimmer/runtime/mlx_executor.cpp b/examples/models/muse-glimmer/runtime/mlx_executor.cpp index 672bf043517..b8369a7ad06 100644 --- a/examples/models/muse-glimmer/runtime/mlx_executor.cpp +++ b/examples/models/muse-glimmer/runtime/mlx_executor.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -67,6 +68,13 @@ struct MuseGlimmerMLXExecutor::DFlash { cache::BatchControl* ctl = nullptr; int block = 0, mask = 0, hidden = 0, context = 0, max_owners = 0; int verify_block = 0, selector_top_k = 0; + int tree_budget = 0, tree_rows = 0, tree_owners = 0; + // PairTree DFlash2 runs every draft call through its own method, whose + // first outputs are draft_forward's, so the worker loads one copy of the + // draft's constants. + const char* method() const { + return tree_budget ? kDFlash2PairTreeMethod : "draft_forward"; + } size_t row_bytes() const { return static_cast(hidden) * runtime::elementSize(activation_dtype); } @@ -90,7 +98,8 @@ MuseGlimmerMLXExecutor::MuseGlimmerMLXExecutor( MuseGlimmerMLXExecutor::~MuseGlimmerMLXExecutor() = default; runtime::Result MuseGlimmerMLXExecutor::create( - const MuseGlimmerBackendConfig& config) { + const MuseGlimmerBackendConfig& config, + std::string* note) { #if ET_HAS_EXCEPTIONS try { #endif @@ -101,7 +110,10 @@ runtime::Result MuseGlimmerMLXExecutor::create( config.image_limits.max_image_pixels <= 0 || config.image_limits.max_image_dimension <= 0 || config.dflash_n_draft < 0 || - (config.dflash_n_draft != 0 && !config.use_dflash)) { + ((config.dflash_n_draft != 0 || + config.dflash_tree_budget.value_or(0) != 0 || + config.dflash_serial_only) && + !config.use_dflash)) { return Error::InvalidArgument; } std::vector data_files; @@ -317,6 +329,8 @@ runtime::Result MuseGlimmerMLXExecutor::create( } else if (!tensor_abi(dl, aten::ScalarType::Float, {1, q, vocab})) { return Error::InvalidProgram; } + const int tree_rows = + static_cast(std::min(pairtree::kMaxRows, width)); cache::CacheGeometry dg; dg.dflash_block_size = static_cast(block); auto dc = cache_config; @@ -348,6 +362,9 @@ runtime::Result MuseGlimmerMLXExecutor::create( dflash->block = static_cast(block); dflash->verify_block = static_cast(verify_block); dflash->selector_top_k = static_cast(top_k); + dflash->tree_rows = tree_rows; + dflash->tree_owners = + static_cast(std::min(owners, tree_rows / 2)); dflash->mask = static_cast(*mask); dflash->hidden = static_cast(h); dflash->context = static_cast(c); @@ -371,6 +388,66 @@ runtime::Result MuseGlimmerMLXExecutor::create( if (!ctl) { return Error::InvalidType; } + std::string mode_note; + if (dflash) { + const int top_k = dflash->selector_top_k; + // A valid PairTree method takes draft_forward's inputs and returns its + // outputs plus the candidates' unary logits and logsumexp. Reading its + // metadata does not load it. + bool pairtree = top_k > 0 && names.count(kDFlash2PairTreeMethod) > 0; + if (pairtree) { + const auto dm = module->method_meta("draft_forward"); + const auto pm = module->method_meta(kDFlash2PairTreeMethod); + const auto same = [](const auto& a, const auto& b) { + return a.ok() && b.ok() && a->scalar_type() == b->scalar_type() && + std::equal( + a->sizes().begin(), + a->sizes().end(), + b->sizes().begin(), + b->sizes().end()); + }; + pairtree = dm.ok() && pm.ok() && check_mlx_backends(*pm) == Error::Ok && + pm->num_inputs() == dm->num_inputs() && pm->num_outputs() == 3; + for (size_t i = 0; pairtree && i < pm->num_inputs(); ++i) { + pairtree = same(pm->input_tensor_meta(i), dm->input_tensor_meta(i)); + } + for (size_t i = 0; pairtree && i < 2; ++i) { + pairtree = same(pm->output_tensor_meta(i), dm->output_tensor_meta(i)); + } + if (pairtree) { + const auto ids = dm->output_tensor_meta(0); + const auto extras = pm->output_tensor_meta(2); + pairtree = ids.ok() && extras.ok() && + tensor_abi(*extras, + aten::ScalarType::Float, + {ids->sizes()[0], ids->sizes()[1], top_k + 1}); + } + } + const auto mode = resolve_dflash_mode( + {config.dflash_tree_budget, + config.dflash_serial_only, + DFlashBackendKind::kMlx, + config.max_decode_sequences}, + {pairtree, ctl->supports_tree_steps(), dflash->tree_rows - 1}); + if (mode.error != Error::Ok) { + const auto refusal = std::string("MLX DFlash: ") + mode.reason + + " (a tree verify takes at most " + + std::to_string(dflash->tree_rows) + " rows)"; + ET_LOG(Error, "%s", refusal.c_str()); + if (note) { + *note = refusal; + } + return mode.error; + } + if (top_k) { + mode_note = + (mode.tree_budget ? "MLX DFlash: PairTree DFlash2, tree budget " + + std::to_string(mode.tree_budget) + : std::string("MLX DFlash: Serial DFlash2")) + + " (" + mode.reason + ")"; + } + dflash->tree_budget = mode.tree_budget; + } const auto seq_limit = ctl->max_seqs(); if (ctl->capacity() < cache_config.capacity || (seq_limit && config.max_sessions > *seq_limit)) { @@ -403,6 +480,12 @@ runtime::Result MuseGlimmerMLXExecutor::create( config.max_sessions)); executor->dflash_ = std::move(dflash); executor->target_taps_ = target_taps; + if (!mode_note.empty()) { + ET_LOG(Info, "%s", mode_note.c_str()); + if (note) { + *note = std::move(mode_note); + } + } return MuseGlimmerBackend{std::move(executor), spec}; #if ET_HAS_EXCEPTIONS } catch (const std::exception& error) { @@ -428,7 +511,7 @@ bool MuseGlimmerMLXExecutor::initialize() { } if (error == Error::Ok && dflash_) { error = batching::load_method_with_cache( - *module_, "draft_forward", kBackend, *dflash_->guard, options); + *module_, dflash_->method(), kBackend, *dflash_->guard, options); } if (error == Error::Ok) { error = embeddings_->initialize(*module_); @@ -739,8 +822,10 @@ bool MuseGlimmerMLXExecutor::draft( const std::vector& owners, const std::vector& anchors, int context_limit, - batching::BatchInput* verification) { + batching::BatchInput* verification, + TreeRound* tree) { const int b = dflash_->block; + const bool round = verification || tree; if (owners.empty() || owners.size() != anchors.size() || owners.size() > static_cast(dflash_->max_owners) || context_limit < 0 || context_limit > dflash_->context) { @@ -757,7 +842,7 @@ bool MuseGlimmerMLXExecutor::draft( const int count = std::min( context_limit, state.hidden.size() / dflash_->row_bytes()); if (start < 0 || start > spec_->max_context_length - b - count || - (verification && count * dflash_->row_bytes() != state.hidden.size())) { + (round && count * dflash_->row_bytes() != state.hidden.size())) { return false; } tokens[i * b] = anchors[i]; @@ -795,7 +880,7 @@ bool MuseGlimmerMLXExecutor::draft( } const int k = dflash_->selector_top_k; const int v = dflash_->verify_block; - const int proposals = verification ? v - 1 : 1; + const int proposals = round ? v - 1 : 1; std::vector inputs{ *token_tensor, *hidden_tensor, *position_tensor, *order_tensor}; TensorPtr proposal_tensor; @@ -805,8 +890,9 @@ bool MuseGlimmerMLXExecutor::draft( proposal_tensor = make_tensor_ptr({proposals}, std::move(proposal_rows)); inputs.emplace_back(*proposal_tensor); } - auto result = module_->execute("draft_forward", inputs); - if (!result.ok() || result->size() != (k ? 2 : 1) || + auto result = module_->execute(dflash_->method(), inputs); + if (!result.ok() || + result->size() != (k ? (dflash_->tree_budget ? 3 : 2) : 1) || !result->at(0).isTensor()) { return false; } @@ -830,6 +916,40 @@ bool MuseGlimmerMLXExecutor::draft( } candidate_ids = logits.const_data_ptr(); candidate_scores = scores.const_data_ptr(); + if (tree) { + if (!result->at(2).isTensor()) { + return false; + } + const auto extras = result->at(2).toTensor(); + if (extras.dim() != 3 || extras.size(0) != owners.size() || + extras.size(1) != proposals || extras.size(2) != k + 1 || + extras.scalar_type() != aten::ScalarType::Float || + !dense_tensor(extras)) { + return false; + } + tree->trees.clear(); + for (size_t i = 0; i < owners.size(); ++i) { + if (sessions_.at(owners[i]).sampling->temperature != 0) { + tree->trees.emplace_back(); // its chain follows below + continue; + } + const size_t row = i * proposals; + auto nodes = pairtree::build( + {candidate_ids + row * k, + candidate_scores + row * k * k, + extras.const_data_ptr() + row * (k + 1), + proposals, + k}, + tree->budgets[i]); + if (!nodes || nodes->empty()) { + // Serial DFlash2 verifies this round, and reports a non-finite + // score on its own path as it always does. + tree->trees.clear(); + break; + } + tree->trees.push_back(std::move(*nodes)); + } + } } else if ( logits.dim() != 3 || logits.size(0) != 1 || logits.size(1) != q || logits.size(2) != spec_->vocab_size || @@ -845,49 +965,70 @@ bool MuseGlimmerMLXExecutor::draft( state.hidden.erase( state.hidden.begin(), state.hidden.begin() + counts[i] * dflash_->row_bytes()); - if (verification) { - auto block = - std::make_shared>(v, anchors[i]); - if (k) { - std::vector> probabilities; - muse_glimmer::SamplingWorkspace workspace; - auto rng = draw_rng(state.seed, ends[i], 1); - // Preserve the existing greedy proposal policy: verification below - // accepts against a point-mass draft distribution. - if (!muse_glimmer::sample_dflash2_path( - rng, - candidate_ids + i * proposals * k, - candidate_scores + i * proposals * k * k, - v - 1, - k, - spec_->vocab_size, - 0, - true, - *block, - probabilities, - workspace)) { - return false; - } - } else { - for (int j = 1; j < v; ++j) { - auto token = - sample_row(logits, i * b + j, owners[i], ends[i] + j, true); - if (!token) { - return false; - } - (*block)[j] = *token; - } + } + // The Serial DFlash2 proposals: verified linearly, or as a sampled owner's + // chain in a tree round. + auto proposals_of = [&](size_t i, std::vector& block) { + const auto& state = sessions_.at(owners[i]); + if (k) { + std::vector> probabilities; + muse_glimmer::SamplingWorkspace workspace; + auto rng = draw_rng(state.seed, ends[i], 1); + // Preserve the existing greedy proposal policy: verification accepts + // against a point-mass draft distribution. + return muse_glimmer::sample_dflash2_path( + rng, + candidate_ids + i * proposals * k, + candidate_scores + i * proposals * k * k, + v - 1, + k, + spec_->vocab_size, + 0, + true, + block, + probabilities, + workspace); + } + for (int j = 1; j < v; ++j) { + auto token = sample_row(logits, i * b + j, owners[i], ends[i] + j, true); + if (!token) { + return false; + } + block[j] = *token; + } + return true; + }; + if (tree && !tree->trees.empty()) { + for (size_t i = 0; i < owners.size(); ++i) { + if (sessions_.at(owners[i]).sampling->temperature == 0) { + continue; + } + std::vector block(v, anchors[i]); + if (!proposals_of(i, block)) { + return false; } - for (int j = 0; j < v; ++j) { - verification->inputs.push_back( - {owners[i], - true, - static_cast(j), - 1, - batching::TokenInputPtr(block), - ends[i]}); + auto& chain = tree->trees[i]; + chain.clear(); + for (int d = 1; d < v; ++d) { + chain.push_back({static_cast(block[d]), d - 2, d, 0}); } } + return true; + } + for (size_t i = 0; verification && i < owners.size(); ++i) { + auto block = std::make_shared>(v, anchors[i]); + if (!proposals_of(i, *block)) { + return false; + } + for (int j = 0; j < v; ++j) { + verification->inputs.push_back( + {owners[i], + true, + static_cast(j), + 1, + batching::TokenInputPtr(block), + ends[i]}); + } } return true; } @@ -896,6 +1037,7 @@ bool MuseGlimmerMLXExecutor::speculate( const batching::BatchInput& batch, batching::BatchOutput& out, bool input_anchors) { + const bool trees = dflash_->tree_budget > 0; const int b = dflash_->verify_block; size_t cursor = 0; while (cursor < batch.inputs.size()) { @@ -903,6 +1045,11 @@ bool MuseGlimmerMLXExecutor::speculate( std::vector anchors; std::vector indices; size_t context = 0; + // With a tree budget, a round holding a greedy session is one PairTree + // round: its sampled sessions' Serial DFlash2 chains share its target + // forward, each taking its full verify_block rows; every greedy session + // needs a root and a node. A round of sampled sessions only is Serial. + int greedy = 0, chain_rows = 0; while (cursor < batch.inputs.size()) { const auto& input = batch.inputs[cursor]; auto& state = sessions_.at(input.sid); @@ -917,11 +1064,20 @@ bool MuseGlimmerMLXExecutor::speculate( return false; } const size_t count = state.hidden.size() / dflash_->row_bytes(); + const bool samples = state.sampling->temperature != 0; + const bool tree_round = trees && (greedy > 0 || !samples); + const int round_rows = + chain_rows + (samples ? b : 0) + 2 * (greedy + !samples); if (owners.size() == static_cast(dflash_->max_owners) || - context + count > static_cast(dflash_->context)) { + context + count > static_cast(dflash_->context) || + (tree_round && + (owners.size() >= static_cast(dflash_->tree_owners) || + round_rows > dflash_->tree_rows))) { break; } context += count; + greedy += !samples; + chain_rows += samples ? b : 0; owners.push_back(input.sid); anchors.push_back( input_anchors ? (*std::get( @@ -932,10 +1088,38 @@ bool MuseGlimmerMLXExecutor::speculate( if (owners.empty()) { continue; } + std::optional tree; + if (trees && greedy > 0) { + // A sampled owner's chain takes its full rows; each greedy owner's tree + // fits its share of the rows the chains leave, and its context. + tree.emplace(); + for (const auto owner : owners) { + const auto& state = sessions_.at(owner); + tree->budgets.push_back( + state.sampling->temperature != 0 + ? b - 1 + : pairtree::round_budget( + dflash_->tree_budget, + dflash_->tree_rows - chain_rows, + greedy, + spec_->max_context_length - ctl_->pos(state.seq_id) - 1)); + } + } batching::BatchInput verification; - if (!draft(owners, anchors, dflash_->context, &verification)) { + if (!draft( + owners, + anchors, + dflash_->context, + &verification, + tree ? &*tree : nullptr)) { return false; } + if (tree && !tree->trees.empty()) { + if (!speculate_tree(owners, anchors, indices, tree->trees, out)) { + return false; + } + continue; + } batching::BatchOutput predictions; if (!execute_impl(verification, predictions, true)) { return false; @@ -969,6 +1153,126 @@ bool MuseGlimmerMLXExecutor::speculate( return true; } +bool MuseGlimmerMLXExecutor::speculate_tree( + const std::vector& owners, + const std::vector& anchors, + const std::vector& indices, + const std::vector>& trees, + batching::BatchOutput& out) { + // Each owner's anchor roots its tree; node i sits at step row base + 1 + i. + const int owner_count = static_cast(owners.size()); + std::vector positions; + std::vector seq_ids, parents; + std::vector inputs; + std::vector bases, starts; + for (int i = 0; i < owner_count; ++i) { + const auto& state = sessions_.at(owners[i]); + const int start = ctl_->pos(state.seq_id); + const int base = static_cast(positions.size()); + bases.push_back(base); + starts.push_back(start); + auto tokens = std::make_shared>(1, anchors[i]); + positions.push_back(start); + parents.push_back(-1); + for (const auto& node : trees[i]) { + if (node.token < 0 || node.token >= spec_->vocab_size) { + return false; + } + tokens->push_back(static_cast(node.token)); + positions.push_back(start + node.depth); + parents.push_back(base + 1 + node.parent); + } + seq_ids.insert(seq_ids.end(), tokens->size(), state.seq_id); + inputs.push_back( + {owners[i], + false, + 0, + tokens->size(), + batching::TokenInputPtr(std::move(tokens)), + start}); + } + const auto n = static_cast(positions.size()); + auto embeddings = embeddings_->materialize(*module_, inputs); + if (!embeddings.ok() || !*embeddings || + (*embeddings)->scalar_type() != spec_->activation_dtype || + (*embeddings)->dim() != 3 || (*embeddings)->size(0) != 1 || + (*embeddings)->size(1) != n || + (*embeddings)->size(2) != spec_->hidden_dim || + !dense_tensor(**embeddings)) { + return false; + } + std::vector selectors(n); + std::iota(selectors.begin(), selectors.end(), 0); + auto position_tensor = make_tensor_ptr({n}, std::move(positions)); + auto selector_tensor = make_tensor_ptr({n}, std::move(selectors)); + if (!ctl_->declare_tree_step(seq_ids, parents)) { + return false; + } + auto result = module_->execute( + kDecoder, {*embeddings, position_tensor, selector_tensor}); + if (!result.ok() || result->size() != 2 || !result->at(0).isTensor() || + !result->at(1).isTensor()) { + return false; + } + auto logits = result->at(0).toTensor(); + const auto& hidden = result->at(1).toTensor(); + if (logits.scalar_type() != aten::ScalarType::Float || logits.dim() != 3 || + logits.size(0) != 1 || logits.size(1) != n || + logits.size(2) != spec_->vocab_size || !dense_tensor(logits) || + hidden.dim() != 3 || hidden.size(0) != 1 || hidden.size(1) != n || + hidden.size(2) != dflash_->hidden || + hidden.scalar_type() != spec_->activation_dtype || + !dense_tensor(hidden)) { + return false; + } + std::vector keep; + std::vector walks; + for (int i = 0; i < owner_count; ++i) { + const auto& nodes = trees[i]; + std::vector predictions; + for (int row = bases[i]; row <= bases[i] + static_cast(nodes.size()); + ++row) { + const int depth = row == bases[i] ? 0 : nodes[row - bases[i] - 1].depth; + const auto token = + sample_row(logits, row, owners[i], starts[i] + depth + 1); + if (!token) { + return false; + } + predictions.push_back(static_cast(*token)); + } + walks.push_back(pairtree::walk(nodes, predictions)); + keep.push_back(bases[i]); + for (const int node : walks.back().path) { + keep.push_back(bases[i] + 1 + node); + } + } + if (!ctl_->retain_tree(keep)) { + return false; + } + const auto* rows = static_cast(hidden.const_data_ptr()); + const size_t row_bytes = dflash_->row_bytes(); + for (int i = 0, kept = 0; i < owner_count; ++i) { + const auto& walk = walks[i]; + const int count = 1 + static_cast(walk.path.size()); + auto& state = sessions_.at(owners[i]); + if (ctl_->pos(state.seq_id) != starts[i] + count || + dflash_->ctl->pos(state.draft_id) + state.hidden.size() / row_bytes != + static_cast(starts[i])) { + return false; + } + for (int j = 0; j < count; ++j, ++kept) { + const auto* row = rows + keep[kept] * row_bytes; + state.hidden.insert(state.hidden.end(), row, row + row_bytes); + } + auto& output = out.outputs[indices[i]]->tokens; + for (const int node : walk.path) { + output.push_back(static_cast(trees[i][node].token)); + } + output.push_back(static_cast(walk.token)); + } + return true; +} + bool MuseGlimmerMLXExecutor::execute( const batching::BatchInput& batch, batching::BatchOutput& out) { diff --git a/examples/models/muse-glimmer/runtime/mlx_executor.h b/examples/models/muse-glimmer/runtime/mlx_executor.h index 3d7050b43ef..b80f7674830 100644 --- a/examples/models/muse-glimmer/runtime/mlx_executor.h +++ b/examples/models/muse-glimmer/runtime/mlx_executor.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include @@ -24,9 +25,13 @@ namespace executorch::extension::llm { class MuseGlimmerModelEmbeddings; class MuseGlimmerMLXExecutor final : public batching::Executor { + friend struct MuseGlimmerMLXTestPeer; + public: + // `note`, if given, receives the DFlash mode and why, or the refusal. static runtime::Result create( - const MuseGlimmerBackendConfig& config); + const MuseGlimmerBackendConfig& config, + std::string* note = nullptr); ~MuseGlimmerMLXExecutor() override; bool initialize() override; @@ -54,6 +59,13 @@ class MuseGlimmerMLXExecutor final : public batching::Executor { std::vector hidden; }; using Rewinds = std::vector>; + // One PairTree DFlash2 round: each owner's node budget, then its tree, a + // chain of its Serial DFlash2 proposals for a sampled owner. No trees: the + // builder refused a table and the round runs Serial DFlash2. + struct TreeRound { + std::vector budgets; + std::vector> trees; + }; MuseGlimmerMLXExecutor( std::unique_ptr module, @@ -73,7 +85,14 @@ class MuseGlimmerMLXExecutor final : public batching::Executor { const std::vector& owners, const std::vector& anchors, int context_limit, - batching::BatchInput* verification); + batching::BatchInput* verification, + TreeRound* tree = nullptr); + bool speculate_tree( + const std::vector& owners, + const std::vector& anchors, + const std::vector& indices, + const std::vector>& trees, + batching::BatchOutput& out); bool speculate( const batching::BatchInput& batch, batching::BatchOutput& out, diff --git a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp index f5774349842..01f54153053 100644 --- a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp +++ b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp @@ -21,7 +21,7 @@ DEFINE_int32(dflash_n_draft, 0, "DFlash proposals; zero uses exported maximum"); DEFINE_int32( dflash_tree_budget, -1, - "PairTree DFlash2 (CUDA, greedy sessions) nodes per session and round; " + "PairTree DFlash2 (greedy sessions) nodes per session and round; " "zero runs Serial DFlash2. Negative (default): PairTree DFlash2 at the " "backend's default budget on a --dflash2-pairtree program, otherwise " "Serial DFlash2"); diff --git a/examples/models/muse-glimmer/serving/serve_batching.py b/examples/models/muse-glimmer/serving/serve_batching.py index b69fc5bc868..b4e69373408 100644 --- a/examples/models/muse-glimmer/serving/serve_batching.py +++ b/examples/models/muse-glimmer/serving/serve_batching.py @@ -68,7 +68,7 @@ def _parse_args(argv=None): parser.add_argument( "--dflash-tree-budget", type=int, - help="PairTree DFlash2 nodes per greedy session and round (CUDA, needs a " + help="PairTree DFlash2 nodes per greedy session and round (needs a " "--dflash2-pairtree export); 0 runs Serial DFlash2. Unset: PairTree " "DFlash2 at the backend's default budget on a --dflash2-pairtree export, " "otherwise Serial DFlash2.", @@ -157,8 +157,8 @@ def _parse_args(argv=None): budget = args.dflash_tree_budget if budget is not None and not 0 <= budget < _MAX_TREE_ROWS: parser.error(f"--dflash-tree-budget must be in [0, {_MAX_TREE_ROWS - 1}]") - if budget and not (args.dflash and args.backend == "cuda"): - parser.error("--dflash-tree-budget requires --dflash and --backend cuda") + if budget and not args.dflash: + parser.error("--dflash-tree-budget requires --dflash") if args.dflash_serial_only and (budget or not args.dflash): parser.error( "--dflash-serial-only requires --dflash and no nonzero --dflash-tree-budget" diff --git a/examples/models/muse-glimmer/tests/README.md b/examples/models/muse-glimmer/tests/README.md index 0d3867965ca..88aa2972914 100644 --- a/examples/models/muse-glimmer/tests/README.md +++ b/examples/models/muse-glimmer/tests/README.md @@ -36,7 +36,21 @@ Input-sensitive continuations check shared-payload slices against target-only de A vendored stateless official reference separately checks DFlash2 model semantics, including sliding-window boundaries. Native sampling checks target-only, original DFlash, and DFlash2 at temperature 0.8 with top-k/top-p filtering; -a separate temperature control detects ignored settings. The MLX CI job runs +a separate temperature control detects ignored settings. Fixtures exported with +the PairTree DFlash2 outputs check tree verification at budgets 1 to 31 against +target-only greedy decoding, the one-node acceptance bound, multi-node +acceptance, greedy trees beside a sampled session, and Serial DFlash2's +sampling distribution for sampled sessions. Serial-only on the random, +always-accepting and quantized fixtures must match Serial DFlash2 on their +plain twins bit for bit, at 1, 4 and 16 sessions (with 4 and 16, also sampled +sessions, a replaced session and second turns): tokens and, after every +execution, each session's target position and pending target hidden rows; it +never loads `draft_forward_pairtree`. PairTree mode drafts with that method +alone. With only sampled sessions it matches Serial DFlash2 the same way, and +when its tree rounds verify sampled sessions' Serial DFlash2 chains beside +greedy sessions, every session emits Serial DFlash2's tokens. So does it on a +fixture whose candidate tables the tree builder refuses, and a fixture with an +invalid `draft_forward_pairtree` runs Serial DFlash2 by default. The MLX CI job runs these fixtures; backend cache and primitive suites cover window semantics and TF32. ## CUDA off-graph batching diff --git a/examples/models/muse-glimmer/tests/export_mlx_dflash_fixture.py b/examples/models/muse-glimmer/tests/export_mlx_dflash_fixture.py index cc2254455c0..7dabf4a39ac 100644 --- a/examples/models/muse-glimmer/tests/export_mlx_dflash_fixture.py +++ b/examples/models/muse-glimmer/tests/export_mlx_dflash_fixture.py @@ -146,7 +146,7 @@ def write_draft_reference(directory, target, draft, config, draft_config): ) -def export_quantized_fixture(directory: Path): +def export_quantized_fixture(directory: Path, pairtree: bool = False): torch.manual_seed(73) checkpoint = directory / "draft.gguf" write_dflash_gguf(checkpoint) @@ -235,6 +235,7 @@ def checked_lower(*args, **kwargs): torch.float16, 4, use_offgraph_kv_cache=True, + pairtree=pairtree, ) @@ -288,6 +289,7 @@ def export_fixture( owner_sensitive: bool = False, block_size: int = 4, routing_sensitive: bool = False, + pairtree: bool = False, ): torch.manual_seed(73) config = MuseGlimmerConfig( @@ -366,6 +368,7 @@ def constants(**kwargs): torch.float16, 4, use_offgraph_kv_cache=True, + pairtree=pairtree, ) @@ -387,3 +390,66 @@ def constants(**kwargs): ) export_quantized_fixture(args.output / "quantized") + # PairTree DFlash2 exports add draft_forward_pairtree. + export_fixture(args.output / "reject_-1_pairtree", -1, pairtree=True) + export_fixture(args.output / "random_pairtree", -1, controlled=False, pairtree=True) + export_quantized_fixture(args.output / "quantized_pairtree", pairtree=True) + # Candidate logsumexps below the candidates' own mass: the tree builder + # refuses every table, so every round falls back to Serial DFlash2. + draft_forward_pairtree = MuseGlimmerWithDFlash.draft_forward_pairtree + + def refused_tables( + self, + draft_tokens, + target_hidden, + input_pos, + valid_ctx_len=None, + proposal_rows=None, + ): + ids, scores, extras = draft_forward_pairtree( + self, draft_tokens, target_hidden, input_pos, valid_ctx_len, proposal_rows + ) + unary = extras[..., :-1] + return ids, scores, torch.cat([unary, unary.amax(-1, keepdim=True) - 10], -1) + + with patch.object(MuseGlimmerWithDFlash, "draft_forward_pairtree", refused_tables): + export_fixture( + args.output / "random_refused_pairtree", + -1, + controlled=False, + pairtree=True, + ) + + def short_extras( + self, + draft_tokens, + target_hidden, + input_pos, + valid_ctx_len=None, + proposal_rows=None, + ): + ids, scores, extras = draft_forward_pairtree( + self, draft_tokens, target_hidden, input_pos, valid_ctx_len, proposal_rows + ) + return ids, scores, extras[..., :-1] + + # Extras without the logsumexp column: an invalid method. + with patch.object(MuseGlimmerWithDFlash, "draft_forward_pairtree", short_extras): + export_fixture( + args.output / "random_short_pairtree", + -1, + controlled=False, + pairtree=True, + ) + # A draft_forward_pairtree without the extras output: an invalid method. + with patch.object( + MuseGlimmerWithDFlash, + "draft_forward_pairtree", + MuseGlimmerWithDFlash.draft_forward, + ): + export_fixture( + args.output / "random_invalid_pairtree", + -1, + controlled=False, + pairtree=True, + ) diff --git a/examples/models/muse-glimmer/tests/mlx_dflash_native_test.cpp b/examples/models/muse-glimmer/tests/mlx_dflash_native_test.cpp index f948c2c923b..a1a86e28488 100644 --- a/examples/models/muse-glimmer/tests/mlx_dflash_native_test.cpp +++ b/examples/models/muse-glimmer/tests/mlx_dflash_native_test.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -18,10 +19,13 @@ #include #include #include +#include #include #include +#include #include #include +#include #include namespace llm = executorch::extension::llm; @@ -47,13 +51,19 @@ b::Input input(b::SessionId sid, int position, Tokens tokens) { position}; } -std::unique_ptr -create(const std::string& path, int proposals, bool speculative = true) { +std::unique_ptr create( + const std::string& path, + int proposals, + bool speculative = true, + std::optional tree_budget = 0, + bool serial_only = false) { llm::MuseGlimmerBackendConfig config; config.model_path = path; config.max_sessions = 4; config.use_dflash = speculative; config.dflash_n_draft = speculative ? proposals : 0; + config.dflash_tree_budget = speculative ? tree_budget : std::nullopt; + config.dflash_serial_only = serial_only; auto backend = llm::MuseGlimmerMLXExecutor::create(config); require(backend.ok(), "production factory rejected fixture"); auto executor = std::move(backend->executor); @@ -196,8 +206,9 @@ void check_input_anchors(const std::string& path) { void check_temperature( const std::string& path, bool speculative, - bool input_anchor = false) { - auto executor = create(path, 3, speculative); + bool input_anchor = false, + int tree_budget = 0) { + auto executor = create(path, 3, speculative, tree_budget); const size_t maximum = speculative ? (input_anchor ? 4 : 5) : 1; const size_t minimum = speculative && !input_anchor ? 2 : 1; for (int variant = 0; variant < 4; ++variant) { @@ -378,6 +389,224 @@ void check_sampling_schedules(const std::string& path) { } } +} // namespace + +namespace executorch::extension::llm { +struct MuseGlimmerMLXTestPeer { + // Each session's target sequence and position, draft sequence, and the + // target hidden rows the draft has not consumed yet, in session order. + static std::string state(const MuseGlimmerMLXExecutor& executor) { + std::map order; + for (const auto& [sid, state] : executor.sessions_) { + order[sid] = &state; + } + std::string out; + for (const auto& [sid, state] : order) { + out += std::to_string(sid) + ":" + std::to_string(state->seq_id) + ":" + + std::to_string(executor.ctl_->pos(state->seq_id)) + ":" + + std::to_string(state->draft_id) + ":"; + out.append(state->hidden.begin(), state->hidden.end()); + out += ";"; + } + return out; + } + static bool loaded(const MuseGlimmerMLXExecutor& executor, const char* name) { + return executor.module_->is_method_loaded(name); + } +}; +} // namespace executorch::extension::llm + +namespace { +using Peer = llm::MuseGlimmerMLXTestPeer; + +struct Script { + std::vector tokens; // per session, every turn + std::vector sampled; // per entry of `tokens` + std::vector states; // Peer::state after every execution + bool draft_loaded = false, pairtree_loaded = false; +}; + +// `sessions` sessions, every third one sampled, decode at least 8 tokens. +// Then the first is closed and a new session opened, every other session +// takes a second turn, and the open sessions decode at least 6 more tokens. +Script run_script( + const std::string& path, + int sessions, + std::optional tree_budget, + bool serial_only, + bool all_sampled = false, + bool one_turn = false) { + llm::MuseGlimmerBackendConfig config; + config.model_path = path; + config.max_sessions = sessions + 1; + config.use_dflash = true; + config.dflash_tree_budget = tree_budget; + config.dflash_serial_only = serial_only; + auto backend = llm::MuseGlimmerMLXExecutor::create(config); + require(backend.ok(), "production factory rejected fixture"); + auto& executor = + static_cast(*backend->executor); + require(executor.initialize(), "executor initialization failed"); + struct Slot { + b::SessionId sid; + Tokens history; // prompts and outputs + size_t fed = 0; // history tokens in the session's context + size_t goal = 0; // history size to stop at + bool sampled = false; + }; + constexpr size_t kRoom = 24; // below the fixture's 32-token context + std::vector slots; + auto open = [&](int seed) { + const auto sid = executor.open_session(); + require(sid.has_value(), "script session allocation failed"); + executor.set_sampling( + *sid, + all_sampled || seed % 3 == 2 ? b::SamplingParams{0.8f, 0.9f, 7} + : b::SamplingParams{}, + 42 + seed); + Tokens prompt; + for (int k = 0; k < 2 + seed % 5; ++k) { + prompt.push_back(1 + (17 * seed + 5 * k) % 60); + } + slots.push_back({*sid, prompt, 0, 0, all_sampled || seed % 3 == 2}); + }; + Script result; + auto decode = [&](size_t tokens) { + for (auto& slot : slots) { + slot.goal = std::min(kRoom, slot.history.size() + tokens); + } + while (true) { + b::BatchInput batch; + std::vector fed; + for (auto& slot : slots) { + if (slot.history.size() < slot.goal) { + batch.inputs.push_back(input( + slot.sid, + static_cast(slot.fed), + Tokens(slot.history.begin() + slot.fed, slot.history.end()))); + slot.fed = slot.history.size(); + fed.push_back(&slot); + } + } + if (fed.empty()) { + return; + } + b::BatchOutput out; + require(executor.execute(batch, out), "script execution failed"); + require(out.outputs.size() == fed.size(), "script output count"); + for (size_t i = 0; i < fed.size(); ++i) { + require( + out.outputs[i] && !out.outputs[i]->tokens.empty(), + "script output missing"); + const auto& tokens = out.outputs[i]->tokens; + fed[i]->history.insert( + fed[i]->history.end(), tokens.begin(), tokens.end()); + // The last output is fed with the next input. + fed[i]->fed = fed[i]->history.size() - 1; + } + result.states.push_back(Peer::state(executor)); + } + }; + for (int i = 0; i < sessions; ++i) { + open(i); + } + if (one_turn) { + decode(16); + for (const auto& slot : slots) { + result.tokens.push_back(slot.history); + result.sampled.push_back(slot.sampled); + } + return result; + } + decode(8); + result.tokens.push_back(slots.front().history); + result.sampled.push_back(slots.front().sampled); + executor.close_session(slots.front().sid); + slots.erase(slots.begin()); + open(sessions); + for (size_t i = 1; i < slots.size(); i += 2) { + auto& history = slots[i].history; + if (history.size() + 4 < kRoom) { + history.insert(history.end(), {3, 5, 8, 13}); + } + } + decode(6); + for (const auto& slot : slots) { + result.tokens.push_back(slot.history); + result.sampled.push_back(slot.sampled); + } + result.draft_loaded = Peer::loaded(executor, "draft_forward"); + result.pairtree_loaded = Peer::loaded(executor, llm::kDFlash2PairTreeMethod); + return result; +} + +// The fixture exporter writes the plain and PairTree programs in one process +// from the same weights. Serial-only on the PairTree program must then be +// bit-identical to Serial DFlash2 on the plain one: tokens, and after every +// execution each session's positions and pending target hidden rows; it +// never loads draft_forward_pairtree. PairTree DFlash2 verifies sampled +// sessions' Serial DFlash2 chains inside its tree rounds: with only sampled +// sessions it must match Serial DFlash2 the same way, and beside greedy +// sessions every session must emit Serial DFlash2's tokens. `accepts_trees`: +// the fixture's trees accept differently from its chains, so PairTree must +// differ in its positions, or the check proves nothing. +void check_serial_only_identity( + const std::string& plain, + const std::string& pairtree, + int sessions, + bool accepts_trees) { + const auto expected = + run_script(plain + "/model.pte", sessions, std::nullopt, false); + for (const auto& [budget, serial_only] : + {std::pair{std::optional{}, true}, + std::pair{std::optional{0}, false}}) { + const auto actual = + run_script(pairtree + "/model.pte", sessions, budget, serial_only); + require( + actual.tokens == expected.tokens && actual.states == expected.states && + actual.draft_loaded && !actual.pairtree_loaded, + "serial-only differs from Serial DFlash2 on the plain program"); + } + const auto sampled = + run_script(plain + "/model.pte", sessions, std::nullopt, false, true); + const auto tree_sampled = + run_script(pairtree + "/model.pte", sessions, std::nullopt, false, true); + require( + tree_sampled.tokens == sampled.tokens && + tree_sampled.states == sampled.states && !tree_sampled.draft_loaded && + tree_sampled.pairtree_loaded, + "PairTree mode changed sampled sessions' Serial DFlash2 rounds"); + const auto tree = + run_script(pairtree + "/model.pte", sessions, std::nullopt, false); + require( + tree.pairtree_loaded && !tree.draft_loaded, + "PairTree DFlash2 did not draft with draft_forward_pairtree alone"); + // One turn of the same sessions: rounds commit different lengths, so each + // session stops at a different length, but every token both runs emitted + // must agree. + const auto serial_turn = run_script( + plain + "/model.pte", sessions, std::nullopt, false, false, true); + const auto tree_turn = run_script( + pairtree + "/model.pte", sessions, std::nullopt, false, false, true); + int compared_sampled = 0; + for (size_t i = 0; i < tree_turn.tokens.size(); ++i) { + const auto& a = tree_turn.tokens[i]; + const auto& b = serial_turn.tokens[i]; + const size_t n = std::min(a.size(), b.size()); + require( + std::equal(a.begin(), a.begin() + n, b.begin()) && n >= 12, + "PairTree DFlash2 changed a session's tokens in a mixed batch"); + compared_sampled += tree_turn.sampled[i]; + } + require( + sessions < 3 || compared_sampled > 0, "the script sampled no session"); + require( + !accepts_trees || tree.states != expected.states, + "the identity check cannot tell PairTree from Serial DFlash2"); + std::cout << "serial-only identity: " << pairtree << ", " << sessions + << " sessions, " << expected.states.size() << " executions\n"; +} + std::vector generate( b::Executor& executor, const std::vector& prompts, @@ -446,7 +675,8 @@ std::vector generate( void check_random_continuations( const std::string& path, - const std::vector& proposal_counts) { + const std::vector& proposal_counts, + std::optional tree_budget = 0) { const std::vector prompts{{1, 2, 3}, {9, 5, 11, 2}, {17, 42}}; std::vector expected; { @@ -469,14 +699,16 @@ void check_random_continuations( "packed target-only continuation differs"); } for (int proposals : proposal_counts) { - auto executor = create(path, proposals); + auto executor = create(path, proposals, true, tree_budget); const auto actual = generate(*executor, prompts, 20); if (actual != expected) { for (size_t owner = 0; owner < actual.size(); ++owner) { for (size_t step = 0; step < actual[owner].size(); ++step) { if (actual[owner][step] != expected[owner][step]) { - std::cerr << "proposals=" << proposals << " owner=" << owner - << " step=" << step << " actual=" << actual[owner][step] + std::cerr << "proposals=" << proposals + << " tree_budget=" << tree_budget.value_or(-1) + << " owner=" << owner << " step=" << step + << " actual=" << actual[owner][step] << " expected=" << expected[owner][step] << '\n'; break; } @@ -890,6 +1122,101 @@ int main(int argc, char** argv) { check_draft_numerics(root + "/quantized", proposals); } check_random_continuations(root + "/quantized/model.pte", {1, 7, 15}); + // PairTree verification: packed, sliced, rewound and cloned sessions match + // target-only greedy decoding at every budget, as does linear + // verification of the same artifacts. + for (const char* fixture : {"/random_pairtree", "/quantized_pairtree"}) { + const auto path = root + fixture + "/model.pte"; + const bool quantized = fixture == std::string("/quantized_pairtree"); + check_random_continuations(path, {quantized ? 15 : 3}); + for (int budget : {1, 3, 7, 15, 31}) { + check_random_continuations(path, {quantized ? 15 : 3}, budget); + } + } + check_random_continuations(root + "/random_pairtree/model.pte", {1, 2}, 7); + // Without a budget, a PairTree program runs PairTree DFlash2 at the + // default budget. + check_random_continuations( + root + "/random_pairtree/model.pte", {3}, std::nullopt); + for (int sessions : {4, 16}) { + // When the builder refuses every candidate table, PairTree DFlash2 runs + // every round as Serial DFlash2 does; with the valid tables of the same + // weights it runs trees and differs. + const auto plain = + run_script(root + "/random/model.pte", sessions, std::nullopt, false); + const auto refused = run_script( + root + "/random_refused_pairtree/model.pte", + sessions, + std::nullopt, + false); + const auto valid = run_script( + root + "/random_pairtree/model.pte", sessions, std::nullopt, false); + require( + refused.tokens == plain.tokens && refused.states == plain.states && + refused.pairtree_loaded && !refused.draft_loaded && + valid.states != plain.states, + "refused tree tables did not fall back to Serial DFlash2"); + } + for (const auto& [plain, pairtree, accepts_trees] : + {std::tuple{"/random", "/random_pairtree", true}, + std::tuple{"/reject_-1", "/reject_-1_pairtree", false}, + std::tuple{"/quantized", "/quantized_pairtree", false}}) { + for (int sessions : {1, 4, 16}) { + check_serial_only_identity( + root + plain, root + pairtree, sessions, accepts_trees); + } + } + { + // A one-node tree accepts at most one proposal per round, whatever the + // linear proposal count. + auto executor = + create(root + "/reject_-1_pairtree/model.pte", 3, true, 1); + const auto sid = executor->open_session(); + require(sid.has_value(), "tree session allocation failed"); + require( + forward(*executor, *sid, 0, {1, 2}).size() == 3 && + forward(*executor, *sid, 4, {7}).size() == 2, + "tree verification did not bound the accepted path"); + executor->close_session(*sid); + } + { + // A wider tree accepts several nodes per round on the always-accepting + // fixture. Greedy owners keep their trees beside a sampled owner, which + // runs Serial DFlash2 in its own round. + auto executor = + create(root + "/reject_-1_pairtree/model.pte", 3, true, 7); + const auto sid = executor->open_session(); + require(sid.has_value(), "tree session allocation failed"); + int position = 0; + Tokens tokens{1, 2}; + size_t longest = 0; + while (position + static_cast(tokens.size()) <= 24) { + const auto output = forward(*executor, *sid, position, tokens); + longest = std::max(longest, output.size()); + position += static_cast(tokens.size() + output.size()) - 1; + tokens = {output.back()}; + } + require(longest >= 4, "tree verification never accepted two nodes"); + executor->close_session(*sid); + auto bounded = create(root + "/reject_-1_pairtree/model.pte", 3, true, 1); + const auto greedy = bounded->open_session(); + const auto sampled = bounded->open_session(); + require(greedy && sampled, "mixed session allocation failed"); + bounded->set_sampling(*greedy, {}, 42); + bounded->set_sampling(*sampled, {0.8f, 1.0f, 0}, 42); + b::BatchInput batch; + batch.inputs = {input(*greedy, 0, {1, 2}), input(*sampled, 0, {1, 2})}; + b::BatchOutput output; + require(bounded->execute(batch, output), "mixed execution failed"); + require( + output.outputs.size() == 2 && output.outputs[0] && + output.outputs[0]->tokens == Tokens(3, 7) && output.outputs[1] && + !output.outputs[1]->tokens.empty(), + "a sampled owner changed a greedy owner's tree round"); + } + // Sampled sessions fall back to linear verification. + check_temperature(root + "/reject_-1_pairtree/model.pte", true, false, 15); + check_temperature(root + "/reject_-1_pairtree/model.pte", true, true, 15); check_cycles(root + "/legacy/model.pte", 3, -1); check_temperature(root + "/reject_-1/model.pte", false); check_temperature(root + "/reject_-1/model.pte", true); @@ -911,6 +1238,89 @@ int main(int argc, char** argv) { llm::MuseGlimmerMLXExecutor::create(invalid).error() == executorch::runtime::Error::InvalidArgument, "out-of-range proposal count was accepted"); + invalid.dflash_n_draft = 0; + invalid.dflash_tree_budget = 7; + require( + llm::MuseGlimmerMLXExecutor::create(invalid).error() == + executorch::runtime::Error::InvalidProgram, + "tree verification was accepted without PairTree draft outputs"); + invalid.model_path = root + "/random_pairtree/model.pte"; + invalid.dflash_tree_budget = 32; + std::string note; + require( + llm::MuseGlimmerMLXExecutor::create(invalid, ¬e).error() == + executorch::runtime::Error::InvalidArgument && + note.find("exceeds the widest tree verify") != std::string::npos, + "a tree budget wider than one forward was accepted"); + { + // A draft_forward_pairtree without the documented outputs is no PairTree + // method: the default runs Serial DFlash2, an explicit budget fails. + auto config = invalid; + config.model_path = root + "/random_invalid_pairtree/model.pte"; + config.dflash_tree_budget = std::nullopt; + require( + llm::MuseGlimmerMLXExecutor::create(config, ¬e).ok() && + note == + "MLX DFlash: Serial DFlash2 (the program has no valid " + "draft_forward_pairtree (--dflash2-pairtree))", + "an invalid PairTree method did not fall back to Serial DFlash2"); + config.dflash_tree_budget = 7; + require( + llm::MuseGlimmerMLXExecutor::create(config, ¬e).error() == + executorch::runtime::Error::InvalidProgram && + note.find("needs a valid draft_forward_pairtree") != + std::string::npos, + "an explicit budget accepted an invalid PairTree method"); + // Extras without the logsumexp column are invalid too. + config.model_path = root + "/random_short_pairtree/model.pte"; + config.dflash_tree_budget = std::nullopt; + require( + llm::MuseGlimmerMLXExecutor::create(config, ¬e).ok() && + note.find("Serial DFlash2 (the program has no valid") != + std::string::npos, + "PairTree extras of the wrong shape were accepted"); + } + { + // The note names the chosen mode and why. + auto config = invalid; + config.dflash_tree_budget = std::nullopt; + require( + llm::MuseGlimmerMLXExecutor::create(config, ¬e).ok() && + note == + "MLX DFlash: PairTree DFlash2, tree budget 15 (default budget)", + "the PairTree note is wrong"); + config.dflash_serial_only = true; + require( + llm::MuseGlimmerMLXExecutor::create(config, ¬e).ok() && + note == "MLX DFlash: Serial DFlash2 (serial-only requested)", + "the serial-only note is wrong"); + } + invalid.dflash_tree_budget = 7; + invalid.dflash_serial_only = true; + require( + llm::MuseGlimmerMLXExecutor::create(invalid).error() == + executorch::runtime::Error::InvalidArgument, + "serial-only was accepted with a nonzero tree budget"); + invalid.dflash_serial_only = false; + invalid.use_dflash = false; + require( + llm::MuseGlimmerMLXExecutor::create(invalid).error() == + executorch::runtime::Error::InvalidArgument, + "a tree budget without DFlash was accepted"); + invalid.dflash_tree_budget = std::nullopt; + invalid.dflash_serial_only = true; + require( + llm::MuseGlimmerMLXExecutor::create(invalid).error() == + executorch::runtime::Error::InvalidArgument, + "serial-only without DFlash was accepted"); + invalid.use_dflash = true; + invalid.dflash_serial_only = false; + invalid.dflash_tree_budget = -1; + require( + llm::MuseGlimmerMLXExecutor::create(invalid, ¬e).error() == + executorch::runtime::Error::InvalidArgument && + note.find("the tree budget is negative") != std::string::npos, + "a negative tree budget was accepted"); std::cout << "Native MLX DFlash verification, fallback, replay, and legacy checks passed\n"; return 0; diff --git a/examples/models/muse-glimmer/tests/test_mlx_offgraph.py b/examples/models/muse-glimmer/tests/test_mlx_offgraph.py index 296dd08c490..0804d63f5ff 100644 --- a/examples/models/muse-glimmer/tests/test_mlx_offgraph.py +++ b/examples/models/muse-glimmer/tests/test_mlx_offgraph.py @@ -10,6 +10,7 @@ import tempfile import unittest from dataclasses import replace +from pathlib import Path from unittest.mock import patch import torch @@ -380,6 +381,57 @@ def test_packed_dflash_export(self): self.assertEqual(logits.shape, (1, 1, CONFIG.vocab_size)) self.assertEqual(hidden.shape, (1, 4, CONFIG.dim)) + def test_dflash2_pairtree_export_keeps_draft_forward(self): + """--dflash2-pairtree adds draft_forward_pairtree and leaves the plain + program's methods and weights byte for byte as they were.""" + from executorch.examples.models.muse_glimmer.export.export_dflash import ( + DFLASH2_PAIRTREE_METHOD, + ) + from executorch.examples.models.muse_glimmer.tests.export_mlx_dflash_fixture import ( + export_fixture, + ) + from executorch.exir._serialize._program import deserialize_pte_binary + + programs = [] + with tempfile.TemporaryDirectory() as directory: + for pairtree in (False, True): + path = Path(directory) / str(pairtree) + export_fixture(path, -1, controlled=False, pairtree=pairtree) + programs.append( + deserialize_pte_binary((path / "model.pte").read_bytes()) + ) + plain, pairtree = programs + names = [{p.name for p in pte.program.execution_plan} for pte in programs] + self.assertEqual(names[1] - names[0], {DFLASH2_PAIRTREE_METHOD}) + + def method(pte, name): + # The plan with each delegate's payload in place of its index. + plan = next(p for p in pte.program.execution_plan if p.name == name) + payloads = [ + pte.program.backend_delegate_data[d.processed.index].data + for d in plan.delegates + ] + return replace(plan, delegates=[]), payloads + + for name in names[0]: + self.assertEqual(method(plain, name), method(pairtree, name), name) + + def named(pte): + data = pte.named_data + return { + key: bytes(data.buffers[entry.buffer_index]) + for key, entry in data.pte_data.items() + } + + plain_named = named(plain) + self.assertEqual( + {key: named(pairtree)[key] for key in plain_named}, plain_named + ) + # The PairTree method shares the draft's weights. + self.assertEqual( + len(plain.named_data.buffers), len(pairtree.named_data.buffers) + ) + def test_legacy_forward_last_logits(self): original = _model() model = copy.deepcopy(original) diff --git a/examples/models/muse-glimmer/tests/test_serve_batching.py b/examples/models/muse-glimmer/tests/test_serve_batching.py index abc71eed132..2c3cfd0ca68 100644 --- a/examples/models/muse-glimmer/tests/test_serve_batching.py +++ b/examples/models/muse-glimmer/tests/test_serve_batching.py @@ -209,11 +209,18 @@ def test_cuda_launcher_forwards_pairtree_budget(arguments, tmp_path): ) == expected +def test_mlx_launcher_forwards_pairtree_budget(arguments): + args = serve_batching._parse_args( + arguments + ["--dflash", "--dflash-tree-budget", "15"] + ) + flags = dict(arg.split("=", 1) for arg in serve_batching._worker_command(args)[1:]) + assert (flags["--backend"], flags["--dflash_tree_budget"]) == ("mlx", "15") + + @pytest.mark.parametrize( "options", [ ["--dflash-tree-budget", "8"], - ["--dflash", "--dflash-tree-budget", "8"], ["--backend", "cuda", "--dflash", "--dflash-tree-budget", "-1"], ["--backend", "cuda", "--dflash", "--dflash-tree-budget", "256"], ["--backend", "cuda", "--dflash-serial-only"], From bec7953d6337b485b0573038c66bea9a35123874 Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Wed, 2 Dec 2026 21:21:13 -0800 Subject: [PATCH 3/3] [MLX] Run the PairTree DFlash2 and DFlash mode tests in MLX CI The Muse Glimmer MLX job now builds and runs muse_glimmer_dflash2_pairtree and muse_glimmer_dflash_mode with the other host-only batching tests; the MLX serial-only identity check runs inside muse_glimmer_mlx_dflash. Authored with AI assistance (Metamate). --- .github/workflows/mlx.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/mlx.yml b/.github/workflows/mlx.yml index d701c214772..71499e55c45 100644 --- a/.github/workflows/mlx.yml +++ b/.github/workflows/mlx.yml @@ -383,9 +383,11 @@ jobs: ${CONDA_RUN} python -m examples.models.muse_glimmer.tests.export_mlx_dflash_fixture \ /tmp/muse-glimmer-mlx-fixtures ${CONDA_RUN} cmake --build "${BATCHING_BIN_DIR}" \ - --target muse_glimmer_batching_test muse_glimmer_mlx_dflash_test sampling_test + --target muse_glimmer_batching_test muse_glimmer_mlx_dflash_test sampling_test \ + muse_glimmer_dflash2_pairtree_test muse_glimmer_dflash_mode_test ${CONDA_RUN} ctest --test-dir "${BATCHING_BIN_DIR}" \ - -R '^muse_glimmer_(batching|sampling)$' --output-on-failure --no-tests=error + -R '^muse_glimmer_(batching|sampling|dflash2_pairtree|dflash_mode)$' \ + --output-on-failure --no-tests=error ${CONDA_RUN} ctest --test-dir "${BATCHING_BIN_DIR}" \ -R '^muse_glimmer_mlx_dflash$' --output-on-failure --no-tests=error test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_runner"