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/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}; 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 619d835e418..9c9fa2ed471 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -357,6 +357,42 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS) extension_llm_serving Threads::Threads ) add_test(NAME muse_glimmer_batching COMMAND muse_glimmer_batching_test) + # Tokenizer include paths contain regex.h; keep GoogleTest and its users on + # the same simple-regex ABI instead of the shadowed POSIX header. Only the + # tests below build it. + add_subdirectory( + ${EXECUTORCH_ROOT}/third-party/googletest + ${CMAKE_CURRENT_BINARY_DIR}/dflash_googletest EXCLUDE_FROM_ALL + ) + target_compile_definitions(gtest PUBLIC GTEST_HAS_POSIX_RE=0) + add_executable( + muse_glimmer_dflash2_pairtree_test tests/dflash2_pairtree_test.cpp + ) + target_include_directories( + muse_glimmer_dflash2_pairtree_test PRIVATE ${_common_include_directories} + ) + target_link_libraries( + muse_glimmer_dflash2_pairtree_test PRIVATE GTest::gtest_main + ) + add_test(NAME muse_glimmer_dflash2_pairtree + COMMAND muse_glimmer_dflash2_pairtree_test + ) + set_tests_properties( + muse_glimmer_dflash2_pairtree + PROPERTIES + ENVIRONMENT + "MUSE_GLIMMER_PAIRTREE_FIXTURE=${CMAKE_CURRENT_SOURCE_DIR}/tests/data/pairtree_reference.bin" + ) + add_executable(muse_glimmer_dflash_mode_test tests/dflash_mode_test.cpp) + target_include_directories( + muse_glimmer_dflash_mode_test PRIVATE ${_common_include_directories} + ) + target_link_libraries( + muse_glimmer_dflash_mode_test PRIVATE GTest::gtest_main + ) + add_test(NAME muse_glimmer_dflash_mode + COMMAND muse_glimmer_dflash_mode_test + ) if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "mlx") add_executable( muse_glimmer_mlx_dflash_test tests/mlx_dflash_native_test.cpp @@ -377,13 +413,6 @@ if(MUSE_GLIMMER_BUILD_BATCHING OR MUSE_GLIMMER_BUILD_BATCHING_TESTS) endif() endif() if(MUSE_GLIMMER_BUILD_BATCHING AND _batching_backend STREQUAL "cuda") - # Tokenizer include paths contain regex.h; keep GoogleTest and its users - # on the same simple-regex ABI instead of the shadowed POSIX header. - add_subdirectory( - ${EXECUTORCH_ROOT}/third-party/googletest - ${CMAKE_CURRENT_BINARY_DIR}/dflash_googletest EXCLUDE_FROM_ALL - ) - target_compile_definitions(gtest PUBLIC GTEST_HAS_POSIX_RE=0) add_executable( muse_glimmer_cuda_dflash_test tests/cuda_dflash_executor_test.cpp tests/cuda_dflash_native_test.cpp 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 2a25e3fafe5..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", @@ -38,6 +40,23 @@ 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 = "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..2314eb34890 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); @@ -37,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/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/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/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/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 40f63d062c8..1d30d1c188d 100644 --- a/examples/models/muse-glimmer/tests/BUCK +++ b/examples/models/muse-glimmer/tests/BUCK @@ -21,6 +21,27 @@ 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 = 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", + src = "data/pairtree_reference.bin", +) + fbcode_target( _kind = runtime.cxx_binary, name = "cuda_dflash_native_runner", @@ -32,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 9142faef1ca..3b8991a0827 100644 --- a/examples/models/muse-glimmer/tests/README.md +++ b/examples/models/muse-glimmer/tests/README.md @@ -66,3 +66,116 @@ 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. + +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 +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/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/data/pairtree_reference.bin b/examples/models/muse-glimmer/tests/data/pairtree_reference.bin new file mode 100644 index 00000000000..2f0893ce18f Binary files /dev/null and b/examples/models/muse-glimmer/tests/data/pairtree_reference.bin differ 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/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/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) 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() 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): 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"], + )