diff --git a/docs/sampler_selection_guard.md b/docs/sampler_selection_guard.md index 2e7745d..939d014 100644 --- a/docs/sampler_selection_guard.md +++ b/docs/sampler_selection_guard.md @@ -56,8 +56,9 @@ contains this guard. `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 +sampler in a CPU chain immediately before ordinary top-k. The wrapper's +`top_k` must be in `[1, 64]` and match the chain's top-k except in the +greedy case below. 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 @@ -69,6 +70,17 @@ 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. +A greedy request may pass `top_k = 1` to the wrapper ahead of a longer +chain top-k when the remaining stages preserve and select the highest +logit, for example with optional top-p, temperature at or below zero and +a greedy selector. Top-k truncation retains a unique maximum. If the +grammar accepts that finite candidate, masking lower logits cannot change +the winner. If the grammar rejects it or the highest logits tie, the +wrapper runs the full mask. Keep the chain's configured top-k so the +same upstream ordering breaks ties. Top-k's sort can order equal logits +differently at different values of k, and greedy takes the first maximum +in the resulting order. + 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. @@ -82,5 +94,7 @@ 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. +and seeded samples with a separate grammar-first chain. It also compares +greedy selection with a one-candidate probe ahead of top-k 64, including a +tie that takes the full mask. A generated vocabulary variant covers JSON +escapes, split UTF-8 and EOG through the real grammar. diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 2ff3f48..210da0e 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -869,8 +869,10 @@ LLAMADART_API struct llama_sampler * llama_dart_sampler_init_grammar_lazy_patter 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 +// the CPU sampler chain. top_k must be in [1, 64] and match the following +// sampler. A greedy chain that preserves and selects the highest logit may +// pass 1 here and keep its configured top-k for tie ordering. +// 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. diff --git a/tests/grammar_top_k_test.cpp b/tests/grammar_top_k_test.cpp index 708369c..4e5508a 100644 --- a/tests/grammar_top_k_test.cpp +++ b/tests/grammar_top_k_test.cpp @@ -109,32 +109,31 @@ llama_sampler *recording_shortlist(trace &record) { } sampler_ptr chain(llama_sampler *grammar, trace &record, int32_t k, - uint32_t seed) { + uint32_t seed, float temperature = 0.8f) { 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 { + if (k != 1) { 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)); + llama_sampler_chain_add(result.get(), llama_sampler_init_temp(temperature)); } + auto *selector = k == 1 || temperature <= 0.0f + ? llama_sampler_init_greedy() + : llama_sampler_init_dist(seed); + llama_sampler_chain_add(result.get(), selector); 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 *wrap_grammar(llama_sampler *grammar, int32_t k) { + sampler_ptr owned_grammar(grammar, llama_sampler_free); llama_sampler *optimized = - llama_dart_sampler_init_grammar_top_k(grammar.get(), k); + llama_dart_sampler_init_grammar_top_k(owned_grammar.get(), k); assert(optimized != nullptr); - grammar.release(); - return chain(optimized, record, k, seed); + owned_grammar.release(); + return optimized; } struct sample_result { @@ -142,7 +141,9 @@ struct sample_result { std::string error; }; -sample_result sample(llama_sampler *chain, candidates input, +template +sample_result sample(llama_sampler *chain, + std::array 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); @@ -167,7 +168,9 @@ struct comparison { 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)), + : optimized( + chain(wrap_grammar(recording_grammar(fast, denied, real_fast), k), + fast, k, seed)), oracle( chain(recording_grammar(full, denied, real_full), full, k, seed)) {} @@ -210,6 +213,51 @@ void test_greedy() { assert((rejected.fast.accepted == std::vector{2})); } +void test_greedy_with_longer_top_k() { + constexpr int32_t chain_k = 64; + constexpr llama_token denied = 1; + trace fast; + trace full; + auto optimized = chain(wrap_grammar(recording_grammar(fast, denied), 1), fast, + chain_k, 42, 0.0f); + auto oracle = chain(recording_grammar(full, denied), full, chain_k, 42, 0.0f); + + std::array input{}; + for (size_t i = 0; i < input.size(); ++i) { + input[i] = {static_cast(i), -static_cast(i), 0.0f}; + } + const auto check = [&](const std::vector &probe_sizes) { + fast.apply_sizes.clear(); + full.apply_sizes.clear(); + const auto actual = sample(optimized.get(), input); + const auto expected = sample(oracle.get(), input); + assert(fast.apply_sizes == probe_sizes); + assert((full.apply_sizes == std::vector{input.size()})); + assert(fast.shortlists.back().size() == chain_k); + assert(full.shortlists.back().size() == chain_k); + assert(actual.error.empty() && expected.error.empty()); + assert(actual.token == expected.token); + assert(fast.accepted == full.accepted); + return actual.token; + }; + + input[3].logit = 4.0f; + input[denied].logit = 3.0f; + assert(check({1}) == 3); + assert(fast.shortlists.back()[1].first == denied); + assert(full.shortlists.back()[1].first != denied); + + std::swap(input[3].logit, input[denied].logit); + assert(check({1, input.size()}) == 3); + + input[denied].logit = 2.0f; + input[5].logit = input[3].logit; + const auto tied = check({input.size()}); + assert(tied == 3 || tied == 5); + assert(tied == full.shortlists.back().front().first); + assert((fast.accepted == std::vector{3, 3, tied})); +} + void test_stochastic() { const auto weights = ranked( {std::log(2.0f), std::log(3.0f), std::log(4.0f), -1, -2, -3, -4, masked}); @@ -397,6 +445,7 @@ void test_real_grammar(const char *path) { int main(int argc, char **argv) { assert(argc == 2); test_greedy(); + test_greedy_with_longer_top_k(); test_stochastic(); test_fallbacks(); test_ownership();