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" diff --git a/backends/mlx/runtime/MLXBatchedCache.h b/backends/mlx/runtime/MLXBatchedCache.h index dee6ffa374d..02b15f53729 100644 --- a/backends/mlx/runtime/MLXBatchedCache.h +++ b/backends/mlx/runtime/MLXBatchedCache.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -60,6 +61,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 +113,80 @@ class MLXBatchedCache : public cache::Cache, return true; } + bool supports_tree_steps() const override { + return !geometry_.dflash_block_size.has_value(); + } + + // Each sequence's tokens are contiguous and form one tree rooted at the + // first of them. + 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 step leaves a pending tree pending. + std::set seen; + for (size_t i = 0; i < parents.size(); ++i) { + const bool first = i == 0 || seq_ids[i] != seq_ids[i - 1]; + if (parents[i] < -1 || parents[i] >= static_cast(i) || + (parents[i] >= 0 && seq_ids[parents[i]] != seq_ids[i]) || + (parents[i] < 0) != first || + (first && !seen.insert(seq_ids[i]).second)) { + 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 Tree& tree = *tree_; + const int length = static_cast(tree.parents.size()); + std::vector kept(length, 0); + for (int32_t index : keep) { + if (index < 0 || index >= length || kept[index]) { + return false; + } + kept[index] = 1; + } + // Kept tokens form root-to-node paths: a kept token's parent is kept and + // keeps no other child. + std::vector children(length, 0); + for (int i = 0; i < length; ++i) { + const int32_t parent = tree.parents[i]; + if (kept[i] && parent >= 0 && (!kept[parent] || children[parent]++)) { + return false; + } + } + std::vector> local(tree.spans.size()); + for (size_t i = 0; i < tree.spans.size(); ++i) { + const Span& span = tree.spans[i]; + for (int j = 0; j < span.q_len; ++j) { + if (kept[span.at + j]) { + local[i].push_back(j); + } + } + const auto& row = rows_.at(span.seq_id); + // The step's forward must be complete before any row changes. + if (row.length() != tree.bases[i] + span.q_len || + !row.can_retain_tree(tree.bases[i], local[i])) { + return false; + } + } + for (size_t i = 0; i < tree.spans.size(); ++i) { + rows_.at(tree.spans[i].seq_id).retain_tree(tree.bases[i], local[i]); + } + invalidate_step(); + return true; + } + std::optional max_seqs() const override { return std::nullopt; } @@ -125,6 +201,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 +225,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 +240,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 +250,27 @@ 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 (size_t i = 0; i < tree_->spans.size(); ++i) { + const Span& span = tree_->spans[i]; + if (span.seq_id == seq_id && + it->second.length() == tree_->bases[i] + span.q_len) { + int kept = 0; + for (const int32_t node : unbranched_paths(tree_->parents)) { + kept += node >= span.at && node < span.at + span.q_len; + } + return tree_->bases[i] + kept; + } + } + } + return it->second.length(); } Tensor attend( @@ -183,6 +282,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 +347,91 @@ class MLXBatchedCache : public cache::Cache, int group_at; }; + // A placed tree step, until retain_tree resolves it. + struct Tree { + std::vector spans; + std::vector bases; + std::vector parents; + }; + + // Each tree's root and the chain below it, up to the first node with + // several children: the longest part that is one path. + static std::vector unbranched_paths( + const std::vector& parents) { + const int length = static_cast(parents.size()); + std::vector children(length, 0), child(length, -1); + for (int i = 0; i < length; ++i) { + if (parents[i] >= 0) { + ++children[parents[i]]; + child[parents[i]] = i; + } + } + std::vector keep; + for (int i = 0; i < length; ++i) { + for (int node = parents[i] < 0 ? i : -1; node >= 0; + node = children[node] == 1 ? child[node] : -1) { + keep.push_back(node); + } + } + return keep; + } + + // Settles an unretained tree before another verb: each tree keeps its root + // and the single path below it, up to the first branch. A step whose + // forward did not complete is dropped like an unfinished ordinary step. + void resolve_tree() { + if (!tree_) { + return; + } + if (!retain_tree(unbranched_paths(tree_->parents))) { + 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{spans_, {}, step_parents_}; + for (const Span& span : spans_) { + tree.bases.push_back(rows_.at(span.seq_id).length()); + } + tree_ = std::move(tree); + step_pos_ = positions; + declared_ = false; + placed_ = true; + } + std::vector outs; + outs.reserve(spans_.size()); + for (const Span& span : spans_) { + std::vector parents( + step_parents_.begin() + span.at, + step_parents_.begin() + span.at + span.q_len); + for (int32_t& parent : parents) { + parent = parent < 0 ? -1 : parent - span.at; + } + outs.push_back(rows_.at(span.seq_id) + .attend_tree( + layer, + parents, + tokens(q, span.at, span.q_len, s), + tokens(k, span.at, span.q_len, s), + tokens(v, span.at, span.q_len, s), + scale, + 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 +538,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 +597,8 @@ class MLXBatchedCache : public cache::Cache, spans_.clear(); groups_.clear(); step_pos_.clear(); + step_parents_.clear(); + tree_.reset(); declared_ = false; placed_ = false; } @@ -408,6 +609,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..ce4286d602b 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,79 @@ 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); + return attend_validated(l, length_, q, incoming, update, scale, s, &mask); + } + + 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 +1230,52 @@ 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) { + using namespace ::mlx::core; + 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) { + 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), {1, history}), + reshape(array(first.data(), Shape{T}, int32), {T, 1})), + mask}, + 1); + } + tree_masks_->masks.push_back( + {window, begin, reshape(mask, {1, 1, T, history + T})}); + return tree_masks_->masks.back().mask; + } + Tensor attend_validated( size_t l, int position, @@ -1055,7 +1283,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 +1299,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 +1321,20 @@ class MLXSequenceCache final : public cache::Cache, return static_cast(layer); } + struct TreeMasks { + struct Entry { + int window, begin; + 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..3849a730099 100644 --- a/backends/mlx/test/mlx_batch_control_test.cpp +++ b/backends/mlx/test/mlx_batch_control_test.cpp @@ -1261,6 +1261,316 @@ 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); +} + +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})); + if (GetParam() != cache::kind::kBatchedCell) { + // Per-sequence caches also need each sequence's tokens contiguous; the + // cell cache takes interleaved sequences. + EXPECT_FALSE(batch_->declare_tree_step({a, b, a}, {-1, -1, 0})); + } + // 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})); + if (GetParam() != cache::kind::kBatchedCell) { + EXPECT_FALSE(batch_->declare_tree_step({a, b, a}, {-1, -1, 0})); + } + 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 8a96c42bb0b..ebffb49e54e 100644 --- a/examples/models/muse-glimmer/BATCHING_SERVING.md +++ b/examples/models/muse-glimmer/BATCHING_SERVING.md @@ -172,6 +172,48 @@ cycles that fell back (`tree_fallback_cycles`, every session of such a round); for a tree, `proposed` counts its nodes and a bonus is an accepted path that ends at a leaf. +### 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 share at most 256 rows and the exported prefill width. + +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 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. 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 00af7a3d559..8ae0c7b4c03 100644 --- a/examples/models/muse-glimmer/README.md +++ b/examples/models/muse-glimmer/README.md @@ -334,6 +334,9 @@ target forward: B = 31 for one decode sequence and 15 otherwise, or `--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 16fd0e455ca..fe435631df8 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") import executorch.extension.llm.export.gguf # noqa: F401 import executorch.extension.llm.export.int4 # noqa: F401 @@ -355,6 +353,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 {}), ) @@ -610,11 +609,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 @@ -773,25 +774,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 @@ -812,6 +831,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} @@ -874,7 +895,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( @@ -1282,7 +1303,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..c44d7e91853 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,14 @@ 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"; + } + bool logged_sampled_fallback = false; size_t row_bytes() const { return static_cast(hidden) * runtime::elementSize(activation_dtype); } @@ -90,7 +99,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 +111,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 +330,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 +363,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 +389,69 @@ runtime::Result MuseGlimmerMLXExecutor::create( if (!ctl) { return Error::InvalidType; } + 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) { + const auto chosen = + (mode.tree_budget ? "MLX DFlash: PairTree DFlash2, tree budget " + + std::to_string(mode.tree_budget) + : std::string("MLX DFlash: Serial DFlash2")) + + " (" + mode.reason + ")"; + ET_LOG(Info, "%s", chosen.c_str()); + if (note) { + *note = chosen; + } + } + 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)) { @@ -428,7 +509,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 +820,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 +840,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 +878,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 +888,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 +914,36 @@ 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) { + 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 || @@ -896,6 +1010,19 @@ bool MuseGlimmerMLXExecutor::speculate( const batching::BatchInput& batch, batching::BatchOutput& out, bool input_anchors) { + // PairTree verifies greedy sessions only. They draft first, in rounds of + // their own, and sampled sessions after them, so a batch interleaving the + // two still forms full rounds. + return (dflash_->tree_budget == 0 || + speculate_rounds(batch, out, input_anchors, true)) && + speculate_rounds(batch, out, input_anchors, false); +} + +bool MuseGlimmerMLXExecutor::speculate_rounds( + const batching::BatchInput& batch, + batching::BatchOutput& out, + bool input_anchors, + bool trees) { const int b = dflash_->verify_block; size_t cursor = 0; while (cursor < batch.inputs.size()) { @@ -909,7 +1036,9 @@ bool MuseGlimmerMLXExecutor::speculate( const int end = input.position + input.offset + input.size - static_cast(input_anchors); if (!out.outputs[cursor] || end != ctl_->pos(state.seq_id) || - end > spec_->max_context_length - dflash_->block) { + end > spec_->max_context_length - dflash_->block || + (dflash_->tree_budget > 0 && + (state.sampling->temperature == 0) != trees)) { ++cursor; continue; } @@ -918,7 +1047,9 @@ bool MuseGlimmerMLXExecutor::speculate( } const size_t count = state.hidden.size() / dflash_->row_bytes(); if (owners.size() == static_cast(dflash_->max_owners) || - context + count > static_cast(dflash_->context)) { + context + count > static_cast(dflash_->context) || + (trees && + owners.size() == static_cast(dflash_->tree_owners))) { break; } context += count; @@ -932,10 +1063,39 @@ bool MuseGlimmerMLXExecutor::speculate( if (owners.empty()) { continue; } + std::optional tree; + if (trees) { + // Each owner's tree fits its share of one forward and its context. + tree.emplace(); + for (const auto owner : owners) { + tree->budgets.push_back(pairtree::round_budget( + dflash_->tree_budget, + dflash_->tree_rows, + static_cast(owners.size()), + spec_->max_context_length - ctl_->pos(sessions_.at(owner).seq_id) - + 1)); + } + } else if (dflash_->tree_budget > 0 && !dflash_->logged_sampled_fallback) { + ET_LOG( + Info, + "PairTree DFlash2 verifies greedy sessions only; sampled sessions run Serial DFlash2"); + dflash_->logged_sampled_fallback = true; + } 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 +1129,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..241b69c0810 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,12 @@ 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. + // 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,11 +84,24 @@ 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, bool input_anchors = false); + // One pass over the batch: its greedy sessions' tree rounds, or the rest. + bool speculate_rounds( + const batching::BatchInput& batch, + batching::BatchOutput& out, + bool input_anchors, + bool trees); bool execute_impl( 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 b38ed058268..56925d3d60e 100644 --- a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp +++ b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp @@ -22,7 +22,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 3b8991a0827..64f8c517bbc 100644 --- a/examples/models/muse-glimmer/tests/README.md +++ b/examples/models/muse-glimmer/tests/README.md @@ -36,7 +36,19 @@ 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 the Serial DFlash2 +fallback for sampled sessions. Serial-only on those fixtures must match +Serial DFlash2 on the plain fixtures 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 and, with only sampled sessions, matches Serial DFlash2 the +same way; 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..e89394943d0 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,8 +19,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -47,13 +50,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 +205,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 +388,191 @@ 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 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) { + 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 + }; + 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}); + }; + 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); + } + decode(8); + result.tokens.push_back(slots.front().history); + 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.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. On the random fixture, PairTree +// DFlash2 accepts differently and must differ, or the check proves nothing; +// the always-accepting fixture accepts every chain proposal either way. +void check_serial_only_identity( + const std::string& plain, + const std::string& pairtree, + int sessions) { + 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"); + } + // PairTree mode drafts with draft_forward_pairtree alone; with only sampled + // sessions it runs no tree, and its candidates must be draft_forward's. + 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"); + require( + pairtree.find("random") == std::string::npos || + 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 +641,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 +665,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 +1088,99 @@ 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] : + {std::pair{"/random", "/random_pairtree"}, + std::pair{"/reject_-1", "/reject_-1_pairtree"}}) { + for (int sessions : {1, 4, 16}) { + check_serial_only_identity(root + plain, root + pairtree, sessions); + } + } + { + // 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 +1202,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"],