diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index aa57eb4..ef0a4e0 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -522,7 +522,7 @@ jobs: cmake --build build/wrapper-contract --target llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_file_sha256_test llamadart_model_fd_test llamadart_threadpool_test - llamadart_grammar_top_k_test + llamadart_grammar_top_k_test llamadart_grammar_top_k_p_test llamadart_f16_dot_accumulation_test llamadart_speculative_api_test llamadart_build_identity_test llamadart_upstream_abi_test @@ -656,6 +656,7 @@ jobs: run: >- cmake --build --preset windows-x64-full --target llamadart_barrier_test + llamadart_grammar_top_k_p_test llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_file_sha256_test llamadart_model_fd_test llamadart_build_identity_test llamadart_upstream_abi_test @@ -676,7 +677,7 @@ jobs: $wrapperDir = (Resolve-Path build/wx64).Path $upstreamDir = (Resolve-Path build/wx64/bin).Path $env:PATH = "$wrapperDir;$upstreamDir;$env:PATH" - ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|file_sha256|model_fd|barrier|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure + ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|file_sha256|model_fd|barrier|grammar_top_k_p|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure - name: Validate wrapper exports shell: pwsh run: | @@ -735,7 +736,7 @@ jobs: run: >- cmake --build ${{ matrix.build_dir }} --target llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_file_sha256_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_grammar_top_k_test llamadart_grammar_top_k_p_test llamadart_build_identity_test llamadart_cancel_flag_test llamadart_f16_dot_accumulation_test llamadart_upstream_abi_test llamadart_mtmd_compat_test diff --git a/CMakeLists.txt b/CMakeLists.txt index dc2df5b..494db48 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -713,6 +713,11 @@ if (LLAMADART_BUILD_TESTS) 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) + add_executable(llamadart_grammar_top_k_p_test tests/grammar_top_k_p_test.cpp) + target_compile_features(llamadart_grammar_top_k_p_test PRIVATE cxx_std_17) + target_compile_definitions(llamadart_grammar_top_k_p_test PRIVATE LLAMADART_TESTING=1) + target_include_directories(llamadart_grammar_top_k_p_test PRIVATE src) + target_link_libraries(llamadart_grammar_top_k_p_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}") @@ -722,6 +727,10 @@ if (LLAMADART_BUILD_TESTS) 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) + add_test(NAME llamadart_grammar_top_k_p_test + COMMAND llamadart_grammar_top_k_p_test "${grammar_top_k_model}") + set_tests_properties(llamadart_grammar_top_k_p_test + PROPERTIES FIXTURES_REQUIRED llamadart_grammar_top_k_model TIMEOUT 60) if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME llamadart_owner_model_test @@ -1003,7 +1012,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_file_sha256_test + llamadart_grammar_top_k_test llamadart_grammar_top_k_p_test llamadart_file_sha256_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 939d014..74e4286 100644 --- a/docs/sampler_selection_guard.md +++ b/docs/sampler_selection_guard.md @@ -81,9 +81,43 @@ 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. +Bindings can check for the optional export and keep the ordinary grammar path +on older runtimes. + +## Progressive strict grammar before top-k, top-p and min-p + +`llama_dart_sampler_init_grammar_top_k_p(grammar, top_k, top_p, min_p, +min_keep)` uses the same ownership, vocabulary lifetime and teardown rules. +Pass the chain's next filter parameters, with `0` for disabled top-k and +min-p, `1` for disabled top-p, and a positive `min_keep`. Pass `1` and `0` +for top-p and min-p if another filter, such as typical sampling, runs +before those filters. A greedy chain that preserves and selects the highest +logit can use `(1, 1, 0, 1)`. + +The wrapper checks a unique raw maximum in the greedy case. It then probes +up to 256 and 1,024 high-logit tokens with the strict grammar's read-only +apply. The second probe reuses the first 256 grammar decisions. When the +ordered legal top-k is fixed, it forwards that exact prefix. Otherwise it +can compact a prefix when both bounds on the rounded top-p cumulative sum +give the same cutoff, or when the actual float min-p threshold excludes +the tail and at least `min_keep` legal tokens clear it. The ordinary +samplers still run, and selection and acceptance stay in the guarded +sampling call. A chain that consumes intermediate top-p probabilities +directly needs the full scan because the compact softmax can produce +different probabilities before the next sampler recomputes them. + +The top-p bound accounts for float softmax accumulation in both input +orders, omitted tokens tied at the probe cutoff, and rounding of each +normalized prefix weight. For an already sorted array, certification +requires the ordered top-k prefix the upstream sampler would retain. +With top-k disabled, min-p alone keeps the full scan because the unsorted +min-p path preserves original token order. K above 128, top-p logits +outside the bucket sort range, adverse rounding modes, insufficient +legal candidates and ambiguous cutoffs also keep the full scan. An +ambiguous top-p cutoff takes the full scan even with min-p enabled. + +The legacy constructor and its behavior are unchanged. The native export +gate now requires 123 symbols, including both constructors. ## Validation @@ -98,3 +132,11 @@ 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. + +`llamadart_grammar_top_k_p_test` checks both probe stages, fallback +boundaries, ordered shortlist and seeded selection against full-mask +chains. It covers analytical chi-squared checks, randomized candidate +arrays, real-grammar escapes, UTF-8 and EOG, and constructor ownership +through clone, reset, allocation failure and free. The exit teardown +`blocked` scenario checks that the constructor cannot take ownership +after teardown. diff --git a/src/llama_dart_grammar_top_k_test_hooks.h b/src/llama_dart_grammar_top_k_test_hooks.h index 2810be4..854023e 100644 --- a/src/llama_dart_grammar_top_k_test_hooks.h +++ b/src/llama_dart_grammar_top_k_test_hooks.h @@ -8,4 +8,6 @@ extern "C" LLAMADART_API llama_token llama_dart_test_sample_candidates( extern "C" LLAMADART_API void llama_dart_test_set_grammar_top_k_init_hook(void (*hook)()); +extern "C" LLAMADART_API void +llama_dart_test_set_grammar_top_k_p_init_hook(void (*hook)()); #endif diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index 31930da..4e37e44 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -2599,6 +2600,343 @@ LLAMADART_API struct llama_sampler *llama_dart_sampler_init_grammar_top_k( }); } +static constexpr size_t grammar_probe_first = 256; +static constexpr size_t grammar_probe_second = 1024; + +struct llama_dart_grammar_top_k_p { + llama_sampler *grammar; + size_t k; + float top_p; + float min_p; + size_t min_keep; + std::array ranked; + std::array probed; + std::array valid; +}; + +static bool grammar_higher_rank(const llama_token_data *a, + const llama_token_data *b) { + // Both stages must choose identical tokens within a tied first prefix. + return a->logit == b->logit ? a < b : a->logit > b->logit; +} + +static void grammar_rank_prefix(llama_dart_grammar_top_k_p &context, + const llama_token_data_array &candidates, + size_t count) { + auto *const begin = context.ranked.data(); + auto *const end = begin + count; + for (size_t i = 0; i < count; ++i) { + begin[i] = candidates.data + i; + } + if (candidates.sorted) { + return; + } + std::make_heap(begin, end, grammar_higher_rank); + for (size_t i = count; i < candidates.size; ++i) { + const auto *candidate = candidates.data + i; + if (candidate->logit > begin[0]->logit) { + std::pop_heap(begin, end, grammar_higher_rank); + end[-1] = candidate; + std::push_heap(begin, end, grammar_higher_rank); + } + } + std::sort_heap(begin, end, grammar_higher_rank); +} + +static bool grammar_unique_prefix(const llama_token_data *valid, size_t count, + size_t kept) { + for (size_t i = 1; i < kept; ++i) { + if (valid[i - 1].logit <= valid[i].logit) { + return false; + } + } + return kept == count || valid[kept - 1].logit > valid[kept].logit; +} + +static void grammar_use_prefix(llama_token_data_array &candidates, + const llama_token_data *data, size_t count) { + std::copy_n(data, count, candidates.data); + candidates.size = count; + candidates.sorted = true; +} + +static bool grammar_certify_top_k(const llama_dart_grammar_top_k_p &context, + const llama_token_data_array &candidates, + size_t count, float cutoff) { + const size_t k = context.k; + if (k == 0 || count < k || context.valid[k - 1].logit <= cutoff || + !grammar_unique_prefix(context.valid.data(), count, k)) { + return false; + } + // A preceding sampler can mark the array sorted. Grammar leaves that flag + // set, even when it masks a token above the cutoff. + return !candidates.sorted || + std::equal(context.valid.begin(), context.valid.begin() + k, + candidates.data, [](const auto &a, const auto &b) { + return a.id == b.id && a.logit == b.logit; + }); +} + +static bool grammar_certify_top_p(const llama_dart_grammar_top_k_p &context, + size_t count, size_t tail, float cutoff) { + const auto *valid = context.valid.data(); + const float max_logit = valid[0].logit; + std::array weights; + double head_sum = 0.0; + for (size_t i = 0; i < count; ++i) { + weights[i] = expf(valid[i].logit - max_logit); + head_sum += weights[i]; + } + + // Bound the sum for both candidate orders, including the unsorted K=0 + // path. Each float addition has relative error <= epsilon/2. For the + // admitted lengths, n*epsilon bounds the total error in either direction, + // with room for the double sum and conversion of the endpoints to float. + static_assert(std::numeric_limits::is_iec559); + constexpr double epsilon = std::numeric_limits::epsilon(); + const double addition_error = (count + tail + 2) * epsilon; + if (addition_error >= 0.125 || std::fegetround() != FE_TONEAREST) { + return false; + } + // The rounded logit subtraction is monotone. Allow a factor of two and a + // subnormal unit for libm expf rounding, including at underflow. + const float tail_delta = cutoff - max_logit; + const double tail_weight = + std::isinf(tail_delta) + ? 0.0 + : std::min(1.0, 2.0 * expf(tail_delta) + + std::numeric_limits::denorm_min()); + const float lower = static_cast(head_sum * (1.0 - addition_error)); + const float upper = static_cast((head_sum + tail * tail_weight) * + (1.0 + addition_error)); + + float cumulative_lower = 0.0f; + float cumulative_upper = 0.0f; + for (size_t i = 0; i < count; ++i) { + const float preceding_upper = cumulative_upper; + cumulative_lower += weights[i] / upper; + cumulative_upper += weights[i] / lower; + const size_t kept = i + 1; + if (kept >= context.min_keep && cumulative_lower >= context.top_p) { + return (kept == context.min_keep || preceding_upper < context.top_p) && + grammar_unique_prefix(valid, count, kept); + } + } + return false; +} + +static bool grammar_certify_min_p(const llama_dart_grammar_top_k_p &context, + size_t count, float cutoff) { + // Without top-k, unsorted min-p preserves the original token order. + if (context.k == 0 || context.min_p == 0.0f) { + return false; + } + const float threshold = context.valid[0].logit + logf(context.min_p); + if (cutoff >= threshold) { + return false; + } + size_t kept = 0; + while (kept < count && context.valid[kept].logit >= threshold) { + ++kept; + } + return kept >= context.min_keep && + grammar_unique_prefix(context.valid.data(), count, kept); +} + +static bool grammar_probe_prefix(llama_dart_grammar_top_k_p &context, + llama_token_data_array &candidates, + size_t start, size_t end) { + grammar_rank_prefix(context, candidates, end + 1); + for (size_t i = start; i < end; ++i) { + context.probed[i] = *context.ranked[i]; + } + llama_token_data_array probe{context.probed.data() + start, end - start, -1, + true}; + llama_sampler_apply(context.grammar, &probe); + + size_t count = 0; + for (size_t i = 0; i < end; ++i) { + if (std::isfinite(context.probed[i].logit)) { + context.valid[count++] = context.probed[i]; + } + } + const float cutoff = context.ranked[end]->logit; + if (grammar_certify_top_k(context, candidates, count, cutoff)) { + grammar_use_prefix(candidates, context.valid.data(), context.k); + return true; + } + + if (candidates.sorted || (context.k != 0 && count >= context.k)) { + return false; + } + size_t tail = candidates.size - end; + // Tied probed tokens cannot be placed ahead of their unseen peers. Count + // their weight in the unknown tail even though grammar already ran on them. + while (count != 0 && context.valid[count - 1].logit <= cutoff) { + --count; + ++tail; + } + if (count < context.min_keep) { + return false; + } + if (context.k != 0) { + tail = std::min(tail, context.k - count); + } + const bool certified = + context.top_p < 1.0f ? grammar_certify_top_p(context, count, tail, cutoff) + : grammar_certify_min_p(context, count, cutoff); + if (certified) { + grammar_use_prefix(candidates, context.valid.data(), count); + } + return certified; +} + +static bool grammar_progressive_probe(llama_dart_grammar_top_k_p &context, + llama_token_data_array &candidates) { + // Above 128, upstream top-k changes to its bucket sort. Keep the full + // grammar path for those K values. + if (candidates.size <= 1 || + candidates.size > + static_cast(std::numeric_limits::max()) || + candidates.selected != -1 || context.k > 128 || + (context.k == 0 && context.top_p >= 1.0f)) { + return false; + } + const auto infinity = std::numeric_limits::infinity(); + // Top-p without top-k can bucket logits using int(6.4*x + 64). + constexpr float max_bucket_logit = + static_cast(std::numeric_limits::max()) / 8.0f; + const bool single = context.k == 1 && context.top_p >= 1.0f && + context.min_p == 0.0f && context.min_keep == 1; + const llama_token_data *best = candidates.data; + float second = -infinity; + for (size_t i = 0; i < candidates.size; ++i) { + const auto *candidate = candidates.data + i; + if (!(candidate->logit < infinity) || + (context.k == 0 && candidate->logit > max_bucket_logit) || + (candidates.sorted && i != 0 && + candidate[-1].logit < candidate->logit)) { + return false; + } + if (single && i != 0) { + if (candidate->logit > best->logit) { + second = best->logit; + best = candidate; + } else { + second = std::max(second, candidate->logit); + } + } + } + if (single && best->logit > second) { + llama_token_data token = *best; + llama_token_data_array probe{&token, 1, -1, true}; + llama_sampler_apply(context.grammar, &probe); + if (std::isfinite(token.logit)) { + grammar_use_prefix(candidates, &token, 1); + return true; + } + } + if (candidates.size <= grammar_probe_first) { + return false; + } + return grammar_probe_prefix(context, candidates, 0, grammar_probe_first) || + (candidates.size > grammar_probe_second && + grammar_probe_prefix(context, candidates, grammar_probe_first, + grammar_probe_second)); +} + +static llama_sampler *llama_dart_grammar_top_k_p_wrap(llama_sampler *grammar, + size_t k, float top_p, + float min_p, + size_t min_keep); + +static llama_sampler_i llama_dart_grammar_top_k_p_interface = [] { + llama_sampler_i callbacks{}; + callbacks.name = [](const llama_sampler *) { + return "llamadart-grammar-top-k-p"; + }; + 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 *data) { + auto &context = *static_cast(sampler->ctx); + if (!grammar_progressive_probe(context, *data)) { + llama_sampler_apply(context.grammar, data); + } + }; + 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_p_wrap(grammar.get(), context.k, context.top_p, + context.min_p, context.min_keep); + 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_p_init_hook)() = nullptr; + +extern "C" void llama_dart_test_set_grammar_top_k_p_init_hook(void (*hook)()) { + g_test_grammar_top_k_p_init_hook = hook; +} +#endif + +static llama_sampler *llama_dart_grammar_top_k_p_wrap(llama_sampler *grammar, + size_t k, float top_p, + float min_p, + size_t min_keep) { + auto context = + std::make_unique(llama_dart_grammar_top_k_p{ + grammar, k, top_p, min_p, min_keep, {}, {}, {}}); +#if defined(LLAMADART_TESTING) + if (g_test_grammar_top_k_p_init_hook != nullptr) { + g_test_grammar_top_k_p_init_hook(); + } +#endif + auto *result = + llama_sampler_init(&llama_dart_grammar_top_k_p_interface, context.get()); + if (result != nullptr) { + context.release(); + } + return result; +} + +LLAMADART_API struct llama_sampler * +llama_dart_sampler_init_grammar_top_k_p(struct llama_sampler *grammar, + int32_t top_k, float top_p, float min_p, + size_t min_keep) { + return llama_dart_barrier(nullptr, [=] { + llama_dart_exit_call call; + if (grammar == nullptr || top_k < 0 || !(top_p > 0.0f && top_p <= 1.0f) || + !(min_p >= 0.0f && min_p <= 1.0f) || min_keep == 0) { + throw std::invalid_argument( + "Strict grammar and valid top-k, top-p, min-p and min-keep required"); + } + return llama_dart_grammar_top_k_p_wrap(grammar, static_cast(top_k), + top_p, min_p, min_keep); + }); +} + 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 210da0e..b14969a 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -880,6 +880,15 @@ LLAMADART_API struct llama_sampler * llama_dart_sampler_init_grammar_top_k( struct llama_sampler * grammar, int32_t top_k); +// Wraps a strict grammar immediately before the matching CPU top-k, top-p, +// and min-p filters. Use 0 to disable top-k and min-p, and 1 to disable +// top-p. If another filter follows top-k, pass 1 and 0 for top-p and min-p +// to allow only top-k certification. The greedy exception for top_k = 1 +// and the ownership, vocabulary lifetime and teardown rules above apply. +LLAMADART_API struct llama_sampler * llama_dart_sampler_init_grammar_top_k_p( + struct llama_sampler * grammar, int32_t top_k, float top_p, float min_p, + size_t min_keep); + // 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 9256bbc..569c7d3 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -423,6 +423,11 @@ int test_blocked() { llama_dart_exit_track(object, free_named, LLAMA_DART_EXIT_STAGE_MODEL)); llama_dart_speculative *ngram = make_test_ngram(4, 8); assert(ngram != nullptr); + static std::atomic grammar_frees{0}; + static llama_sampler_i grammar_iface{}; + grammar_iface.free = [](llama_sampler *) { grammar_frees.fetch_add(1); }; + auto *grammar = llama_sampler_init(&grammar_iface, nullptr); + assert(grammar != nullptr); llama_dart_exit_teardown(); assert(recorded() == std::vector({"object"})); @@ -480,6 +485,12 @@ int test_blocked() { late([](void *) { llama_dart_process(nullptr, 0, nullptr); }, nullptr); late([](void *) { llama_dart_synchronize(nullptr); }, nullptr); late([](void *) { llama_dart_sampler_sample(nullptr, nullptr, 0); }, nullptr); + late( + [](void *argument) { + llama_dart_sampler_init_grammar_top_k_p( + static_cast(argument), 64, 0.95f, 0.0f, 1); + }, + grammar); late( [](void *) { llama_dart_sampler_init_reasoning_budget(nullptr, "", "", @@ -553,6 +564,9 @@ int test_blocked() { } sleep_ms(300); assert(returned.load() == 0); + assert(grammar_frees.load() == 0); + llama_sampler_free(grammar); + assert(grammar_frees.load() == 1); assert(recorded() == std::vector({"object"})); return 0; } @@ -812,8 +826,8 @@ const llama_token kNewlineToken = 6; 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; + std::initializer_list extra_pieces = {}, + uint32_t vocab_size = 256) { const uint32_t context_length = 512; const uint32_t embedding_length = shared_mtp && mtp_head ? 64 : 128; const uint32_t feed_forward_length = 256; @@ -4164,7 +4178,7 @@ int main(int argc, char **argv) { } if (scenario == "make-grammar-top-k-model") { return make_model(first, false, true, false, false, - grammar_top_k_pieces); + grammar_top_k_pieces, 512); } if (scenario == "make-shared-mtp-target") { return make_model(first, false, true, false, true); diff --git a/tests/grammar_top_k_p_test.cpp b/tests/grammar_top_k_p_test.cpp new file mode 100644 index 0000000..1637ca5 --- /dev/null +++ b/tests/grammar_top_k_p_test.cpp @@ -0,0 +1,701 @@ +#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 +#include +#include + +namespace { + +using sampler_ptr = + std::unique_ptr; +using candidates = std::vector; +using shortlist = std::vector>; + +constexpr size_t wide = 2048; +constexpr float masked = -std::numeric_limits::infinity(); +constexpr float nan = std::numeric_limits::quiet_NaN(); + +struct settings { + int32_t k = 64; + float p = 0.95f; + float min_p = 0.0f; + size_t keep = 1; + bool greedy = false; + bool typical = false; + bool xtc = false; + bool dynamic_temp = false; +}; + +struct trace { + std::vector sizes; + std::vector accepted; + int frees = 0; + int clones = 0; + int resets = 0; +}; + +struct grammar_state { + trace &record; + const std::vector *allowed; + sampler_ptr real; +}; + +llama_sampler *recording_grammar(trace &record, + const std::vector &allowed, + llama_sampler *real = 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.sizes.push_back(array->size); + if (state.real) { + llama_sampler_apply(state.real.get(), array); + return; + } + for (size_t i = 0; i < array->size; ++i) { + if (!(*state.allowed)[array->data[i].id]) { + 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); + if (state.real) { + llama_sampler_accept(state.real.get(), token); + } else { + assert((*state.allowed)[token]); + } + }; + callbacks.reset = [](llama_sampler *sampler) { + auto &state = *static_cast(sampler->ctx); + ++state.record.resets; + if (state.real) { + llama_sampler_reset(state.real.get()); + } + }; + callbacks.clone = [](const llama_sampler *sampler) { + const auto &state = *static_cast(sampler->ctx); + ++state.record.clones; + return recording_grammar( + state.record, *state.allowed, + state.real ? llama_sampler_clone(state.real.get()) : nullptr); + }; + 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, &allowed, {real, llama_sampler_free}}); +} + +llama_sampler *wrap(llama_sampler *grammar, const settings &options) { + sampler_ptr owned(grammar, llama_sampler_free); + auto *wrapped = llama_dart_sampler_init_grammar_top_k_p( + grammar, options.k, options.typical ? 1.0f : options.p, + options.typical ? 0.0f : options.min_p, options.keep); + assert(wrapped != nullptr); + owned.release(); + return wrapped; +} + +llama_sampler *capture(shortlist &output) { + static llama_sampler_i iface = [] { + llama_sampler_i callbacks{}; + callbacks.name = [](const llama_sampler *) { return "capture-shortlist"; }; + callbacks.apply = [](llama_sampler *sampler, + llama_token_data_array *array) { + auto &out = *static_cast(sampler->ctx); + out.clear(); + for (size_t i = 0; i < array->size; ++i) { + out.emplace_back(array->data[i].id, array->data[i].logit); + } + }; + callbacks.clone = [](const llama_sampler *sampler) { + return capture(*static_cast(sampler->ctx)); + }; + return callbacks; + }(); + return llama_sampler_init(&iface, &output); +} + +sampler_ptr make_chain(llama_sampler *grammar, const settings &options, + uint32_t seed, shortlist &output) { + sampler_ptr chain( + llama_sampler_chain_init(llama_sampler_chain_default_params()), + llama_sampler_free); + llama_sampler_chain_add(chain.get(), grammar); + if (options.k > 0) { + llama_sampler_chain_add(chain.get(), llama_sampler_init_top_k(options.k)); + } + if (options.typical) { + llama_sampler_chain_add(chain.get(), llama_sampler_init_typical(0.8f, 1)); + } + if (options.p < 1.0f) { + llama_sampler_chain_add(chain.get(), + llama_sampler_init_top_p(options.p, options.keep)); + } + if (options.min_p > 0.0f) { + llama_sampler_chain_add( + chain.get(), llama_sampler_init_min_p(options.min_p, options.keep)); + } + if (options.xtc) { + llama_sampler_chain_add(chain.get(), + llama_sampler_init_xtc(1.0f, 0.02f, 1, seed)); + } + if (options.dynamic_temp) { + llama_sampler_chain_add(chain.get(), + llama_sampler_init_temp_ext(1.0f, 0.2f, 1.0f)); + } else { + llama_sampler_chain_add(chain.get(), llama_sampler_init_temp(1.0f)); + } + llama_sampler_chain_add(chain.get(), capture(output)); + llama_sampler_chain_add(chain.get(), options.greedy + ? llama_sampler_init_greedy() + : llama_sampler_init_dist(seed)); + return chain; +} + +std::pair sample(llama_sampler *chain, + candidates input, bool sorted) { + 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 ? error : ""}; +} + +struct comparison { + trace fast; + trace full; + shortlist fast_list; + shortlist full_list; + sampler_ptr optimized; + sampler_ptr oracle; + + comparison(const settings &options, const std::vector &allowed, + uint32_t seed = 42, llama_sampler *fast_grammar = nullptr, + llama_sampler *full_grammar = nullptr) + : optimized(make_chain( + wrap(recording_grammar(fast, allowed, fast_grammar), options), + options, seed, fast_list)), + oracle(make_chain(recording_grammar(full, allowed, full_grammar), + options, seed, full_list)) {} + + llama_token check(const candidates &input, + const std::vector &expected_sizes = {}, + bool sorted = false) { + fast.sizes.clear(); + full.sizes.clear(); + const auto actual = sample(optimized.get(), input, sorted); + const auto expected = sample(oracle.get(), input, sorted); + if (!expected_sizes.empty() && fast.sizes != expected_sizes) { + std::fputs("Expected grammar probe sizes:", stderr); + for (size_t size : expected_sizes) { + std::fprintf(stderr, " %zu", size); + } + std::fputs("; got:", stderr); + for (size_t size : fast.sizes) { + std::fprintf(stderr, " %zu", size); + } + std::fputc('\n', stderr); + assert(fast.sizes == expected_sizes); + } + assert((full.sizes == std::vector{input.size()})); + assert(actual == expected); + assert(fast_list == full_list); + assert(fast.accepted == full.accepted); + return actual.first; + } +}; + +candidates ranked(size_t size = wide) { + candidates input(size); + for (size_t i = 0; i < size; ++i) { + input[i] = {static_cast(i), -static_cast(i) / 32.0f, + 0.0f}; + } + return input; +} + +candidates sharp(size_t size = wide) { + auto input = ranked(size); + input[0].logit = 22.0f; + input[1].logit = 12.0f; + input[2].logit = 10.0f; + return input; +} + +void test_probe_paths() { + std::vector allowed(wide, true); + std::fill_n(allowed.begin(), 20, false); + const auto input = ranked(); + comparison({}, allowed).check(input, {256}); + comparison({64, 0.95f, 0.0f, 1, false, true}, allowed).check(input, {256}); + comparison({64, 0.95f, 0.0f, 1, false, false, true, true}, allowed) + .check(input, {256}); + + std::fill_n(allowed.begin(), 216, false); + comparison({}, allowed).check(input, {256, 768}); + + std::fill(allowed.begin(), allowed.end(), false); + allowed[0] = allowed[1] = allowed[2] = true; + const auto structure = sharp(); + comparison({}, allowed).check(structure, {256}); + comparison({0, 0.95f}, allowed).check(structure, {256}); + comparison({64, 1.0f, 0.05f}, allowed).check(structure, {256}); + + allowed[0] = false; + comparison({1, 1.0f, 0.0f, 1, true}, allowed).check(structure, {1, 256}); +} + +void test_certificate_failures() { + const std::vector fallback{256, 768, wide}; + std::vector allowed(wide, false); + auto input = ranked(); + + // The best unseen token can tie the Kth legal token at both stage cutoffs. + std::fill_n(allowed.begin(), 63, true); + allowed[250] = allowed[257] = allowed[1024] = true; + for (size_t i = 249; i <= 1024; ++i) { + input[i].logit = -8.0f; + } + comparison({64, 1.0f}, allowed).check(input, fallback); + + // Ties inside a retained prefix can alter the RNG's token-to-weight mapping. + allowed[63] = true; + input[1].logit = input[0].logit; + comparison({64, 1.0f}, allowed).check(input, fallback); + + // The compact prefix would stop at one token. The full chain stops at two. + std::fill(allowed.begin(), allowed.end(), false); + allowed[0] = allowed[1] = true; + input = ranked(); + input[0].logit = 9.0f; + input[1].logit = 5.82f; + for (size_t i = 2; i < wide; ++i) { + input[i].logit = 1.0f; + allowed[i] = i >= 1024 && i < 1070; + } + comparison boundary({64, 0.95f, 0.02f}, allowed); + boundary.check(input, fallback); + assert(boundary.full_list.size() == 2); + + // A tied cutoff can omit probed tokens as well as unchecked ones. + input = ranked(257); + allowed.assign(input.size(), true); + input[0].logit = 7.0f; + for (size_t i = 1; i < input.size(); ++i) { + input[i].logit = 0.0f; + } + comparison tied_tail({0, 0.95f}, allowed); + tied_tail.check(input, {256, 257}); + assert(tied_tail.full_list.size() > 1); + + input = sharp(); + allowed.assign(wide, false); + allowed[0] = allowed[1] = allowed[1400] = true; + comparison({64, 0.95f, 0.0f, 3}, allowed).check(input, fallback); + comparison({64, 1.0f, 0.05f, 3}, allowed).check(input, fallback); + + // Unsorted min-p preserves input order if it keeps enough tokens. + input[1].logit = 21.0f; + std::swap(input[0], input[1]); + comparison({0, 1.0f, 0.05f}, allowed).check(input, {wide}); + + // The reference adds logf(min_p) in float, rounding the threshold down. + input = ranked(); + input[0].logit = 10000000.0f; + for (size_t i = 1; i < wide; ++i) { + input[i].logit = 9999999.0f; + } + comparison({64, 1.0f, 0.5f}, allowed).check(input, fallback); + + input = sharp(); + std::swap(input[1], input[3]); + comparison({}, allowed).check(input, {wide}, true); + std::swap(input[1], input[3]); + comparison({}, allowed).check(input, fallback, true); + std::fill(allowed.begin(), allowed.end(), true); + comparison({}, allowed).check(input, {256}, true); +} + +void test_top_p_certificate_boundaries() { + // Compact top-p sums descending weights; unsorted input sums small weights + // first, so ignoring softmax rounding (addition_error = 0) drops a token. + { + candidates input(3262); + std::vector allowed(input.size(), false); + for (size_t i = 0; i < 200; ++i) { + input[i] = {static_cast(i), + -17.5f - static_cast(i) * 0.001f, 0.0f}; + allowed[i] = true; + } + input[200] = {200, -0.5f, 0.0f}; + allowed[200] = true; + input[201] = {201, 0.0f, 0.0f}; + allowed[201] = true; + for (size_t i = 202; i < input.size(); ++i) { + input[i] = {static_cast(i), -40.0f, 0.0f}; + } + const float compact_p0 = 1.0f / (1.0f + expf(-0.5f)); + comparison rounding({0, compact_p0, 0.01f, 1}, allowed); + rounding.check(input, {256, 768, input.size()}); + assert(rounding.full_list.size() == 2); + } + + // An unseen legal token within K must reserve a tail slot (K - count, not + // K - count - 1) so top-p cannot certify without accounting for it. + { + auto input = ranked(905); + std::vector allowed(input.size(), false); + const std::array head_logits{10.0f, 9.0f, 8.0f, 7.2f}; + for (size_t i = 0; i < head_logits.size(); ++i) { + input[i].logit = head_logits[i]; + allowed[i] = true; + } + for (size_t i = head_logits.size(); i < 256; ++i) { + input[i].logit = 7.15f; + } + input[256].logit = 7.10f; + allowed[256] = true; + for (size_t i = 257; i < input.size(); ++i) { + input[i].logit = 7.0f; + } + comparison tail_cap({5, 0.99f, 0.05f, 1}, allowed); + tail_cap.check(input, {256, input.size()}); + assert(tail_cap.full_list.size() == 5); + } + + // Trimming probed tokens tied at the cutoff must use <= so a tied token is + // moved to the unknown tail rather than counted toward min_keep. + { + auto input = ranked(257); + std::vector allowed(input.size(), false); + input[0].logit = 2.0f; + allowed[0] = true; + input[1].logit = 0.0f; + allowed[1] = true; + for (size_t i = 2; i < 256; ++i) { + input[i].logit = 1.0f; + } + input[256].logit = 0.0f; + allowed[256] = true; + comparison tied_cutoff({3, 0.5f, 0.0f, 2}, allowed); + tied_cutoff.check(input, {256, input.size()}); + assert(tied_cutoff.full_list.size() == 2); + } + + // The preceding cumulative upper bound must be strictly less than top_p. + { + auto input = ranked(257); + std::vector allowed(input.size(), false); + input[0].logit = 0.0f; + allowed[0] = true; + input[1].logit = -1.0f; + allowed[1] = true; + for (size_t i = 2; i < 256; ++i) { + input[i].logit = -5.0f; + } + input[256].logit = -5.0f; + allowed[256] = true; + const double head_sum = 1.0 + static_cast(expf(-1.0f)); + const double addition_error = + (2 + 1 + 2) * + static_cast(std::numeric_limits::epsilon()); + const float lower = static_cast(head_sum * (1.0 - addition_error)); + const float preceding_upper = 1.0f / lower; + comparison boundary_eq({0, preceding_upper, 0.0f, 1}, allowed); + boundary_eq.check(input, {256, input.size()}); + comparison boundary_above( + {0, std::nextafter(preceding_upper, 1.0f), 0.0f, 1}, allowed); + boundary_above.check(input, {256}); + } +} + +void test_nonfinite() { + std::vector allowed(wide, true); + auto input = ranked(); + input[1].logit = masked; + comparison({}, allowed).check(input, {256}); + input.back().logit = -masked; + assert(comparison({64, 1.0f, 0.0f, 1, true}, allowed).check(input, {wide}) == + LLAMA_TOKEN_NULL); + + input = ranked(); + input.back().logit = nan; + comparison({}, allowed).check(input, {wide}, true); + + for (auto &token : input) { + token.logit = masked; + } + comparison rejected({1, 1.0f, 0.0f, 1, true}, allowed); + assert(rejected.check(input, {256, 768, wide}) == LLAMA_TOKEN_NULL); + assert(rejected.fast.accepted.empty()); +} + +void test_distribution() { + auto input = ranked(); + input[0].logit = 2.0f; + input[1].logit = 2.0f; + input[2].logit = 1.9f; + std::vector allowed(wide, false); + allowed[1] = allowed[2] = true; + size_t first = 0; + constexpr uint32_t draws = 10000; + for (uint32_t seed = 0; seed < draws; ++seed) { + comparison paths({2, 1.0f}, allowed, seed); + const auto selected = paths.check(input, {256}); + assert(selected == 1 || selected == 2); + first += selected == 1; + } + const double probability = 1.0 / (1.0 + std::exp(-0.1)); + const double expected = draws * probability; + const double chi_squared = std::pow(first - expected, 2) / expected + + std::pow(first - expected, 2) / (draws - expected); + assert(chi_squared < 10.827566); // one degree of freedom, p > 0.001 + + std::fill(allowed.begin(), allowed.end(), true); + for (size_t i = 0; i < 60; i += 2) { + allowed[i] = false; + } + input = ranked(); + std::vector support; + std::vector weights; + double sum = 0.0; + for (const auto &candidate : input) { + if (allowed[candidate.id] && support.size() < 64) { + const double weight = std::exp(static_cast(candidate.logit)); + sum += weight; + support.push_back(candidate.id); + weights.push_back(weight); + } + } + size_t nucleus = 0; + double nucleus_mass = 0.0; + while (nucleus_mass < 0.95 * sum) { + nucleus_mass += weights[nucleus++]; + } + assert(nucleus == 52); + std::vector histogram(wide, 0); + for (uint32_t seed = 0; seed < draws; ++seed) { + comparison paths({}, allowed, seed); + const auto selected = paths.check(input, {256}); + assert(allowed[selected]); + ++histogram[selected]; + } + double statistic = 0.0; + size_t total = 0; + for (size_t i = 0; i < nucleus; ++i) { + const double expected_count = draws * weights[i] / nucleus_mass; + const size_t measured = histogram[support[i]]; + total += measured; + statistic += std::pow(measured - expected_count, 2) / expected_count; + } + assert(total == draws); + assert(statistic < 87.9679); // 51 degrees of freedom, p > 0.001 +} + +void test_randomized_reference() { + std::mt19937 random(0x2444); + size_t hits = 0; + size_t fallbacks = 0; + for (uint32_t trial = 0; trial < 3500; ++trial) { + const size_t size = + std::array{255, 257, 1025, wide}[random() % 4]; + auto input = ranked(size); + std::vector allowed(size); + const size_t allowed_prefix = 1 + random() % (trial % 2 == 0 ? 20 : size); + const float logit_step = + std::array{0.004f, 0.035f, 0.3f, 3.0f}[random() % 4]; + for (size_t i = 0; i < size; ++i) { + input[i].logit = -static_cast(i) * logit_step; + if (trial % 5 == 0) { + input[i].logit = std::floor(input[i].logit); + } + allowed[i] = i < allowed_prefix || random() % 32 == 0; + } + const bool sorted = trial % 7 == 0; + if (!sorted) { + std::shuffle(input.begin(), input.end(), random); + } else if (trial % 35 == 0) { + std::shuffle(input.begin() + 1, input.end(), random); + } + settings options{ + std::array{0, 1, 2, 64, 128, 129}[random() % 6], + std::array{0.2f, 0.5f, 0.95f, 0.95003f, 0.9999f, + 1.0f}[random() % 6], + std::array{0.0f, 0.05f, 0.5f}[random() % 3], + 1 + random() % 4, + }; + if (trial % 8 == 1) { + float two_weights = 1.0f + expf(-logit_step); + options.p = + std::nextafter(1.0f / two_weights, trial % 16 == 1 ? 1.0f : 0.0f); + } + comparison paths(options, allowed, trial); + paths.check(input, {}, sorted); + (paths.fast.sizes.back() == size ? fallbacks : hits)++; + } + assert(hits > 100 && fallbacks > 100); +} + +void test_ownership() { + trace record; + const std::vector allowed(wide, true); + sampler_ptr grammar(recording_grammar(record, allowed), llama_sampler_free); + assert(llama_dart_sampler_init_grammar_top_k_p(nullptr, 64, 0.95f, 0, 1) == + nullptr); + assert(llama_dart_last_error() != nullptr); + for (const settings invalid : { + settings{-1}, + settings{0, 0.0f}, + settings{0, 1.01f}, + settings{0, nan}, + settings{0, 0.95f, -0.05f}, + settings{0, 0.95f, 1.01f}, + settings{0, 0.95f, nan}, + settings{0, 0.95f, 0.0f, 0}, + }) { + assert(llama_dart_sampler_init_grammar_top_k_p(grammar.get(), invalid.k, + invalid.p, invalid.min_p, + invalid.keep) == nullptr); + assert(llama_dart_last_error() != nullptr); + assert(record.frees == 0); + } + llama_dart_test_set_grammar_top_k_p_init_hook([] { throw std::bad_alloc(); }); + assert(llama_dart_sampler_init_grammar_top_k_p(grammar.get(), 64, 0.95f, 0, + 1) == nullptr); + assert(llama_dart_last_error() != nullptr); + assert(record.frees == 0); + llama_dart_test_set_grammar_top_k_p_init_hook(nullptr); + sampler_ptr optimized(wrap(grammar.release(), {}), llama_sampler_free); + assert(llama_dart_last_error() == nullptr); + sampler_ptr clone(llama_sampler_clone(optimized.get()), llama_sampler_free); + assert(clone && record.clones == 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); + auto input = ranked(); + llama_token_data_array array{input.data(), input.size(), -1, false}; + llama_sampler_apply(clone.get(), &array); + assert((record.sizes == std::vector{256})); + assert(array.size == 64 && array.sorted && array.selected == -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 size = + llama_token_to_piece(vocab, id, buffer, sizeof(buffer), 0, false); + if (size > 0 && std::string(buffer, static_cast(size)) == piece) { + return id; + } + } + assert(false && "missing grammar fixture token"); + return LLAMA_TOKEN_NULL; +} + +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 make_grammar = [&] { + llama_sampler *result = llama_sampler_init_grammar(vocab, grammar, "root"); + assert(result != nullptr); + return result; + }; + const std::vector unused; + { + comparison paths({}, unused, 42, make_grammar(), make_grammar()); + const auto make_input = [&](llama_token next, bool bad_eog) { + auto input = ranked(llama_vocab_n_tokens(vocab)); + for (auto &token : input) { + token.logit = token.id == next ? 22.0f : -40.0f; + if (bad_eog && token.id == eog) { + token.logit = 24.0f; + } + } + return input; + }; + auto invalid = make_input(eog, false); + for (auto &token : invalid) { + if (token.id != eog) { + token.logit = masked; + } + } + comparison rejection({1, 1.0f, 0.0f, 1, true}, unused, 42, make_grammar(), + make_grammar()); + assert(rejection.check(invalid, {1, 256, invalid.size()}) == + LLAMA_TOKEN_NULL); + assert(rejection.fast.accepted.empty()); + + const std::vector json = { + "{", "\"", "a", "\"", ":", "\"", "\\", "u", "2", + "0", "a", "c", "\xE2", "\x82", "\xAC", "\"", "}", + }; + const auto append = [&](size_t index) { + const llama_token next = token_for(vocab, json[index]); + assert(paths.check(make_input(next, true), {256}) == next); + }; + for (size_t i = 0; i <= 12; ++i) { + append(i); + } + sampler_ptr fork(llama_sampler_clone(paths.optimized.get()), + llama_sampler_free); + const llama_token continuation = token_for(vocab, json[13]); + assert(sample(fork.get(), make_input(continuation, true), false).first == + continuation); + llama_sampler_reset(fork.get()); + const llama_token first = token_for(vocab, json.front()); + assert(sample(fork.get(), make_input(first, true), false).first == first); + paths.fast.accepted.resize(paths.full.accepted.size()); + for (size_t i = 13; i < json.size(); ++i) { + append(i); + } + assert(paths.check(make_input(eog, false), {256}) == eog); + } + llama_dart_exit_free(model); +} + +} // namespace + +int main(int argc, char **argv) { + assert(argc == 2); + test_probe_paths(); + test_certificate_failures(); + test_top_p_certificate_boundaries(); + test_nonfinite(); + test_distribution(); + test_randomized_reference(); + test_ownership(); + test_real_grammar(argv[1]); +} diff --git a/tests/test_validate_exports.py b/tests/test_validate_exports.py index 110a425..653ada4 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), 122) - self.assertEqual(len(required), 122) + self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 123) + self.assertEqual(len(required), 123) 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,7 @@ 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 122 required export(s)', diagnostics) + self.assertIn('Validated 123 required export(s)', diagnostics) def test_file_hash_requires_both_version_and_operation(self): for name in ('llama_dart_file_sha256', 'llama_dart_file_sha256_api_version'): @@ -98,13 +98,15 @@ def test_file_hash_requires_both_version_and_operation(self): self.assertEqual(result, 1, diagnostics) self.assertIn(f' - {name}\n', 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_both_grammar_shortlist_constructors_are_required(self): + for constructor in ('llama_dart_sampler_init_grammar_top_k', + 'llama_dart_sampler_init_grammar_top_k_p'): + with self.subTest(symbol=constructor): + 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 e6db416..52498e7 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -58,6 +58,7 @@ "llama_dart_sampler_accept", "llama_dart_sampler_init_grammar_lazy_patterns", "llama_dart_sampler_init_grammar_top_k", + "llama_dart_sampler_init_grammar_top_k_p", "llama_dart_sampler_init_dry", "llama_dart_sampler_init_reasoning_budget", "llama_dart_sampler_init_reasoning_budget_multi",