Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions docs/sampler_selection_guard.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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.
6 changes: 4 additions & 2 deletions src/llama_dart_wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
79 changes: 64 additions & 15 deletions tests/grammar_top_k_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,40 +109,41 @@ 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 {
llama_token token;
std::string error;
};

sample_result sample(llama_sampler *chain, candidates input,
template <size_t N>
sample_result sample(llama_sampler *chain,
std::array<llama_token_data, N> 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);
Expand All @@ -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)) {}

Expand Down Expand Up @@ -210,6 +213,51 @@ void test_greedy() {
assert((rejected.fast.accepted == std::vector<llama_token>{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<llama_token_data, chain_k + 1> input{};
for (size_t i = 0; i < input.size(); ++i) {
input[i] = {static_cast<llama_token>(i), -static_cast<float>(i), 0.0f};
}
const auto check = [&](const std::vector<size_t> &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<size_t>{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<llama_token>{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});
Expand Down Expand Up @@ -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();
Expand Down