From 2870cb29bf2281c62649c61e551e4141a2d1aacc Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Wed, 2 Dec 2026 22:06:16 -0800 Subject: [PATCH 1/5] Add tree steps to the cell KV cache A tree step declares, per token, the step index of its parent, so one forward can verify a tree of speculative continuations per sequence. A root continues its sequence and a child sits one position past its parent. Of the step's own cells, a query attends only its ancestors, never their siblings; history and the sliding window are unchanged. After the forward, retain_tree keeps an accepted root-to-node path per tree and frees every other cell the step claimed. A tree no one retains stays pending until the next verb that changes the table resolves it: each tree keeps its root and the single path below it up to the first branch, so siblings never become history. While a tree is pending, pos() already reports its sequences as that resolution leaves them, so positions a caller derives from it hold for the next step. The DFlash draft layout, whose steps are owner blocks, refuses tree steps. The tests cover sibling isolation, retained paths continuing as history, implicit resolution and pos() while pending, several sequences, windowed layers, branch reclamation, malformed trees and keep sets, and a fuzz of the mask against a brute-force rule. A test-only hook, reached through the shared CellCacheTestPeer test header, makes siblings visible for negative controls; the fuzz runs again with it on and must then catch the leak. Authored with AI assistance (Claude, via Metamate). --- extension/llm/cache/cache.h | 30 ++ extension/llm/cache/cell_cache.cpp | 187 ++++++- extension/llm/cache/cell_cache.h | 32 +- extension/llm/cache/test/CMakeLists.txt | 4 +- .../llm/cache/test/cell_cache_test_peer.h | 33 ++ .../llm/cache/test/cell_cache_tree_test.cpp | 506 ++++++++++++++++++ extension/llm/cache/test/targets.bzl | 13 +- 7 files changed, 800 insertions(+), 5 deletions(-) create mode 100644 extension/llm/cache/test/cell_cache_test_peer.h create mode 100644 extension/llm/cache/test/cell_cache_tree_test.cpp diff --git a/extension/llm/cache/cache.h b/extension/llm/cache/cache.h index 89c7f5d9530..3b95582b790 100644 --- a/extension/llm/cache/cache.h +++ b/extension/llm/cache/cache.h @@ -135,6 +135,36 @@ class ET_EXPERIMENTAL BatchControl : public CacheControl { // Where the sequence stands: one past its newest position, and so where it // continues. Positions are dense from 0, so this is also how many it holds. virtual int pos(int32_t seq_id) const = 0; + + // Tree steps, for tree-shaped speculative verification. A layout without + // them keeps these defaults. + virtual bool supports_tree_steps() const { + return false; + } + // Declares a step whose tokens form one tree per sequence. parents[i] is the + // step index of token i's parent, earlier in the step and of the same + // sequence, or -1 for a root, which continues its sequence. A token sits one + // position past its parent and attends its sequence's history and its own + // ancestors in the step, never their siblings. Admission as declare_step. + virtual bool declare_tree_step( + const std::vector& /*seq_ids*/, + const std::vector& /*parents*/) { + return false; + } + // After the forward of the last placed tree step, keeps only the listed step + // indices, at most one root-to-node path per tree, and frees every other + // cell the step claimed; a tree whose root is not kept leaves its sequence + // as it was before the step. Until then the tree is pending, and + // declare_step, a well-formed declare_tree_step, seq_clone, seq_rm and + // rewind first resolve it instead: each tree keeps its root and the path + // below it up to the first node with several children, so siblings never + // become history. pos() already reports a pending tree's sequences as that + // resolution leaves them. False = no pending tree, or `keep` is not such a + // set (an index out of range or repeated, a node without its parent, or two + // kept siblings); nothing changes. + virtual bool retain_tree(const std::vector& /*keep*/) { + return false; + } }; // Per-layer cache kind and its parameters. diff --git a/extension/llm/cache/cell_cache.cpp b/extension/llm/cache/cell_cache.cpp index 2148718e637..c052f2cd7c9 100644 --- a/extension/llm/cache/cell_cache.cpp +++ b/extension/llm/cache/cell_cache.cpp @@ -10,6 +10,7 @@ #include #include +#include namespace executorch { namespace extension { @@ -45,13 +46,16 @@ void CellCache::clear() { reserved_ = 0; declared_ = false; step_seq_ids_.clear(); + step_parents_.clear(); step_pos_.clear(); + tree_.reset(); invalidate_steps(); } // -- BatchControl ------------------------------------------------------------ bool CellCache::declare_step(const std::vector& seq_ids) { + resolve_tree(); if (seq_ids.empty() || !has_room(static_cast(seq_ids.size()))) { return false; } @@ -77,11 +81,127 @@ bool CellCache::declare_step(const std::vector& seq_ids) { } } step_seq_ids_ = seq_ids; + step_parents_.clear(); declared_ = true; invalidate_steps(); return true; } +bool CellCache::supports_tree_steps() const { + return !dflash_block_size_; +} + +bool CellCache::declare_tree_step( + const std::vector& seq_ids, + const std::vector& parents) { + if (dflash_block_size_ || parents.size() != seq_ids.size()) { + return false; + } + uint64_t rooted = 0; + for (size_t i = 0; i < parents.size(); ++i) { + const int32_t parent = parents[i]; + if (parent < -1 || parent >= static_cast(i) || + (parent >= 0 && seq_ids[parent] != seq_ids[i])) { + return false; + } + if (parent < 0) { + // One root per sequence, so each sequence's tokens form one tree. + if (!valid_seq(seq_ids[i]) || (rooted & bit(seq_ids[i]))) { + return false; + } + rooted |= bit(seq_ids[i]); + } + } + if (!CellCache::declare_step(seq_ids)) { + return false; + } + step_parents_ = parents; + return true; +} + +bool CellCache::retain_tree(const std::vector& keep) { + if (!tree_) { + return false; + } + const PlacedTree& tree = *tree_; + const int length = static_cast(tree.cells.size()); + std::vector kept(length, 0); + for (const int32_t index : keep) { + if (index < 0 || index >= length || kept[index]) { + return false; + } + kept[index] = 1; + } + // Root-to-node paths: a kept node's parent is kept, and keeps no other + // child. + std::vector kept_child(length, 0); + for (int i = 0; i < length; ++i) { + const int32_t parent = tree.parents[i]; + if (kept[i] && parent >= 0 && + (!kept[parent] || std::exchange(kept_child[parent], 1))) { + return false; + } + } + uint64_t touched = 0; + for (int i = 0; i < length; ++i) { + if (kept[i]) { + continue; + } + const int cell = tree.cells[i]; + const uint64_t b = bit(tree.seq_ids[i]); + touched |= b; + owners_[cell] &= ~b; + if (owners_[cell] == 0) { + pos_[cell] = -1; + --used_count_; + } + } + while (used_end_ > 0 && pos_[used_end_ - 1] < 0) { + --used_end_; + } + for (int32_t seq_id = 0; seq_id < kMaxSeqs; ++seq_id) { + if (touched & bit(seq_id)) { + rescan(seq_id); + } + } + tree_.reset(); + invalidate_steps(); + return true; +} + +namespace { +// Each tree's root and the chain below it, up to the first node with several +// children: the longest part that is one path. +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; +} +} // namespace + +void CellCache::resolve_tree() { + if (!tree_) { + return; + } + const bool retained = + CellCache::retain_tree(unbranched_paths(tree_->parents)); + assert(retained); + (void)retained; +} + bool CellCache::live(int32_t seq_id) const { return (reserved_ & bit(seq_id)) != 0; } @@ -103,6 +223,7 @@ std::optional CellCache::seq_new() { std::optional CellCache::seq_clone( int32_t src, std::optional upto) { + resolve_tree(); if (!valid_seq(src) || info_[src].count == 0) { return std::nullopt; } @@ -122,6 +243,7 @@ std::optional CellCache::seq_clone( } bool CellCache::seq_rm(int32_t seq_id) { + resolve_tree(); if (!valid_seq(seq_id) || !live(seq_id)) { return false; } @@ -132,6 +254,7 @@ bool CellCache::seq_rm(int32_t seq_id) { } bool CellCache::rewind(int32_t seq_id, int position) { + resolve_tree(); if (!valid_seq(seq_id) || !live(seq_id) || position < 0 || position > pos(seq_id)) { return false; @@ -159,7 +282,22 @@ void CellCache::drop_from(int32_t seq_id, int from) { } int CellCache::pos(int32_t seq_id) const { - return valid_seq(seq_id) ? info_[seq_id].max_pos + 1 : 0; + if (!valid_seq(seq_id)) { + return 0; + } + if (tree_) { + // As the pending tree will resolve: its root and unbranched chain. + int end = -1; + for (const int32_t node : unbranched_paths(tree_->parents)) { + if (tree_->seq_ids[node] == seq_id) { + end = std::max(end, pos_[tree_->cells[node]] + 1); + } + } + if (end >= 0) { + return end; + } + } + return info_[seq_id].max_pos + 1; } int CellCache::free_cells() const { @@ -196,13 +334,17 @@ CellCache::place_step(int layer, const int32_t* positions, int length) { if (!declared_ || length != static_cast(step_seq_ids_.size())) { return nullptr; // no declaration, or a token count disagreeing with it } - if (!continues(positions, length)) { + if (step_parents_.empty() ? !continues(positions, length) + : !tree_continues(positions, length)) { return nullptr; // a position a sequence already holds } step_pos_.assign(positions, positions + length); if (!place()) { return nullptr; // out of cells } + if (!step_parents_.empty()) { + tree_ = PlacedTree{cells_, step_seq_ids_, step_parents_}; + } declared_ = false; // one declaration, one placement placed_ = true; return &step_for(windows_[layer]); @@ -214,8 +356,11 @@ void CellCache::end_step() { void CellCache::abandon_step() { if (!placed_) { + resolve_tree(); return; } + // The failed step's cells all go, a tree's included. + tree_.reset(); // Each sequence's first position in the step. std::map starts; for (size_t i = 0; i < step_seq_ids_.size(); ++i) { @@ -254,6 +399,18 @@ bool CellCache::continues(const int32_t* positions, int length) const { return true; } +bool CellCache::tree_continues(const int32_t* positions, int length) const { + for (int i = 0; i < length; ++i) { + const int32_t parent = step_parents_[i]; + const int32_t expected = parent < 0 ? info_[step_seq_ids_[i]].max_pos + 1 + : positions[parent] + 1; + if (positions[i] != expected) { + return false; + } + } + return true; +} + int CellCache::lowest_free(int from) const { for (int i = from; i < capacity_; ++i) { if (pos_[i] < 0) { @@ -340,12 +497,38 @@ std::vector CellCache::build_mask(int window) const { const int length = static_cast(cells_.size()); std::vector bits( static_cast(length) * static_cast(used_end_), 0); + const bool tree = !step_parents_.empty(); + // Step index per cell of this step, -1 for history. + std::vector step_of_cell; + std::vector ancestor; + if (tree) { + step_of_cell.assign(used_end_, -1); + for (int k = 0; k < length; ++k) { + step_of_cell[cells_[k]] = k; + } + ancestor.resize(length); + } for (int i = 0; i < length; ++i) { const uint64_t tok_bit = bit(step_seq_ids_[i]); const int32_t tok_pos = step_pos_[i]; const int32_t oldest = window > 0 ? tok_pos - window + 1 : 0; uint8_t* row = bits.data() + static_cast(i) * used_end_; + if (tree) { + std::fill(ancestor.begin(), ancestor.end(), 0); + for (int32_t a = i; a >= 0; a = step_parents_[a]) { + ancestor[a] = 1; + } + } for (int j = 0; j < used_end_; ++j) { + if (tree && step_of_cell[j] >= 0) { + const int32_t k = step_of_cell[j]; + const bool visible = tree_siblings_visible_ + ? step_seq_ids_[k] == step_seq_ids_[i] && pos_[j] <= tok_pos && + k <= i + : ancestor[k] != 0; + row[j] = static_cast(visible && pos_[j] >= oldest); + continue; + } row[j] = static_cast( pos_[j] >= 0 && // occupied: a freed cell holds nothing (owners_[j] & tok_bit) && // one of this query's sequences diff --git a/extension/llm/cache/cell_cache.h b/extension/llm/cache/cell_cache.h index a47ac17d04a..a6be67c16cc 100644 --- a/extension/llm/cache/cell_cache.h +++ b/extension/llm/cache/cell_cache.h @@ -77,6 +77,12 @@ class ET_EXPERIMENTAL CellCache : public Cache, // -- BatchControl ------------------------------------------------------ bool declare_step(const std::vector& seq_ids) override; + // Not on a DFlash draft layout, whose steps are owner blocks. + bool supports_tree_steps() const override; + bool declare_tree_step( + const std::vector& seq_ids, + const std::vector& parents) override; + bool retain_tree(const std::vector& keep) override; // kMaxSeqs: one bit each in the owner bitset. std::optional max_seqs() const override; std::optional seq_new() override; @@ -103,7 +109,12 @@ class ET_EXPERIMENTAL CellCache : public Cache, void end_step(); // Ends the placed step after its forward failed: each of its sequences // drops back to its first position in the step, giving back the cells the - // step claimed. Does nothing without a placed step. + // step claimed. Without a placed step it only resolves a pending tree. + // + // A step's cells are shared by every layer, so a step counts as placed, and + // a tree step as pending, once any layer has placed it: until abandon_step + // undoes it, pos() and every other verb treat it as if its forward ran, a + // linear step and a tree alike. void abandon_step(); protected: @@ -126,6 +137,12 @@ class ET_EXPERIMENTAL CellCache : public Cache, // Whether every position is the next one for its sequence. bool continues(const int32_t* positions, int length) const; + // Tree steps: a root continues its sequence; a child sits one past its + // parent. + bool tree_continues(const int32_t* positions, int length) const; + // Settles an unretained tree before another verb: each tree keeps its root + // and the single path below it, up to the first branch. + void resolve_tree(); // Placement policy: the lowest free cell, so freed cells refill before the // extent grows. The choice moves only the read window's width and how often a @@ -160,8 +177,11 @@ class ET_EXPERIMENTAL CellCache : public Cache, // Query i attends cell j iff j is occupied, shares a sequence with i, is no // newer than i, and on a windowed layer no older than its window. The step's // cells are already placed, so a query sees itself and its earlier tokens. + // In a tree step a query sees, of the step's own cells, only its ancestors. std::vector build_mask(int window) const; + friend struct CellCacheTestPeer; + int capacity_; const std::optional dflash_block_size_; std::vector pos_; // per cell; -1 = free @@ -172,6 +192,16 @@ class ET_EXPERIMENTAL CellCache : public Cache, uint64_t reserved_ = 0; // ids handed out by seq_new std::vector step_seq_ids_; // set by declare_step + // Parent step index per token of a declared tree step; empty otherwise. + std::vector step_parents_; + // The last placed tree step, until retain_tree or another verb resolves it. + struct PlacedTree { + std::vector cells, seq_ids, parents; + }; + std::optional tree_; + // Test-only (CellCacheTestPeer): tree masks fall back to the position rule, + // so siblings see one another. Verification against it must fail. + bool tree_siblings_visible_ = false; std::vector step_pos_; // set when the step is placed std::vector cells_; // the step's placement, shared by every layer std::vector windows_; // per layer; 0 = keeps all history diff --git a/extension/llm/cache/test/CMakeLists.txt b/extension/llm/cache/test/CMakeLists.txt index 9fc67427ace..3ff9fd4f526 100644 --- a/extension/llm/cache/test/CMakeLists.txt +++ b/extension/llm/cache/test/CMakeLists.txt @@ -10,7 +10,9 @@ set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../../..) include(${EXECUTORCH_ROOT}/tools/cmake/Test.cmake) -set(_test_srcs cache_test.cpp sequence_clone_attention_test.cpp) +set(_test_srcs cache_test.cpp cell_cache_tree_test.cpp + sequence_clone_attention_test.cpp +) et_cxx_test( extension_llm_cache_test SOURCES ${_test_srcs} EXTRA_LIBS extension_llm_cache diff --git a/extension/llm/cache/test/cell_cache_test_peer.h b/extension/llm/cache/test/cell_cache_test_peer.h new file mode 100644 index 00000000000..bedc402dacb --- /dev/null +++ b/extension/llm/cache/test/cell_cache_test_peer.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#pragma once + +#include + +#include + +namespace executorch::extension::llm::cache { + +// Test access to CellCache internals, shared by the cache and executor tests. +struct CellCacheTestPeer { + // Lets in-step tree nodes attend their siblings, for negative controls. + static void set_tree_siblings_visible(CellCache& cache, bool visible) { + cache.tree_siblings_visible_ = visible; + } + // Every cell's position and owners, appended to `bytes`. + static void append_table(const CellCache& cache, std::string& bytes) { + bytes.append( + reinterpret_cast(cache.pos_.data()), + cache.pos_.size() * sizeof(cache.pos_[0])); + bytes.append( + reinterpret_cast(cache.owners_.data()), + cache.owners_.size() * sizeof(cache.owners_[0])); + } +}; + +} // namespace executorch::extension::llm::cache diff --git a/extension/llm/cache/test/cell_cache_tree_test.cpp b/extension/llm/cache/test/cell_cache_tree_test.cpp new file mode 100644 index 00000000000..b4562d6a9ab --- /dev/null +++ b/extension/llm/cache/test/cell_cache_tree_test.cpp @@ -0,0 +1,506 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include + +#include +#include +#include + +#include + +using executorch::extension::llm::cache::CacheConfig; +using executorch::extension::llm::cache::CacheGeometry; +using executorch::extension::llm::cache::CellCache; +using executorch::extension::llm::cache::CellCacheTestPeer; +using executorch::extension::llm::cache::CellStep; +using executorch::extension::llm::cache::LayerPolicy; + +namespace { +using Ints = std::vector; + +// Layer 0 keeps all history; layer 1 is a ring of `window`. +struct TreeCache { + TreeCache(int capacity, int window) + : cache(geometry(window), {capacity, 0}) {} + static CacheGeometry geometry(int window) { + CacheGeometry geometry; + geometry.layers.push_back({{LayerPolicy::Kind::Flat, 0}, 1, 8}); + geometry.layers.push_back({{LayerPolicy::Kind::Ring, window}, 1, 8}); + return geometry; + } + bool append(int32_t seq, int n) { + Ints ids(n, seq), positions(n); + for (int i = 0; i < n; ++i) { + positions[i] = cache.pos(seq) + i; + } + return cache.declare_step(ids) && + cache.place_step(0, positions.data(), n) && + cache.place_step(1, positions.data(), n); + } + // The flat and ring steps of a placed tree, or nulls. + std::pair + tree(const Ints& ids, const Ints& parents, const Ints& positions) { + if (!cache.declare_tree_step(ids, parents)) { + return {nullptr, nullptr}; + } + const int n = static_cast(ids.size()); + const CellStep* flat = cache.place_step(0, positions.data(), n); + return {flat, cache.place_step(1, positions.data(), n)}; + } + CellCache cache; +}; + +bool sees(const CellStep* step, int row, int cell) { + return step->mask_bits[static_cast(row) * step->read_len + cell]; +} + +int visible(const CellStep* step, int row) { + int count = 0; + for (int cell = 0; cell < step->read_len; ++cell) { + count += sees(step, row, cell); + } + return count; +} +} // namespace + +TEST(CellCacheTreeTest, SiblingsNeverSeeEachOther) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 5)); + EXPECT_TRUE(t.cache.supports_tree_steps()); + // Root r(5); siblings x(6) and y(6); z(7) under y and w(7) under x. + const Ints ids(5, a), parents{-1, 0, 0, 2, 1}, positions{5, 6, 6, 7, 7}; + const auto [s, ring] = t.tree(ids, parents, positions); + ASSERT_TRUE(s && ring); + const auto cell = [&](int k) { return s->cells[k]; }; + for (int row = 0; row < 5; ++row) { + for (int history = 0; history < 5; ++history) { + EXPECT_TRUE(sees(s, row, history)); + } + EXPECT_TRUE(sees(s, row, cell(row))); + } + for (int k = 1; k < 5; ++k) { + EXPECT_FALSE(sees(s, 0, cell(k))); + } + EXPECT_TRUE(sees(s, 3, cell(0)) && sees(s, 3, cell(2))); + // The position rule would let y see its earlier sibling x. + EXPECT_FALSE(sees(s, 2, cell(1))); + EXPECT_FALSE(sees(s, 1, cell(2))); + EXPECT_FALSE(sees(s, 3, cell(1)) || sees(s, 3, cell(4))); + EXPECT_FALSE(sees(s, 4, cell(2)) || sees(s, 4, cell(3))); + + // Without the tree, the repeated positions are refused at placement. + TreeCache flat(64, 1000); + const int32_t b = *flat.cache.seq_new(); + ASSERT_TRUE(flat.append(b, 5)); + ASSERT_TRUE(flat.cache.declare_step(ids)); + EXPECT_EQ(flat.cache.place_step(0, positions.data(), 5), nullptr); +} + +TEST(CellCacheTreeTest, RetainedPathBecomesHistory) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 5)); + ASSERT_TRUE(t.tree(Ints(5, a), {-1, 0, 0, 2, 1}, {5, 6, 6, 7, 7}).first); + // Pending, the tree counts as it would resolve: the root branches. + EXPECT_EQ(t.cache.pos(a), 6); + ASSERT_TRUE(t.cache.retain_tree({0, 2, 3})); + EXPECT_EQ(t.cache.pos(a), 8); + EXPECT_EQ(t.cache.free_cells(), 64 - 8); + EXPECT_FALSE(t.cache.retain_tree({0})); + const auto [next, ring] = t.tree({a}, {-1}, {8}); + ASSERT_TRUE(next); + EXPECT_EQ(visible(next, 0), 9); + ASSERT_TRUE(t.cache.retain_tree({0})); + EXPECT_EQ(t.cache.pos(a), 9); +} + +TEST(CellCacheTreeTest, OwnersStayIsolatedAndRetainDifferentDepths) { + TreeCache t(128, 1000); + const int32_t a = *t.cache.seq_new(); + const int32_t b = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 3)); + ASSERT_TRUE(t.append(b, 10)); + const auto [s, ring] = + t.tree({b, b, b, a, a, a}, {-1, 0, 0, -1, 3, 3}, {10, 11, 11, 3, 4, 4}); + ASSERT_TRUE(s); + for (int row = 0; row < 3; ++row) { + for (int k = 3; k < 6; ++k) { + EXPECT_FALSE(sees(s, row, s->cells[k])); + EXPECT_FALSE(sees(s, k, s->cells[row])); + } + } + EXPECT_EQ(visible(s, 4), 3 + 2); + EXPECT_EQ(visible(s, 1), 10 + 2); + ASSERT_TRUE(t.cache.retain_tree({0, 2, 3})); + EXPECT_EQ(t.cache.pos(b), 12); + EXPECT_EQ(t.cache.pos(a), 4); + // A sequence with no history roots a tree at position 0. + const int32_t c = *t.cache.seq_new(); + const auto [fresh, fresh_ring] = t.tree({c, c, c}, {-1, 0, 0}, {0, 1, 1}); + ASSERT_TRUE(fresh); + EXPECT_FALSE(sees(fresh, 1, fresh->cells[2])); + ASSERT_TRUE(t.cache.retain_tree({0, 1})); + EXPECT_EQ(t.cache.pos(c), 2); +} + +TEST(CellCacheTreeTest, WindowStillBoundsTreeQueries) { + constexpr int kWindow = 4; + TreeCache t(64, kWindow); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 6)); + // Chain root(6) -> child(7) -> grandchild(8), plus a second child(7). + const auto [flat, ring] = t.tree(Ints(4, a), {-1, 0, 1, 0}, {6, 7, 8, 7}); + ASSERT_TRUE(flat && ring); + // History 5, root, child and itself; never the sibling. + EXPECT_EQ(visible(ring, 2), kWindow); + EXPECT_FALSE(sees(ring, 2, ring->cells[3])); + for (int history = 0; history < 5; ++history) { + EXPECT_FALSE(sees(ring, 2, history)); + EXPECT_TRUE(sees(flat, 2, history)); + } + ASSERT_TRUE(t.cache.retain_tree({0, 3})); + EXPECT_EQ(t.cache.pos(a), 8); +} + +TEST(CellCacheTreeTest, DroppedBranchesFreeTheirCells) { + TreeCache t(16, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 4)); + // Eight cells a round: without reclaiming branches the pool runs out on the + // second round. + for (int round = 0; round < 5; ++round) { + const int p = t.cache.pos(a); + ASSERT_TRUE(t.tree( + Ints(8, a), + {-1, 0, 0, 1, 1, 2, 2, 3}, + {p, p + 1, p + 1, p + 2, p + 2, p + 2, p + 2, p + 3}) + .first); + ASSERT_TRUE(t.cache.retain_tree({0})); + EXPECT_EQ(t.cache.pos(a), p + 1); + } + EXPECT_EQ(t.cache.free_cells(), 16 - t.cache.pos(a)); +} + +TEST(CellCacheTreeTest, MalformedTreesAreRefused) { + TreeCache t(16, 1000); + const int32_t a = *t.cache.seq_new(); + const int32_t b = *t.cache.seq_new(); + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-1, 1})); // not earlier + EXPECT_FALSE(t.cache.declare_tree_step({a, b}, {-1, 0})); // other sequence + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-1})); // size mismatch + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-1, -1})); // two roots + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-2, 0})); + EXPECT_FALSE(t.cache.retain_tree({})); + ASSERT_TRUE(t.cache.declare_tree_step({a, a}, {-1, 0})); + const Ints skipped{0, 2}; + EXPECT_EQ(t.cache.place_step(0, skipped.data(), 2), nullptr); +} + +TEST(CellCacheTreeTest, KeptNodesMustBeRootToNodePaths) { + TreeCache t(32, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 3)); + ASSERT_TRUE(t.tree(Ints(4, a), {-1, 0, 0, 1}, {3, 4, 4, 5}).first); + const int free = t.cache.free_cells(); + // Pending, the tree counts as it would resolve: the root alone. + EXPECT_EQ(t.cache.pos(a), 4); + EXPECT_FALSE(t.cache.retain_tree({0, 3})); // a node without its parent + EXPECT_FALSE(t.cache.retain_tree({0, 1, 2})); // two siblings + EXPECT_FALSE(t.cache.retain_tree({0, 4})); // out of range + EXPECT_FALSE(t.cache.retain_tree({0, 0})); // repeated + EXPECT_FALSE(t.cache.retain_tree({0, 1, 3, 1})); + // Refusals change nothing: the tree is still pending, its cells all held. + EXPECT_EQ(t.cache.free_cells(), free); + EXPECT_EQ(t.cache.pos(a), 4); + ASSERT_TRUE(t.cache.retain_tree({0, 1, 3})); + EXPECT_EQ(t.cache.pos(a), 6); + EXPECT_EQ(t.cache.free_cells(), free + 1); + const Ints next{6}; + ASSERT_TRUE(t.cache.declare_step({a})); + const CellStep* step = t.cache.place_step(0, next.data(), 1); + ASSERT_NE(step, nullptr); + EXPECT_EQ(visible(step, 0), 7); +} + +TEST(CellCacheTreeTest, EveryOtherVerbResolvesTheTree) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 4)); + ASSERT_TRUE(t.tree({a, a, a}, {-1, 0, 0}, {4, 5, 5}).first); + t.cache.abandon_step(); + EXPECT_EQ(t.cache.pos(a), 4); + EXPECT_FALSE(t.cache.retain_tree({0})); + ASSERT_TRUE(t.append(a, 3)); + EXPECT_FALSE(t.cache.retain_tree({0})); + + // A chain is kept whole. + ASSERT_TRUE(t.tree({a, a}, {-1, 0}, {7, 8}).first); + ASSERT_TRUE(t.cache.declare_step({a})); + EXPECT_FALSE(t.cache.retain_tree({0})); + EXPECT_EQ(t.cache.pos(a), 9); + ASSERT_TRUE(t.cache.rewind(a, 7)); + + ASSERT_TRUE(t.tree({a, a}, {-1, 0}, {7, 8}).first); + ASSERT_TRUE(t.cache.rewind(a, 9)); + EXPECT_FALSE(t.cache.retain_tree({0})); + ASSERT_TRUE(t.cache.rewind(a, 7)); + + ASSERT_TRUE(t.tree({a, a}, {-1, 0}, {7, 8}).first); + const auto clone = t.cache.seq_clone(a, std::nullopt); + ASSERT_TRUE(clone); + EXPECT_FALSE(t.cache.retain_tree({0})); + EXPECT_EQ(t.cache.pos(*clone), 9); + ASSERT_TRUE(t.cache.seq_rm(*clone)); + ASSERT_TRUE(t.cache.rewind(a, 7)); + + ASSERT_TRUE(t.tree({a, a}, {-1, 0}, {7, 8}).first); + const int32_t other = *t.cache.seq_new(); + ASSERT_TRUE(t.cache.seq_rm(other)); + EXPECT_FALSE(t.cache.retain_tree({0})); + + // An ended step is resolved by abandon_step, not dropped. + ASSERT_TRUE(t.cache.rewind(a, 7)); + ASSERT_TRUE(t.tree({a, a}, {-1, 0}, {7, 8}).first); + t.cache.end_step(); + t.cache.abandon_step(); + EXPECT_EQ(t.cache.pos(a), 9); + EXPECT_FALSE(t.cache.retain_tree({0})); + + t.cache.clear(); + EXPECT_FALSE(t.cache.retain_tree({0})); +} + +// A tree no one retained keeps only its unbranched part: the next step attends +// history, the root and the single path below it, never a sibling. +TEST(CellCacheTreeTest, ImplicitResolutionDropsBranches) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + const int32_t b = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 3)); + ASSERT_TRUE(t.append(b, 3)); + // a: root(3) with siblings (4, 4). b: root(3) -> child(4) -> two + // grandchildren (5, 5). + ASSERT_TRUE(t.tree( + {a, a, a, b, b, b, b}, + {-1, 0, 0, -1, 3, 4, 4}, + {3, 4, 4, 3, 4, 5, 5}) + .first); + const int free = t.cache.free_cells(); + // pos() reports where the resolution leaves each sequence before it runs. + EXPECT_EQ(t.cache.pos(a), 4); + EXPECT_EQ(t.cache.pos(b), 5); + ASSERT_TRUE(t.cache.declare_step({a, b})); + EXPECT_EQ(t.cache.pos(a), 4); + EXPECT_EQ(t.cache.pos(b), 5); + EXPECT_EQ(t.cache.free_cells(), free + 4); + const Ints next{4, 5}; + const CellStep* step = t.cache.place_step(0, next.data(), 2); + ASSERT_NE(step, nullptr); + EXPECT_EQ(visible(step, 0), 3 + 1 + 1); + EXPECT_EQ(visible(step, 1), 3 + 2 + 1); + + // Retaining no node of a tree drops all of it. + ASSERT_TRUE(t.tree({a, a, b}, {-1, 0, -1}, {5, 6, 6}).first); + ASSERT_TRUE(t.cache.retain_tree({2})); + EXPECT_EQ(t.cache.pos(a), 5); + EXPECT_EQ(t.cache.pos(b), 7); +} + +// A tree placed on one layer only is already pending: pos() reports its +// resolution, which the next verb performs; abandon_step drops it whole. +TEST(CellCacheTreeTest, PartlyPlacedTreesResolveOrAbandonWhole) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 3)); + const int free = t.cache.free_cells(); + const Ints branched{3, 4, 4, 5}; + ASSERT_TRUE(t.cache.declare_tree_step(Ints(4, a), {-1, 0, 0, 1})); + ASSERT_NE(t.cache.place_step(0, branched.data(), 4), nullptr); + EXPECT_EQ(t.cache.pos(a), 4); + t.cache.abandon_step(); + EXPECT_EQ(t.cache.pos(a), 3); + EXPECT_EQ(t.cache.free_cells(), free); + EXPECT_FALSE(t.cache.retain_tree({0})); + + const Ints chain{3, 4}; + ASSERT_TRUE(t.cache.declare_tree_step(Ints(2, a), {-1, 0})); + ASSERT_NE(t.cache.place_step(0, chain.data(), 2), nullptr); + EXPECT_EQ(t.cache.pos(a), 5); + ASSERT_TRUE(t.cache.declare_step({a})); + EXPECT_EQ(t.cache.pos(a), 5); + EXPECT_EQ(t.cache.free_cells(), free - 2); + const Ints next{5}; + const CellStep* step = t.cache.place_step(0, next.data(), 1); + ASSERT_NE(step, nullptr); + EXPECT_EQ(visible(step, 0), 6); +} + +// A malformed declare_tree_step is refused before it resolves anything: the +// pending tree, its cells and pos() stay as they were. +TEST(CellCacheTreeTest, MalformedDeclarationsLeaveThePendingTree) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 3)); + ASSERT_TRUE(t.tree({a, a, a}, {-1, 0, 0}, {3, 4, 4}).first); + const int free = t.cache.free_cells(); + EXPECT_EQ(t.cache.pos(a), 4); + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-1, 1})); // not earlier + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-1, -1})); // two roots + EXPECT_FALSE(t.cache.declare_tree_step({a, a}, {-1})); // sizes differ + EXPECT_EQ(t.cache.pos(a), 4); + EXPECT_EQ(t.cache.free_cells(), free); + ASSERT_TRUE(t.cache.retain_tree({0, 2})); + EXPECT_EQ(t.cache.pos(a), 5); +} + +TEST(CellCacheTreeTest, DFlashLayoutRefusesTrees) { + CacheGeometry geometry = TreeCache::geometry(4); + geometry.dflash_block_size = 2; + CellCache cache(geometry, CacheConfig{64, 0}); + const int32_t a = *cache.seq_new(); + EXPECT_FALSE(cache.supports_tree_steps()); + EXPECT_FALSE(cache.declare_tree_step({a, a}, {-1, 0})); +} + +TEST(CellCacheTreeTest, VisibleSiblingsTestHookLeaks) { + TreeCache t(64, 1000); + const int32_t a = *t.cache.seq_new(); + ASSERT_TRUE(t.append(a, 2)); + CellCacheTestPeer::set_tree_siblings_visible(t.cache, true); + const auto [s, ring] = t.tree({a, a, a}, {-1, 0, 0}, {2, 3, 3}); + ASSERT_TRUE(s); + EXPECT_TRUE(sees(s, 2, s->cells[1])); + EXPECT_FALSE(sees(s, 1, s->cells[2])); +} + +// Random forests over several sequences, against the rule computed directly: +// a query sees its sequence's history inside its window and, of the step, its +// own ancestors inside its window. Then a random path per tree is retained. +static void run_mask_fuzz(bool leaky) { + unsigned seed = 12345; + const auto random = [&](int n) { + seed = seed * 1103515245u + 12345u; + return static_cast((seed >> 16) % static_cast(n)); + }; + int trials = 0, leaking = 0; + for (int trial = 0; trial < 3000; ++trial) { + const int window = 1 + random(6); + TreeCache t(256, window); + CellCacheTestPeer::set_tree_siblings_visible(t.cache, leaky); + std::vector seqs; + for (int q = 1 + random(3); q > 0; --q) { + seqs.push_back(*t.cache.seq_new()); + const int history = random(9); + ASSERT_TRUE(history == 0 || t.append(seqs.back(), history)); + } + std::vector history_len; + for (const int32_t seq : seqs) { + history_len.push_back(t.cache.pos(seq)); + } + Ints ids, parents, positions; + for (const int32_t seq : seqs) { + if (random(4) == 0) { + continue; + } + const int base = static_cast(ids.size()); + for (int k = 0, n = 1 + random(12); k < n; ++k) { + const int parent = k == 0 ? -1 : base + random(k); + ids.push_back(seq); + parents.push_back(parent); + positions.push_back( + parent < 0 ? t.cache.pos(seq) : positions[parent] + 1); + } + } + if (ids.empty()) { + continue; + } + const auto [flat, ring] = t.tree(ids, parents, positions); + ASSERT_TRUE(flat && ring); + ++trials; + int mismatches = 0; + const int length = static_cast(ids.size()); + std::vector step_of(flat->read_len, -1); + for (int k = 0; k < length; ++k) { + step_of[flat->cells[k]] = k; + } + for (const CellStep* step : {flat, ring}) { + const int w = step == flat ? 0 : window; + for (int i = 0; i < length; ++i) { + std::vector ancestor(length, 0); + for (int a = i; a >= 0; a = parents[a]) { + ancestor[a] = 1; + } + const int oldest = w == 0 ? 0 : std::max(0, positions[i] - w + 1); + int history_seen = 0; + for (int j = 0; j < step->read_len; ++j) { + const int k = step_of[j]; + if (k >= 0) { + const bool expected = ancestor[k] && positions[k] >= oldest; + if (leaky) { + mismatches += sees(step, i, j) != expected; + } else { + ASSERT_EQ(sees(step, i, j), expected) + << "trial " << trial << " row " << i << " node " << k; + } + } else { + history_seen += sees(step, i, j); + } + } + const auto q = + std::find(seqs.begin(), seqs.end(), ids[i]) - seqs.begin(); + ASSERT_EQ(history_seen, std::max(0, history_len[q] - oldest)) + << "trial " << trial << " row " << i; + } + } + leaking += mismatches > 0; + Ints keep; + std::vector expected = history_len; + for (int k = 0; k < length; ++k) { + if (parents[k] >= 0) { + continue; + } + int node = k; + keep.push_back(node); + while (true) { + std::vector children; + for (int c = node + 1; c < length; ++c) { + if (parents[c] == node) { + children.push_back(c); + } + } + if (children.empty() || random(3) == 0) { + break; + } + node = children[random(static_cast(children.size()))]; + keep.push_back(node); + } + const auto q = std::find(seqs.begin(), seqs.end(), ids[k]) - seqs.begin(); + expected[q] = positions[node] + 1; + } + ASSERT_TRUE(t.cache.retain_tree(keep)); + for (size_t q = 0; q < seqs.size(); ++q) { + ASSERT_EQ(t.cache.pos(seqs[q]), expected[q]) << "trial " << trial; + } + } + EXPECT_GT(trials, 2000); + if (leaky) { + EXPECT_GT(leaking, trials / 4); + } else { + EXPECT_EQ(leaking, 0); + } +} + +// With the sibling-leak test hook on, the rule must catch the leak. +TEST(CellCacheTreeTest, MaskFuzzMatchesBruteForce) { + for (const bool leaky : {false, true}) { + run_mask_fuzz(leaky); + } +} diff --git a/extension/llm/cache/test/targets.bzl b/extension/llm/cache/test/targets.bzl index 7aabe8a52e5..2d6cac197d7 100644 --- a/extension/llm/cache/test/targets.bzl +++ b/extension/llm/cache/test/targets.bzl @@ -6,9 +6,20 @@ def define_common_targets(is_fbcode = False): runtime.cxx_test( name = "cache_test", - srcs = ["cache_test.cpp"], + srcs = [ + "cache_test.cpp", + "cell_cache_tree_test.cpp", + ], deps = [ + ":cell_cache_test_peer", "//executorch/extension/llm/cache:kv_cache", "//executorch/test/utils:utils", ], ) + + runtime.cxx_library( + name = "cell_cache_test_peer", + exported_headers = ["cell_cache_test_peer.h"], + visibility = ["PUBLIC"], + exported_deps = ["//executorch/extension/llm/cache:kv_cache"], + ) From 3a3bcb467902f4223c2c0e02ff92b8486a365813 Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Wed, 2 Dec 2026 22:06:16 -0800 Subject: [PATCH 2/5] Add the PairTree DFlash2 tree builder for Muse Glimmer A header-only, backend-neutral builder for PairTree DFlash2: from one session's DFlash2 candidate table, it keeps the budget's best proposal prefixes, ranked by the retained unary candidate mass plus the selector's pairwise log-softmax, as the PairTree reference (dflash2_pairwise_k16) does. The greedy walk follows the children the target predicts and returns the target's next token. Tables the reference refuses return no tree, and so do non-finite ones. The unit test checks trees and walks against fixtures produced by the original PairTree code on synthetic tables and on tables recorded from the Muse Glimmer 30B DFlash2 draft. gen_pairtree_reference.py regenerates the fixture from a PairTree checkout (tests/README.md has the command). On a larger sample of 120 synthetic and 60 recorded tables at budgets up to 255, every tree matched except three in synthetic rounds with exact score ties, where float32 reductions accumulated in double order candidates differently within a fraction of an ulp. Authored with AI assistance (Claude, via Metamate). --- examples/models/muse-glimmer/CMakeLists.txt | 33 +- examples/models/muse-glimmer/runtime/BUCK | 8 + .../muse-glimmer/runtime/dflash2_pairtree.h | 229 ++++++++++++++ examples/models/muse-glimmer/tests/BUCK | 14 + examples/models/muse-glimmer/tests/README.md | 44 +++ .../tests/data/pairtree_reference.bin | Bin 0 -> 79620 bytes .../tests/dflash2_pairtree_test.cpp | 261 ++++++++++++++++ .../tests/gen_pairtree_reference.py | 291 ++++++++++++++++++ 8 files changed, 873 insertions(+), 7 deletions(-) create mode 100644 examples/models/muse-glimmer/runtime/dflash2_pairtree.h create mode 100644 examples/models/muse-glimmer/tests/data/pairtree_reference.bin create mode 100644 examples/models/muse-glimmer/tests/dflash2_pairtree_test.cpp create mode 100644 examples/models/muse-glimmer/tests/gen_pairtree_reference.py diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 619d835e418..77da9ed38ea 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -357,6 +357,32 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS) extension_llm_serving Threads::Threads ) add_test(NAME muse_glimmer_batching COMMAND muse_glimmer_batching_test) + # Tokenizer include paths contain regex.h; keep GoogleTest and its users on + # the same simple-regex ABI instead of the shadowed POSIX header. Only the + # tests below build it. + add_subdirectory( + ${EXECUTORCH_ROOT}/third-party/googletest + ${CMAKE_CURRENT_BINARY_DIR}/dflash_googletest EXCLUDE_FROM_ALL + ) + target_compile_definitions(gtest PUBLIC GTEST_HAS_POSIX_RE=0) + add_executable( + muse_glimmer_dflash2_pairtree_test tests/dflash2_pairtree_test.cpp + ) + target_include_directories( + muse_glimmer_dflash2_pairtree_test PRIVATE ${_common_include_directories} + ) + target_link_libraries( + muse_glimmer_dflash2_pairtree_test PRIVATE GTest::gtest_main + ) + add_test(NAME muse_glimmer_dflash2_pairtree + COMMAND muse_glimmer_dflash2_pairtree_test + ) + set_tests_properties( + muse_glimmer_dflash2_pairtree + PROPERTIES + ENVIRONMENT + "MUSE_GLIMMER_PAIRTREE_FIXTURE=${CMAKE_CURRENT_SOURCE_DIR}/tests/data/pairtree_reference.bin" + ) if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "mlx") add_executable( muse_glimmer_mlx_dflash_test tests/mlx_dflash_native_test.cpp @@ -377,13 +403,6 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS) endif() endif() if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "cuda") - # Tokenizer include paths contain regex.h; keep GoogleTest and its users - # on the same simple-regex ABI instead of the shadowed POSIX header. - add_subdirectory( - ${EXECUTORCH_ROOT}/third-party/googletest - ${CMAKE_CURRENT_BINARY_DIR}/dflash_googletest EXCLUDE_FROM_ALL - ) - target_compile_definitions(gtest PUBLIC GTEST_HAS_POSIX_RE=0) add_executable( muse_glimmer_cuda_dflash_test tests/cuda_dflash_executor_test.cpp tests/cuda_dflash_native_test.cpp diff --git a/examples/models/muse-glimmer/runtime/BUCK b/examples/models/muse-glimmer/runtime/BUCK index 2a25e3fafe5..0bc88f56786 100644 --- a/examples/models/muse-glimmer/runtime/BUCK +++ b/examples/models/muse-glimmer/runtime/BUCK @@ -38,6 +38,14 @@ fbcode_target( external_deps = [("cuda", None, "cuda-lazy"), "nlohmann_json"], ) +fbcode_target( + _kind = runtime.cxx_library, + name = "dflash2_pairtree", + header_namespace = "executorch/examples/models/muse-glimmer/runtime", + exported_headers = ["dflash2_pairtree.h"], + visibility = ["PUBLIC"], +) + fbcode_target( _kind = runtime.cxx_library, name = "muse_glimmer_batching_preparation", diff --git a/examples/models/muse-glimmer/runtime/dflash2_pairtree.h b/examples/models/muse-glimmer/runtime/dflash2_pairtree.h new file mode 100644 index 00000000000..bc321899bbf --- /dev/null +++ b/examples/models/muse-glimmer/runtime/dflash2_pairtree.h @@ -0,0 +1,229 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#pragma once + +// PairTree DFlash2: a bounded proposal tree over one owner's DFlash2 candidate +// table, verified by the target in a single forward. Follows the PairTree +// reference builder (github.com/Eliran-Turgeman/pairtree, dflash2_pairwise_k16) +// node for node: best-first expansion of prefixes scored by the retained unary +// mass plus the selector's pairwise log-softmax. Its float32 reductions are +// emulated with double accumulation, so near-ties within a fraction of an ulp +// may order differently. + +#include +#include +#include +#include +#include +#include +#include + +namespace executorch::extension::llm::pairtree { + +// The most verify rows one PairTree DFlash2 round sends to the target. +inline constexpr int kMaxRows = 256; + +// One owner's node budget when `owners` trees, each rooted at its owner's +// anchor, share a target forward of `rows` tokens, and its context has `room` +// positions past the anchor. +inline int round_budget(int budget, int rows, int owners, int room) { + return std::min({budget, rows / owners - 1, room}); +} + +struct Node { + std::int64_t token; + int parent; // node index; -1 = the anchor + int depth; // 1 = the first proposal + double score; // cumulative log score +}; + +// One owner's table, for `steps` proposals with `top_k` candidates each. +struct Candidates { + const std::int64_t* ids; // [steps, top_k] + // [steps, top_k, top_k] selector logits; row p conditions on the previous + // proposal's candidate p. Step 0 reads row 0. + const float* scores; + // [steps, top_k + 1]: the candidates' unary draft logits, then the + // full-vocabulary logsumexp. + const float* extras; + int steps; + int top_k; +}; + +namespace detail { + +// torch's float32 logsumexp and log_softmax, accumulated in double. +inline float logsumexp(const float* x, int n) { + float max = -std::numeric_limits::infinity(); + for (int i = 0; i < n; ++i) { + max = std::max(max, x[i]); + } + const float shift = std::isinf(max) ? 0.0f : max; + double sum = 0; + for (int i = 0; i < n; ++i) { + sum += std::exp(static_cast(x[i] - shift)); + } + return static_cast(static_cast(std::log(sum)) + max); +} + +inline void log_softmax(const float* x, int n, float* out) { + const float max = *std::max_element(x, x + n); + double sum = 0; + for (int i = 0; i < n; ++i) { + sum += std::exp(static_cast(x[i] - max)); + } + const float log_sum = static_cast(std::log(sum)); + for (int i = 0; i < n; ++i) { + out[i] = (x[i] - max) - log_sum; + } +} + +struct Entry { + double score; + // Candidate index per depth; the reference breaks score ties on it. + std::vector path; + int parent; +}; + +struct Later { + bool operator()(const Entry& a, const Entry& b) const { + if (a.score != b.score) { + return a.score < b.score; + } + return std::lexicographical_compare( + b.path.begin(), b.path.end(), a.path.begin(), a.path.end()); + } +}; + +} // namespace detail + +// The `budget` best nodes, parents before children, at most `steps` deep. +// nullopt where the reference refuses the table: retained candidate mass above +// one, a positive extension log score, or a node with two children of one +// token. Unlike the reference, a table with a non-finite value is refused too, +// so no NaN or infinity reaches a tree. +inline std::optional> build( + const Candidates& in, + int budget) { + const int k = in.top_k; + const int steps = in.steps; + if (k <= 0 || steps <= 0 || budget < 0) { + return std::nullopt; + } + const auto row_count = static_cast(steps) * k; + if (!std::all_of( + in.scores, + in.scores + row_count * k, + [](float v) { return std::isfinite(v); }) || + !std::all_of(in.extras, in.extras + row_count + steps, [](float v) { + return std::isfinite(v); + })) { + return std::nullopt; + } + // Extension log scores: the step's retained unary mass plus the pairwise + // conditional, [steps, k (predecessor), k]. + std::vector extension(row_count * k); + for (int t = 0; t < steps; ++t) { + const float* extras = in.extras + static_cast(t) * (k + 1); + if (detail::logsumexp(extras, k) - extras[k] > 1e-5f) { + return std::nullopt; + } + } + for (int t = 0; t < steps; ++t) { + const float* extras = in.extras + static_cast(t) * (k + 1); + const float retained = detail::logsumexp(extras, k) - extras[k]; + for (int p = 0; p < (t == 0 ? 1 : k); ++p) { + float* out = extension.data() + (static_cast(t) * k + p) * k; + detail::log_softmax( + in.scores + (static_cast(t) * k + p) * k, k, out); + for (int c = 0; c < k; ++c) { + out[c] += retained; + } + if (*std::max_element(out, out + k) > 1e-5f) { + return std::nullopt; + } + } + } + std::vector nodes; + std::priority_queue, detail::Later> + frontier; + for (int c = 0; c < k; ++c) { + frontier.push( + {std::min(extension[c], 0.0), std::vector{c}, -1}); + } + while (!frontier.empty() && static_cast(nodes.size()) < budget) { + const detail::Entry entry = frontier.top(); + frontier.pop(); + const int depth = static_cast(entry.path.size()); + const int candidate = entry.path.back(); + nodes.push_back( + {in.ids[static_cast(depth - 1) * k + candidate], + entry.parent, + depth, + entry.score}); + if (depth >= steps) { + continue; + } + const int node = static_cast(nodes.size()) - 1; + const float* row = extension.data() + + (static_cast(depth) * k + candidate) * k; + for (int c = 0; c < k; ++c) { + std::vector path = entry.path; + path.push_back(c); + frontier.push( + {std::min(entry.score + row[c], entry.score), + std::move(path), + node}); + } + } + // As the reference verifier, a parent may not have two children with one + // token. Each node has at most k children. + std::vector> children(nodes.size() + 1); + for (const auto& node : nodes) { + auto& siblings = children[node.parent + 1]; + if (std::find(siblings.begin(), siblings.end(), node.token) != + siblings.end()) { + return std::nullopt; + } + siblings.push_back(node.token); + } + return nodes; +} + +struct Walk { + std::vector path; // accepted node indices, root to leaf + std::int64_t token = -1; // the target's token after the path +}; + +// Greedy verification: predictions[0] is the target's argmax after the +// anchor, predictions[1 + i] after node i. Follows the child the target +// predicts until none matches. Children of a node carry distinct tokens. +inline Walk walk( + const std::vector& nodes, + const std::vector& predictions) { + Walk result; + int current = -1; + while (true) { + const std::int64_t want = predictions[current + 1]; + int next = -1; + for (int i = current + 1; i < static_cast(nodes.size()); ++i) { + if (nodes[i].parent == current && nodes[i].token == want) { + next = i; + break; + } + } + if (next < 0) { + result.token = want; + return result; + } + result.path.push_back(next); + current = next; + } +} + +} // namespace executorch::extension::llm::pairtree diff --git a/examples/models/muse-glimmer/tests/BUCK b/examples/models/muse-glimmer/tests/BUCK index 40f63d062c8..5864cc6091f 100644 --- a/examples/models/muse-glimmer/tests/BUCK +++ b/examples/models/muse-glimmer/tests/BUCK @@ -21,6 +21,20 @@ fbcode_target( external_deps = [("cuda", None, "cuda-lazy"), "nlohmann_json"], ) +fbcode_target( + _kind = cpp_unittest, + name = "dflash2_pairtree_test", + srcs = ["dflash2_pairtree_test.cpp"], + env = {"MUSE_GLIMMER_PAIRTREE_FIXTURE": "$(location :pairtree_reference)"}, + deps = ["//executorch/examples/models/muse-glimmer/runtime:dflash2_pairtree"], +) + +fbcode_target( + _kind = runtime.export_file, + name = "pairtree_reference", + src = "data/pairtree_reference.bin", +) + fbcode_target( _kind = runtime.cxx_binary, name = "cuda_dflash_native_runner", diff --git a/examples/models/muse-glimmer/tests/README.md b/examples/models/muse-glimmer/tests/README.md index 9142faef1ca..78989f09ba3 100644 --- a/examples/models/muse-glimmer/tests/README.md +++ b/examples/models/muse-glimmer/tests/README.md @@ -66,3 +66,47 @@ predecessor's row favors the expected next proposal. The native test checks the 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. + +## PairTree DFlash2 builder + +`dflash2_pairtree_test` checks the tree builder and greedy walk on the CPU +against `data/pairtree_reference.bin`: trees and walks produced by the original +PairTree code (github.com/Eliran-Turgeman/pairtree at b62eb90, +`src/dflash2_tree.py::build_dflash2_verifier_tree` with +`dflash2_pairwise_k16`, `require_checkpoint_shape=False`, +`anchor_final_scores = scores[0, 0]`, `pairwise_final_scores = scores[1:]`, +exact `torch.topk` ties broken by lower index, and its +`compile_ddtree_tree` / `follow_verified_tree` walk given the target's greedy +continuation). The fixture holds four synthetic 6-step tables (random, low +retained mass, flat, and repeated candidates, which the reference refuses) at +budgets 7 and 31, and two 15-step tables recorded from the Muse Glimmer 30B +DFlash2 draft on CUDA at budgets 15, 63 and 255. Tables with exact score ties +are left out: there the builder's double-accumulated float32 reductions may +order candidates within a fraction of an ulp differently from torch's. + +The file is little-endian: `PTREE001`, an int32 round count, then per round +int32 steps S and candidates K, int64 ids [S, K], float32 scores [S, K, K], +float32 unary logits and logsumexp [S, K + 1], an int32 length and the int64 +greedy continuation, and an int32 budget count. Each budget holds int32 budget, +int32 built (0 = the reference refused) and node count, then per node int64 +token and int32 parent and depth; for a built tree, an int32 accepted-path +length (-1 = not walked), the int32 node indices and the int64 next token. + +```sh +ctest --test-dir cmake-out/examples/models/muse-glimmer-batching -R '^muse_glimmer_dflash2_pairtree$' --output-on-failure --no-tests=error +``` + +`gen_pairtree_reference.py` writes the fixture with a PairTree checkout at +b62eb90, using torch and numpy only. With `--tables` it recomputes every +expected tree and walk for the tables already in the file and reproduces it +byte for byte; `--synthetic N --seed S --budgets 7,31` adds new synthetic +tables. The recorded tables came from a Serial DFlash2 run of the 30B draft +and are kept in the fixture. + +```sh +git clone https://github.com/Eliran-Turgeman/pairtree /tmp/pairtree +git -C /tmp/pairtree checkout b62eb9020d6e1e6c6125f81876c9ae7df9cd2383 +python examples/models/muse-glimmer/tests/gen_pairtree_reference.py --pairtree /tmp/pairtree \ + --tables examples/models/muse-glimmer/tests/data/pairtree_reference.bin \ + --out examples/models/muse-glimmer/tests/data/pairtree_reference.bin +``` diff --git a/examples/models/muse-glimmer/tests/data/pairtree_reference.bin b/examples/models/muse-glimmer/tests/data/pairtree_reference.bin new file mode 100644 index 0000000000000000000000000000000000000000..2f0893ce18f43d29a54d452f25dd1a4530808e51 GIT binary patch literal 79620 zcmeF3`Bx8L;Qu2n+V_MgWh+_A+VZ;3i3+6<63G@qwi0RIH|>&=Hbv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r i_=SH&eGS05(tLc}0Dri?TG_2mdd$XwQcL literal 0 HcmV?d00001 diff --git a/examples/models/muse-glimmer/tests/dflash2_pairtree_test.cpp b/examples/models/muse-glimmer/tests/dflash2_pairtree_test.cpp new file mode 100644 index 00000000000..c1007b2e0a3 --- /dev/null +++ b/examples/models/muse-glimmer/tests/dflash2_pairtree_test.cpp @@ -0,0 +1,261 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pairtree = executorch::extension::llm::pairtree; + +namespace { + +// tests/data/pairtree_reference.bin; see tests/README.md for its provenance. +std::string fixture_path() { + if (const char* path = std::getenv("MUSE_GLIMMER_PAIRTREE_FIXTURE")) { + return path; + } + const std::string here = __FILE__; + return here.substr(0, here.find_last_of('/')) + + "/data/pairtree_reference.bin"; +} + +class Reader { + public: + explicit Reader(const std::string& path) { + std::ifstream file(path, std::ios::binary); + bytes_.assign( + std::istreambuf_iterator(file), std::istreambuf_iterator()); + } + bool empty() const { + return bytes_.empty(); + } + bool done() const { + return offset_ == bytes_.size(); + } + template + T read() { + T value{}; + if (offset_ + sizeof(T) > bytes_.size()) { + ADD_FAILURE() << "truncated fixture"; + offset_ = bytes_.size(); + return value; + } + std::memcpy(&value, bytes_.data() + offset_, sizeof(T)); + offset_ += sizeof(T); + return value; + } + template + std::vector read(std::size_t count) { + std::vector values(count); + for (auto& value : values) { + value = read(); + } + return values; + } + + private: + std::vector bytes_; + std::size_t offset_ = 0; +}; + +using NodeKey = std::tuple; + +std::vector keys(const std::vector& nodes) { + std::vector result; + for (const auto& node : nodes) { + result.emplace_back(node.token, node.parent, node.depth); + } + return result; +} + +// The target's greedy token after the anchor and after every node on its own +// path; -1 elsewhere, which no child matches. +std::vector predictions( + const std::vector& nodes, + const std::vector& continuation) { + std::vector result(nodes.size() + 1, -1); + std::vector on_path(nodes.size(), 0); + result[0] = continuation[0]; + for (std::size_t i = 0; i < nodes.size(); ++i) { + const auto& node = nodes[i]; + on_path[i] = (node.parent < 0 || on_path[node.parent]) && + node.depth - 1 < static_cast(continuation.size()) && + node.token == continuation[node.depth - 1]; + if (on_path[i] && node.depth < static_cast(continuation.size())) { + result[i + 1] = continuation[node.depth]; + } + } + return result; +} + +// Trees and greedy walks of the original PairTree code on synthetic tables +// and on tables recorded from the Muse Glimmer DFlash2 draft. +TEST(DFlash2PairTree, MatchesReferenceImplementation) { + Reader in(fixture_path()); + ASSERT_FALSE(in.empty()) << "missing " << fixture_path(); + const auto magic = in.read(8); + ASSERT_EQ(std::string(magic.begin(), magic.end()), "PTREE001"); + const int rounds = in.read(); + int checked = 0, refused = 0; + for (int round = 0; round < rounds && !in.done(); ++round) { + const int steps = in.read(); + const int k = in.read(); + const auto ids = in.read(steps * k); + const auto scores = in.read(steps * k * k); + const auto extras = in.read(steps * (k + 1)); + const auto continuation = in.read(in.read()); + const pairtree::Candidates table{ + ids.data(), scores.data(), extras.data(), steps, k}; + for (int b = in.read(); b > 0; --b) { + const int budget = in.read(); + const bool built = in.read() != 0; + std::vector expected; + for (int n = in.read(); n > 0; --n) { + const auto token = in.read(); + const auto parent = in.read(); + expected.emplace_back(token, parent, in.read()); + } + SCOPED_TRACE( + ::testing::Message() << "round " << round << " budget " << budget); + const auto tree = pairtree::build(table, budget); + if (!built) { + EXPECT_FALSE(tree); + ++refused; + continue; + } + ASSERT_TRUE(tree); + EXPECT_EQ(keys(*tree), expected); + const int accepted = in.read(); + if (accepted < 0) { + continue; + } + const auto path = in.read(accepted); + const auto bonus = in.read(); + const auto walk = pairtree::walk(*tree, predictions(*tree, continuation)); + EXPECT_EQ(walk.path, std::vector(path.begin(), path.end())); + EXPECT_EQ(walk.token, bonus); + ++checked; + } + } + EXPECT_TRUE(in.done()); + EXPECT_GT(checked, 0); + EXPECT_GT(refused, 0); +} + +struct Table { + Table(int steps, int k) : steps(steps), k(k) { + for (int i = 0; i < steps * k; ++i) { + ids.push_back(100 + i % k + 1000 * (i / k)); + } + scores.resize(steps * k * k); + for (int i = 0; i < steps * k * k; ++i) { + scores[i] = std::sin(0.37f * i); + } + // Unary logits whose top-k keeps about 90% of the full mass. + for (int t = 0; t < steps; ++t) { + for (int c = 0; c < k; ++c) { + extras.push_back(-0.25f * c); + } + extras.push_back( + pairtree::detail::logsumexp(&*(extras.end() - k), k) + 0.1f); + } + } + pairtree::Candidates view() const { + return {ids.data(), scores.data(), extras.data(), steps, k}; + } + int steps, k; + std::vector ids; + std::vector scores, extras; +}; + +TEST(DFlash2PairTree, TreesAreBoundedAndTopological) { + const Table table(5, 4); + for (const int budget : {0, 1, 3, 17, 200}) { + SCOPED_TRACE(budget); + const auto tree = pairtree::build(table.view(), budget); + ASSERT_TRUE(tree); + // Four roots plus their subtrees five deep hold 4 + 16 + ... + 4^5 nodes. + EXPECT_EQ(tree->size(), static_cast(std::min(budget, 1364))); + for (std::size_t i = 0; i < tree->size(); ++i) { + const auto& node = (*tree)[i]; + EXPECT_LT(node.parent, static_cast(i)); + EXPECT_EQ( + node.depth, node.parent < 0 ? 1 : (*tree)[node.parent].depth + 1); + EXPECT_LE(node.depth, table.steps); + EXPECT_EQ(node.token / 1000, node.depth - 1); + if (node.parent >= 0) { + EXPECT_LE(node.score, (*tree)[node.parent].score); + } + } + } +} + +TEST(DFlash2PairTree, UnusableTablesAreRefused) { + for (const float bad : + {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity()}) { + Table scores(3, 4); + scores.scores[7] = bad; + EXPECT_FALSE(pairtree::build(scores.view(), 8)); + Table extras(3, 4); + extras.extras[6] = bad; + EXPECT_FALSE(pairtree::build(extras.view(), 8)); + } + // The candidates cannot hold more than the whole distribution. + Table mass(3, 4); + mass.extras[4] -= 1.0f; + EXPECT_FALSE(pairtree::build(mass.view(), 8)); + // A node cannot have two children of one token. + Table repeated(3, 4); + repeated.ids[5] = repeated.ids[4]; + EXPECT_FALSE(pairtree::build(repeated.view(), 32)); + EXPECT_TRUE(pairtree::build(repeated.view(), 0)); +} + +TEST(DFlash2PairTree, RoundBudgetSharesOneForwardAndTheContext) { + EXPECT_EQ(pairtree::round_budget(63, 256, 4, 1000), 63); + EXPECT_EQ(pairtree::round_budget(63, 64, 4, 1000), 15); + EXPECT_EQ(pairtree::round_budget(63, 32, 1, 1000), 31); + EXPECT_EQ(pairtree::round_budget(63, 256, 2, 20), 20); +} + +TEST(DFlash2PairTree, GreedyWalkFollowsTheTargetsOwnPredictions) { + // anchor -> A(10), B(20); A -> C(30), D(40); B -> C(30); C under A -> E(50). + const std::vector nodes{ + {10, -1, 1, 0}, + {20, -1, 1, 0}, + {30, 0, 2, 0}, + {40, 0, 2, 0}, + {30, 1, 2, 0}, + {50, 2, 3, 0}}; + auto walk = pairtree::walk(nodes, {10, 30, 30, 50, 0, 0, 99}); + EXPECT_EQ(walk.path, (std::vector{0, 2, 5})); + EXPECT_EQ(walk.token, 99); + walk = pairtree::walk(nodes, {77, 30, 30, 50, 0, 0, 99}); + EXPECT_TRUE(walk.path.empty()); + EXPECT_EQ(walk.token, 77); + walk = pairtree::walk(nodes, {10, 41, 30, 50, 0, 0, 99}); + EXPECT_EQ(walk.path, (std::vector{0})); + EXPECT_EQ(walk.token, 41); + // C under B: its own prediction, not that of C under A, decides. + walk = pairtree::walk(nodes, {20, 30, 30, 50, 0, 66, 99}); + EXPECT_EQ(walk.path, (std::vector{1, 4})); + EXPECT_EQ(walk.token, 66); +} + +} // namespace diff --git a/examples/models/muse-glimmer/tests/gen_pairtree_reference.py b/examples/models/muse-glimmer/tests/gen_pairtree_reference.py new file mode 100644 index 00000000000..045eff32dad --- /dev/null +++ b/examples/models/muse-glimmer/tests/gen_pairtree_reference.py @@ -0,0 +1,291 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Writes data/pairtree_reference.bin with the original PairTree code. + + git clone https://github.com/Eliran-Turgeman/pairtree /tmp/pairtree + git -C /tmp/pairtree checkout b62eb9020d6e1e6c6125f81876c9ae7df9cd2383 + python examples/models/muse-glimmer/tests/gen_pairtree_reference.py \\ + --pairtree /tmp/pairtree \\ + --tables examples/models/muse-glimmer/tests/data/pairtree_reference.bin \\ + --out examples/models/muse-glimmer/tests/data/pairtree_reference.bin + +Needs torch and numpy only: the PairTree functions are executed from their +pinned source files, without the modules' model and logging imports. With +--tables, the candidate tables, continuations and budgets of an existing file +are kept and every expected tree and walk is recomputed, which reproduces the +checked-in file byte for byte. --synthetic N adds N seeded synthetic tables. +The file format is described in tests/README.md. +""" + +import argparse +import ast +import contextlib +import hashlib +import importlib.util +import struct +import sys +from pathlib import Path + +import numpy as np +import torch + +MAGIC = b"PTREE001" +PINNED = { + "src/offline_dflash2_trees.py": "04c70331e6019b2e81ead9aa8dbde7bbe4d891dd28222d89c52feeff438004a1", + "src/ddtree.py": "94ba34a73b1e1df3b4614ee148016531a2f4f913268f48484cff5cda376e8752", + "src/dflash2_tree.py": "7568aa83dc017bed302e812a29d5c8f3bc2d4083f3d26b4197c36262bd22c95f", +} + + +def load_pairtree(root: Path) -> dict: + """The reference builder, verifier compiler and walk, from pinned files.""" + for name, digest in PINNED.items(): + if hashlib.sha256((root / name).read_bytes()).hexdigest() != digest: + raise SystemExit(f"{root / name} is not the pinned b62eb90 file") + spec = importlib.util.spec_from_file_location( + "pairtree_offline_dflash2_trees", root / "src/offline_dflash2_trees.py" + ) + offline = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = offline + spec.loader.exec_module(offline) + namespace = {"torch": torch, "np": np, "__name__": "pairtree_reference"} + for name in ( + "PAIRWISE_MASS_PRESERVING", + "UNARY_FULL_MASS", + "TreeNode", + "build_best_first_tree", + "build_scorer", + "validate_lattice_tensors", + "validate_unary_lattice_tensors", + ): + namespace[name] = getattr(offline, name) + import heapq + + namespace["heapq"] = heapq + for name, wanted in ( + ( + "src/ddtree.py", + {"compile_generic_tree_for_verifier", "follow_verified_tree"}, + ), + ( + "src/dflash2_tree.py", + { + "DFLASH2_UNARY_K16", + "DFLASH2_UNARY_K32", + "DFLASH2_UNARY_K64", + "DFLASH2_ORIGINAL_DDTREE", + "DFLASH2_PAIRWISE_K16", + "DFLASH2_UNARY_METHODS", + "DFLASH2_TREE_METHODS", + "EXPECTED_DRAFT_DEPTH", + "EXPECTED_CANDIDATE_COUNT", + "build_dflash2_verifier_tree", + }, + ), + ): + source = (root / name).read_text() + found = set() + for node in ast.parse(source).body: + if isinstance(node, (ast.FunctionDef, ast.ClassDef)): + defined = node.name + elif isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + defined = node.targets[0].id + else: + continue + if defined in wanted: + module = ast.Module(body=[node], type_ignores=[]) + exec(compile(module, str(root / name), "exec"), namespace) # noqa: S102 + found.add(defined) + if found != wanted: + raise SystemExit(f"{name} lacks {sorted(wanted - found)}") + return namespace + + +@contextlib.contextmanager +def stable_topk(): + """Breaks exact torch.topk ties by lower index, as the C++ builder does.""" + + def topk(values, k, dim=-1, largest=True, sorted=True): + ordered, indices = torch.sort(values, dim=dim, descending=True, stable=True) + return torch.return_types.topk( + (ordered.narrow(dim, 0, k), indices.narrow(dim, 0, k)) + ) + + original, tensor_original = torch.topk, torch.Tensor.topk + torch.topk = topk + torch.Tensor.topk = topk + try: + yield + finally: + torch.topk, torch.Tensor.topk = original, tensor_original + + +def reference(namespace, ids, scores, extras, continuation, budget): + """(nodes, accepted node indices, next token) or None if it raises. + + Nodes are (token, parent, depth). The walk is None when the continuation + ends before the accepted path does. + """ + k = ids.shape[1] + lattice = { + "candidate_token_ids": torch.from_numpy(ids.copy()).long(), + "candidate_unary_logits": torch.from_numpy(extras[:, :k].copy()).float(), + "unary_logsumexp": torch.from_numpy(extras[:, k].copy()).float(), + "anchor_final_scores": torch.from_numpy(scores[0, 0].copy()).float(), + "pairwise_final_scores": torch.from_numpy(scores[1:].copy()).float(), + } + try: + with stable_topk(): + nodes, _, _, parents, child_maps, _ = namespace[ + "build_dflash2_verifier_tree" + ]( + lattice, + namespace["DFLASH2_PAIRWISE_K16"], + budget, + require_checkpoint_shape=False, + validate_lattice=True, + ) + except ValueError: + return None + tokens = [-1] + [int(node.token_id) for node in nodes] + depths = [0] + [int(node.depth) for node in nodes] + # The target's greedy token after every tree index on its own path. + posterior = np.full(len(tokens), -1, np.int64) + on_path = [True] + [False] * len(nodes) + for i in range(1, len(tokens)): + depth = depths[i] + on_path[i] = bool( + on_path[parents[i]] + and depth - 1 < len(continuation) + and tokens[i] == continuation[depth - 1] + ) + for i in range(len(tokens)): + if on_path[i]: + depth = depths[i] + posterior[i] = continuation[depth] if depth < len(continuation) else -2 + accepted, _ = namespace["follow_verified_tree"]( + child_maps, torch.from_numpy(posterior)[None] + ) + length = len(accepted) - 1 + walk = None + if length < len(continuation): + walk = ([int(i) - 1 for i in accepted[1:]], int(continuation[length])) + keys = [(int(node.token_id), int(node.parent), int(node.depth)) for node in nodes] + return keys, walk + + +def read_tables(path: Path): + data = path.read_bytes() + if data[:8] != MAGIC: + raise SystemExit(f"{path} is not a PairTree reference file") + offset = 8 + + def take(fmt): + nonlocal offset + values = struct.unpack_from(fmt, data, offset) + offset += struct.calcsize(fmt) + return values + + def array(dtype, count): + nonlocal offset + values = np.frombuffer(data, dtype, count, offset).copy() + offset += values.nbytes + return values + + tables = [] + for _ in range(take("= 0: + offset += accepted * 4 + 8 + budgets.append(budget) + tables.append((ids, scores, extras, continuation, budgets)) + return tables + + +def synthetic(rng, kind, steps=6, k=16, vocab=50000): + """A random table; low_retained keeps little of the mass, repeated + candidates make the reference refuse a large enough tree.""" + ids = np.stack([rng.choice(vocab, k, replace=False) for _ in range(steps)]) + spread = 0.05 if kind == "flat" else 3.0 + unary = np.sort(rng.normal(4.0, spread, (steps, k)), axis=1)[:, ::-1] + retained = rng.uniform(0.01, 0.1 if kind == "low_retained" else 0.99, steps) + lse = np.log(np.exp(unary).sum(1)) - np.log(retained) + scores = unary[:, None, :] + rng.normal(0, 1.5, (steps, k, k)) + scores[0] = scores[0, :1] + if kind == "repeated": + ids[:, 5] = ids[:, 2] + continuation = [int(ids[t, rng.integers(k)]) for t in range(steps)] + continuation.append(int(rng.integers(vocab))) + extras = np.concatenate([unary, lse[:, None]], 1) + return ( + ids.astype(np.int64), + scores.astype(np.float32), + extras.astype(np.float32), + np.asarray(continuation, np.int64), + ) + + +def write(path: Path, namespace, tables): + with path.open("wb") as out: + out.write(MAGIC) + out.write(struct.pack(" None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--pairtree", required=True, type=Path) + parser.add_argument("--out", required=True, type=Path) + parser.add_argument("--tables", type=Path, help="Reuse this file's tables") + parser.add_argument("--synthetic", type=int, default=0) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--budgets", default="7,31") + args = parser.parse_args() + namespace = load_pairtree(args.pairtree) + tables = read_tables(args.tables) if args.tables else [] + rng = np.random.default_rng(args.seed) + kinds = ("random", "low_retained", "flat", "repeated") + budgets = [int(b) for b in args.budgets.split(",")] + for i in range(args.synthetic): + tables.append((*synthetic(rng, kinds[i % len(kinds)]), budgets)) + write(args.out, namespace, tables) + print(f"Wrote {len(tables)} tables to {args.out}") + + +if __name__ == "__main__": + main() From 49d4482b079dc9885c7b65edcddb766846d044e1 Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Wed, 2 Dec 2026 22:06:16 -0800 Subject: [PATCH 3/5] Plumb the PairTree DFlash2 option and export its draft method A Muse Glimmer DFlash2 program exported with --dflash2-pairtree gets a second draft method, draft_forward_pairtree. It takes draft_forward's inputs and returns its candidate ids and scores plus what PairTree DFlash2 weighs each step by: the candidates' unary logits and the full-vocabulary logsumexp, [owners, N, K + 1] float32. draft_forward stays the exact program it is without the flag, so Serial DFlash2 runs the same programs on either export. The extras cannot come from a cheaper method next to an unchanged draft_forward, because they need the draft's full-vocabulary logits, which draft_forward does not return; the second method shares the draft's weights and cache, so the .ptd stores the weights once and only the .pte grows by one compiled draft. The shared draft code offers the method for every backend (DFlashPackedExportModel with pairtree, MuseGlimmerWithDFlash.draft_forward_pairtree); the CUDA exporter writes it. A draft without a candidate selector is refused before anything is traced. resolve_dflash_mode (runtime/dflash_mode.h) is the one place the mode is picked at startup, refusals included; each DFlash executor passes its backend kind and what its program offers. --dflash_serial_only (launcher --dflash-serial-only) runs Serial DFlash2 and refuses a nonzero budget. --dflash_tree_budget (launcher --dflash-tree-budget) sets the PairTree node budget per session and round, zero being Serial DFlash2, and is refused when the program or target cannot serve it. Unset, a program with the PairTree method runs PairTree at the backend's default budget, capped by the widest tree verify: on CUDA 31 for one decode sequence and 15 otherwise, so that up to four owners verify the 64 rows Serial DFlash2 with 15 proposals does (the MLX default, 15, takes effect once MLX supports the method). The decode sequences count logical sessions only, not prefix-cache ones. A program without the method runs Serial DFlash2 and says why. The backend factory refuses only what no backend offers and returns the executor's note: the chosen mode and why, or the resolver's refusal, which the batching runtime prints at startup and adds to its error. The launcher repeats the worker's flag checks to fail before starting it. MuseGlimmerBackendConfig carries the budget, the switch and the decode sequences, and the docs describe the export, the rule and the switch. Until the CUDA executor supports PairTree DFlash2 in a later commit, it accepts these settings and runs Serial DFlash2. Authored with AI assistance (Claude, via Metamate). --- .../models/muse-glimmer/BATCHING_SERVING.md | 74 ++++++++++ examples/models/muse-glimmer/CMakeLists.txt | 10 ++ examples/models/muse-glimmer/README.md | 9 ++ .../muse-glimmer/export/export_dflash.py | 80 +++++++--- .../models/muse-glimmer/export/export_solo.py | 2 + .../models/muse-glimmer/model/dflash_model.py | 69 ++++++++- examples/models/muse-glimmer/runtime/BUCK | 9 ++ .../muse-glimmer/runtime/backend_factory.cpp | 19 ++- .../muse-glimmer/runtime/backend_factory.h | 17 ++- .../models/muse-glimmer/runtime/dflash_mode.h | 137 ++++++++++++++++++ .../runtime/runners/batching_bootstrap.cpp | 28 +++- .../muse-glimmer/serving/serve_batching.py | 28 ++++ examples/models/muse-glimmer/tests/BUCK | 7 + .../muse-glimmer/tests/dflash_mode_test.cpp | 126 ++++++++++++++++ .../tests/test_cuda_dflash_packed.py | 112 ++++++++++++++ .../muse-glimmer/tests/test_serve_batching.py | 42 ++++++ 16 files changed, 735 insertions(+), 34 deletions(-) create mode 100644 examples/models/muse-glimmer/runtime/dflash_mode.h create mode 100644 examples/models/muse-glimmer/tests/dflash_mode_test.cpp diff --git a/examples/models/muse-glimmer/BATCHING_SERVING.md b/examples/models/muse-glimmer/BATCHING_SERVING.md index 0e497dd4fd5..8a96c42bb0b 100644 --- a/examples/models/muse-glimmer/BATCHING_SERVING.md +++ b/examples/models/muse-glimmer/BATCHING_SERVING.md @@ -101,6 +101,77 @@ that shortlist. Re-export earlier CUDA DFlash2 artifacts to use this ordering. If the selected DFlash2 score row contains a NaN or infinity, both backends fail the requests in that execution batch. Other sessions can continue. +### PairTree DFlash2 on CUDA + +Serial DFlash2 verifies one chain of N proposals per session. PairTree DFlash2 +verifies a bounded tree per greedy session instead: from the same DFlash2 +draft call, it keeps the B most likely proposal prefixes, at most N deep, and +the target checks every node in one forward with each node attending only its +own ancestors. The session commits the longest prefix the target's own greedy +tokens follow, plus the target's next token, so the output is the target's +greedy continuation, as with Serial DFlash2. The tree follows the PairTree +reference builder (`dflash2_pairwise_k16`): prefixes are ranked by the retained +unary candidate mass plus the selector's pairwise log-softmax. + +Export with `--dflash2-pairtree` to use it. The program then has a second +draft method, `draft_forward_pairtree`, which returns what `draft_forward` +returns plus what PairTree reads: the candidates' unary logits and the +full-vocabulary logsumexp. `draft_forward` itself is the same program as +without the flag, and both methods share the draft's weights, which the +`.ptd` stores once. A round's trees must fit one static target forward, +capped at 256 rows: for every session of a full round to get B nodes, add a +forward size of at least `--max-draft-owners` x (B + 1) tokens. A static +forward returns FP32 logits for every row (256 x the 202,048-token vocabulary +x 4 bytes is about 200 MB) and each added size captures its own CUDA graph, so +add only the sizes you need: + +```sh +python -m executorch.examples.models.muse_glimmer.export.export_dflash \ + --backend cuda --use-offgraph-kv-cache --activation-dtype bfloat16 \ + --target-gguf /path/to/Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf \ + --draft-gguf /path/to/Muse-Glimmer-30B-DFlash2-Q4_K_M.gguf \ + --forward-sizes 1,2,4,8,16,32,64 --dflash2-pairtree \ + --output-dir /path/to/muse-dflash2-pairtree +``` + +A worker started with `--dflash` on such a program runs PairTree DFlash2 with +a default budget per session and round: B = 31 when it decodes one sequence +at a time (`--max_decode_sequences 1` or `--max_sessions 1`) and B = 15 +otherwise. A CUDA round holds at most four sessions (`--max-draft-owners`), +and four trees of 15 nodes verify the 64 rows Serial DFlash2 with 15 +proposals does; wider verifies, such as 128 rows at B = 31, cost much more per +row on the 30B export. The default never exceeds the widest static forward. +`--dflash_tree_budget B` (the Python launcher: `--dflash-tree-budget B`) sets +the budget instead, and 0 runs Serial DFlash2; startup fails when B + 1 +exceeds the widest static target forward, the program lacks +`draft_forward_pairtree`, or the target uses the sequence KV layout. Rounds +with several sessions share that forward: each session's tree gets at most +`widest / sessions - 1` nodes. `--dflash-n-draft` still sets the depth. The +worker prints the mode, the budget and why to stderr once at startup, and a +refusal's reason with its error; `CudaDFlashStats::tree_budget` reports the +budget too (0 for Serial DFlash2). + +To keep Serial DFlash2 on a `--dflash2-pairtree` program, pass +`--dflash_serial_only` (launcher: `--dflash-serial-only`) or a zero tree +budget; the launcher leaves the budget unset unless given. Either way the +worker never loads `draft_forward_pairtree` and runs the same methods, rounds +and KV-cache steps as on the program exported without the flag. Its tokens +are bit-identical to that program's when both were exported with the same +kernel picks, since the export times kernel variants on the device (see +`tests/README.md`). `--dflash_serial_only` refuses a nonzero tree budget. A +program without `draft_forward_pairtree` always runs Serial DFlash2, and only +an explicit nonzero budget makes it fail. + +Sampled sessions (temperature > 0) keep Serial DFlash2: each batch drafts its +greedy sessions in tree rounds first and its sampled sessions after them, +with `draft_forward`; the worker logs this once. If the tree builder refuses +one session's candidate table (a non-finite value, for example), that whole +round runs Serial DFlash2, which reports a non-finite selected row as it +always does. `CudaDFlashStats` counts tree cycles (`tree_cycles`) and the +cycles that fell back (`tree_fallback_cycles`, every session of such a +round); for a tree, `proposed` counts its nodes and a bonus is an accepted +path that ends at a leaf. + ## Build On Apple Silicon, run the Make target from the ExecuTorch checkout: @@ -422,6 +493,9 @@ and `--max-draft-owners`), then add `--dflash` to the serve command above. The CUDA verifier accepts 2 to D - 1 proposals for a trained block of size D. Original DFlash can run static decode drafts in CUDA graphs. DFlash2 uses the dynamic draft method so the output projection can select the requested prefix. +A program exported with `--dflash2-pairtree` and wide enough `--forward-sizes` +runs PairTree DFlash2 unless `--dflash-serial-only` is given; see +[PairTree DFlash2 on CUDA](#pairtree-dflash2-on-cuda). ATEM tool intent must start a line outside Markdown code or immediately follow a tool recipient header. User-directed examples and quoted markers remain content. diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 77da9ed38ea..9c9fa2ed471 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -383,6 +383,16 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS) ENVIRONMENT "MUSE_GLIMMER_PAIRTREE_FIXTURE=${CMAKE_CURRENT_SOURCE_DIR}/tests/data/pairtree_reference.bin" ) + add_executable(muse_glimmer_dflash_mode_test tests/dflash_mode_test.cpp) + target_include_directories( + muse_glimmer_dflash_mode_test PRIVATE ${_common_include_directories} + ) + target_link_libraries( + muse_glimmer_dflash_mode_test PRIVATE GTest::gtest_main + ) + add_test(NAME muse_glimmer_dflash_mode + COMMAND muse_glimmer_dflash_mode_test + ) if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "mlx") add_executable( muse_glimmer_mlx_dflash_test tests/mlx_dflash_native_test.cpp diff --git a/examples/models/muse-glimmer/README.md b/examples/models/muse-glimmer/README.md index 7bea4d522da..00af7a3d559 100644 --- a/examples/models/muse-glimmer/README.md +++ b/examples/models/muse-glimmer/README.md @@ -326,6 +326,15 @@ The CUDA batching verifier accepts 2 to D - 1 proposals. Draft proposals are greedy on both batching backends. Per-request temperature, top-p, and top-k apply to target sampling. +On CUDA, a DFlash2 export with `--dflash2-pairtree` runs greedy sessions with +PairTree DFlash2, which verifies a tree of up to B proposals per session in one +target forward: B = 31 for one decode sequence and 15 otherwise, or +`--dflash-tree-budget B`. Full rounds need a static forward size of at least +`--max-draft-owners` x (B + 1). Sampled sessions keep Serial DFlash2; +`--dflash-serial-only` or `--dflash-tree-budget 0` runs the export with Serial +DFlash2's methods and steps. See +[PairTree DFlash2](BATCHING_SERVING.md#pairtree-dflash2-on-cuda). + Choose concurrency and prefix-cache limits to fit available memory. Prefix snapshots are disabled by default; omit `--prefix-cache-entries` to disable them. If the export stores weights separately, also pass `--data-path` with its data diff --git a/examples/models/muse-glimmer/export/export_dflash.py b/examples/models/muse-glimmer/export/export_dflash.py index b3104017f4e..16fd0e455ca 100644 --- a/examples/models/muse-glimmer/export/export_dflash.py +++ b/examples/models/muse-glimmer/export/export_dflash.py @@ -106,6 +106,9 @@ def _export_cuda_sampler_methods( STATIC_DRAFT_PREFIX = "draft_forward_" +# draft_forward plus the PairTree DFlash2 extras (kDFlash2PairTreeMethod in +# runtime/dflash_mode.h); present only in --dflash2-pairtree programs. +DFLASH2_PAIRTREE_METHOD = "draft_forward_pairtree" VERIFY_METHOD = "dflash_verify" VERIFY_ARGMAX_METHOD = "dflash_verify_argmax" SELECTOR_TOP_K_METHOD = "get_dflash_selector_top_k" @@ -210,6 +213,7 @@ def export_dflash( forward_sizes=None, kv_layout: str = "cell", max_kv_seqs: int = 4, + pairtree: bool = False, ) -> None: """Export DFlash target + draft to one CUDA or MLX .pte. @@ -221,6 +225,10 @@ 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" + ) import executorch.extension.llm.export.gguf # noqa: F401 import executorch.extension.llm.export.int4 # noqa: F401 @@ -235,11 +243,16 @@ def export_dflash( read_dflash_mlx_config, ) + draft_config = None if draft_gguf is not None: draft_config = read_dflash_gguf_config(draft_gguf) validate_dflash_export_options(backend, use_offgraph_kv_cache, draft_config) if draft_mlx is not None: - read_dflash_mlx_config(draft_mlx, max_seq_len) + draft_config = read_dflash_mlx_config(draft_mlx, max_seq_len) + if pairtree and draft_config is not None and not draft_config.selector_top_k: + raise ValueError( + "--dflash2-pairtree requires a DFlash2 draft (one with a candidate selector)" + ) # -- Load target model -- print("=" * 60) @@ -325,6 +338,7 @@ def export_dflash( max_vision_patches=max_vision_patches, kv_layout=kv_layout, max_kv_seqs=max_kv_seqs, + dflash_pairtree=pairtree, ) return @@ -381,12 +395,16 @@ def prepare_cuda_packed_draft( max_owners: int, kv_layout: str = "cell", max_kv_seqs: int = 4, + pairtree: bool = False, ): """Trace the packed draft and publish its independent cache geometry. On the sequence layout the draft keeps one private history per resident session. Sliding layers use a symmetric per-query window; flat layers see - all of the context and draft block. + all of the context and draft block. ``pairtree`` also exports + ``draft_forward_pairtree``: ``draft_forward`` with the DFlash2 candidates' + unary logits and logsumexp, which PairTree DFlash2 reads, as a third + output. ``draft_forward`` itself is the same program either way. """ from executorch.examples.models.muse_glimmer.export.export_solo import ( batched_sequence_manifest, @@ -464,28 +482,34 @@ def prepare_cuda_packed_draft( proposal_shapes = ( {0: Dim("draft_proposals", min=1, max=block - 1)} if block > 2 else None, ) - with torch.no_grad(): - program = export( - combined, - ( - torch.zeros((sample_owners, block), dtype=torch.long), - torch.zeros( - (1, 2, config.n_target_layers * config.dim), dtype=torch.bfloat16 - ), - torch.arange(2 + sample_queries, dtype=torch.long), - torch.arange(2 + sample_queries, dtype=torch.long), - ) - + proposal_inputs, - dynamic_shapes=( - {0: owners} if max_owners > 1 else None, - {1: context}, - {0: kv_width}, - {0: kv_width}, + inputs = ( + torch.zeros((sample_owners, block), dtype=torch.long), + torch.zeros((1, 2, config.n_target_layers * config.dim), dtype=torch.bfloat16), + torch.arange(2 + sample_queries, dtype=torch.long), + torch.arange(2 + sample_queries, dtype=torch.long), + ) + proposal_inputs + dynamic_shapes = ( + {0: owners} if max_owners > 1 else None, + {1: context}, + {0: kv_width}, + {0: kv_width}, + ) + proposal_shapes + # The PairTree method shares the draft's weights and cache; the CUDA + # backend stores each weight once for the whole program. + methods = {"draft_forward": combined} | ( + { + DFLASH2_PAIRTREE_METHOD: DFlashPackedExportModel( + target_model, draft_model, dflash2_top_candidates, pairtree=True ) - + proposal_shapes, - strict=True, - ) - programs = {"draft_forward": program} + } + if pairtree + else {} + ) + with torch.no_grad(): + programs = { + name: export(module, inputs, dynamic_shapes=dynamic_shapes, strict=True) + for name, module in methods.items() + } geometry = offgraph_kv_cache_geometry(draft_model) metadata = { key.replace("get_", "get_draft_", 1): value for key, value in geometry.items() @@ -1253,6 +1277,15 @@ def main() -> None: add_kv_layout_arguments(parser) parser.add_argument("--forward-sizes", default="1,2,4,8,16,32,64") + parser.add_argument( + "--dflash2-pairtree", + 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 " + "--max-draft-owners sessions needs a static forward of at least " + "owners * (B + 1) tokens in --forward-sizes.", + ) args = parser.parse_args() logging.basicConfig() logging.getLogger("executorch.backends.cuda.cuda_backend").setLevel(logging.INFO) @@ -1291,6 +1324,7 @@ def main() -> None: forward_sizes=[int(n) for n in args.forward_sizes.split(",") if n], kv_layout=args.kv_layout, max_kv_seqs=args.max_kv_seqs, + pairtree=args.dflash2_pairtree, ) diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py index 3b18afa78ef..a1bdc4768d7 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -426,6 +426,7 @@ def export_cuda_batching( # noqa: C901 max_vision_patches: int = 16384, kv_layout: str = "cell", max_kv_seqs: int = 4, + dflash_pairtree: bool = False, ): """Exports the forward methods and writes the artifact. @@ -486,6 +487,7 @@ def export_cuda_batching( # noqa: C901 max_owners=max_draft_owners, kv_layout=kv_layout, max_kv_seqs=max_kv_seqs, + pairtree=dflash_pairtree, ) forward_sizes = tuple(sorted({int(n) for n in forward_sizes})) diff --git a/examples/models/muse-glimmer/model/dflash_model.py b/examples/models/muse-glimmer/model/dflash_model.py index 8402d416e36..cebd5162160 100644 --- a/examples/models/muse-glimmer/model/dflash_model.py +++ b/examples/models/muse-glimmer/model/dflash_model.py @@ -496,13 +496,22 @@ def forward( class DFlashPackedExportModel(nn.Module): """Packed export with shared weights named exactly as in target forwards.""" - def __init__(self, target: nn.Module, draft: nn.Module, top_candidates=torch.topk): + def __init__( + self, + target: nn.Module, + draft: nn.Module, + top_candidates=torch.topk, + pairtree: bool = False, + ): super().__init__() + if pairtree and draft.candidate_selector is None: + raise ValueError("PairTree DFlash2 requires a DFlash2 (selector) draft") self.embed_tokens = target.embed_tokens self.lm_head = target.lm_head self.draft = draft self.activation_dtype = target.activation_dtype self.top_candidates = top_candidates + self.pairtree = pairtree def forward( self, draft_tokens, target_hidden, positions, kv_order, proposal_rows=None @@ -519,6 +528,7 @@ def forward( kv_order, proposal_rows, self.top_candidates, + self.pairtree, ) @@ -533,6 +543,7 @@ def _packed_draft_forward( kv_order, proposal_rows=None, top_candidates=torch.topk, + pairtree=False, ): # Owners and blocks are separate axes, as in the MLX packed draft ABI. torch._check(draft_tokens.shape[1] == draft.config.block_size) @@ -546,13 +557,23 @@ def _packed_draft_forward( if draft.config.input_embedding_scale != 1.0: noise_embedding = noise_embedding * draft.config.input_embedding_scale h = draft(noise_embedding, target_hidden, positions, kv_order) - return _draft_output(lm_head, draft, h, draft_tokens, proposal_rows, top_candidates) + return _draft_output( + lm_head, draft, h, draft_tokens, proposal_rows, top_candidates, pairtree + ) def _draft_output( - lm_head, draft, h, draft_tokens, proposal_rows, top_candidates=torch.topk + lm_head, + draft, + h, + draft_tokens, + proposal_rows, + top_candidates=torch.topk, + pairtree=False, ): if draft.candidate_selector is None: + if pairtree: + raise ValueError("PairTree DFlash2 requires a DFlash2 (selector) draft") return lm_head(h).float() torch._check(draft_tokens.shape[1] == draft.config.block_size) h = h.reshape(draft_tokens.shape[0], draft_tokens.shape[1], -1) @@ -563,9 +584,16 @@ def _draft_output( if softcap is not None: logits = torch.tanh(logits / softcap) * softcap unary, candidate_ids = top_candidates(logits, draft.config.selector_top_k) - return candidate_ids, draft.candidate_selector( - candidate_ids, unary, h, draft_tokens[:, 0] + scores = draft.candidate_selector(candidate_ids, unary, h, draft_tokens[:, 0]) + if not pairtree: + return candidate_ids, scores + # PairTree DFlash2 weighs each step by the mass its candidates retain: + # [owners, proposals, K + 1] = the candidates' logits, then the + # full-vocabulary logsumexp. + extras = torch.cat( + (unary.float(), torch.logsumexp(logits, dim=-1, keepdim=True)), dim=-1 ) + return candidate_ids, scores, extras class MuseGlimmerWithDFlash(nn.Module): @@ -620,7 +648,9 @@ def draft_forward( input_pos: torch.Tensor, valid_ctx_len: torch.Tensor | None = None, proposal_rows: torch.Tensor | None = None, - ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + *, + pairtree: bool = False, + ) -> torch.Tensor | tuple[torch.Tensor, ...]: draft = self.draft noise_embedding = self.target.embed_tokens(draft_tokens).to( self.target.activation_dtype @@ -634,7 +664,32 @@ def draft_forward( input_pos, *(() if valid_ctx_len is None else (valid_ctx_len,)), ) - return _draft_output(self.target.lm_head, draft, h, draft_tokens, proposal_rows) + return _draft_output( + self.target.lm_head, + draft, + h, + draft_tokens, + proposal_rows, + pairtree=pairtree, + ) + + def draft_forward_pairtree( + self, + draft_tokens: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + valid_ctx_len: torch.Tensor | None = None, + proposal_rows: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """draft_forward plus the PairTree DFlash2 extras (see _draft_output).""" + return self.draft_forward( + draft_tokens, + target_hidden, + input_pos, + valid_ctx_len, + proposal_rows, + pairtree=True, + ) def draft_forward_packed( self, diff --git a/examples/models/muse-glimmer/runtime/BUCK b/examples/models/muse-glimmer/runtime/BUCK index 0bc88f56786..27809063b5c 100644 --- a/examples/models/muse-glimmer/runtime/BUCK +++ b/examples/models/muse-glimmer/runtime/BUCK @@ -46,6 +46,15 @@ fbcode_target( visibility = ["PUBLIC"], ) +fbcode_target( + _kind = runtime.cxx_library, + name = "dflash_mode", + header_namespace = "executorch/examples/models/muse-glimmer/runtime", + exported_headers = ["dflash_mode.h"], + visibility = ["PUBLIC"], + exported_deps = ["//executorch/runtime/core:core"], +) + fbcode_target( _kind = runtime.cxx_library, name = "muse_glimmer_batching_preparation", diff --git a/examples/models/muse-glimmer/runtime/backend_factory.cpp b/examples/models/muse-glimmer/runtime/backend_factory.cpp index e94b58e31fa..da12721f21f 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.cpp +++ b/examples/models/muse-glimmer/runtime/backend_factory.cpp @@ -15,11 +15,28 @@ #endif #include +#include #include namespace executorch::extension::llm { runtime::Result create_muse_glimmer_backend( - const MuseGlimmerBackendConfig& config) { + const MuseGlimmerBackendConfig& config, + std::string* note) { + const char* refusal = nullptr; + if (config.dflash_tree_budget.value_or(0) && + !(config.backend == "cuda" && config.use_dflash)) { + refusal = + "Muse Glimmer: PairTree DFlash2 (dflash_tree_budget) requires CUDA DFlash"; + } else if (config.dflash_serial_only && !config.use_dflash) { + refusal = "Muse Glimmer: dflash_serial_only requires DFlash"; + } + if (refusal) { + ET_LOG(Error, "%s", refusal); + if (note) { + *note = refusal; + } + return runtime::Error::InvalidArgument; + } #if defined(EXECUTORCH_BUILD_MLX) if (config.backend == "mlx") { return MuseGlimmerMLXExecutor::create(config); diff --git a/examples/models/muse-glimmer/runtime/backend_factory.h b/examples/models/muse-glimmer/runtime/backend_factory.h index cb908851cc5..1b0b310c6ff 100644 --- a/examples/models/muse-glimmer/runtime/backend_factory.h +++ b/examples/models/muse-glimmer/runtime/backend_factory.h @@ -10,6 +10,9 @@ #include #include +#include +#include + namespace executorch::extension::llm { struct MuseGlimmerBackendConfig { @@ -24,6 +27,13 @@ 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 + // Serial DFlash2, and nullopt picks the mode (resolve_dflash_mode). + std::optional dflash_tree_budget; + // Serial DFlash2 even on a --dflash2-pairtree program. + bool dflash_serial_only = false; + // Decode sequences a batch can hold; selects the default tree budget. + int max_decode_sequences = 4; }; struct MuseGlimmerBackend { @@ -31,7 +41,12 @@ struct MuseGlimmerBackend { std::shared_ptr preparation; }; +// `note`, if given, receives the DFlash mode the backend chose and why, or +// why it refused the request. Which mode a DFlash executor runs, and whether +// the flags conflict, is resolve_dflash_mode's to decide; the factory only +// refuses what no backend here offers. runtime::Result create_muse_glimmer_backend( - const MuseGlimmerBackendConfig& config); + const MuseGlimmerBackendConfig& config, + std::string* note = nullptr); } // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/dflash_mode.h b/examples/models/muse-glimmer/runtime/dflash_mode.h new file mode 100644 index 00000000000..c470ad90404 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/dflash_mode.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#pragma once + +#include + +#include +#include + +namespace executorch::extension::llm { + +// The PairTree DFlash2 draft method, exported next to draft_forward by +// --dflash2-pairtree and advertised by its presence. Same inputs as +// draft_forward; it returns draft_forward's candidate ids and scores plus +// [owners, proposals, K + 1] float32: the candidates' unary logits, then the +// full-vocabulary logsumexp. Serial DFlash2 never loads it. +inline constexpr char kDFlash2PairTreeMethod[] = "draft_forward_pairtree"; + +enum class DFlashBackendKind { kCuda, kMlx }; + +// The PairTree DFlash2 node budget per session and round when none is given. +// CUDA: 31 for one decode sequence; with more, 15, so a round of four owners +// verifies the 64 rows Serial DFlash2 with 15 proposals does, since wider +// verifies cost much more per row. MLX: 15. +inline int default_tree_budget( + DFlashBackendKind backend, + int max_decode_sequences) { + return backend == DFlashBackendKind::kCuda && max_decode_sequences <= 1 ? 31 + : 15; +} + +// The sequences one batch decodes at most, which select the default budget: +// --max_decode_sequences, but no more than the logical sessions, since +// prefix-cache sessions never decode. +inline int dflash_decode_sequences( + int max_decode_sequences, + int logical_sessions) { + return std::min(max_decode_sequences, logical_sessions); +} + +struct DFlashModeRequest { + std::optional tree_budget; // explicit budget; zero is Serial DFlash2 + bool serial_only = false; + DFlashBackendKind backend = DFlashBackendKind::kCuda; + int max_decode_sequences = 4; // as MuseGlimmerBackendConfig's +}; + +// What the program and the executor offer PairTree DFlash2. +struct DFlashTreeCapability { + // The program has kDFlash2PairTreeMethod with the documented signature. + bool pairtree_method = false; + bool tree_verify = false; // the target can verify trees + int max_budget = 0; // widest tree verify rows minus the root +}; + +struct DFlashMode { + int tree_budget = 0; // zero is Serial DFlash2 + runtime::Error error = runtime::Error::Ok; + const char* reason = ""; // for the startup log line, or the refusal +}; + +// The one place a DFlash executor's mode is decided, refusals included. +// Serial-only is Serial DFlash2 and refuses a nonzero budget. An explicit +// budget is used as given, or refused if the capability cannot serve it. +// Otherwise a program with every PairTree requirement runs PairTree DFlash2 +// at the backend's default, capped by max_budget, and anything missing runs +// Serial DFlash2 with the reason. +inline DFlashMode resolve_dflash_mode( + const DFlashModeRequest& request, + const DFlashTreeCapability& capability) { + using runtime::Error; + const auto& budget = request.tree_budget; + if (budget && *budget < 0) { + return {0, Error::InvalidArgument, "the tree budget is negative"}; + } + if (request.serial_only) { + if (budget.value_or(0)) { + return { + 0, + Error::InvalidArgument, + "dflash_serial_only conflicts with a nonzero tree budget"}; + } + return {0, Error::Ok, "serial-only requested"}; + } + if (budget) { + if (!*budget) { + return {0, Error::Ok, "tree budget 0 requested"}; + } + if (!capability.pairtree_method) { + return { + 0, + Error::InvalidProgram, + "PairTree DFlash2 needs a valid draft_forward_pairtree, from a DFlash2 export with --dflash2-pairtree"}; + } + if (!capability.tree_verify) { + return { + 0, + Error::InvalidProgram, + "PairTree DFlash2 needs a target that verifies trees"}; + } + if (*budget > capability.max_budget) { + return { + 0, + Error::InvalidArgument, + "the tree budget exceeds the widest tree verify"}; + } + return {*budget, Error::Ok, "tree budget requested"}; + } + if (!capability.pairtree_method) { + return { + 0, + Error::Ok, + "the program has no valid draft_forward_pairtree (--dflash2-pairtree)"}; + } + if (!capability.tree_verify) { + return {0, Error::Ok, "the target cannot verify trees"}; + } + if (capability.max_budget < 1) { + return {0, Error::Ok, "no target forward fits a tree"}; + } + const int fallback = + default_tree_budget(request.backend, request.max_decode_sequences); + if (fallback > capability.max_budget) { + return { + capability.max_budget, + Error::Ok, + "default budget capped by the widest tree verify"}; + } + return {fallback, Error::Ok, "default budget"}; +} + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp index 7e8ce57d739..b38ed058268 100644 --- a/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp +++ b/examples/models/muse-glimmer/runtime/runners/batching_bootstrap.cpp @@ -5,10 +5,12 @@ * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ +#include #include #include #include #include +#include #include #include #include @@ -17,6 +19,18 @@ DEFINE_string(pte, "", "Muse Glimmer off-graph program"); DEFINE_bool(dflash, false, "Enable DFlash with an off-graph DFlash program"); 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; " + "zero runs Serial DFlash2. Negative (default): PairTree DFlash2 at the " + "backend's default budget on a --dflash2-pairtree program, otherwise " + "Serial DFlash2"); +DEFINE_bool( + dflash_serial_only, + false, + "Run Serial DFlash2 even on a --dflash2-pairtree program; refuses a " + "nonzero --dflash_tree_budget"); DEFINE_string(tokenizer, "", "Matching Hugging Face tokenizer JSON"); DEFINE_string(data_path, "", "Optional external weights file"); DEFINE_string(pos_embed_path, "", "Optional vision positional table path"); @@ -133,11 +147,21 @@ create_muse_glimmer_batching_runtime() { backend.bos_id = FLAGS_bos_id; backend.use_dflash = FLAGS_dflash; backend.dflash_n_draft = FLAGS_dflash_n_draft; - auto created = create_muse_glimmer_backend(backend); + if (FLAGS_dflash_tree_budget >= 0) { + backend.dflash_tree_budget = FLAGS_dflash_tree_budget; + } + backend.dflash_serial_only = FLAGS_dflash_serial_only; + backend.max_decode_sequences = + dflash_decode_sequences(FLAGS_max_decode_sequences, FLAGS_max_sessions); + std::string note; + auto created = create_muse_glimmer_backend(backend, ¬e); if (!created.ok()) throw std::runtime_error( "could not create batching Muse Glimmer executor: error " + - std::to_string(static_cast(created.error()))); + std::to_string(static_cast(created.error())) + + (note.empty() ? "" : ": " + note)); + if (!note.empty()) + std::fprintf(stderr, "%s\n", note.c_str()); result->backend = std::move(*created); const size_t width = result->backend.executor->preferred_batch_tokens(); // A width-one artifact still works: the core physically splits the batch. diff --git a/examples/models/muse-glimmer/serving/serve_batching.py b/examples/models/muse-glimmer/serving/serve_batching.py index df69a687e6e..b69fc5bc868 100644 --- a/examples/models/muse-glimmer/serving/serve_batching.py +++ b/examples/models/muse-glimmer/serving/serve_batching.py @@ -44,6 +44,9 @@ _MAX_MESSAGE_BYTES = 1024 * 1024 _INT32_MAX = (1 << 31) - 1 _UINT64_MAX = (1 << 64) - 1 +# One PairTree DFlash2 round sends at most this many verify rows to the target +# (pairtree::kMaxRows in runtime/dflash2_pairtree.h). +_MAX_TREE_ROWS = 256 def _parse_args(argv=None): @@ -62,6 +65,19 @@ def _parse_args(argv=None): default=0, help="Draft proposals per round; 0 uses the exported maximum minus one.", ) + parser.add_argument( + "--dflash-tree-budget", + type=int, + help="PairTree DFlash2 nodes per greedy session and round (CUDA, 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.", + ) + parser.add_argument( + "--dflash-serial-only", + action="store_true", + help="Run Serial DFlash2 even on a --dflash2-pairtree export.", + ) parser.add_argument("--model-id", default="muse_glimmer") parser.add_argument("--max-context", type=int, required=True) parser.add_argument("--max-sessions", type=int, default=4) @@ -137,6 +153,16 @@ def _parse_args(argv=None): parser.error("--dflash-n-draft must be nonnegative and below INT32_MAX") if args.dflash_n_draft and not args.dflash: parser.error("--dflash-n-draft requires --dflash") + # The worker checks these too; checking here fails before it starts. + 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 args.dflash_serial_only and (budget or not args.dflash): + parser.error( + "--dflash-serial-only requires --dflash and no nonzero --dflash-tree-budget" + ) if not 4 <= args.max_vision_patches <= _INT32_MAX: parser.error(f"--max-vision-patches must be between 4 and {_INT32_MAX}") if args.max_context <= 1: @@ -196,6 +222,8 @@ def _worker_command(args): ("backend", args.backend), ("dflash", str(args.dflash).lower()), ("dflash_n_draft", args.dflash_n_draft), + ("dflash_tree_budget", args.dflash_tree_budget), + ("dflash_serial_only", "true" if args.dflash_serial_only else None), ("max_sessions", args.max_sessions), ("max_session_tokens", args.max_context), ("max_decode_sequences", args.max_decode_sequences), diff --git a/examples/models/muse-glimmer/tests/BUCK b/examples/models/muse-glimmer/tests/BUCK index 5864cc6091f..06236d1881e 100644 --- a/examples/models/muse-glimmer/tests/BUCK +++ b/examples/models/muse-glimmer/tests/BUCK @@ -29,6 +29,13 @@ fbcode_target( deps = ["//executorch/examples/models/muse-glimmer/runtime:dflash2_pairtree"], ) +fbcode_target( + _kind = cpp_unittest, + name = "dflash_mode_test", + srcs = ["dflash_mode_test.cpp"], + deps = ["//executorch/examples/models/muse-glimmer/runtime:dflash_mode"], +) + fbcode_target( _kind = runtime.export_file, name = "pairtree_reference", diff --git a/examples/models/muse-glimmer/tests/dflash_mode_test.cpp b/examples/models/muse-glimmer/tests/dflash_mode_test.cpp new file mode 100644 index 00000000000..b801dc9db25 --- /dev/null +++ b/examples/models/muse-glimmer/tests/dflash_mode_test.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#include + +#include + +#include +#include +#include + +namespace { + +namespace llm = executorch::extension::llm; +using executorch::runtime::Error; +using llm::DFlashBackendKind; + +llm::DFlashTreeCapability pairtree_program() { + return {true, true, 255}; +} + +llm::DFlashMode resolve( + std::optional budget, + bool serial_only = false, + llm::DFlashTreeCapability capability = pairtree_program(), + DFlashBackendKind backend = DFlashBackendKind::kCuda, + int max_decode_sequences = 4) { + return llm::resolve_dflash_mode( + {budget, serial_only, backend, max_decode_sequences}, capability); +} + +bool says(const llm::DFlashMode& mode, const char* text) { + return std::string(mode.reason).find(text) != std::string::npos; +} + +TEST(DFlashModeResolution, DefaultBudgetPerBackend) { + EXPECT_EQ(llm::default_tree_budget(DFlashBackendKind::kCuda, 1), 31); + EXPECT_EQ(llm::default_tree_budget(DFlashBackendKind::kCuda, 2), 15); + EXPECT_EQ(llm::default_tree_budget(DFlashBackendKind::kCuda, 16), 15); + EXPECT_EQ(llm::default_tree_budget(DFlashBackendKind::kMlx, 1), 15); + EXPECT_EQ(llm::default_tree_budget(DFlashBackendKind::kMlx, 4), 15); + for (const auto& [backend, sequences, budget] : + {std::tuple{DFlashBackendKind::kCuda, 1, 31}, + std::tuple{DFlashBackendKind::kCuda, 4, 15}, + std::tuple{DFlashBackendKind::kMlx, 1, 15}}) { + const auto mode = + resolve(std::nullopt, false, pairtree_program(), backend, sequences); + EXPECT_EQ(mode.error, Error::Ok); + EXPECT_EQ(mode.tree_budget, budget); + } +} + +// Prefix-cache sessions add physical sessions that never decode: one logical +// session decodes alone whatever --max_decode_sequences says. +TEST(DFlashModeResolution, DecodeSequencesCountLogicalSessions) { + EXPECT_EQ(llm::dflash_decode_sequences(4, 1), 1); + EXPECT_EQ(llm::dflash_decode_sequences(4, 16), 4); + EXPECT_EQ(llm::dflash_decode_sequences(1, 4), 1); + EXPECT_EQ( + llm::default_tree_budget( + DFlashBackendKind::kCuda, llm::dflash_decode_sequences(4, 1)), + 31); +} + +TEST(DFlashModeResolution, DefaultIsCappedByTheWidestTreeVerify) { + auto narrow = pairtree_program(); + narrow.max_budget = 7; + const auto mode = + resolve(std::nullopt, false, narrow, DFlashBackendKind::kCuda, 1); + EXPECT_EQ(mode.tree_budget, 7); + EXPECT_TRUE(says(mode, "capped")); + narrow.max_budget = 0; + EXPECT_EQ(resolve(std::nullopt, false, narrow).tree_budget, 0); + EXPECT_EQ(resolve(std::nullopt, false, narrow).error, Error::Ok); +} + +TEST(DFlashModeResolution, ExplicitBudgetOverridesTheDefault) { + EXPECT_EQ(resolve(7).tree_budget, 7); + EXPECT_EQ(resolve(63).tree_budget, 63); + const auto zero = resolve(0); + EXPECT_EQ(zero.error, Error::Ok); + EXPECT_EQ(zero.tree_budget, 0); + EXPECT_EQ(resolve(-1).error, Error::InvalidArgument); + EXPECT_EQ(resolve(256).error, Error::InvalidArgument); +} + +TEST(DFlashModeResolution, SerialOnlyRunsSerialAndRefusesANonzeroBudget) { + for (const std::optional budget : + {std::optional{}, std::optional{0}}) { + const auto mode = resolve(budget, true); + EXPECT_EQ(mode.error, Error::Ok); + EXPECT_EQ(mode.tree_budget, 0); + } + const auto conflict = resolve(15, true); + EXPECT_EQ(conflict.error, Error::InvalidArgument); + EXPECT_TRUE(says(conflict, "dflash_serial_only")); +} + +TEST(DFlashModeResolution, ProgramWithoutThePairTreeMethodRunsSerial) { + auto plain = pairtree_program(); + plain.pairtree_method = false; + const auto mode = resolve(std::nullopt, false, plain); + EXPECT_EQ(mode.error, Error::Ok); + EXPECT_EQ(mode.tree_budget, 0); + EXPECT_TRUE(says(mode, "--dflash2-pairtree")); + EXPECT_EQ(resolve(0, false, plain).tree_budget, 0); + // An explicit nonzero budget keeps the startup refusal. + const auto refused = resolve(31, false, plain); + EXPECT_EQ(refused.error, Error::InvalidProgram); + EXPECT_TRUE(says(refused, "--dflash2-pairtree")); +} + +TEST(DFlashModeResolution, TargetWithoutTreeVerifyRunsSerialUnlessAsked) { + auto sequence = pairtree_program(); + sequence.tree_verify = false; + const auto mode = resolve(std::nullopt, false, sequence); + EXPECT_EQ(mode.error, Error::Ok); + EXPECT_EQ(mode.tree_budget, 0); + EXPECT_EQ(resolve(15, false, sequence).error, Error::InvalidProgram); +} + +} // namespace diff --git a/examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py b/examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py index bd612823862..29862a4e50e 100644 --- a/examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py +++ b/examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py @@ -20,6 +20,8 @@ from executorch.examples.models.muse_glimmer.export import common from executorch.examples.models.muse_glimmer.export.export_dflash import ( cuda_owner_verifier_programs, + DFLASH2_PAIRTREE_METHOD, + export_dflash, prepare_cuda_packed_draft, ) from executorch.examples.models.muse_glimmer.export.export_solo import step_forward @@ -296,6 +298,116 @@ def test_dflash2_export_contract(self): finally: REGISTRY.uninstall(key) + def test_dflash2_pairtree_export_adds_a_method_with_candidate_logits(self): + """--dflash2-pairtree keeps draft_forward and adds draft_forward_pairtree, + which also returns [owners, steps, K + 1] unary logits and logsumexp.""" + target, original = models() + config = replace( + original.config, + conv_kernel_size=2, + conv_group_size=8, + selector_rank=8, + selector_top_k=4, + ) + draft = ( + DFlashDraftModel(config, max_context_length=64).to(torch.bfloat16).eval() + ) + serial_target, _ = models() + programs, _, _ = prepare_cuda_packed_draft( + target, + target.config, + copy.deepcopy(draft), + max_step_tokens=16, + max_cells=64, + max_owners=2, + pairtree=True, + ) + serial, _, _ = prepare_cuda_packed_draft( + serial_target, + serial_target.config, + draft, + max_step_tokens=16, + max_cells=64, + max_owners=2, + ) + key = "packed-dflash2-pairtree" + inputs = ( + torch.zeros(2, 4, dtype=torch.long), + torch.empty(1, 0, 64, dtype=torch.bfloat16), + torch.arange(4).repeat(2), + torch.arange(8), + torch.arange(3), + ) + self.assertEqual(set(programs), {"draft_forward", DFLASH2_PAIRTREE_METHOD}) + self.assertEqual(set(serial), {"draft_forward"}) + self.assertEqual( + programs["draft_forward"].graph_module.code, + serial["draft_forward"].graph_module.code, + ) + outputs = [] + for program in ( + programs[DFLASH2_PAIRTREE_METHOD], + programs["draft_forward"], + serial["draft_forward"], + ): + REGISTRY.install(key, PackedOracleCache([0, 0], 4)) + try: + with torch.no_grad(), REGISTRY.active(key): + outputs.append(program.module()(*inputs)) + finally: + REGISTRY.uninstall(key) + (ids, scores, extras), regular, (serial_ids, serial_scores) = outputs + self.assertEqual(len(regular), 2) + torch.testing.assert_close(regular[0], serial_ids, rtol=0, atol=0) + torch.testing.assert_close(regular[1], serial_scores, rtol=0, atol=0) + torch.testing.assert_close(ids, serial_ids) + torch.testing.assert_close(scores, serial_scores) + self.assertEqual(extras.shape, (2, 3, 5)) + self.assertEqual(extras.dtype, torch.float32) + # The candidates hold part of the full-vocabulary mass. + retained = extras[..., :4].logsumexp(-1) - extras[..., 4] + self.assertTrue(bool((retained <= 1e-5).all())) + self.assertTrue(bool((retained > -20).all())) + + def test_dflash2_pairtree_export_needs_a_dflash2_draft(self): + target, draft = models() + # Refused from the draft's config, before any model is loaded. + with unittest.mock.patch( + "executorch.examples.models.muse_glimmer.loaders.dflash_loader." + "read_dflash_gguf_config", + return_value=draft.config, + ), self.assertRaisesRegex(ValueError, "candidate selector"): + export_dflash( + "unused", + target_gguf="unused.gguf", + draft_gguf="unused.gguf", + backend="cuda", + use_offgraph_kv_cache=True, + pairtree=True, + ) + with self.assertRaisesRegex(ValueError, "selector"): + MuseGlimmerWithDFlash( + target, draft, target.config, draft.config + ).draft_forward_pairtree( + torch.zeros(1, draft.config.block_size, dtype=torch.long), + torch.zeros(1, 0, draft.config.n_target_layers * draft.config.dim).to( + torch.bfloat16 + ), + torch.arange(draft.config.block_size), + ) + with self.assertRaisesRegex(ValueError, "selector"): + prepare_cuda_packed_draft( + target, + target.config, + draft, + max_step_tokens=16, + max_cells=64, + max_owners=2, + pairtree=True, + ) + with self.assertRaisesRegex(ValueError, "--dflash2-pairtree"): + export_dflash("unused", backend="mlx", pairtree=True) + def test_taps_keep_every_row_and_selected_logits_match(self): target, _ = models() ordinary = copy.deepcopy(target) diff --git a/examples/models/muse-glimmer/tests/test_serve_batching.py b/examples/models/muse-glimmer/tests/test_serve_batching.py index d63864b8a72..abc71eed132 100644 --- a/examples/models/muse-glimmer/tests/test_serve_batching.py +++ b/examples/models/muse-glimmer/tests/test_serve_batching.py @@ -185,6 +185,48 @@ def test_cuda_launcher_forwards_dflash(arguments, tmp_path): "true", "15", ) + assert "--dflash_tree_budget" not in flags + assert "--dflash_serial_only" not in flags + + +def test_cuda_launcher_forwards_pairtree_budget(arguments, tmp_path): + data = tmp_path / "aoti_cuda_blob.ptd" + data.touch() + base = arguments + ["--backend", "cuda", "--data-path", str(data), "--dflash"] + for options, expected in ( + (["--dflash-tree-budget", "63"], ("63", None)), + # An explicit 0 differs from unset, which picks the budget from the export. + (["--dflash-tree-budget", "0"], ("0", None)), + (["--dflash-serial-only"], (None, "true")), + (["--dflash-serial-only", "--dflash-tree-budget", "0"], ("0", "true")), + ): + args = serve_batching._parse_args(base + options) + command = serve_batching._worker_command(args)[1:] + flags = dict(arg.split("=", 1) for arg in command) + assert ( + flags.get("--dflash_tree_budget"), + flags.get("--dflash_serial_only"), + ) == expected + + +@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"], + ["--backend", "cuda", "--dflash", "--dflash-serial-only"] + + ["--dflash-tree-budget", "15"], + ], +) +def test_launcher_rejects_invalid_pairtree_budget(arguments, tmp_path, options): + data = tmp_path / "aoti_cuda_blob.ptd" + data.touch() + with pytest.raises(SystemExit) as error: + serve_batching._parse_args(arguments + ["--data-path", str(data)] + options) + assert error.value.code == 2 def test_cuda_launcher_requires_the_weights_file(arguments): From 5bbd1a225863898b291131fe26be42aabd74b4e0 Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Wed, 2 Dec 2026 22:06:16 -0800 Subject: [PATCH 4/5] [CUDA] Run tree steps on the CUDA cell KV cache The CUDA cell cache derives a tree step's positions from its parents and uploads the tree mask the base cell cache builds. A RawTargetStep with parents runs as a tree step. It must fit one token forward, and its positions, which RoPE reads, must agree with its parents. The executor also reports its widest static forward, the most tokens one forward runs with a logit row for each. Authored with AI assistance (Claude, via Metamate). --- backends/cuda/batching/cuda_executor.cpp | 38 ++++++++++++++++++++++-- backends/cuda/batching/cuda_executor.h | 10 +++++++ backends/cuda/runtime/cuda_kv_cache.cpp | 31 +++++++++++++++++-- 3 files changed, 74 insertions(+), 5 deletions(-) diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index b33cb492fbf..740fa2dabf5 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -699,6 +699,26 @@ bool CudaExecutor::execute_raw( return false; } } + const auto slices = plan_slices(total, methods_); + if (!step.parents.empty()) { + if (step.embeddings || step.parents.size() != step.tokens.size() || + slices.size() != 1) { + ET_LOG(Error, "CudaExecutor: a tree step must fit one token forward"); + return false; + } + // RoPE reads step.positions, while the cache derives them from parents. + for (int i = 0; i < total; ++i) { + const auto parent = step.parents[i]; + const bool placed = parent < 0 + ? parent == -1 && step.positions[i] == ctl_->pos(step.seq_ids[i]) + : parent < i && step.seq_ids[parent] == step.seq_ids[i] && + step.positions[i] == step.positions[parent] + 1; + if (!placed) { + ET_LOG(Error, "CudaExecutor: tree positions disagree with its parents"); + return false; + } + } + } struct Reset { explicit Reset(bool& target) : flag(target) { flag = true; @@ -715,7 +735,7 @@ bool CudaExecutor::execute_raw( if (step.embeddings) { return execute_embeddings(step, consume); } - for (const auto& slice : plan_slices(total, methods_)) { + for (const auto& slice : slices) { const int off = slice.offset; const int n = slice.length; const auto& method = methods_[slice.method]; @@ -743,8 +763,11 @@ bool CudaExecutor::execute_raw( ? slice.width : std::max(selected.size(), min_selected_rows_); selected.resize(rows, selected.empty() ? 0 : selected.back()); - if (!ctl_->declare_step(std::vector( - step.seq_ids.begin() + off, step.seq_ids.begin() + off + n))) { + const std::vector seq_ids( + step.seq_ids.begin() + off, step.seq_ids.begin() + off + n); + if (!(step.parents.empty() + ? ctl_->declare_step(seq_ids) + : ctl_->declare_tree_step(seq_ids, step.parents))) { return false; } std::vector token_values( @@ -800,6 +823,15 @@ bool CudaExecutor::execute_raw( return true; } +int CudaExecutor::widest_static_tokens() const { + for (auto it = methods_.rbegin(); it != methods_.rend(); ++it) { + if (it->is_static) { + return it->max_tokens; + } + } + return 0; +} + std::optional> CudaExecutor::argmax_rows( const ::executorch::aten::Tensor& logits, std::size_t rows) { diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 4e0cf7bc7da..8241222b5d1 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -105,6 +105,12 @@ struct RawTargetStep { // Global token-row indices; -1 discards a result. Repeats and reordering are // allowed. Callback selected_indices maps rows back into this vector. std::vector logit_indices; + // When set, the step is a token tree: parents[i] is the step index of token + // i's parent, or -1 for its sequence's root + // (BatchControl::declare_tree_step). positions must agree: a root continues + // its sequence, a child sits one past its parent. A tree must fit one forward + // and cannot take embeddings. + std::vector parents; // Host [1, tokens, hidden] decoder inputs. When set, the step runs through // kEmbeddingsMethod and `tokens` is not read. ::executorch::extension::TensorPtr embeddings; @@ -169,6 +175,10 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { std::size_t preferred_batch_tokens() const override { return static_cast(methods_.back().max_tokens); } + // The widest static method's step: the most tokens one forward runs with a + // logit row selected for each of them. A wider dynamic forward_others is not + // counted: its selector is bounded separately. + int widest_static_tokens() const; // Loads every method here, so the delegate that resolves the cache binds on // the thread that runs it. diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 98bc447449c..41f61fd61fe 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -347,6 +347,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { } cache::CellCache::clear(); step_seq_ids_.clear(); + step_parents_.clear(); active_owners_.clear(); pending_width_ = 0; poisoned_ = false; @@ -364,9 +365,27 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { return false; } step_seq_ids_ = seq_ids; + step_parents_.clear(); return true; } + bool declare_tree_step( + const std::vector& seq_ids, + const std::vector& parents) override { + std::lock_guard guard(mutex_); + if (poisoned_ || !cache::CellCache::declare_tree_step(seq_ids, parents)) { + return false; + } + step_seq_ids_ = seq_ids; + step_parents_ = parents; + return true; + } + + bool retain_tree(const std::vector& keep) override { + std::lock_guard guard(mutex_); + return cache::CellCache::retain_tree(keep); + } + std::optional seq_new() override { std::lock_guard guard(mutex_); return cache::CellCache::seq_new(); @@ -468,12 +487,18 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { width, tokens); - // Every declared token continues its sequence, so the positions follow - // from the declaration; nothing is read back from the device. + // Every declared token continues its sequence, or in a tree step sits one + // past its parent, so the positions follow from the declaration; nothing + // is read back from the device. positions_.resize(tokens); std::vector next(kMaxSeqs, -1); for (int i = 0; i < tokens; ++i) { const int32_t seq_id = step_seq_ids_[i]; + if (!step_parents_.empty()) { + positions_[i] = step_parents_[i] < 0 ? cache::CellCache::pos(seq_id) + : positions_[step_parents_[i]] + 1; + continue; + } if (next[seq_id] < 0) { next[seq_id] = cache::CellCache::pos(seq_id); } @@ -521,6 +546,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { return uploaded; } step_seq_ids_.clear(); + step_parents_.clear(); return Error::Ok; } @@ -786,6 +812,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { std::vector window_layers_; CudaKVPool pool_; std::vector step_seq_ids_; + std::vector step_parents_; std::vector positions_; std::vector active_owners_; int pending_width_{0}; From 58c2e5236b7a37992eadc7e004809f6feff3363a Mon Sep 17 00:00:00 2001 From: gasoonjia Date: Thu, 3 Dec 2026 03:14:41 -0800 Subject: [PATCH 5/5] [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. Each batch drafts its greedy sessions in tree rounds first and its sampled sessions in Serial DFlash2 rounds with draft_forward after them (logged once). A round in which the builder refuses a table runs Serial DFlash2 as a whole. CudaDFlashStats counts 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, and on a PairTree export of the controlled fixture with its NaN row, a refused table must fall back to Serial DFlash2 and fail only its batch. 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, interleaved greedy and sampled sessions, 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 | 351 ++++- .../runtime/cuda_dflash_executor.h | 52 +- examples/models/muse-glimmer/tests/BUCK | 1 + examples/models/muse-glimmer/tests/README.md | 69 + .../tests/cuda_dflash_native_test.cpp | 1152 ++++++++++++++++- .../tests/export_cuda_dflash_tiny.py | 125 +- 9 files changed, 1727 insertions(+), 33 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..c60848b451d 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,83 @@ 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 auto refusal = std::string("CUDA DFlash: ") + mode.reason + + " (static target forwards take at most " + std::to_string(tree_rows) + + " rows)"; + 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 +834,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 +865,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 +1277,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 +1313,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 +1336,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 +1345,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 +1385,49 @@ 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) { + 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)); + } + if (!tree->trees.empty()) { + stats_.warmed_context_tokens += c; + return DraftStatus::Ok; + } + stats_.tree_fallback_cycles += owners.size(); + } auto sampled = target_->module().execute(df::kDFlash2Sample, {first, scores}); if (!sampled.ok() || sampled->size() != 1 || !sampled->at(0).isTensor()) { @@ -1358,6 +1497,24 @@ MuseGlimmerCudaDFlashExecutor::speculate( const batching::BatchInput& batch, batching::BatchOutput& out, bool pending_decode) { + // 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. + if (tree_budget_ > 0) { + const auto status = speculate_rounds(batch, out, pending_decode, true); + if (status != DraftStatus::Ok) { + return status; + } + } + return speculate_rounds(batch, out, pending_decode, false); +} + +MuseGlimmerCudaDFlashExecutor::DraftStatus +MuseGlimmerCudaDFlashExecutor::speculate_rounds( + const batching::BatchInput& batch, + batching::BatchOutput& out, + bool pending_decode, + bool trees) { std::size_t cursor = 0; while (cursor < batch.inputs.size()) { std::vector owners; @@ -1375,6 +1532,11 @@ MuseGlimmerCudaDFlashExecutor::speculate( ++cursor; continue; } + if (tree_budget_ > 0 && + (sessions_.at(input.sid).sampling->temperature == 0.0f) != trees) { + ++cursor; + continue; + } if (!drain(input.sid)) { return DraftStatus::Failed; } @@ -1383,7 +1545,8 @@ MuseGlimmerCudaDFlashExecutor::speculate( return DraftStatus::Failed; } if (owners.size() == static_cast(max_owners_) || - rows > static_cast(fresh_context_ - context)) { + rows > static_cast(fresh_context_ - context) || + (trees && owners.size() == static_cast(tree_owners_))) { break; } context += static_cast(rows); @@ -1398,10 +1561,39 @@ MuseGlimmerCudaDFlashExecutor::speculate( continue; } std::vector> proposals; - const auto status = draft(owners, anchors, fresh_context_, &proposals); + 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( + tree_budget_, + tree_rows_, + static_cast(owners.size()), + max_context_ - sessions_.at(owner).frontier - 1)); + } + } else if (tree_budget_ > 0) { + stats_.tree_fallback_cycles += owners.size(); + if (!logged_sampled_fallback_) { + ET_LOG( + Info, + "PairTree DFlash2 verifies greedy sessions only; sampled sessions run Serial DFlash2"); + logged_sampled_fallback_ = true; + } + } + 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, out); + if (verified != DraftStatus::Ok) { + return verified; + } + continue; + } RawStep verification; std::vector candidates; std::vector starts; @@ -1473,6 +1665,147 @@ 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, + batching::BatchOutput& out) { + // Each owner's anchor roots its tree; node i sits at step row base + 1 + i. + RawStep step; + std::vector bases, starts; + 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); + } + 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); + ++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_; + } + // sample_argmax is torch.argmax over float logits, as Serial DFlash2's + // dflash_verify_argmax is: a tie goes to the lowest token id. + const auto vocab = target_->vocab_size(); + auto* logits = static_cast(output.logits.mutable_data_ptr()); + 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, + aten::Device( + aten::DeviceType::CUDA, output.logits.device_index())); + auto tokens = target_->argmax_rows(*view, count); + if (!tokens) { + return false; + } + for (std::size_t row = 0; row < count; ++row) { + predictions[output.selected_indices[first + row]] = (*tokens)[row]; + } + } + return true; + }); + if (!ok) { + return DraftStatus::Failed; + } + // Commit the anchors and accepted paths; every other branch's KV goes. + std::vector walks; + std::vector keep; + for (std::size_t i = 0; i < owners.size(); ++i) { + const int base = bases[i]; + auto walk = pairtree::walk( + trees[i], + std::vector( + predictions.begin() + base, + predictions.begin() + base + 1 + trees[i].size())); + 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_; + } + walks.push_back(std::move(walk)); + } + 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; + 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_.cycles; + ++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..ce70cc031cb 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,15 @@ 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: per-owner cycles verified as a tree, and cycles that fell + // back to Serial DFlash2 instead, whether or not their round then verified: + // sampled sessions, and every session of a round in which the tree builder + // refused one session's candidate table. 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 +193,16 @@ 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 keep Serial DFlash2. 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 +276,38 @@ class MuseGlimmerCudaDFlashExecutor final : public batching::Executor { const; bool drain(batching::SessionId owner); enum class DraftStatus { Ok, NonFiniteScore, Failed }; + // A PairTree DFlash2 round: the node budget per owner in, a tree per owner + // out. No trees means the round fell back to Serial DFlash2 proposals. + struct TreeRound { + 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); + // Drafts and verifies the batch's greedy sessions as PairTree rounds when + // `trees` is set; otherwise its other sessions, or every session without a + // tree budget, as Serial DFlash2 rounds. + DraftStatus speculate_rounds( + const batching::BatchInput& batch, + batching::BatchOutput& out, + bool pending_decode, + bool trees); + // Verifies one tree per owner in a single target forward and commits each + // owner's longest accepted path plus the target's next token. + DraftStatus verify_tree( + const std::vector& owners, + const std::vector& anchors, + const std::vector& indices, + const std::vector>& trees, + batching::BatchOutput& out); bool fail_batch( const batching::BatchInput& batch, batching::BatchOutput& out, @@ -283,6 +323,14 @@ 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; + bool logged_sampled_fallback_ = false; 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..3b8991a0827 100644 --- a/examples/models/muse-glimmer/tests/README.md +++ b/examples/models/muse-glimmer/tests/README.md @@ -67,6 +67,75 @@ 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_nan/` is the controlled +fixture with the method in its own shape, NaN row included. 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 four interleaved greedy and sampled sessions, which take one tree +round and one Serial DFlash2 round per batch. 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. Sampled sessions must run Serial DFlash2, 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_nan/`, a round with the NaN +row must fall back from PairTree DFlash2 to Serial DFlash2 and fail 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..69672a63efd 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,136 @@ 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, 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 +496,304 @@ 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; +}; + +// 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); + 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 +910,730 @@ 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, PairTreeLeavesSampledSessionsToSerialDFlash2) { + 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_EQ(tree.stats.tree_cycles, 0u); + EXPECT_GT(tree.stats.cycles, 0u); + EXPECT_EQ(tree.stats.tree_fallback_cycles, tree.stats.cycles); + + Generation target, mixed; + ASSERT_NO_FATAL_FAILURE(generate(dir, {std::nullopt}, target)); + ASSERT_NO_FATAL_FAILURE(generate(dir, {0, 15, {{}, sampled}}, mixed)); + EXPECT_LE(expect_greedy(dir, {kPrompts[0]}, {mixed.tokens[0]}), 2); + EXPECT_GT(mixed.stats.tree_cycles, 0u); + EXPECT_GT(mixed.stats.tree_fallback_cycles, 0u); + EXPECT_EQ( + mixed.stats.tree_cycles + mixed.stats.tree_fallback_cycles, + mixed.stats.cycles); +} + +// Four sessions, greedy and sampled interleaved, verify in one tree round and +// one Serial DFlash2 round per batch, not one round per run of a kind. +TEST(CudaDFlash2Native, PairTreeGroupsGreedySessionsAcrossTheBatch) { + 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}; + const std::vector prompts{ + {1, 7, 2}, {3, 8}, {5, 2, 9, 11, 6, 4}, {4, 4, 1}}; + Generation target, mixed; + ASSERT_NO_FATAL_FAILURE( + generate(dir, {std::nullopt, 0, {}, prompts}, target)); + ASSERT_NO_FATAL_FAILURE( + generate(dir, {0, 15, {{}, sampled, {}, sampled}, prompts}, mixed)); + EXPECT_LE( + expect_greedy( + dir, {prompts[0], prompts[2]}, {mixed.tokens[0], mixed.tokens[2]}), + 2); + EXPECT_GT(mixed.stats.tree_cycles, 0u); + EXPECT_GT(mixed.stats.tree_fallback_cycles, 0u); + EXPECT_LE(mixed.stats.target_verify_calls, 2 * mixed.stats.executions); +} + +// 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 table (here a NaN score), +// the round runs Serial DFlash2 from draft_forward_pairtree's outputs and +// fails only its batch, as Serial DFlash2 does. +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_nan"; + 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..6ef0b4f26f6 100644 --- a/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py +++ b/examples/models/muse-glimmer/tests/export_cuda_dflash_tiny.py @@ -11,9 +11,21 @@ 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), and `pairtree/controlled_nan/` is the controlled fixture with +`draft_forward_pairtree` in its own shape, NaN row included. 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 @@ -65,8 +77,17 @@ 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 +) -> 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. + """ + wide = pairtree if wide is None else wide from executorch.examples.models.muse_glimmer.loaders.dflash_loader import ( load_dflash_gguf, ) @@ -75,6 +96,7 @@ 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) @@ -96,16 +118,27 @@ 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=40 if wide else 32, + max_cells=1024 if wide else 512, + forward_sizes=(1, 4, 32) if wide else (1, 4), dflash_draft=draft, max_draft_owners=2, + 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 +) -> 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. + """ + wide = pairtree if wide is None else wide from executorch.examples.models.muse_glimmer.tests.dflash_controlled_fixture import ( initialize_controlled_weights, RejectByAnchor, @@ -150,19 +183,64 @@ 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), + # A step must be wider than the widest static forward. + max_step_tokens=40 if wide else 32, + max_cells=1024 if wide else 512, + forward_sizes=(1, 4, 32) if wide else (1, 4), dflash_draft=draft.to(torch.bfloat16), max_draft_owners=2, + 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 +250,27 @@ 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_nan", pairtree=True, wide=False + ) + check_pinned(output_dir / "plain", output_dir) + check_pinned(output_dir / "controlled_plain", output_dir / "controlled") else: export(args.output_dir)