From fe570a65260df6e4e3913cf179b563a79a9bab4c Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sun, 29 Nov 2026 17:42:38 -0500 Subject: [PATCH 1/2] Add optional strict grammar top-k shortlist sampler --- .github/workflows/validate_wrapper.yml | 4 +- CMakeLists.txt | 17 + docs/sampler_selection_guard.md | 25 ++ src/llama_dart_grammar_top_k_test_hooks.h | 11 + src/llama_dart_wrapper.cpp | 183 +++++++++- src/llama_dart_wrapper.h | 10 + tests/exit_teardown_test.cpp | 17 +- tests/grammar_top_k_fixture.h | 27 ++ tests/grammar_top_k_test.cpp | 404 ++++++++++++++++++++++ tests/test_validate_exports.py | 14 +- tools/validate_exports.py | 1 + 11 files changed, 694 insertions(+), 19 deletions(-) create mode 100644 src/llama_dart_grammar_top_k_test_hooks.h create mode 100644 tests/grammar_top_k_fixture.h create mode 100644 tests/grammar_top_k_test.cpp diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index 57ccc164..3ced051d 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -522,6 +522,7 @@ jobs: cmake --build build/wrapper-contract --target llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_model_fd_test llamadart_threadpool_test + llamadart_grammar_top_k_test llamadart_f16_dot_accumulation_test llamadart_speculative_api_test llamadart_build_identity_test llamadart_upstream_abi_test @@ -734,6 +735,7 @@ jobs: run: >- cmake --build ${{ matrix.build_dir }} --target llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_model_fd_test llamadart_threadpool_test llamadart_exit_teardown_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test + llamadart_grammar_top_k_test llamadart_build_identity_test llamadart_cancel_flag_test llamadart_f16_dot_accumulation_test llamadart_upstream_abi_test llamadart_mtmd_compat_test @@ -748,7 +750,7 @@ jobs: # the Metal library, which takes most of a minute. - name: Run the exit teardown scenarios run: >- - ctest --test-dir ${{ matrix.build_dir }} -R "owner_|model_fd|threadpool|exit_teardown|image_token_limit|fit_api|device_memory|build_identity|cancel_flag|f16_dot_accumulation|f16_residual_kernels|upstream_abi|mtmd_compat|asr_stream" + ctest --test-dir ${{ matrix.build_dir }} -R "owner_|model_fd|threadpool|exit_teardown|grammar_top_k|image_token_limit|fit_api|device_memory|build_identity|cancel_flag|f16_dot_accumulation|f16_residual_kernels|upstream_abi|mtmd_compat|asr_stream" --timeout 300 --output-on-failure # Apple CPUs have FHM, so the shipped build takes the FMLAL branch of # patch 0005. ARMv8.2-A with FP16 compiles its conversion branch, as on diff --git a/CMakeLists.txt b/CMakeLists.txt index 60165f8b..e6a00d68 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -697,6 +697,22 @@ if (LLAMADART_BUILD_TESTS) "${exit_teardown_vocabulary_model}") set_tests_properties(llamadart_exit_teardown_make-vocabulary-model PROPERTIES FIXTURES_SETUP llamadart_exit_teardown_vocabulary_model) + + add_executable(llamadart_grammar_top_k_test tests/grammar_top_k_test.cpp) + target_compile_features(llamadart_grammar_top_k_test PRIVATE cxx_std_17) + target_compile_definitions(llamadart_grammar_top_k_test PRIVATE LLAMADART_TESTING=1) + target_include_directories(llamadart_grammar_top_k_test PRIVATE src) + target_link_libraries(llamadart_grammar_top_k_test PRIVATE llamadart_lib) + set(grammar_top_k_model "${CMAKE_CURRENT_BINARY_DIR}/grammar_top_k_model.gguf") + add_test(NAME llamadart_grammar_top_k_make-model + COMMAND llamadart_exit_teardown_test make-grammar-top-k-model "${grammar_top_k_model}") + set_tests_properties(llamadart_grammar_top_k_make-model + PROPERTIES FIXTURES_SETUP llamadart_grammar_top_k_model TIMEOUT 30) + add_test(NAME llamadart_grammar_top_k_test + COMMAND llamadart_grammar_top_k_test "${grammar_top_k_model}") + set_tests_properties(llamadart_grammar_top_k_test + PROPERTIES FIXTURES_REQUIRED llamadart_grammar_top_k_model TIMEOUT 30) + if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME llamadart_owner_model_test COMMAND llamadart_owner_api_test "${exit_teardown_vocabulary_model}") @@ -977,6 +993,7 @@ if (LLAMADART_BUILD_TESTS) llamadart_build_identity_test llamadart_upstream_abi_test llamadart_cancel_flag_test llamadart_tts_eval_test llamadart_tts_seed_test llamadart_tts_batch_test llamadart_tts_sampler_test llamadart_exit_teardown_test llamadart_model_fd_test llamadart_threadpool_test + llamadart_grammar_top_k_test llamadart_mtmd_compat_test llamadart_vulkan_device_info_test llamadart_barrier_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test) diff --git a/docs/sampler_selection_guard.md b/docs/sampler_selection_guard.md index 0d1526ef..2e7745df 100644 --- a/docs/sampler_selection_guard.md +++ b/docs/sampler_selection_guard.md @@ -52,6 +52,27 @@ A binding that wants a typed error must treat a bare `LLAMA_TOKEN_NULL` from error is set in both cases. `llamadart` does that after it pins an artifact that contains this guard. +## Strict grammar before top-k + +`llama_dart_sampler_init_grammar_top_k(grammar, top_k)` is an optional +consumer ABI addition. Use it with a strict `llama_sampler_init_grammar` +sampler in a CPU chain immediately before ordinary top-k with the same +`top_k` in `[1, 64]`. Bias, penalties and suppression can run before the +grammar. The wrapper owns the grammar after a successful call and forwards +accept, reset, clone and free. A `NULL` result reports a constructor error +through `llama_dart_last_error` and leaves ownership with the caller. The +grammar's vocabulary must outlive the wrapper and its clones. + +The wrapper checks the leading candidates on scratch storage. When all +survive and their order and cutoff are unambiguous, the chain's own top-k and +selector run as usual. A rejection, tie, or unsuitable input takes the full +grammar path with the original candidates. Selection, the finite-logit check +and acceptance remain in the guarded sampling call. + +Bindings can check for the new export and keep the ordinary grammar path on +older runtimes. No existing signatures, structs or API versions change. The +native export gate requires 120 symbols including the new constructor. + ## Validation `llamadart_exit_teardown_model-nonfinite-selection` covers both exports with an @@ -59,3 +80,7 @@ all `-inf` chain under an unfinished grammar that selects the end of generation, NaN and `+inf` selections, a chain that selects nothing, a failure at the second step of a batch, and valid sampling afterwards. Without the check the first case ends the process with SIGABRT. + +`llamadart_grammar_top_k_test` compares ordered shortlists, accepted tokens +and seeded samples with a separate grammar-first chain. A generated vocabulary +variant covers JSON escapes, split UTF-8 and EOG through the real grammar. diff --git a/src/llama_dart_grammar_top_k_test_hooks.h b/src/llama_dart_grammar_top_k_test_hooks.h new file mode 100644 index 00000000..2810be40 --- /dev/null +++ b/src/llama_dart_grammar_top_k_test_hooks.h @@ -0,0 +1,11 @@ +#pragma once + +#if defined(LLAMADART_TESTING) +#include "llama_dart_wrapper.h" + +extern "C" LLAMADART_API llama_token llama_dart_test_sample_candidates( + struct llama_sampler *sampler, struct llama_token_data_array *candidates); + +extern "C" LLAMADART_API void +llama_dart_test_set_grammar_top_k_init_hook(void (*hook)()); +#endif diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index b7d00863..dbb7518b 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -6,6 +6,7 @@ #if defined(LLAMADART_TESTING) #include "llama_dart_asr_test_hooks.h" #include "llama_dart_fit_test_hooks.h" +#include "llama_dart_grammar_top_k_test_hooks.h" #include "llama_dart_reasoning_budget_test_hooks.h" #include "llama_dart_threadpool_test_hooks.h" #include "llama_dart_tts_test_hooks.h" @@ -36,6 +37,7 @@ #include "speculative.h" #include +#include #include #include #include @@ -2347,6 +2349,23 @@ LLAMADART_API void llama_dart_synchronize(struct llama_context *ctx) { // can still select one, and a grammar sampler that accepts an end-of-generation // token it has not finished with ends the process in GGML_ABORT, which no // exception barrier catches. Throws, so the barrier records the failure. +static llama_token llama_dart_sample_checked(struct llama_sampler *smpl, + llama_token_data_array &array) { + llama_sampler_apply(smpl, &array); + + if (array.selected < 0 || + array.selected >= static_cast(array.size)) { + throw std::runtime_error("The sampler selected no candidate"); + } + const llama_token_data &selected = array.data[array.selected]; + if (!std::isfinite(selected.logit)) { + throw std::runtime_error( + "The sampler selected a candidate with a non-finite logit"); + } + llama_sampler_accept(smpl, selected.id); + return selected.id; +} + static llama_token llama_dart_sample_checked(struct llama_sampler *smpl, struct llama_context *ctx, int32_t idx) { @@ -2393,20 +2412,18 @@ static llama_token llama_dart_sample_checked(struct llama_sampler *smpl, /* .selected = */ -1, /* .sorted = */ false, }; - llama_sampler_apply(smpl, &array); + return llama_dart_sample_checked(smpl, array); +} - if (array.selected < 0 || - array.selected >= static_cast(array.size)) { - throw std::runtime_error("The sampler selected no candidate"); - } - const llama_token_data &selected = array.data[array.selected]; - if (!std::isfinite(selected.logit)) { - throw std::runtime_error( - "The sampler selected a candidate with a non-finite logit"); - } - llama_sampler_accept(smpl, selected.id); - return selected.id; +#if defined(LLAMADART_TESTING) +extern "C" llama_token llama_dart_test_sample_candidates( + struct llama_sampler *sampler, struct llama_token_data_array *candidates) { + return llama_dart_barrier(LLAMA_TOKEN_NULL, [=] { + llama_dart_exit_call call; + return llama_dart_sample_checked(sampler, *candidates); + }); } +#endif LLAMADART_API llama_token llama_dart_sampler_sample(struct llama_sampler *smpl, struct llama_context *ctx, @@ -2440,6 +2457,148 @@ llama_dart_sampler_init_grammar_lazy_patterns( }); } +static constexpr int32_t llama_dart_grammar_top_k_max = 64; + +struct llama_dart_grammar_top_k { + llama_sampler *grammar; + size_t k; +}; + +static bool llama_dart_grammar_top_k_survives( + const llama_dart_grammar_top_k &context, + const llama_token_data_array &candidates) { + const size_t k = context.k; + if (candidates.size <= k) { + return false; + } + + // Keep one extra candidate to detect ties at the cutoff without touching + // the array the real top-k or the full grammar fallback will receive. + std::array shortlist; + const auto higher_logit = [](const llama_token_data &a, + const llama_token_data &b) { + return a.logit > b.logit; + }; + const float infinity = std::numeric_limits::infinity(); + auto *const begin = shortlist.data(); + auto *const end = begin + k + 1; + for (size_t i = 0; i <= k; ++i) { + if (!(candidates.data[i].logit < infinity)) { + return false; + } + shortlist[i] = candidates.data[i]; + } + std::make_heap(begin, end, higher_logit); + for (size_t i = k + 1; i < candidates.size; ++i) { + const auto &candidate = candidates.data[i]; + if (!(candidate.logit < infinity)) { + return false; + } + if (higher_logit(candidate, shortlist.front())) { + std::pop_heap(begin, end, higher_logit); + shortlist[k] = candidate; + std::push_heap(begin, end, higher_logit); + } + } + std::sort_heap(begin, end, higher_logit); + + for (size_t i = 0; i < k; ++i) { + if (!higher_logit(shortlist[i], shortlist[i + 1])) { + return false; + } + // Upstream top-k retains the prefix verbatim if sorted is already set. + if (candidates.sorted && + shortlist[i].logit != candidates.data[i].logit) { + return false; + } + } + + llama_token_data_array probe{begin, k, -1, true}; + llama_sampler_apply(context.grammar, &probe); + return std::all_of(begin, begin + k, [](const llama_token_data &candidate) { + return std::isfinite(candidate.logit); + }); +} + +static llama_sampler *llama_dart_grammar_top_k_wrap(llama_sampler *grammar, + size_t k); + +static llama_sampler_i llama_dart_grammar_top_k_interface = [] { + llama_sampler_i callbacks{}; + callbacks.name = [](const llama_sampler *) { return "llamadart-grammar-top-k"; }; + callbacks.accept = [](llama_sampler *sampler, llama_token token) { + auto *context = static_cast(sampler->ctx); + llama_sampler_accept(context->grammar, token); + }; + callbacks.apply = [](llama_sampler *sampler, + llama_token_data_array *candidates) { + const auto &context = *static_cast(sampler->ctx); + if (!llama_dart_grammar_top_k_survives(context, *candidates)) { + llama_sampler_apply(context.grammar, candidates); + } + }; + callbacks.reset = [](llama_sampler *sampler) { + auto *context = static_cast(sampler->ctx); + llama_sampler_reset(context->grammar); + }; + callbacks.clone = [](const llama_sampler *sampler) -> llama_sampler * { + const auto &context = + *static_cast(sampler->ctx); + std::unique_ptr grammar( + llama_sampler_clone(context.grammar), llama_sampler_free); + if (!grammar) { + return nullptr; + } + auto *result = llama_dart_grammar_top_k_wrap(grammar.get(), context.k); + if (result != nullptr) { + grammar.release(); + } + return result; + }; + callbacks.free = [](llama_sampler *sampler) { + auto *context = static_cast(sampler->ctx); + llama_sampler_free(context->grammar); + delete context; + }; + return callbacks; +}(); + +#if defined(LLAMADART_TESTING) +static void (*g_test_grammar_top_k_init_hook)() = nullptr; + +extern "C" void llama_dart_test_set_grammar_top_k_init_hook(void (*hook)()) { + g_test_grammar_top_k_init_hook = hook; +} +#endif + +static llama_sampler *llama_dart_grammar_top_k_wrap(llama_sampler *grammar, + size_t k) { + auto context = std::make_unique( + llama_dart_grammar_top_k{grammar, k}); +#if defined(LLAMADART_TESTING) + if (g_test_grammar_top_k_init_hook != nullptr) { + g_test_grammar_top_k_init_hook(); + } +#endif + auto *result = + llama_sampler_init(&llama_dart_grammar_top_k_interface, context.get()); + if (result != nullptr) { + context.release(); + } + return result; +} + +LLAMADART_API struct llama_sampler *llama_dart_sampler_init_grammar_top_k( + struct llama_sampler *grammar, int32_t top_k) { + return llama_dart_barrier(nullptr, [=] { + llama_dart_exit_call call; + if (grammar == nullptr || top_k < 1 || top_k > llama_dart_grammar_top_k_max) { + throw std::invalid_argument("Strict grammar and top-k in [1, 64] required"); + } + return llama_dart_grammar_top_k_wrap(grammar, static_cast(top_k)); + }); +} + LLAMADART_API struct llama_sampler *llama_dart_sampler_init_dry( const struct llama_vocab *vocab, float dry_multiplier, float dry_base, int32_t dry_allowed_length, int32_t dry_penalty_last_n, diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 3a213b00..e19e56cd 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -844,6 +844,16 @@ LLAMADART_API struct llama_sampler * llama_dart_sampler_init_grammar_lazy_patter const llama_token * trigger_tokens, size_t num_trigger_tokens); +// Wraps a strict grammar that is immediately followed by ordinary top-k in +// the CPU sampler chain. top_k must match the following sampler and be in +// [1, 64]. On success the wrapper owns grammar and is freed with +// llama_sampler_free. On failure returns NULL, sets llama_dart_last_error, +// and leaves grammar owned by the caller. Keep the vocabulary alive until +// the wrapper and all its clones are freed. Blocks after exit teardown. +LLAMADART_API struct llama_sampler * llama_dart_sampler_init_grammar_top_k( + struct llama_sampler * grammar, + int32_t top_k); + // The DRY sampler constructor, which detokenizes the whole vocabulary and // tokenizes every sequence breaker: it throws for a vocabulary that cannot // tokenize a breaker, and for an allocation failure. NULL after a caught diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index 3c4769b8..9256bbc3 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -8,6 +8,7 @@ #include "llama_dart_tts_test_hooks.h" #include "llama_dart_wrapper.h" +#include "grammar_top_k_fixture.h" #include "ggml-backend-impl.h" #include "gguf.h" #include "mtmd.h" @@ -21,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -807,9 +809,10 @@ const llama_token kNewlineToken = 6; // load, offload and evaluate, and needs no download. It has no tokenizer // unless with_vocabulary asks for one, which a grammar sampler needs. // shared_mtp selects a Gemma4/assistant pair whose draft reads target KV. -int make_model(const char *path, bool is_encoder, - bool with_vocabulary = false, bool mtp_head = false, - bool shared_mtp = false) { +int make_model( + const char *path, bool is_encoder, bool with_vocabulary = false, + bool mtp_head = false, bool shared_mtp = false, + std::initializer_list extra_pieces = {}) { const uint32_t vocab_size = 256; const uint32_t context_length = 512; const uint32_t embedding_length = shared_mtp && mtp_head ? 64 : 128; @@ -884,6 +887,10 @@ int make_model(const char *path, bool is_encoder, types[220] = types[221] = types[222] = LLAMA_TOKEN_TYPE_CONTROL; pieces[223] = "<0xE2>"; types[223] = LLAMA_TOKEN_TYPE_BYTE; + for (const auto &extra : extra_pieces) { + pieces.at(extra.id) = extra.piece; + types.at(extra.id) = extra.type; + } std::vector texts; for (const std::string &piece : pieces) { texts.push_back(piece.c_str()); @@ -4155,6 +4162,10 @@ int main(int argc, char **argv) { if (scenario == "make-vocabulary-model") { return make_model(first, false, true); } + if (scenario == "make-grammar-top-k-model") { + return make_model(first, false, true, false, false, + grammar_top_k_pieces); + } if (scenario == "make-shared-mtp-target") { return make_model(first, false, true, false, true); } diff --git a/tests/grammar_top_k_fixture.h b/tests/grammar_top_k_fixture.h new file mode 100644 index 00000000..e426cade --- /dev/null +++ b/tests/grammar_top_k_fixture.h @@ -0,0 +1,27 @@ +#pragma once + +#include "llama.h" + +#include + +struct vocabulary_piece_override { + llama_token id; + const char *piece; + llama_token_type type = LLAMA_TOKEN_TYPE_NORMAL; +}; + +inline constexpr std::initializer_list + grammar_top_k_pieces = { + {224, "{"}, + {225, "}"}, + {226, "\""}, + {227, ":"}, + {228, "\\"}, + {229, "u"}, + {230, "2"}, + {231, "0"}, + {232, "a"}, + {233, "c"}, + {234, "<0x82>", LLAMA_TOKEN_TYPE_BYTE}, + {235, "<0xAC>", LLAMA_TOKEN_TYPE_BYTE}, +}; diff --git a/tests/grammar_top_k_test.cpp b/tests/grammar_top_k_test.cpp new file mode 100644 index 00000000..708369c8 --- /dev/null +++ b/tests/grammar_top_k_test.cpp @@ -0,0 +1,404 @@ +#ifdef NDEBUG +#error "Wrapper contract tests require active assertions in every configuration" +#endif + +#include "llama_dart_grammar_top_k_test_hooks.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using sampler_ptr = + std::unique_ptr; +using candidates = std::array; +using shortlist = std::vector>; + +constexpr float masked = -std::numeric_limits::infinity(); + +struct trace { + std::vector apply_sizes; + std::vector accepted; + std::vector shortlists; + trace *clone_record = nullptr; + int resets = 0; + int clones = 0; + int frees = 0; +}; + +struct grammar_state { + trace &record; + sampler_ptr child; + llama_token denied; +}; + +llama_sampler *recording_grammar(trace &record, llama_token denied, + llama_sampler *child = nullptr) { + static llama_sampler_i iface = [] { + llama_sampler_i callbacks{}; + callbacks.name = [](const llama_sampler *) { return "recording-grammar"; }; + callbacks.apply = [](llama_sampler *sampler, + llama_token_data_array *array) { + auto &state = *static_cast(sampler->ctx); + state.record.apply_sizes.push_back(array->size); + if (state.child) { + llama_sampler_apply(state.child.get(), array); + } else { + for (size_t i = 0; i < array->size; ++i) { + if (array->data[i].id == state.denied) { + array->data[i].logit = masked; + } + } + } + }; + callbacks.accept = [](llama_sampler *sampler, llama_token token) { + auto &state = *static_cast(sampler->ctx); + state.record.accepted.push_back(token); + llama_sampler_accept(state.child.get(), token); + }; + callbacks.reset = [](llama_sampler *sampler) { + auto &state = *static_cast(sampler->ctx); + ++state.record.resets; + llama_sampler_reset(state.child.get()); + }; + callbacks.clone = [](const llama_sampler *sampler) { + const auto &state = *static_cast(sampler->ctx); + ++state.record.clones; + trace &record = state.record.clone_record == nullptr + ? state.record + : *state.record.clone_record; + return recording_grammar(record, state.denied, + llama_sampler_clone(state.child.get())); + }; + callbacks.free = [](llama_sampler *sampler) { + auto *state = static_cast(sampler->ctx); + ++state->record.frees; + delete state; + }; + return callbacks; + }(); + return llama_sampler_init( + &iface, new grammar_state{record, {child, llama_sampler_free}, denied}); +} + +llama_sampler *recording_shortlist(trace &record) { + static llama_sampler_i iface = [] { + llama_sampler_i callbacks{}; + callbacks.name = [](const llama_sampler *) { + return "recording-shortlist"; + }; + callbacks.apply = [](llama_sampler *sampler, + llama_token_data_array *array) { + auto &captured = + static_cast(sampler->ctx)->shortlists.emplace_back(); + for (size_t i = 0; i < array->size; ++i) { + captured.emplace_back(array->data[i].id, array->data[i].logit); + } + }; + return callbacks; + }(); + return llama_sampler_init(&iface, &record); +} + +sampler_ptr chain(llama_sampler *grammar, trace &record, int32_t k, + uint32_t seed) { + sampler_ptr result( + llama_sampler_chain_init(llama_sampler_chain_default_params()), + llama_sampler_free); + llama_sampler_chain_add(result.get(), grammar); + llama_sampler_chain_add(result.get(), llama_sampler_init_top_k(k)); + llama_sampler_chain_add(result.get(), recording_shortlist(record)); + if (k == 1) { + llama_sampler_chain_add(result.get(), llama_sampler_init_greedy()); + } else { + llama_sampler_chain_add(result.get(), llama_sampler_init_top_p(0.95f, 1)); + llama_sampler_chain_add(result.get(), llama_sampler_init_temp(0.8f)); + llama_sampler_chain_add(result.get(), llama_sampler_init_dist(seed)); + } + return result; +} + +sampler_ptr optimized_chain(trace &record, llama_token denied, int32_t k, + uint32_t seed, llama_sampler *real = nullptr) { + sampler_ptr grammar(recording_grammar(record, denied, real), + llama_sampler_free); + llama_sampler *optimized = + llama_dart_sampler_init_grammar_top_k(grammar.get(), k); + assert(optimized != nullptr); + grammar.release(); + return chain(optimized, record, k, seed); +} + +struct sample_result { + llama_token token; + std::string error; +}; + +sample_result sample(llama_sampler *chain, candidates input, + bool sorted = false) { + llama_token_data_array array{input.data(), input.size(), -1, sorted}; + const llama_token token = llama_dart_test_sample_candidates(chain, &array); + const char *error = llama_dart_last_error(); + return {token, error == nullptr ? "" : error}; +} + +candidates ranked(const std::array &logits) { + candidates input{}; + for (size_t i = 0; i < input.size(); ++i) { + input[i] = {static_cast(i), logits[i], 0.0f}; + } + return input; +} + +struct comparison { + trace fast; + trace full; + sampler_ptr optimized; + sampler_ptr oracle; + + comparison(int32_t k, llama_token denied = LLAMA_TOKEN_NULL, + uint32_t seed = 42, llama_sampler *real_fast = nullptr, + llama_sampler *real_full = nullptr) + : optimized(optimized_chain(fast, denied, k, seed, real_fast)), + oracle( + chain(recording_grammar(full, denied, real_full), full, k, seed)) {} + + llama_token check(const candidates &input, std::vector fast_sizes, + bool sorted = false) { + const size_t accepted = full.accepted.size(); + fast.apply_sizes.clear(); + full.apply_sizes.clear(); + fast.shortlists.clear(); + full.shortlists.clear(); + const auto actual = sample(optimized.get(), input, sorted); + const auto expected = sample(oracle.get(), input, sorted); + assert(fast.apply_sizes == fast_sizes); + assert((full.apply_sizes == std::vector{input.size()})); + assert(fast.shortlists.size() == 1); + assert(fast.shortlists == full.shortlists); + assert(actual.token == expected.token); + assert(actual.error == expected.error); + if (expected.token == LLAMA_TOKEN_NULL) { + assert(expected.error.find("non-finite logit") != std::string::npos); + assert(full.accepted.size() == accepted); + } else { + assert(expected.error.empty()); + assert(full.accepted.size() == accepted + 1); + assert(full.accepted.back() == expected.token); + } + assert(fast.accepted == full.accepted); + return actual.token; + } +}; + +void test_greedy() { + const auto input = ranked({1, 4, 3, 2, 0, -1, -2, masked}); + comparison allowed(1); + assert(allowed.check(input, {1}) == 1); + assert(allowed.check(input, {1}) == 1); + + comparison rejected(1, 1); + assert(rejected.check(input, {1, 8}) == 2); + assert((rejected.fast.accepted == std::vector{2})); +} + +void test_stochastic() { + const auto weights = ranked( + {std::log(2.0f), std::log(3.0f), std::log(4.0f), -1, -2, -3, -4, masked}); + auto reversed = weights; + std::swap(reversed[1].logit, reversed[2].logit); + for (const uint32_t seed : {1u, 42u, 9001u}) { + comparison allowed(2, LLAMA_TOKEN_NULL, seed); + comparison rejected(2, 1, seed); + for (int step = 0; step < 64; ++step) { + const auto &input = step % 3 == 0 ? reversed : weights; + const llama_token fast = allowed.check(input, {2}); + const llama_token fallback = rejected.check(input, {2, 8}); + assert(fast == 1 || fast == 2); + assert(fallback == 0 || fallback == 2); + const auto &top = rejected.fast.shortlists.front(); + assert(top[0].first == 2 && top[0].second == input[2].logit); + assert(top[1].first == 0 && top[1].second == input[0].logit); + } + assert(std::count(allowed.fast.accepted.begin(), + allowed.fast.accepted.end(), 1) > 0); + assert(std::count(allowed.fast.accepted.begin(), + allowed.fast.accepted.end(), 2) > 0); + } +} + +void test_fallbacks() { + comparison greedy(1, 1); + assert(greedy.check(ranked({4, 4, 3, 2, 1, 0, -1, -2}), {8}) == 0); + comparison stochastic(2); + stochastic.check(ranked({4, 4, 3, 2, 1, 0, -1, -2}), {8}); + stochastic.check(ranked({4, 3, 3, 2, 1, 0, -1, -2}), {8}); + stochastic.check(ranked({4, 3, 2, 2, 1, 0, -1, -2}), {2}); + // A sorted input skips upstream's sort, even if a preceding filter made + // the sorted flag stale. A shortlist must preserve that prefix as well. + stochastic.check(ranked({4, 3, 2, 1, 0, -1, -2, masked}), {2}, true); + comparison stale(2, 1); + stale.check(ranked({4, 1, 3, 2, 0, -1, -2, masked}), {8}, true); + comparison suppressed(1); + assert(suppressed.check(ranked({masked, masked, masked, masked, masked, + masked, masked, masked}), + {8}) == LLAMA_TOKEN_NULL); + assert(suppressed.check(ranked({-masked, 4, 3, 2, 1, 0, -1, -2}), {8}, + true) == LLAMA_TOKEN_NULL); + assert(suppressed.check(ranked({4, 3, 2, 1, 0, -1, -2, + std::numeric_limits::quiet_NaN()}), + {8}, true) == 0); +} + +void test_ownership() { + trace record; + sampler_ptr grammar(recording_grammar(record, LLAMA_TOKEN_NULL), + llama_sampler_free); + assert(llama_dart_sampler_init_grammar_top_k(nullptr, 1) == nullptr); + assert(llama_dart_last_error() != nullptr); + for (int32_t k : {0, 65}) { + assert(llama_dart_sampler_init_grammar_top_k(grammar.get(), k) == nullptr); + assert(llama_dart_last_error() != nullptr); + assert(record.frees == 0); + } + llama_dart_test_set_grammar_top_k_init_hook([] { throw std::bad_alloc(); }); + assert(llama_dart_sampler_init_grammar_top_k(grammar.get(), 64) == nullptr); + assert(llama_dart_last_error() != nullptr); + assert(record.frees == 0); + llama_dart_test_set_grammar_top_k_init_hook(nullptr); + sampler_ptr optimized( + llama_dart_sampler_init_grammar_top_k(grammar.get(), 64), + llama_sampler_free); + assert(optimized != nullptr && llama_dart_last_error() == nullptr); + grammar.release(); + sampler_ptr clone(llama_sampler_clone(optimized.get()), llama_sampler_free); + assert(clone != nullptr && record.clones == 1); + std::array wide{}; + for (size_t i = 0; i < wide.size(); ++i) { + wide[i] = {static_cast(i), static_cast(i), 0.0f}; + } + llama_token_data_array array{wide.data(), wide.size(), -1, false}; + llama_sampler_apply(clone.get(), &array); + assert((record.apply_sizes == std::vector{64})); + assert(array.data == wide.data() && array.size == wide.size() && + !array.sorted && array.selected == -1); + assert(llama_dart_sampler_accept(clone.get(), 3)); + assert((record.accepted == std::vector{3})); + llama_sampler_reset(clone.get()); + assert(record.resets == 1); + optimized.reset(); + assert(record.frees == 1); + clone.reset(); + assert(record.frees == 2); +} + +llama_token token_for(const llama_vocab *vocab, const std::string &piece) { + for (llama_token id = 0; id < llama_vocab_n_tokens(vocab); ++id) { + char buffer[32]; + const int length = + llama_token_to_piece(vocab, id, buffer, sizeof(buffer), 0, false); + if (length > 0 && + std::string(buffer, static_cast(length)) == piece) { + return id; + } + } + assert(false && "missing grammar fixture token"); + return LLAMA_TOKEN_NULL; +} + +candidates grammar_candidates(llama_token next, llama_token eog, + bool try_eog_first = false) { + auto input = ranked({7, 8, 6, 5, 4, 3, 2, 1}); + input[0].id = eog; + input[1].id = next; + for (size_t i = 2; i < input.size(); ++i) { + input[i].id = static_cast(i + 8); + } + if (try_eog_first) { + std::swap(input[0].logit, input[1].logit); + } + return input; +} + +void test_real_grammar(const char *path) { + auto params = llama_model_default_params(); + params.vocab_only = true; + llama_model *model = llama_dart_model_load_from_file(path, params); + assert(model != nullptr); + const llama_vocab *vocab = llama_model_get_vocab(model); + const llama_token eog = llama_vocab_eos(vocab); + assert(llama_vocab_is_eog(vocab, eog)); + const char *grammar = + R"gbnf(root ::= "{" "\"" "a" "\"" ":" "\"" "\\" "u" "2" "0" "a" "c" "\u20ac" "\"" "}")gbnf"; + const auto create_grammar = [&] { + llama_sampler *result = llama_sampler_init_grammar(vocab, grammar, "root"); + assert(result != nullptr); + return result; + }; + { + comparison paths(1, LLAMA_TOKEN_NULL, 42, create_grammar(), + create_grammar()); + auto invalid = grammar_candidates(token_for(vocab, "{"), eog, true); + for (size_t i = 1; i < invalid.size(); ++i) { + invalid[i].logit = masked; + } + assert(paths.check(invalid, {1, 8}) == LLAMA_TOKEN_NULL); + + const std::vector json = { + "{", "\"", "a", "\"", ":", "\"", "\\", "u", "2", + "0", "a", "c", "\xE2", "\x82", "\xAC", "\"", "}", + }; + const auto first = token_for(vocab, json.front()); + const auto append = [&](size_t index, bool reject_eog) { + const auto next = token_for(vocab, json[index]); + auto input = grammar_candidates(next, eog, reject_eog); + assert(paths.check(input, reject_eog ? std::vector{1, 8} + : std::vector{1}) == next); + }; + for (size_t i = 0; i <= 12; ++i) { + append(i, i == 0); + } + trace fork; + paths.fast.clone_record = ⋔ + llama_sampler *optimized = + llama_sampler_chain_get(paths.optimized.get(), 0); + sampler_ptr cloned(llama_sampler_clone(optimized), llama_sampler_free); + assert(cloned != nullptr); + auto fork_chain = chain(cloned.release(), fork, 1, 42); + const auto continuation = token_for(vocab, json[13]); + assert(sample(fork_chain.get(), grammar_candidates(continuation, eog, true)) + .token == continuation); + llama_sampler_reset(fork_chain.get()); + assert( + sample(fork_chain.get(), grammar_candidates(first, eog, true)).token == + first); + assert((fork.accepted == std::vector{continuation, first})); + for (size_t i = 13; i < json.size(); ++i) { + append(i, i == 13); + } + auto eog_first = grammar_candidates(first, eog, true); + assert(paths.check(eog_first, {1}) == eog); + assert(std::count(paths.fast.accepted.begin(), paths.fast.accepted.end(), + eog) == 1); + } + llama_dart_exit_free(model); +} + +} // namespace + +int main(int argc, char **argv) { + assert(argc == 2); + test_greedy(); + test_stochastic(); + test_fallbacks(); + test_ownership(); + test_real_grammar(argv[1]); +} diff --git a/tests/test_validate_exports.py b/tests/test_validate_exports.py index 27497930..ec0a1d26 100644 --- a/tests/test_validate_exports.py +++ b/tests/test_validate_exports.py @@ -56,8 +56,8 @@ def test_speculative_retirement_inventory_retains_nextn_query(self): self.assertEqual(len(retiring), 15) required = set(validate_exports.DEFAULT_REQUIRED_SYMBOLS) self.assertFalse(required & retiring) - self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 119) - self.assertEqual(len(required), 119) + self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 120) + self.assertEqual(len(required), 120) self.assertIn('llama_dart_speculative_need_embd_nextn', required) self.assertEqual(len(validate_exports.RETIRED_SPECULATIVE_SYMBOLS), 15) self.assertEqual(set(validate_exports.RETIRED_SPECULATIVE_SYMBOLS), retiring) @@ -88,7 +88,15 @@ def test_full_surviving_export_inventory_is_accepted(self): result, diagnostics = self.validate_synthetic_exports( validate_exports.DEFAULT_REQUIRED_SYMBOLS) self.assertEqual(result, 0, diagnostics) - self.assertIn('Validated 119 required export(s)', diagnostics) + self.assertIn('Validated 120 required export(s)', diagnostics) + + def test_missing_grammar_top_k_constructor_fails_with_other_required_exports(self): + constructor = 'llama_dart_sampler_init_grammar_top_k' + result, diagnostics = self.validate_synthetic_exports( + symbol for symbol in validate_exports.DEFAULT_REQUIRED_SYMBOLS + if symbol != constructor) + self.assertEqual(result, 1, diagnostics) + self.assertIn(f' - {constructor}\n', diagnostics) def test_retired_embedding_query_fails_with_all_required_exports(self): result, diagnostics = self.validate_synthetic_exports([ diff --git a/tools/validate_exports.py b/tools/validate_exports.py index 4a0b1769..507cec3c 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -55,6 +55,7 @@ "llama_dart_sampler_sample", "llama_dart_sampler_accept", "llama_dart_sampler_init_grammar_lazy_patterns", + "llama_dart_sampler_init_grammar_top_k", "llama_dart_sampler_init_dry", "llama_dart_sampler_init_reasoning_budget", "llama_dart_sampler_init_reasoning_budget_multi", From 025cfacfe142b523f9b1fb0219a0a88c7e24593f Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sun, 29 Nov 2026 17:45:30 -0500 Subject: [PATCH 2/2] Use distinct names for checked sampling helpers --- src/llama_dart_wrapper.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index dbb7518b..31930dac 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -2349,8 +2349,8 @@ LLAMADART_API void llama_dart_synchronize(struct llama_context *ctx) { // can still select one, and a grammar sampler that accepts an end-of-generation // token it has not finished with ends the process in GGML_ABORT, which no // exception barrier catches. Throws, so the barrier records the failure. -static llama_token llama_dart_sample_checked(struct llama_sampler *smpl, - llama_token_data_array &array) { +static llama_token llama_dart_sample_candidates_checked( + struct llama_sampler *smpl, llama_token_data_array &array) { llama_sampler_apply(smpl, &array); if (array.selected < 0 || @@ -2412,7 +2412,7 @@ static llama_token llama_dart_sample_checked(struct llama_sampler *smpl, /* .selected = */ -1, /* .sorted = */ false, }; - return llama_dart_sample_checked(smpl, array); + return llama_dart_sample_candidates_checked(smpl, array); } #if defined(LLAMADART_TESTING) @@ -2420,7 +2420,7 @@ extern "C" llama_token llama_dart_test_sample_candidates( struct llama_sampler *sampler, struct llama_token_data_array *candidates) { return llama_dart_barrier(LLAMA_TOKEN_NULL, [=] { llama_dart_exit_call call; - return llama_dart_sample_checked(sampler, *candidates); + return llama_dart_sample_candidates_checked(sampler, *candidates); }); } #endif