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
4 changes: 3 additions & 1 deletion .github/workflows/validate_wrapper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
17 changes: 17 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down Expand Up @@ -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)
Expand Down
25 changes: 25 additions & 0 deletions docs/sampler_selection_guard.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,35 @@ 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
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.
11 changes: 11 additions & 0 deletions src/llama_dart_grammar_top_k_test_hooks.h
Original file line number Diff line number Diff line change
@@ -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
183 changes: 171 additions & 12 deletions src/llama_dart_wrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -36,6 +37,7 @@
#include "speculative.h"

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
Expand Down Expand Up @@ -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_candidates_checked(
struct llama_sampler *smpl, llama_token_data_array &array) {
llama_sampler_apply(smpl, &array);

if (array.selected < 0 ||
array.selected >= static_cast<int64_t>(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) {
Expand Down Expand Up @@ -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_candidates_checked(smpl, array);
}

if (array.selected < 0 ||
array.selected >= static_cast<int64_t>(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>(LLAMA_TOKEN_NULL, [=] {
llama_dart_exit_call call;
return llama_dart_sample_candidates_checked(sampler, *candidates);
});
}
#endif

LLAMADART_API llama_token llama_dart_sampler_sample(struct llama_sampler *smpl,
struct llama_context *ctx,
Expand Down Expand Up @@ -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<llama_token_data, llama_dart_grammar_top_k_max + 1> 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<float>::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<llama_dart_grammar_top_k *>(sampler->ctx);
llama_sampler_accept(context->grammar, token);
};
callbacks.apply = [](llama_sampler *sampler,
llama_token_data_array *candidates) {
const auto &context = *static_cast<llama_dart_grammar_top_k *>(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<llama_dart_grammar_top_k *>(sampler->ctx);
llama_sampler_reset(context->grammar);
};
callbacks.clone = [](const llama_sampler *sampler) -> llama_sampler * {
const auto &context =
*static_cast<const llama_dart_grammar_top_k *>(sampler->ctx);
std::unique_ptr<llama_sampler, decltype(&llama_sampler_free)> 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<llama_dart_grammar_top_k *>(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>(
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<llama_sampler *>(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<size_t>(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,
Expand Down
10 changes: 10 additions & 0 deletions src/llama_dart_wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 14 additions & 3 deletions tests/exit_teardown_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -21,6 +22,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <limits>
#include <memory>
#include <mutex>
Expand Down Expand Up @@ -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<vocabulary_piece_override> 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;
Expand Down Expand Up @@ -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<const char *> texts;
for (const std::string &piece : pieces) {
texts.push_back(piece.c_str());
Expand Down Expand Up @@ -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);
}
Expand Down
Loading
Loading