diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 8e3c88dac9dc748bd440ba9e83b767fd53265378..751e2fc8034d96ef153ce3bd5a34a3264499211b 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -139,6 +139,12 @@ target_include_directories(${TARGET} PUBLIC .) target_link_libraries (${TARGET} PUBLIC vendor::nlohmann vendor::sheredom) target_compile_features (${TARGET} PUBLIC cxx_std_17) +# draft-dfly test hooks for tests/dfly-server, never in a production build +option(LLAMA_DFLY_TEST_HOOKS "llama-common, llama-server: build the draft-dfly test hooks" OFF) +if (LLAMA_DFLY_TEST_HOOKS) + target_compile_definitions(${TARGET} PRIVATE LLAMA_DFLY_TEST_HOOKS) +endif() + if (LLAMA_SUBPROCESS) target_compile_definitions(${TARGET} PUBLIC LLAMA_SUBPROCESS) endif() diff --git a/common/arg.cpp b/common/arg.cpp index e3ab084c67f942e02d8d22657cb4635634b2a250..60c003d346d7ed0a86e4ad48fe4ac9ba874d6fb8 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -330,6 +330,9 @@ static std::string get_default_local_path(const std::string & url) { return fs_get_cache_file(string_split(f, '/').back()).string(); } +// where the option handlers being called get their values from: cli, env or preset (outside of the parser too) +static const char * g_arg_source = "preset"; + static bool spec_types_is_default(const common_params & params) { return params.speculative.types == std::vector{COMMON_SPECULATIVE_TYPE_NONE}; } @@ -756,6 +759,7 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context common_log_set_verbosity_thold(params.verbosity); // config file applies first, so env variables and CLI arguments override it + g_arg_source = "preset"; common_params_apply_system_config(params, ctx_arg.ex); std::unordered_map> arg_to_options; @@ -769,6 +773,7 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context } // handle environment variables + g_arg_source = "env"; for (auto & opt : ctx_arg.options) { std::string value; if (opt.get_value_from_env(value)) { @@ -865,7 +870,9 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context }; // parse all CLI args now, so that -hf is available below for remote preset resolution + g_arg_source = "cli"; parse_cli_args(); + g_arg_source = "preset"; postprocess_cpu_params(params.cpuparams, nullptr); postprocess_cpu_params(params.cpuparams_batch, ¶ms.cpuparams); @@ -1671,6 +1678,44 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.cache_ram_explicit = true; } ).set_env("LLAMA_ARG_CACHE_RAM").set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI})); + add_opt(common_arg( + {"--prompt-quota"}, "N", + string_format("while slots generate, add at most N prompt tokens to a decode and let the prompts take turns (default: %d, 0 = no limit)", params.prompt_quota), + [](common_params & params, int value) { + if (value < 0) { + throw std::invalid_argument("prompt-quota must be non-negative"); + } + params.prompt_quota = value; + } + ).set_env("LLAMA_ARG_PROMPT_QUOTA").set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--cache-slot-copy"}, + {"--no-cache-slot-copy"}, + string_format("with a unified KV cache, a new task takes the prompt of another slot when that keeps more of it than its own slot and the prompt cache (default: %s)", params.cache_slot_copy ? "enabled" : "disabled"), + [](common_params & params, bool value) { + params.cache_slot_copy = value; + } + ).set_env("LLAMA_ARG_CACHE_SLOT_COPY").set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--cache-ram-min-drop"}, "N", + string_format("also save a slot to the cache when a new prompt would drop at least N of its computed tokens (default: %d, 0 = only when less than half is kept)", params.cache_ram_min_drop), + [](common_params & params, int value) { + if (value < 0) { + throw std::invalid_argument("cache-ram-min-drop must be non-negative"); + } + params.cache_ram_min_drop = value; + } + ).set_env("LLAMA_ARG_CACHE_RAM_MIN_DROP").set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI})); + add_opt(common_arg( + {"--cache-ram-min-gain"}, "N", + string_format("load a cached prompt only when it restores at least N more tokens than the slot keeps (default: %d, 0 = any gain)", params.cache_ram_min_gain), + [](common_params & params, int value) { + if (value < 0) { + throw std::invalid_argument("cache-ram-min-gain must be non-negative"); + } + params.cache_ram_min_gain = value; + } + ).set_env("LLAMA_ARG_CACHE_RAM_MIN_GAIN").set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI})); add_opt(common_arg( {"-kvu", "--kv-unified"}, {"-no-kvu", "--no-kv-unified"}, @@ -3565,7 +3610,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex [](common_params & params, bool value) { params.cache_prompt = value; } - ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CACHE_PROMPT")); + ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_CACHE_PROMPT")); add_opt(common_arg( {"--cache-reuse"}, "N", string_format( @@ -4133,12 +4178,15 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--spec-draft-n-max"}, "N", - string_format("number of tokens to draft for speculative decoding (default: %d)", params.speculative.draft.n_max), + string_format("number of tokens to draft for speculative decoding (default: %d; draft-dfly: 4, at most the block size - 1)", params.speculative.draft.n_max), [](common_params & params, int value) { if (value < 0) { throw std::invalid_argument("invalid value"); } params.speculative.draft.n_max = value; + params.speculative.draft.n_max_requested = value; + params.speculative.draft.n_max_explicit = true; + params.speculative.draft.n_max_source = g_arg_source; } ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_MAX")); add_opt(common_arg( @@ -4273,6 +4321,9 @@ common_params_context common_params_parser_init(common_params & params, llama_ex const auto types_str = string_split(value, ','); auto types = common_speculative_types_from_names(types_str); params.speculative.types.insert(params.speculative.types.end(), types.begin(), types.end()); + // the names as given: the parsed list folds "none" in a mix, common_dfly_prepare rejects that + params.speculative.types_requested.insert(params.speculative.types_requested.end(), types_str.begin(), types_str.end()); + params.speculative.types_explicit = true; } ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_TYPE")); add_opt(common_arg( diff --git a/common/common.h b/common/common.h index e970fb39b25df91dd1b44bbdd3ff139513f05263..762e7c7c0032b0d1aa2a438aeffe393d2587ad38 100644 --- a/common/common.h +++ b/common/common.h @@ -185,6 +185,7 @@ enum common_speculative_type { COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, // self-speculative decoding with n-gram keys and 4 m-gram values COMMON_SPECULATIVE_TYPE_NGRAM_MOD, COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, // self-speculative decoding with 3-level n-gram cache + COMMON_SPECULATIVE_TYPE_DRAFT_DFLY, // DFly draft (hy_v4_next_dfly) on the target's captured state COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type }; @@ -329,6 +330,11 @@ struct common_params_model { // draft-model-based speculative decoding parameters struct common_params_speculative_draft { int32_t n_max = 3; // maximum number of tokens to draft during speculative decoding + + // --spec-draft-n-max as given; common_dfly_prepare rewrites n_max from it on every load + int32_t n_max_requested = -1; + bool n_max_explicit = false; + std::string n_max_source = "default"; // cli, env or preset when explicit int32_t n_min = 0; // minimum number of draft tokens to use for speculative decoding float p_split = 0.1f; // speculative decoding split probability @@ -376,9 +382,29 @@ struct common_params_speculative_ngram_cache { std::string lookup_cache_dynamic; // path of dynamic ngram cache file for lookup decoding }; +// what common_dfly_prepare resolved for a hy_v4_next_dfly draft, kept for the next prepare and the logs +struct common_params_speculative_dfly { + common_params_model mparams; // the draft as given, the active one is cleared when DFly is disabled + + bool is_dfly = false; // the draft file is a hy_v4_next_dfly model + bool active = false; // the draft-dfly type is set up with K_effective > 0 + int32_t block_size = 0; // B + bool causal = false; + int32_t n_max_requested = 0; // K_requested + int32_t n_max_effective = 0; // K_effective + std::string disabled; // why a DFly draft does not run, empty if it does + std::vector target_layers; // the target layers whose KV the draft reads +}; + struct common_params_speculative { std::vector types = { COMMON_SPECULATIVE_TYPE_NONE }; + // --spec-type names as given, in order; the GGUF inference does not set them + std::vector types_requested; + bool types_explicit = false; + + common_params_speculative_dfly dfly; + double synth_len = -1.0; std::vector synth_rates; @@ -643,6 +669,10 @@ struct common_params { int32_t checkpoint_min_step = 8192; // minimum spacing between context checkpoints int32_t cache_ram_mib = 8192; // -1 = no limit, 0 - disable, 1 = 1 MiB, etc. bool cache_ram_explicit = false; // set by --cache-ram, decision models disable the cache otherwise + int32_t cache_ram_min_drop = 512; // also save a slot that would drop this many computed tokens, 0 = off + int32_t cache_ram_min_gain = 256; // load a cached prompt only if it restores this many more tokens than the slot + int32_t prompt_quota = 0; // max prompt tokens per decode while slots generate, 0 = no limit + bool cache_slot_copy = true; // a new task takes the prompt of another slot that keeps more of it (unified KV) // llama-connect params bool server_connect = false; @@ -778,6 +808,11 @@ struct common_params { bool is_gen_docs = false; // whether we are running inside llama-gen-docs }; +// whether the request asks for draft-dfly: the type is named or the draft model is a hy_v4_next_dfly GGUF +// for the entry points without draft-dfly support (router, memory measure, examples), which must refuse it +// (defined in speculative.cpp, next to common_dfly_prepare) +bool common_dfly_requested(const common_params & params); + // call once at the start of a program if it uses libcommon // initializes the logging system and prints info about the build void common_init(); diff --git a/common/speculative.cpp b/common/speculative.cpp index 14fee2b2c5012587d7158c86496075b011c9a883..5f8c5f289e2cacf3b542a9081e5b6620cb0012ce 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -13,6 +13,7 @@ #include "../src/llama-ext.h" // staging API: llama_set_embeddings_nextn / llama_get_embeddings_nextn_ith (used by MTP) #include +#include #include #include #include @@ -20,6 +21,8 @@ #include #include #include +#include +#include #include #define SPC_DBG(fmt, ...) LOG_DBG("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__) @@ -82,7 +85,8 @@ const std::map common_speculative_type_fro {"ngram-map-k", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K}, {"ngram-map-k4v", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V}, {"ngram-mod", COMMON_SPECULATIVE_TYPE_NGRAM_MOD}, - {"ngram-cache", COMMON_SPECULATIVE_TYPE_NGRAM_CACHE} + {"ngram-cache", COMMON_SPECULATIVE_TYPE_NGRAM_CACHE}, + {"draft-dfly", COMMON_SPECULATIVE_TYPE_DRAFT_DFLY} }; static std::string common_speculative_get_devices_str(const std::vector & devices) { @@ -215,6 +219,12 @@ struct common_speculative_impl { // (optional) serialize/restore per-seq internal state (e.g. eagle3's deferred boundary). virtual bool get_state(llama_seq_id /*seq_id*/, std::vector & /*data*/) const { return false; } virtual void set_state(llama_seq_id /*seq_id*/, const std::vector & /*data*/) {} + + // whether draft() reads dp.prompt; the caller may skip copying the prompt for each draft otherwise + virtual bool needs_prompt() const { return true; } + + // (optional) implementation-specific statistics, printed by common_speculative_print_stats + virtual std::string stats_extra() const { return {}; } }; struct common_speculative_impl_draft_simple : public common_speculative_impl { @@ -1969,6 +1979,223 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { } }; +// DFly draft (hy_v4_next_dfly), plan sections 9 and 10.2 +// +// the draft holds no KV: every decode of the target captures the rows the next propose reads, +// the propose for anchor position a uses the row of position a - 1 +struct common_speculative_impl_draft_dfly : public common_speculative_impl { + llama_context * ctx_dft = nullptr; + + std::vector tokens; // propose output, K_effective entries + + // propose results by llama_dfly_status, and the capture pulls by status + std::array n_propose = {}; + std::array n_pull = {}; + + // plan 6.3: the status of the first propose with K_step > 0 of a request is logged once, per sequence + std::vector first_pending; + +#ifdef LLAMA_DFLY_TEST_HOOKS + // the script of the request, re-read at its start: see tests/dfly-server/README.md + struct test_script { + std::vector ref; // reference token per absolute position + std::vector r; // accepted drafts per round + std::map wrong; // round -> the rejected draft token + std::set propose_fail; // rounds whose draft comes back empty + int32_t verify_fail_n = 0; // the n-th verify (1-based) of the request fails ... + int32_t verify_fail_ret = 0; // ... with this llama_decode result + }; + test_script script; + std::vector test_rounds; // per sequence: drafts with K_step > 0 in its request + std::vector test_last; // per sequence +#endif + + common_speculative_impl_draft_dfly(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl(COMMON_SPECULATIVE_TYPE_DRAFT_DFLY, n_seq, params.draft.n_max) + , ctx_dft(params.draft.ctx_dft) + { + if (n_seq < 1) { + throw std::runtime_error(string_format("draft-dfly needs at least one sequence, got %u", n_seq)); + } + if (n_max < 1 || n_max > COMMON_DFLY_K_SUPPORTED_MAX) { + throw std::runtime_error(string_format("draft-dfly: K_effective = %d is outside [1, %d]", n_max, COMMON_DFLY_K_SUPPORTED_MAX)); + } + + // the server creates the implementations after the target warmup and the seq_rm probe, which the capture must not see + const llama_dfly_status status = llama_dfly_capture_enable(ctx_dft); + if (status != LLAMA_DFLY_OK) { + throw std::runtime_error(string_format("llama_dfly_capture_enable failed with status %d", (int) status)); + } + + tokens.resize(n_max); + first_pending.assign(n_seq, false); +#ifdef LLAMA_DFLY_TEST_HOOKS + test_rounds.assign(n_seq, 0); + test_last.assign(n_seq, {}); +#endif + + SPC_INF("DFly capture enabled, K_effective = %d, n_seq = %u\n", n_max, n_seq); + } + + // the prefill row that process() just captured is the snapshot of the first propose, keep it + void begin(llama_seq_id seq_id, const llama_tokens & /*prompt*/) override { + if (seq_id >= 0 && seq_id < (llama_seq_id) first_pending.size()) { + first_pending[seq_id] = true; + } + } + + bool process(const common_batch & /*batch*/) override { + const llama_dfly_status status = llama_dfly_capture_pull(ctx_dft); + if (status >= 0 && status < (int) n_pull.size()) { + n_pull[status]++; + } + if (status == LLAMA_DFLY_BAD_REQUEST) { + SPC_ERR("%s", "llama_dfly_capture_pull failed with BAD_REQUEST\n"); + } + // a bad capture is already invalidated: the next draft finds no snapshot and that round runs without a draft, + // the result of this decode stands (false would end the server loop) + return true; + } + + void draft(common_speculative_draft_params_vec & dparams) override { + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) dparams.size(); ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } + + // plan 4.4: limit K before the propose, cutting the result short would waste serial heads and misreport W + int32_t k_step = n_max; + if (dp.n_max == 0) { + k_step = 0; + } else if (dp.n_max > 0) { + k_step = std::min(n_max, dp.n_max); + } + +#ifdef LLAMA_DFLY_TEST_HOOKS + test_last[seq_id] = { -1, k_step, dp.n_max, dp.pos0 }; + const int32_t round = k_step > 0 ? test_rounds[seq_id]++ : -1; + if (round >= 0 && script.propose_fail.count(round)) { + test_last[seq_id].status = -2; + continue; + } +#endif + + if (k_step == 0) { + continue; + } + + const llama_dfly_request request = { seq_id, dp.id_last, dp.pos0, k_step }; + llama_dfly_result result = { tokens.data(), (int32_t) tokens.size(), 0 }; + + const llama_dfly_status status = llama_dfly_propose(ctx_dft, &request, &result); + if (status >= 0 && status < (int) n_propose.size()) { + n_propose[status]++; + } + if (first_pending[seq_id]) { + static const char * const names[] = { "ok", "no_snapshot", "bad_snapshot", "bad_token", "compute_failed", "bad_request" }; + SPC_INF("first_propose_status = %d (%s), pos = %d, seq = %d\n", (int) status, + status >= 0 && status <= LLAMA_DFLY_BAD_REQUEST ? names[status] : "unknown", dp.pos0, seq_id); + first_pending[seq_id] = false; + } +#ifdef LLAMA_DFLY_TEST_HOOKS + test_last[seq_id].status = status; +#endif + if (status != LLAMA_DFLY_OK) { + // an empty draft: this round decodes the anchor alone, its capture serves the next propose + SPC_DBG("propose at pos %d returned status %d\n", dp.pos0, (int) status); + continue; + } + + dp.result->assign(tokens.begin(), tokens.begin() + result.n_tokens); + +#ifdef LLAMA_DFLY_TEST_HOOKS + test_rewrite(round, dp.pos0, *dp.result); +#endif + } + } + + void accept(llama_seq_id /*seq_id*/, uint16_t /*n_accepted*/, bool /*is_other*/) override { + // statistics only, counted by common_speculative_accept; the server rolls the target back + } + + bool needs_prompt() const override { + return false; + } + + std::string stats_extra() const override { + return string_format("propose ok = %zu, no_snapshot = %zu, bad_snapshot = %zu, bad_token = %zu, compute_failed = %zu, bad_request = %zu; " + "pull ok = %zu, no_snapshot = %zu, bad_snapshot = %zu, bad_request = %zu", + n_propose[LLAMA_DFLY_OK], n_propose[LLAMA_DFLY_NO_SNAPSHOT], n_propose[LLAMA_DFLY_BAD_SNAPSHOT], + n_propose[LLAMA_DFLY_BAD_TOKEN], n_propose[LLAMA_DFLY_COMPUTE_FAILED], n_propose[LLAMA_DFLY_BAD_REQUEST], + n_pull[LLAMA_DFLY_OK], n_pull[LLAMA_DFLY_NO_SNAPSHOT], n_pull[LLAMA_DFLY_BAD_SNAPSHOT], n_pull[LLAMA_DFLY_BAD_REQUEST]); + } + +#ifdef LLAMA_DFLY_TEST_HOOKS + // the script is shared, each sequence counts its own rounds + void test_begin_request(llama_seq_id seq_id) { + script = {}; + if (seq_id >= 0 && seq_id < (llama_seq_id) test_rounds.size()) { + test_rounds[seq_id] = 0; + test_last[seq_id] = {}; + } + + const char * path = getenv("LLAMA_DFLY_TEST_SCRIPT"); + if (path == nullptr) { + return; + } + std::ifstream f(path); + std::string line; + while (std::getline(f, line)) { + std::istringstream ss(line); + std::string key; + ss >> key; + std::vector v; + int32_t x; + while (ss >> x) { + v.push_back(x); + } + if (key == "ref") { + script.ref.assign(v.begin(), v.end()); + } else if (key == "r") { + script.r = v; + } else if (key == "wrong" && v.size() == 2) { + script.wrong[v[0]] = v[1]; + } else if (key == "propose_fail") { + script.propose_fail.insert(v.begin(), v.end()); + } else if (key == "verify_fail" && v.size() == 2) { + script.verify_fail_n = v[0]; + script.verify_fail_ret = v[1]; + } + } + SPC_INF("DFly test script '%s': %zu ref tokens, %zu rounds\n", path, script.ref.size(), script.r.size()); + } + + // H1: the first r drafts take the reference tokens, draft r gets a token other than the reference + void test_rewrite(int32_t round, llama_pos a, llama_tokens & draft) const { + if (round < 0 || round >= (int32_t) script.r.size() || script.ref.empty()) { + return; + } + const int32_t k = (int32_t) draft.size(); + const int32_t r = std::min(script.r[round], k); + for (int32_t j = 0; j <= r && j < k; ++j) { + const size_t pos = (size_t) a + 1 + j; + if (pos >= script.ref.size()) { + SPC_WRN("DFly test script: no reference token at pos %zu\n", pos); + return; + } + if (j < r) { + draft[j] = script.ref[pos]; + } else { + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx_dft))); + const auto it = script.wrong.find(round); + draft[j] = it != script.wrong.end() ? it->second : (script.ref[pos] + 1) % n_vocab; + } + } + } +#endif +}; + // state of self-speculation (simple implementation, not ngram-map) struct common_speculative_impl_ngram_simple : public common_speculative_impl { common_params_speculative_ngram_map params; @@ -2460,6 +2687,7 @@ std::string common_speculative_type_to_str(common_speculative_type type) { case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: return "ngram-map-k4v"; case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: return "ngram-mod"; case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: return "ngram-cache"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLY: return "draft-dfly"; default: return "unknown"; } } @@ -2508,8 +2736,19 @@ std::vector common_speculative_types_from_gguf(const st } const std::string arch = gguf_get_val_str(gguf_ctx.get(), arch_id); + + // before the MTP probe: a DFly draft is a model of its own, its last block has no nextn tensors + if (arch == "hy_v4_next_dfly") { + SPC_INF("%s", "auto-detected speculative type 'draft-dfly' from the draft model metadata\n"); + return { COMMON_SPECULATIVE_TYPE_DRAFT_DFLY }; + } + if (arch != "dflash") { - const uint32_t block_count = gguf_get_val_u32(gguf_ctx.get(), gguf_find_key(gguf_ctx.get(), (arch + ".block_count").c_str())); + const int64_t block_count_id = gguf_find_key(gguf_ctx.get(), (arch + ".block_count").c_str()); + if (block_count_id < 0 || gguf_get_kv_type(gguf_ctx.get(), block_count_id) != GGUF_TYPE_UINT32) { + return {}; + } + const uint32_t block_count = gguf_get_val_u32(gguf_ctx.get(), block_count_id); if (gguf_find_tensor(gguf_ctx.get(), ("blk." + std::to_string(block_count - 1) + ".nextn.eh_proj.weight").c_str()) >= 0) { return { COMMON_SPECULATIVE_TYPE_DRAFT_MTP }; @@ -2546,6 +2785,7 @@ int32_t common_speculative_n_max(const common_params_speculative * spec) { case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLY: // n_max is K_effective, see common_dfly_prepare n_max = std::max(n_max, std::max(0, spec->draft.n_max)); break; case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: @@ -2765,6 +3005,24 @@ common_speculative_init_result::common_speculative_init_result( cparams.n_rs_seq = 0; cparams.ctx_other = ctx_tgt; + // plan 8.7: one ubatch of anchor + K_effective drafts, no KV and no standard outputs; llama checks these again + const bool spec_dfly = std::find(params.speculative.types.begin(), params.speculative.types.end(), + COMMON_SPECULATIVE_TYPE_DRAFT_DFLY) != params.speculative.types.end(); + if (spec_dfly) { + const llama_context_params defaults = llama_context_default_params(); + + cparams.n_batch = 1 + params.speculative.draft.n_max; + cparams.n_ubatch = 1 + params.speculative.draft.n_max; + cparams.n_seq_max = 1; + cparams.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; + cparams.type_k = GGML_TYPE_F16; + cparams.type_v = GGML_TYPE_F16; + cparams.offload_kqv = true; + cparams.moe_cache_size = 0; + cparams.n_outputs_max = defaults.n_outputs_max; + cparams.n_outputs_max_per_seq = defaults.n_outputs_max_per_seq; + } + std::string model_path; if (has_draft) { model_path = params.speculative.draft.mparams.path; @@ -2780,7 +3038,7 @@ common_speculative_init_result::common_speculative_init_result( llama_context * ctx_dft = llama_init_from_model(model_dft, cparams); if (ctx_dft == nullptr) { - LOG_ERR("%s: failed to create MTP context\n", __func__); + LOG_ERR("%s: failed to create %s context\n", __func__, spec_dfly ? "the DFly" : "MTP"); return; } @@ -2840,7 +3098,7 @@ common_speculative * common_speculative_init(common_params_speculative & params, }; // when adding a new type - update here the logic above - static_assert(COMMON_SPECULATIVE_TYPE_COUNT == 11); + static_assert(COMMON_SPECULATIVE_TYPE_COUNT == 12); // this list here defines the priority of the speculators // the one with highest priority are listed first @@ -2855,6 +3113,7 @@ common_speculative * common_speculative_init(common_params_speculative & params, add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, params.draft.ctx_dft != nullptr); add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, params.draft.ctx_dft != nullptr); add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLY, params.draft.ctx_dft != nullptr); } std::vector> impls = {}; @@ -2884,6 +3143,11 @@ common_speculative * common_speculative_init(common_params_speculative & params, config.params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK)); break; } + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLY: { + // throws on failure, the caller must not fall back to the target alone (plan 4.3 fatal) + impls.push_back(std::make_unique(config.params, n_seq)); + break; + } case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: { common_ngram_map ngram_map = get_common_ngram_map(config.type, config.params.ngram_simple); @@ -3205,5 +3469,328 @@ void common_speculative_print_stats(const common_speculative * spec) { impl->n_acc_tokens, str_stats.c_str(), str_perf.c_str()); + + const std::string extra = impl->stats_extra(); + if (!extra.empty()) { + SPC_INF("statistics %16s: %s\n", common_speculative_type_to_str(impl->type).c_str(), extra.c_str()); + } + } +} + +bool common_speculative_needs_prompt(const common_speculative * spec) { + if (spec == nullptr) { + return false; + } + + for (const auto & impl : spec->impls) { + if (impl->needs_prompt()) { + return true; + } + } + + return false; +} + +// +// draft-dfly +// + +static void common_dfly_disable(common_params_speculative & sp, const std::string & reason) { + sp.dfly.active = false; + sp.dfly.disabled = reason; + + // the request (types_requested, n_max_requested, dfly.mparams) stays for the next prepare + sp.draft.mparams = {}; + sp.types = { COMMON_SPECULATIVE_TYPE_NONE }; + sp.draft.n_max = 0; + + LOG_INF("%s: DFly disabled, target-only: %s\n", __func__, reason.c_str()); +} + +bool common_dfly_prepare(common_params & params, std::string & err) { + auto & sp = params.speculative; + + const auto & names = sp.types_requested; + const bool name_dfly = std::find(names.begin(), names.end(), "draft-dfly") != names.end(); + const bool none_only = sp.types_explicit && !names.empty() && + std::all_of(names.begin(), names.end(), [](const std::string & n) { return n == "none"; }); + + // a disabled DFly draft is no longer in draft.mparams, the request still is + const common_params_model mparams = sp.dfly.is_dfly ? sp.dfly.mparams : sp.draft.mparams; + + if (mparams.path.empty()) { + if (name_dfly) { + err = "--spec-type draft-dfly needs a hy_v4_next_dfly draft model (--spec-draft-model)"; + return false; + } + return true; + } + + gguf_init_params gparams = { /* .no_alloc = */ true, /* .ctx = */ nullptr }; + gguf_context_ptr ctx(gguf_init_from_file(mparams.path.c_str(), gparams)); + if (!ctx) { + if (name_dfly) { + err = string_format("failed to read the GGUF header of the draft model '%s'", mparams.path.c_str()); + return false; + } + return true; // not ours to report, the model loader does + } + + std::string arch; + { + const int64_t id = gguf_find_key(ctx.get(), "general.architecture"); + if (id >= 0 && gguf_get_kv_type(ctx.get(), id) == GGUF_TYPE_STRING) { + arch = gguf_get_val_str(ctx.get(), id); + } + } + + if (arch != "hy_v4_next_dfly") { + if (name_dfly) { + err = string_format("--spec-type draft-dfly needs a hy_v4_next_dfly draft model, '%s' has architecture '%s'", + mparams.path.c_str(), arch.c_str()); + return false; + } + return true; + } + + sp.dfly = {}; + sp.dfly.mparams = mparams; + sp.dfly.is_dfly = true; + + if (none_only) { + common_dfly_disable(sp, "explicit --spec-type none"); + return true; + } + + // an inferred type (e.g. draft-dflash from a sidecar) is corrected by the architecture, an explicit one must match it + if (sp.types_explicit) { + for (const auto & n : names) { + if (n != "draft-dfly") { + err = string_format("--spec-type %s conflicts with the hy_v4_next_dfly draft model '%s', which runs as draft-dfly only", + string_join(names, ",").c_str(), mparams.path.c_str()); + return false; + } + } + } + + auto get_key = [&](const char * key, gguf_type type, int64_t & id) { + id = gguf_find_key(ctx.get(), key); + if (id < 0) { + err = string_format("draft model '%s': key %s is missing", mparams.path.c_str(), key); + return false; + } + if (gguf_get_kv_type(ctx.get(), id) != type) { + err = string_format("draft model '%s': key %s has type %s, expected %s", mparams.path.c_str(), key, + gguf_type_name(gguf_get_kv_type(ctx.get(), id)), gguf_type_name(type)); + return false; + } + return true; + }; + + int64_t id = -1; + if (!get_key("hy_v4_next_dfly.schema_version", GGUF_TYPE_UINT32, id)) { + return false; + } + if (gguf_get_val_u32(ctx.get(), id) != 1) { + err = string_format("draft model '%s': key hy_v4_next_dfly.schema_version is %u, expected 1", + mparams.path.c_str(), gguf_get_val_u32(ctx.get(), id)); + return false; + } + if (!get_key("hy_v4_next_dfly.block_size", GGUF_TYPE_UINT32, id)) { + return false; + } + const int64_t B = gguf_get_val_u32(ctx.get(), id); + if (B < 2) { + err = string_format("draft model '%s': key hy_v4_next_dfly.block_size is %" PRId64 ", expected at least 2", + mparams.path.c_str(), B); + return false; + } + if (!get_key("hy_v4_next_dfly.attention.causal", GGUF_TYPE_BOOL, id)) { + return false; + } + if (!gguf_get_val_bool(ctx.get(), id)) { + err = string_format("draft model '%s': key hy_v4_next_dfly.attention.causal is false, only the causal block is supported", + mparams.path.c_str()); + return false; + } + + // the global --spec-draft-n-max default (3) is not DFly's: an unset K means 4 + const int64_t k_req = sp.draft.n_max_explicit ? (int64_t) sp.draft.n_max_requested : 4; + if (k_req < 0) { + err = string_format("--spec-draft-n-max %" PRId64 " is negative", k_req); + return false; + } + const int64_t k_eff = std::min(k_req, B - 1); + if (k_eff < k_req) { + LOG_WRN("%s: DFly K_requested = %" PRId64 " exceeds the block size B = %" PRId64 " minus 1, K_effective = %" PRId64 "\n", + __func__, k_req, B, k_eff); + } + if (k_eff > COMMON_DFLY_K_SUPPORTED_MAX) { + err = string_format("DFly K_effective = %" PRId64 " exceeds the supported maximum %d, set --spec-draft-n-max", + k_eff, COMMON_DFLY_K_SUPPORTED_MAX); + return false; + } + + sp.dfly.block_size = (int32_t) B; + sp.dfly.causal = true; + sp.dfly.n_max_requested = (int32_t) k_req; + sp.dfly.n_max_effective = (int32_t) k_eff; + + { + const int64_t kid = gguf_find_key(ctx.get(), "hy_v4_next_dfly.target_kv_layers"); + if (kid >= 0 && gguf_get_kv_type(ctx.get(), kid) == GGUF_TYPE_ARRAY && gguf_get_arr_type(ctx.get(), kid) == GGUF_TYPE_UINT32) { + const auto * data = (const uint32_t *) gguf_get_arr_data(ctx.get(), kid); + sp.dfly.target_layers.assign(data, data + gguf_get_arr_n(ctx.get(), kid)); + } + } + + if (k_eff == 0) { + common_dfly_disable(sp, "--spec-draft-n-max 0"); + return true; + } + + // plan 4.3, table rows 2-5: the final configuration, checked rather than rewritten; K = 0 skips all of it + std::vector need; + if (params.n_parallel < 1) { + need.push_back(string_format("--parallel 1 (n_parallel is %d; the server uses 4 when it is not set)", params.n_parallel)); + } else if (params.n_parallel > 1) { + // several slots: each target decode must be one ubatch of one shared KV stream, so that no verify is split + if (!params.kv_unified) { + need.push_back(string_format("-kvu (--kv-unified): several DFly slots need one shared KV stream (n_parallel is %d)", + params.n_parallel)); + } + if (params.n_batch != params.n_ubatch) { + need.push_back(string_format("--batch-size equal to --ubatch-size (they are %d and %d): with several slots each decode " + "must be one ubatch", params.n_batch, params.n_ubatch)); + } + if ((int64_t) params.n_parallel * (1 + k_eff) > params.n_ubatch) { + need.push_back(string_format("--ubatch-size of at least n_parallel * (1 + K) = %" PRId64 " (it is %d)", + (int64_t) params.n_parallel * (1 + k_eff), params.n_ubatch)); + } + } + if (params.fit_params) { + need.push_back("--fit off"); + } + if (params.ctx_shift) { + need.push_back("--no-context-shift"); + } + if (params.n_cache_reuse != 0) { + need.push_back(string_format("--cache-reuse 0 (it is %d)", params.n_cache_reuse)); + } + if (params.swa_full) { + need.push_back("no --swa-full"); + } + if (!params.slot_save_path.empty()) { + need.push_back("no --slot-save-path"); + } + if (params.sampling.backend_sampling) { + need.push_back("no --backend-sampling"); + } + if (params.cache_type_k != params.cache_type_v || + (params.cache_type_k != GGML_TYPE_F16 && params.cache_type_k != GGML_TYPE_BF16)) { + need.push_back(string_format("--cache-type-k and --cache-type-v both f16 or both bf16 (they are %s and %s)", + ggml_type_name(params.cache_type_k), ggml_type_name(params.cache_type_v))); + } + if (1 + k_eff > params.n_ubatch || params.n_ubatch > params.n_batch) { + need.push_back(string_format("--ubatch-size of at least %" PRId64 " and --batch-size of at least the ubatch size " + "(they are %d and %d): a verify must fit in one ubatch", 1 + k_eff, params.n_ubatch, params.n_batch)); + } + if (!params.mmproj.path.empty()) { + need.push_back(string_format("no multimodal projector (--no-mmproj; '%s' is set)", params.mmproj.path.c_str())); + } + if (sp.draft.n_min != 0) { + need.push_back("--spec-draft-n-min 0"); + } + if (sp.draft.p_min != 0.0f) { + need.push_back("--spec-draft-p-min 0"); + } + if (sp.draft.probabilistic) { + need.push_back("--spec-draft-sampling greedy"); + } + if (sp.has_synth()) { + need.push_back("no synthetic acceptance (--spec-synth-len, --spec-synth-rates)"); + } + if (!params.lora_adapters.empty()) { + need.push_back("no --lora adapters"); + } + if (!need.empty()) { + err = "draft-dfly (K_effective = " + std::to_string(k_eff) + ") does not support this configuration, it needs: " + string_join(need, "; "); + return false; + } + + // the output limits, the DFly context width and the server round limit all follow from this n_max + sp.dfly.active = true; + sp.draft.mparams = mparams; + sp.types = { COMMON_SPECULATIVE_TYPE_DRAFT_DFLY }; + sp.draft.n_max = (int32_t) k_eff; + + LOG_INF("%s: DFly: B = %" PRId64 ", causal = true, K_requested = %" PRId64 " (%s), K_effective = %" PRId64 ", W_max = %" PRId64 "\n", + __func__, B, k_req, sp.draft.n_max_explicit ? sp.draft.n_max_source.c_str() : "default", k_eff, k_eff + 1); + + return true; +} + +bool common_dfly_requested(const common_params & params) { + const auto & names = params.speculative.types_requested; + if (std::find(names.begin(), names.end(), "draft-dfly") != names.end()) { + return true; + } + const auto & types = params.speculative.types; + if (std::find(types.begin(), types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_DFLY) != types.end()) { + return true; + } + if (params.speculative.dfly.is_dfly) { + return true; + } + + const std::string & path = params.speculative.draft.mparams.path; + if (path.empty()) { + return false; + } + gguf_init_params gparams = { /* .no_alloc = */ true, /* .ctx = */ nullptr }; + gguf_context_ptr ctx(gguf_init_from_file(path.c_str(), gparams)); + if (!ctx) { + return false; + } + const int64_t id = gguf_find_key(ctx.get(), "general.architecture"); + return id >= 0 && gguf_get_kv_type(ctx.get(), id) == GGUF_TYPE_STRING && + std::string(gguf_get_val_str(ctx.get(), id)) == "hy_v4_next_dfly"; +} + +#ifdef LLAMA_DFLY_TEST_HOOKS +static common_speculative_impl_draft_dfly * common_speculative_dfly_impl(const common_speculative * spec) { + if (spec == nullptr) { + return nullptr; + } + for (const auto & impl : spec->impls) { + if (impl->type == COMMON_SPECULATIVE_TYPE_DRAFT_DFLY) { + return static_cast(impl.get()); + } + } + return nullptr; +} + +void common_speculative_dfly_test_begin_request(common_speculative * spec, llama_seq_id seq_id) { + if (auto * impl = common_speculative_dfly_impl(spec)) { + impl->test_begin_request(seq_id); + } +} + +bool common_speculative_dfly_test_take_round(common_speculative * spec, llama_seq_id seq_id, common_speculative_dfly_test_round & out) { + auto * impl = common_speculative_dfly_impl(spec); + if (impl == nullptr || seq_id < 0 || seq_id >= (llama_seq_id) impl->test_last.size() || impl->test_last[seq_id].pos0 < 0) { + return false; + } + out = impl->test_last[seq_id]; + impl->test_last[seq_id] = {}; + return true; +} + +int32_t common_speculative_dfly_test_verify_ret(const common_speculative * spec, int32_t n_verify) { + const auto * impl = common_speculative_dfly_impl(spec); + if (impl == nullptr || impl->script.verify_fail_n != n_verify) { + return 0; } + return impl->script.verify_fail_ret; } +#endif diff --git a/common/speculative.h b/common/speculative.h index 4262327cbbc29b193e4616ebcb89c62555b5a2ef..166768fec9d7330074dac89391bc7a0ee0ec91f8 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -102,6 +102,37 @@ void common_speculative_set_state(common_speculative * spec, llama_seq_id seq_id // print statistics about the speculative decoding void common_speculative_print_stats(const common_speculative * spec); +// whether an implementation reads common_speculative_draft_params::prompt; if not, the caller may leave it empty +bool common_speculative_needs_prompt(const common_speculative * spec); + +// the draft-dfly limit on K, independent of the trained block size B +constexpr int32_t COMMON_DFLY_K_SUPPORTED_MAX = 7; + +// resolve the speculative type and K for a hy_v4_next_dfly draft model (plan 4.3) +// reads only the GGUF header; recomputes from the request kept in params.speculative on every call +// (types_requested, draft.n_max_requested and dfly.mparams), so a reload after sleep resolves the same way +// returns false with err set if the configuration is invalid; the model must not load then +bool common_dfly_prepare(common_params & params, std::string & err); + +#ifdef LLAMA_DFLY_TEST_HOOKS +// test hooks of draft-dfly, built with LLAMA_DFLY_TEST_HOOKS only (tests/dfly-server) +struct common_speculative_dfly_test_round { + int32_t status = -1; // llama_dfly_status of the propose; -1 none, -2 failure forced by the script + int32_t k_step = 0; + int32_t n_max = 0; // common_speculative_draft_params::n_max of the draft + llama_pos pos0 = -1; +}; + +// re-read the script of $LLAMA_DFLY_TEST_SCRIPT at the start of a request of seq_id, whose round count restarts +void common_speculative_dfly_test_begin_request(common_speculative * spec, llama_seq_id seq_id); + +// the last draft of the request of seq_id, cleared by the call; false if there was none +bool common_speculative_dfly_test_take_round(common_speculative * spec, llama_seq_id seq_id, common_speculative_dfly_test_round & out); + +// the llama_decode result the script forces on the n-th verify (1-based) of the request, 0 if none +int32_t common_speculative_dfly_test_verify_ret(const common_speculative * spec, int32_t n_verify); +#endif + struct common_speculative_deleter { void operator()(common_speculative * s) { common_speculative_free(s); } }; diff --git a/conversion/__init__.py b/conversion/__init__.py index 6a34da41fe4aa8b133371551e391a4d5b4068839..4759e95c98e8329025ddb7f22f25fc20258aa545 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -139,6 +139,8 @@ TEXT_MODEL_MAP: dict[str, str] = { "HrmTextForCausalLM": "hrm_text", "HYV3ForCausalLM": "hunyuan", "HYV4ForCausalLM": "hy_v4", + "HYV4NextForCausalLM": "hy_v4_flash", + "HYV4NextVLForConditionalGeneration": "hy_v4_flash", "IQuestCoderForCausalLM": "llama", "InternLM2ForCausalLM": "internlm", "InternLM3ForCausalLM": "internlm", @@ -357,6 +359,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = { "GraniteSpeechForConditionalGeneration": "granite", "GraniteSpeechPlusForConditionalGeneration": "granite", "HunYuanVLForConditionalGeneration": "hunyuan", + "HYV4NextVLForConditionalGeneration": "hy_v4_flash_vision", "Idefics3ForConditionalGeneration": "smolvlm", "InternVisionModel": "internvl", "JanusForConditionalGeneration": "januspro", diff --git a/conversion/hy_v4_flash.py b/conversion/hy_v4_flash.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7085221f7257c518b94387dd3225fd57b2699e --- /dev/null +++ b/conversion/hy_v4_flash.py @@ -0,0 +1,569 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Iterable + +import numpy as np +import torch + +from .base import ModelBase, gguf, logger +from .hy_v4 import HYV4Model + +# the hash multipliers are not stored in the checkpoint: the reference derives them from the +# Engram seed, the 1-based layer id and the compressed vocabulary size +ENGRAM_SEED_STRIDE = 10007 + + +@ModelBase.register("HYV4NextForCausalLM", "HYV4NextVLForConditionalGeneration") +@ModelBase.example("tencent/Hy4-Flash") +class HYV4FlashModel(HYV4Model): + """HY_V4_FLASH: hy_v4's iHC + gated MLA + learnable sink with a hybrid attention stack. + + The stack mixes "sparse" full-attention layers with sliding-window layers, in the order given + by layer_types rather than a fixed alternation. Both are MLA over the same latent geometry and + differ only in head count and rope base, so the head count is exported per layer and the window + layers get their own rope frequency. + + Added over hy_v4: sandwich norms (after the attention output and after the FFN) and routed + experts that run in a latent space reached by routed_expert_down_proj / _up_proj, while the + router and the shared expert stay at hidden_size. + + The MTP (nextn) draft block is exported as one extra sparse layer with no hyper-connections of + its own; it is fed the next token's embedding and the trunk's final hidden state. + + Dropped: the vision tower, which is converted separately as an mmproj. + """ + + model_arch = gguf.MODEL_ARCH.HY_V4_FLASH + + # the draft block is exported, and _engram_modify re-enters the normal path under a block index + # past the trunk. DeepseekV2Model.modify_tensors drops exactly that range when skip_mtp is set, + # which would silently lose most of the block. + skip_mtp = False + + # dropped subsystems, see the class docstring + DROP_PREFIXES = ("vit.",) + DROP_SUBSTRINGS = () + + # compressed_indexer tail -> the tensor the graph reads it as + INDEXER_MAP = { + "token_key_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_K, + "token_key_norm.weight": gguf.MODEL_TENSOR.INDEXER_K_NORM, + "key_value_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_VALUE, + "key_gate_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_GATE, + "intra_group_ape": gguf.MODEL_TENSOR.INDEXER_KPOOL_APE, + "key_norm.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_NORM, + "query_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_Q_B, + "head_weight_projection.weight": gguf.MODEL_TENSOR.INDEXER_PROJ, + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # the draft block is an extra block as far as tensor naming goes; block_count is what the + # loader reads as n_layer_all and it subtracts the nextn count back off + if not getattr(self, "no_mtp", False): + self.block_count += self._n_nextn() + self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count) + # Engram weights arrive one at a time but are written fused, so they wait here + self._engram_buf: dict[int, dict[str, torch.Tensor]] = {} + self._engram_tables: dict[int, torch.Tensor] = {} + + @classmethod + def filter_tensors(cls, item): + name = item[0] + if name.startswith(cls.DROP_PREFIXES) or any(s in name for s in cls.DROP_SUBSTRINGS): + return None + if name.startswith("model.mtp_layers."): + # hy_v4 drops the draft block; this model exports it, so skip that filter + return super(HYV4Model, cls).filter_tensors(item) + return super().filter_tensors(item) + + def _layer_types(self) -> list[str]: + cached = getattr(self, "_layer_types_cache", None) + if cached is not None: + return cached + layer_types = self.hparams.get("layer_types") + n_layer = self.hparams["num_hidden_layers"] + if not layer_types or len(layer_types) < n_layer: + raise ValueError("HY_V4_FLASH needs a layer_types entry per layer") + unknown = set(layer_types[:n_layer]) - {"sparse_attention", "sliding_attention"} + if unknown: + raise ValueError(f"HY_V4_FLASH unknown layer_types values: {sorted(unknown)}") + self._layer_types_cache = list(layer_types[:n_layer]) + return self._layer_types_cache + + # ---- Engram ------------------------------------------------------------------------------ + # + # Four n-gram hash modules, one per Engram layer. All of their buckets are packed into a single + # table, so each module's head offsets are rebased into it, matching deepseek41's layout. + + def _engram_enabled(self) -> bool: + return bool(self.hparams.get("engram_enable")) and bool(self.hparams.get("engram_layer_ids")) + + def _engram_ids(self) -> list[int]: + """The config's engram_layer_ids, 1-based, in ascending order.""" + ids = sorted(int(i) for i in self.hparams["engram_layer_ids"]) + n_layer = self.hparams["num_hidden_layers"] + for i in ids: + # 1-based: the tensors live at model.layers.{i-1}.engram_layer.* + if not 1 <= i <= n_layer: + raise ValueError(f"HY_V4_FLASH engram_layer_ids has {i}, outside 1..{n_layer}") + return ids + + def _engram_primes(self) -> dict[int, list[int]]: + """Per 1-based layer id, the 16 bucket counts flattened from their [ngram][head] nesting.""" + raw = self.hparams.get("engram_layer_head_vocab_sizes") or {} + n_gram = self.hparams["engram_max_ngram_size"] + n_head = self.hparams["engram_n_head_per_ngram"] + out = {} + for i in self._engram_ids(): + # the keys are strings in the config + groups = raw.get(str(i)) or raw.get(i) + if groups is None: + raise ValueError(f"HY_V4_FLASH engram_layer_head_vocab_sizes has no entry for layer {i}") + if len(groups) != n_gram - 1 or any(len(g) != n_head for g in groups): + raise ValueError( + f"HY_V4_FLASH engram layer {i}: expected {n_gram - 1} groups of {n_head} bucket " + f"counts, got {[len(g) for g in groups]}") + out[i] = [int(p) for g in groups for p in g] + return out + + def _engram_vocab_map(self) -> tuple[list[int], int]: + """The token -> compressed id map, extended by identity, and the compressed vocab size. + + The map covers only the source tokenizer, which is shorter than the model's vocabulary. The + reference extends it by identity, which puts the trailing reserved ids outside the + compressed range; they hash to a row anyway because the hash is taken modulo the bucket + count, so they stay in range but are not reachable by any trained token. + """ + path = Path(self.dir_model) / "engram_vocab_map.npz" + if not path.is_file(): + raise FileNotFoundError(f"HY_V4_FLASH engram needs {path}") + with np.load(path) as z: + table = z["lookup_table"].astype(np.int64) + meta = json.loads(bytes(z["metadata"]).decode("utf-8").rstrip("\x00")) + + compressed = int(meta["compressed_vocab_size"]) + if int(table.max()) + 1 > compressed: + raise ValueError("HY_V4_FLASH engram lookup table exceeds its compressed vocab size") + if int(meta["engram_seed"]) != int(self.hparams.get("engram_seed", 0)): + raise ValueError("HY_V4_FLASH engram seed disagrees between the config and the vocab map") + + n_vocab = self.hparams["vocab_size"] + token_map = list(map(int, table)) + token_map += list(range(len(token_map), n_vocab)) + return token_map, compressed + + def _engram_multipliers(self, layer_id: int, compressed: int) -> list[int]: + seed = int(self.hparams.get("engram_seed", 0)) + n_gram = self.hparams["engram_max_ngram_size"] + bound = max(1, (np.iinfo(np.int64).max // compressed) // 2) + rng = np.random.default_rng(seed + ENGRAM_SEED_STRIDE*layer_id) + return [int(m) for m in rng.integers(0, bound, size=n_gram)*2 + 1] + + def _engram_set_gguf_parameters(self): + hparams = self.hparams + ids = self._engram_ids() + primes = self._engram_primes() + token_map, compressed = self._engram_vocab_map() + + n_gram = hparams["engram_max_ngram_size"] + n_head = hparams["engram_n_head_per_ngram"] + head_dim, rem = divmod(hparams["engram_n_embed_per_ngram"], n_head) + if rem: + raise ValueError("HY_V4_FLASH engram_n_embed_per_ngram is not a multiple of the head count") + + # offsets rebase each module's buckets into the single shared table; row ids are int32, so + # the loader rejects a table whose last bucket ends past INT32_MAX + offsets: list[int] = [] + multipliers: list[int] = [] + base = 0 + for i in ids: + for p in primes[i]: + offsets.append(base) + base += p + multipliers += self._engram_multipliers(i, compressed) + if base > np.iinfo(np.int32).max: + raise ValueError(f"HY_V4_FLASH engram table needs {base} rows, past the int32 row id limit") + + w = self.gguf_writer + w.add_ple_layers([i - 1 for i in ids]) + w.add_ple_ngram_size(n_gram) + w.add_ple_heads_per_ngram(n_head) + w.add_embedding_length_per_layer_input(head_dim) + w.add_ple_layer_multipliers(multipliers) + w.add_ple_head_offsets(offsets) + w.add_ple_head_vocab_sizes([p for i in ids for p in primes[i]]) + w.add_engram_pad_token_id(hparams["engram_pad_id"]) + w.add_engram_token_map(token_map) + + logger.info( + "HY_V4_FLASH engram: %d module(s) at 0-based layers %s, %d-gram x %d heads x %d dims, " + "%d table rows, compressed vocab %d", + len(ids), [i - 1 for i in ids], n_gram, n_head, head_dim, base, compressed) + + def _n_nextn(self) -> int: + return int(self.hparams.get("num_nextn_predict_layers", 0) or 0) + + def _layer_type_of(self, bid: int) -> str: + """Layer type of any block, including the draft one. + + A draft block defaults to a sparse layer that owns an indexer, which is the shape the + checkpoints are exported with, and `mtp_layer_types` overrides it per draft layer. The + graph only drives a sparse draft block, so refuse anything else rather than write a file + whose head count and rope would silently disagree with it. + """ + n_layer = self.hparams["num_hidden_layers"] + if bid < n_layer: + return self._layer_types()[bid] + + types = self.hparams.get("mtp_layer_types") or [] + if not types: + return "sparse_attention" + + t = types[min(bid - n_layer, len(types) - 1)] + if t != "sparse_attention": + raise ValueError( + f"HY_V4_FLASH: mtp_layer_types gives {t!r} for draft block {bid}, " + "but only 'sparse_attention' draft blocks are supported") + return t + + def _rope_for(self, layer_type: str) -> dict: + params = self.hparams.get("rope_parameters") + if not isinstance(params, dict) or layer_type not in params: + raise ValueError(f"HY_V4_FLASH needs rope_parameters[{layer_type!r}]") + return params[layer_type] + + def set_gguf_parameters(self): + hparams = self.hparams + layer_types = self._layer_types() + is_swa = [t == "sliding_attention" for t in layer_types] + + if not any(is_swa) or all(is_swa): + raise ValueError("HY_V4_FLASH expects a mix of sparse and sliding attention layers") + + # The graph applies the sandwich post-norms on every layer unconditionally, so refuse a + # config that asks for either of them to be skipped: the tensors ship in both cases, so + # the file would convert cleanly and then quietly compute something else. + if not hparams.get("sandwich_norm", False): + raise ValueError("HY_V4_FLASH expects sandwich_norm, the graph always applies the post-norms") + if hparams.get("dsa_skip_attn_post_norm", False): + raise ValueError( + "HY_V4_FLASH: dsa_skip_attn_post_norm is not supported - the graph applies " + "attn_post_norm on the sparse layers too") + + # the base reads rope_parameters["full_attention"], which this config does not have: + # its non-sliding entry is keyed "sparse_attention". Without this the sparse layers + # would silently fall back to the default rope base. + sparse_rope = self._rope_for("sparse_attention") + window_rope = self._rope_for("sliding_attention") + + # hy_v4 warns that it drops the draft block. This model exports it, so keep the key out of + # sight for that one call rather than let the warning mislead. + n_nextn = self.hparams.pop("num_nextn_predict_layers", None) + try: + super().set_gguf_parameters() + finally: + if n_nextn is not None: + self.hparams["num_nextn_predict_layers"] = n_nextn + + self.gguf_writer.add_rope_freq_base(sparse_rope["rope_theta"]) + + # per-layer head count: the window layers carry swa_num_attention_heads + n_head = hparams["num_attention_heads"] + n_head_swa = hparams["swa_num_attention_heads"] + self.gguf_writer.remove_key( + gguf.Keys.Attention.HEAD_COUNT.format(arch=self.gguf_writer.arch)) + # the arrays are read over n_layer_all, so the draft block needs an entry too: it is a + # sparse layer, so the global head count and no window + is_swa_all = is_swa + [False]*self._n_nextn() + self.gguf_writer.add_head_count( + [n_head_swa if swa else n_head for swa in is_swa_all]) + + # the base already derives rope.freq_base_swa from rope_parameters["sliding_attention"] + self.gguf_writer.add_sliding_window(hparams["sliding_window"]) + self.gguf_writer.add_sliding_window_pattern(is_swa_all) + + # routed experts run here, the router and the shared expert stay at hidden_size + latent = hparams.get("routed_expert_hidden_size") + if latent: + self.gguf_writer.add_expert_latent_length(latent) + + if self._n_nextn() and not getattr(self, "no_mtp", False): + self.gguf_writer.add_nextn_predict_layers(self._n_nextn()) + + if self._indexer_enabled(): + # the base writes head_count / key_length / top_k / types off indexer_is_full(); the + # pool size is this model's compress_ratio, and the current partial group is always kept + ratio = hparams["compressed_indexer_compress_ratio"] + self.gguf_writer.add_indexer_kpool(ratio) + self.gguf_writer.add_indexer_kpool_select_tail(True) + + # the reference's own config check: the candidate budget is the group budget expanded + group_topk = hparams.get("compressed_indexer_group_topk") + candidate = hparams.get("compressed_indexer_candidate_topk") + if group_topk and candidate and group_topk * ratio != candidate: + raise ValueError( + f"HY_V4_FLASH indexer: candidate_topk {candidate} != " + f"group_topk {group_topk} x compress_ratio {ratio}") + if hparams["index_topk"] % ratio: + raise ValueError( + f"HY_V4_FLASH indexer: index_topk {hparams['index_topk']} is not a multiple " + f"of compress_ratio {ratio}") + logger.info( + "HY_V4_FLASH indexer: %d pooled groups of %d, keeping the best %d plus the " + "current group (index_topk %d)", + sum(self.indexer_is_full()), ratio, hparams["index_topk"] // ratio, + hparams["index_topk"]) + + if self._engram_enabled(): + self._engram_set_gguf_parameters() + + self._check_mla_geometry() + + logger.info( + "HY_V4_FLASH: %d sparse (%d heads, rope_theta %g) + %d sliding " + "(%d heads, rope_theta %g, window %d) layers", + is_swa.count(False), n_head, sparse_rope["rope_theta"], + is_swa.count(True), n_head_swa, window_rope["rope_theta"], + hparams["sliding_window"], + ) + if hparams.get("engram_layer_ids") and not self._engram_enabled(): + logger.warning( + "HY_V4_FLASH: engram_enable is off, dropping %d Engram layer(s)", + len(hparams["engram_layer_ids"])) + if hparams.get("use_compressed_indexer") and not self._indexer_enabled(): + logger.warning( + "HY_V4_FLASH: dropping the compressed indexer - the sparse layers will " + "attend their whole context instead of the top %s tokens", + hparams.get("index_topk"), + ) + + def _check_mla_geometry(self): + """The window layers must share the sparse layers' MLA geometry. + + Only the head count may differ: the graph keeps one latent cache for both layer types + and reads a single set of MLA dimensions. + """ + hparams = self.hparams + for sparse_key, window_key in ( + ("qk_nope_head_dim", "swa_qk_nope_head_dim"), + ("qk_rope_head_dim", "swa_qk_rope_head_dim"), + ("v_head_dim", "swa_v_head_dim"), + ("qk_head_dim", "swa_qk_head_dim"), + ("kv_lora_rank", "swa_kv_lora_rank"), + ): + if window_key not in hparams: + continue + if hparams[window_key] != hparams[sparse_key]: + raise NotImplementedError( + f"HY_V4_FLASH needs one MLA geometry for both layer types, but " + f"{window_key}={hparams[window_key]} != {sparse_key}={hparams[sparse_key]}" + ) + + def _indexer_enabled(self) -> bool: + return bool(self.hparams.get("use_dsa")) and bool(self.hparams.get("use_compressed_indexer")) + + def indexer_is_full(self) -> list[bool] | None: + """Which layers own a k-pool indexer. + + Derived from layer_types, not from indexer_types: the config marks all 42 layers "full", + which there means the layer carries an indexer *config*, while only the sparse layers + actually hold compressed_indexer weights. llama.cpp's flag means "owns one". + """ + if not self._indexer_enabled(): + return None + n_all = self.hparams["num_hidden_layers"] + self._n_nextn() + return [self._layer_type_of(i) == "sparse_attention" for i in range(n_all)] + + def prepare_tensors(self): + """Validate against this model's own indexer, then skip hy_v4's check. + + hy_v4 looks for the lightning indexer's `self_attn.indexer.*`; this model instead carries + `self_attn.compressed_indexer.*` on its sparse layers, so the inherited check would reject + every file. + """ + self.hparams["num_key_value_heads"] = self.hparams["num_attention_heads"] + + is_full = self.indexer_is_full() + if is_full is not None: + want = set(self.INDEXER_MAP) + n_layer = self.hparams["num_hidden_layers"] + present: dict[int, set[str]] = {} + for name in self.model_tensors: + head, sep, tail = name.partition(".self_attn.compressed_indexer.") + if not sep: + continue + # the draft block carries its own indexer, under a different prefix + if head.startswith("model.layers."): + present.setdefault(int(head.split(".")[2]), set()).add(tail) + elif head.startswith("model.mtp_layers."): + present.setdefault(n_layer + int(head.split(".")[2]), set()).add(tail) + for il, expect in enumerate(is_full): + seen = present.get(il, set()) + if expect and seen != want: + raise ValueError( + f"HY_V4_FLASH layer {il} owns an indexer but is missing " + f"{sorted(want - seen)}" + (f" and carries unexpected {sorted(seen - want)}" + if seen - want else "")) + if not expect and seen: + raise ValueError( + f"HY_V4_FLASH layer {il} owns no indexer but carries {sorted(seen)}") + + # straight to the grandparent: hy_v4's own validation does not apply here + super(HYV4Model, self).prepare_tensors() + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int): + # the graph feeds these straight to ggml_add / ggml_mul as the second operand, which has no + # f16 kernel. deepseek41 keeps engram_gate f32 for the same reason; all three are tiny. + if new_name.endswith((".engram_gate.weight", ".engram_kv_b.weight", ".engram_hc_scale.weight")): + return gguf.GGMLQuantizationType.F32 + # same for the pooled-key position bias, which is a ggml_add operand. glm keeps every + # indexer_compressor_ tensor f32; here the norms already fall under the base class's + # *_norm.weight rule and the rest are matmul operands, so only the ape needs it. + if new_name.endswith(".indexer_compressor_ape.weight"): + return gguf.GGMLQuantizationType.F32 + # The router picks which experts fire, so it stays f32 like every other arch's. The base + # class's rule for it matches the tensor name against the *source* layer id, which no + # longer agrees with the name once the draft block has been renumbered into the trunk's + # range - so without this the draft block's router alone would ship at the source dtype. + if new_name.endswith((".ffn_gate_inp.weight", ".ffn_gate_inp_shexp.weight")): + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def _engram_modify(self, data_torch: torch.Tensor, name: str, + bid: int | None) -> Iterable[tuple[str, torch.Tensor]]: + """Fuse a layer's Engram weights into the tensors the graph reads. + + The per-hc key projections and the single value projection become one matmul plus one bias, + and the two gate norms multiply into one, both matching deepseek41's fused layout. Nothing + is emitted until a group is complete, because the fused tensor needs every part. + """ + if bid is None: + raise ValueError(f"HY_V4_FLASH: engram tensor without a layer id: {name}") + + hc = self.hparams["hc_mult"] + n_head = self.hparams["engram_n_head_per_ngram"] * (self.hparams["engram_max_ngram_size"] - 1) + + buf = self._engram_buf.setdefault(bid, {}) + tail = name.split(".engram_layer.", 1)[1] + buf[tail] = data_torch + + tn = self.format_tensor_name + T = gguf.MODEL_TENSOR + + def ready(*names) -> bool: + return all(n in buf for n in names) + + def take(*names): + return [buf.pop(n) for n in names] + + # the fused matmul: hc key projections then the value projection, which is the order the + # graph's views assume + kv_parts = [f"key_projs.{c}.weight" for c in range(hc)] + ["value_proj.weight"] + if ready(*kv_parts): + yield tn(T.ENGRAM_KV, bid), torch.cat(take(*kv_parts), dim=0) + + kvb_parts = [f"key_projs.{c}.bias" for c in range(hc)] + ["value_proj.bias"] + if ready(*kvb_parts): + yield tn(T.ENGRAM_KV_B, bid), torch.stack(take(*kvb_parts), dim=0) + + # engram_gate folds the key and query norms, as deepseek41 does + gate_parts = [f"norm_key.{c}.weight" for c in range(hc)] + [f"norm_query.{c}.weight" for c in range(hc)] + if ready(*gate_parts): + parts = take(*gate_parts) + yield tn(T.ENGRAM_GATE, bid), torch.stack( + [parts[c]*parts[hc + c] for c in range(hc)], dim=0) + + norm_parts = [f"lookup_per_head_norms.{c}.weight" for c in range(n_head)] + if ready(*norm_parts): + yield tn(T.ENGRAM_LOOKUP_NORM, bid), torch.stack(take(*norm_parts), dim=0) + + scale_parts = [f"unified_per_hc_scales.{c}" for c in range(hc)] + if ready(*scale_parts): + yield tn(T.ENGRAM_HC_SCALE, bid), torch.stack(take(*scale_parts), dim=0) + + if ready("unified_pre_gamma"): + yield tn(T.ENGRAM_PRE_GAMMA, bid), take("unified_pre_gamma")[0] + + # every module's buckets share one table, concatenated in layer order, so it can only be + # written once the last module has arrived + if ready("multi_head_embedding.embedding.weight"): + self._engram_tables[bid] = take("multi_head_embedding.embedding.weight")[0] + want = [i - 1 for i in self._engram_ids()] + if all(i in self._engram_tables for i in want): + tables = [self._engram_tables.pop(i) for i in want] + yield (tn(T.PER_LAYER_TOKEN_EMBD), + tables[0] if len(tables) == 1 else torch.cat(tables, dim=0)) + + NEXTN_MAP = { + "eh_proj.weight": gguf.MODEL_TENSOR.NEXTN_EH_PROJ, + "enorm.weight": gguf.MODEL_TENSOR.NEXTN_ENORM, + "hnorm.weight": gguf.MODEL_TENSOR.NEXTN_HNORM, + "final_layernorm.weight": gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM, + } + + def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]: + if name.startswith("model.mtp_layers."): + if not self._n_nextn() or getattr(self, "no_mtp", False): + return + parts = name.split(".", 3) + nbid = self.hparams["num_hidden_layers"] + int(parts[2]) + tail = parts[3] + key = self.NEXTN_MAP.get(tail) + if key is not None: + yield self.format_tensor_name(key, nbid), data_torch + return + # the rest of the block is an ordinary sparse layer, so re-enter under its block index + yield from self.modify_tensors(data_torch, f"model.layers.{nbid}.{tail}", nbid) + return + + if ".compressed_indexer." in name: + # dropped wholesale when the indexer is off, so the GGUF stays loadable as a + # full-attention model + if not self._indexer_enabled(): + return + tail = name.split(".compressed_indexer.", 1)[1] + key = self.INDEXER_MAP.get(tail) + if key is None: + raise ValueError(f"HY_V4_FLASH: unmapped compressed_indexer tensor {name}") + # intra_group_ape is numpy [kpool, head_dim], which gguf writes as ne (head_dim, kpool) + # already, so no transpose is needed anywhere here + yield self.format_tensor_name(key, bid), data_torch + return + + if ".engram_layer." in name: + if not self._engram_enabled(): + return + yield from self._engram_modify(data_torch, name, bid) + return + + # the base splits kv_b_proj with one global head count; here the sliding-window + # layers carry swa_num_attention_heads over the same MLA geometry, so the split + # has to read the head count of this layer + if name.endswith("kv_b_proj.weight") and bid is not None: + hparams = self.hparams + n_head = (hparams["swa_num_attention_heads"] + if self._layer_type_of(bid) == "sliding_attention" + else hparams["num_attention_heads"]) + v_head_dim = hparams["v_head_dim"] + qk_nope_head_dim = hparams["qk_nope_head_dim"] + + expected = n_head * (v_head_dim + qk_nope_head_dim) + if data_torch.shape[0] != expected: + raise ValueError( + f"HY_V4_FLASH layer {bid}: {name} has {data_torch.shape[0]} rows, " + f"expected {expected} = {n_head} heads x ({qk_nope_head_dim} + {v_head_dim})" + ) + + kv_b = data_torch.view(n_head, qk_nope_head_dim + v_head_dim, data_torch.shape[-1]) + k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1) + k_b = k_b.transpose(1, 2) + + tn = self.format_tensor_name + yield from ModelBase.modify_tensors(self, k_b, tn(gguf.MODEL_TENSOR.ATTN_K_B, bid), bid) + yield from ModelBase.modify_tensors(self, v_b, tn(gguf.MODEL_TENSOR.ATTN_V_B, bid), bid) + return + + yield from super().modify_tensors(data_torch, name, bid) diff --git a/conversion/hy_v4_flash_vision.py b/conversion/hy_v4_flash_vision.py new file mode 100644 index 0000000000000000000000000000000000000000..f65313396b4434d7c91f7fe3cfb9500c66ba091a --- /dev/null +++ b/conversion/hy_v4_flash_vision.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import Callable, Iterable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import MmprojModel, ModelBase, gguf + + +@ModelBase.register("HYV4NextVLForConditionalGeneration") +@ModelBase.example("tencent/Hy4-Flash") +class HYV4FlashVisionModel(MmprojModel): + """Vision tower of HY_V4_FLASH: a SigLIP-shaped encoder with a rmsnorm_mlp_adapter projector. + + The encoder is pre-norm with LayerNorm, biased qkv and a gelu ffn, and has no rope: positions + come from a learned 128x128 grid that the encoder bilinearly resamples to the patch grid. + + The projector merges each 2x2 patch block with a strided conv2d, runs a 1x1 conv2d to the text + hidden size and appends one learned newline embedding to every output row. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + assert self.hparams_vision is not None + # there is no image_size, the position-embedding grid is max_image_size / patch_size + self.hparams_vision["image_size"] = self.hparams_vision.get("max_image_size", 2048) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + assert self.hparams_vision is not None + vcfg = self.hparams_vision + projector_type = vcfg.get("projector_type") + if projector_type != "rmsnorm_mlp_adapter": + raise ValueError(f"unsupported projector_type {projector_type!r}") + self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.HY_V4_FLASH) + self.gguf_writer.add_vision_use_gelu(True) + # rms_norm_eps is also the LayerNorm eps of the encoder blocks + self.gguf_writer.add_vision_attention_layernorm_eps(vcfg.get("rms_norm_eps", 1e-5)) + self.gguf_writer.add_vision_spatial_merge_size(vcfg.get("spatial_merge_size", 2)) + self.gguf_writer.add_vision_min_pixels(int(self.preprocessor_config["min_pixels"])) + self.gguf_writer.add_vision_max_pixels(int(self.preprocessor_config["max_pixels"])) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + + if not name.startswith("vit."): + return None + + return super().filter_tensors(item) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # row 0 of the position embedding is an unused CLS slot, the reference resamples rows 1: + if "position_embedding" in name: + data_torch = data_torch[1:] + yield from super().modify_tensors(data_torch, name, bid) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # force conv weights to F32 or F16 to avoid BF16 IM2COL issues on Metal + if ("mm.0." in new_name or "mm.2." in new_name) and new_name.endswith(".weight"): + return gguf.GGMLQuantizationType.F16 if self.ftype == gguf.LlamaFileType.MOSTLY_F16 else gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) diff --git a/conversion/hy_v4_next_dfly.py b/conversion/hy_v4_next_dfly.py new file mode 100644 index 0000000000000000000000000000000000000000..c3765369967e76efaddf552b5993faafd7ffff69 --- /dev/null +++ b/conversion/hy_v4_next_dfly.py @@ -0,0 +1,887 @@ +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import math +import os +import subprocess +import sys +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Iterable + +import numpy as np +import torch + +from .base import LazyTorchTensor, ModelBase, ModelType, TextModel, get_model_architecture, gguf, logger + +if TYPE_CHECKING: + from torch import Tensor + +# the AngelSpec and vLLM commits this schema was derived from; recorded, not detected +ANGELSPEC_COMMIT = "368069f22d8d3f2ad07ca6dd288e840046bdc63c" +VLLM_COMMIT = "ebc72e673771959ac921376c906e183e72c74fc9" + +DEFAULT_SOURCE = "converter-declared value; training provenance unconfirmed" +TARGET_ARCHES = ("HYV4NextForCausalLM", "HYV4NextVLForConditionalGeneration") +# the only fields that may hold an int where a float is expected +FLOAT_FIELDS = ("rms_norm_eps", "rope_theta") +ABSENT = "" + + +def is_hy4_dfly_config(hparams: dict[str, Any]) -> bool: + """A HY4-Next DFly draft config, which only --dfly converts correctly.""" + return (hparams.get("architectures") == ["DSparkDraftModel"] and hparams.get("attention_type") == "mla" + and ("target_kv_layers" in hparams or "target_index_layer" in hparams)) + + +def _same(actual: Any, expected: Any, numeric: bool = False) -> bool: + # exact JSON types at every level, so 1 is not True and 3072.0 is not 3072 + if numeric and type(actual) in (int, float): + return actual == expected + if type(actual) is not type(expected): + return False + if isinstance(expected, list): + return len(actual) == len(expected) and all(_same(a, e) for a, e in zip(actual, expected)) + if isinstance(expected, dict): + return actual.keys() == expected.keys() and all(_same(actual[k], v, k in FLOAT_FIELDS) for k, v in expected.items()) + return actual == expected + + +def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ValueError(f"duplicate key {key!r}") + out[key] = value + return out + + +def _load_json(path: Path) -> Any: + try: + with open(path, "r", encoding="utf-8") as f: + return json.load(f, object_pairs_hook=_unique_keys) + except ValueError as e: + raise ValueError(f"{path}: {e}") from None + + +def _weight_map(index: Path) -> dict[str, str]: + data = _load_json(index) + weight_map = data.get("weight_map") if isinstance(data, dict) else None + if not isinstance(weight_map, dict) or not all(isinstance(v, str) for v in weight_map.values()): + raise ValueError(f"{index}: no valid weight_map") + return weight_map + + +def _scan_safetensors(path: Path) -> dict[str, gguf.LocalTensor]: + """Strict header parse: unique keys, well-formed entries, in-range and non-overlapping data.""" + file_size = path.stat().st_size + with open(path, "rb") as f: + n = int.from_bytes(f.read(8), byteorder="little") + if file_size < 8 or n > file_size - 8: + raise ValueError(f"{path}: truncated safetensors header") + raw = f.read(n) + try: + # bytes would let json guess UTF-16/32 + header = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_keys) + except ValueError as e: + raise ValueError(f"{path}: bad safetensors header: {e}") from None + if not isinstance(header, dict): + raise ValueError(f"{path}: bad safetensors header") + + start = 8 + n + tensors: dict[str, gguf.LocalTensor] = {} + spans: list[tuple[int, int, str]] = [] + for name, meta in header.items(): + if name == "__metadata__": + continue + meta = meta if isinstance(meta, dict) else {} + dtype, shape, offsets = meta.get("dtype"), meta.get("shape"), meta.get("data_offsets") + if not (isinstance(dtype, str) and isinstance(shape, list) and all(type(d) is int and d >= 0 for d in shape) + and isinstance(offsets, list) and len(offsets) == 2 and all(type(o) is int for o in offsets)): + raise ValueError(f"{path}: malformed header entry for {name}") + begin, end = offsets + if not 0 <= begin <= end <= file_size - start: + raise ValueError(f"{path}: {name} data_offsets {offsets} are outside the {file_size - start}-byte data section") + torch_dtype = LazyTorchTensor._dtype_str_map.get(dtype) + if torch_dtype is not None and end - begin != math.prod(shape) * torch_dtype.itemsize: + raise ValueError(f"{path}: {name} data_offsets {offsets} hold {end - begin} bytes, {dtype} {shape} needs {math.prod(shape) * torch_dtype.itemsize}") + spans.append((begin, end, name)) + tensors[name] = gguf.LocalTensor(dtype=dtype, shape=tuple(shape), data_range=gguf.LocalTensorRange(path, start + begin, end - begin)) + + spans.sort() + for (_, end0, name0), (begin1, _, name1) in zip(spans, spans[1:]): + if begin1 < end0: + raise ValueError(f"{path}: the data of {name0} and {name1} overlap") + return tensors + + +def _sha256(path: Path, offset: int = 0, size: int | None = None) -> str: + h = hashlib.sha256() + left = path.stat().st_size - offset if size is None else size + with open(path, "rb") as f: + f.seek(offset) + while left > 0: + chunk = f.read(min(left, 64 << 20)) + if not chunk: + raise ValueError(f"{path}: short read") + h.update(chunk) + left -= len(chunk) + return h.hexdigest() + + +def _payload_sha256(t: gguf.LocalTensor) -> str: + return _sha256(t.data_range.filename, t.data_range.offset, t.data_range.size) + + +def _bf16(t: gguf.LocalTensor) -> np.ndarray: + return t.mmap_bytes().view(np.uint16).reshape(t.shape) + + +def _bf16_to_f32(bits: np.ndarray) -> np.ndarray: + return (bits.astype(np.uint32) << 16).view(np.float32) + + +def _copy_diff(draft: gguf.LocalTensor, target: gguf.LocalTensor, what: str, rows: int = 4096) -> dict[str, Any]: + # relL2 against the target norm over exact F32 values, summed in float64 + a = _bf16(draft).reshape(draft.shape[0], -1) + b = _bf16(target).reshape(target.shape[0], -1) + num = den = 0.0 + same = 0 + for r in range(0, a.shape[0], rows): + x, y = a[r:r + rows], b[r:r + rows] + same += int(np.count_nonzero(np.all(x == y, axis=1))) + fx = _bf16_to_f32(x).astype(np.float64) + fy = _bf16_to_f32(y).astype(np.float64) + num += float(np.sum((fx - fy) ** 2)) + den += float(np.sum(fy ** 2)) + if not (math.isfinite(num) and math.isfinite(den)): + raise ValueError(f"DFly shared copy {what} holds NaN or Inf values") + return {"rel_l2": math.sqrt(num / den) if den > 0 else None, "identical_rows": same, "rows": int(a.shape[0])} + + +def _repo_state() -> tuple[str, bool | None]: + # tracked changes only, without taking the index lock + git = ["git", "--no-optional-locks", "-C", str(Path(__file__).resolve().parent.parent)] + try: + head = subprocess.run([*git, "rev-parse", "HEAD"], capture_output=True, check=True, timeout=60).stdout + status = subprocess.run([*git, "status", "--porcelain", "--untracked-files=no"], capture_output=True, check=True, timeout=60).stdout + except (OSError, subprocess.SubprocessError): + return "unknown", None + return head.decode("utf-8", errors="replace").strip(), bool(status.strip()) + + +class HYV4NextDFlyModel(TextModel): + """HY4-Next DFly draft (HF DSparkDraftModel with MLA, vLLM method dfly) as a schema v1 GGUF. + + Only reached through --dfly and never registered, so the Qwen DSpark route keeps DSparkDraftModel. + Tensor names come from the explicit tables below, not from TensorNameMap: its block map lists + post_attention_layernorm under two tensor types and the winner depends on process state. + The embedding/lm_head copies are only checked against the target; the graph borrows the target's. + """ + + model_arch = gguf.MODEL_ARCH.HY_V4_NEXT_DFLY + + # the schema v1 production profile, compared exactly; tests override it with tiny dims + PROFILE: dict[str, Any] = { + "architectures": ["DSparkDraftModel"], + "model_type": "dspark", + "model_arch": "dflash", + "layer_arch": "dflash", + "attention_type": "mla", + "num_hidden_layers": 5, + "hidden_size": 3072, + "intermediate_size": 9216, + "num_attention_heads": 32, + "hidden_act": "silu", + "q_lora_rank": 1024, + "kv_lora_rank": 512, + "qk_nope_head_dim": 192, + "qk_rope_head_dim": 64, + "v_head_dim": 256, + "learnable_sink": True, + "gating_type": "elementwise", + "gated_mla": True, + "attn_post_proj_norm": True, + "target_kv_layers": [25, 29, 33, 37, 41], + "target_index_layer": [25, 29, 33, 37, 41], + "target_index_topk": 2048, + "mtp_fusion": "slot0", + "enable_hidden_correction": True, + "enable_confidence_head": True, + "markov_rank": 0, + "vocab_size": 120832, + "mask_token_id": 120009, + "max_position_embeddings": 1048576, + "rms_norm_eps": 1e-05, + "rope_parameters": { + "rope_theta": 10000000.0, + "rope_type": "default", + "mrope_section": [12, 10, 10], + "mrope_interleaved": True, + }, + } + # features this schema does not have: absent, or one of these values + PROFILE_UNSET: dict[str, tuple[Any, ...]] = { + "context_local_window": (None,), + "index_topk": (None,), + "context_kv_source_layers": (None, []), + "attentive_correction": (None, False), + "enable_hidden_correction_topk": (None, False), + "enable_path_selector": (None, False), + } + + # per-layer source key suffix -> GGUF tensor + LAYER_MAP: dict[str, gguf.MODEL_TENSOR] = { + "input_layernorm.weight": gguf.MODEL_TENSOR.ATTN_NORM, + "self_attn.q_a_proj.weight": gguf.MODEL_TENSOR.ATTN_Q_A, + "self_attn.q_a_layernorm.weight": gguf.MODEL_TENSOR.ATTN_Q_A_NORM, + "self_attn.q_b_proj.weight": gguf.MODEL_TENSOR.ATTN_Q_B, + "self_attn.kv_a_proj_with_mqa.weight": gguf.MODEL_TENSOR.ATTN_KV_A_MQA, + "self_attn.kv_a_layernorm.weight": gguf.MODEL_TENSOR.ATTN_KV_A_NORM, + "self_attn.learnable_sink_param": gguf.MODEL_TENSOR.ATTN_SINKS, + "self_attn.linear_gate.weight": gguf.MODEL_TENSOR.ATTN_GATE, + "self_attn.o_proj.weight": gguf.MODEL_TENSOR.ATTN_OUT, + # after o_proj, before the first residual + "self_attn.post_proj_norm.weight": gguf.MODEL_TENSOR.ATTN_POST_NORM, + # after the first residual, before the MLP + "post_attention_layernorm.weight": gguf.MODEL_TENSOR.FFN_NORM, + "mlp.gate_proj.weight": gguf.MODEL_TENSOR.FFN_GATE, + "mlp.up_proj.weight": gguf.MODEL_TENSOR.FFN_UP, + "mlp.down_proj.weight": gguf.MODEL_TENSOR.FFN_DOWN, + } + # split per head into ATTN_K_B and ATTN_V_B + KV_B = "self_attn.kv_b_proj.weight" + + # global source key -> GGUF tensor and suffix + GLOBAL_MAP: dict[str, tuple[gguf.MODEL_TENSOR, str]] = { + "final_norm.weight": (gguf.MODEL_TENSOR.OUTPUT_NORM, ".weight"), + "mtp_fusion.enorm.weight": (gguf.MODEL_TENSOR.DFLY_FUSION_ENORM, ".weight"), + "mtp_fusion.hnorm.weight": (gguf.MODEL_TENSOR.DFLY_FUSION_HNORM, ".weight"), + "mtp_fusion.eh_proj.weight": (gguf.MODEL_TENSOR.DFLY_FUSION_EH, ".weight"), + "mtp_fusion.gate": (gguf.MODEL_TENSOR.DFLY_FUSION_GATE, ".weight"), + "hidden_correction.hidden_norm.weight": (gguf.MODEL_TENSOR.DFLY_CORRECTION_HNORM, ".weight"), + "hidden_correction.embed_norm.weight": (gguf.MODEL_TENSOR.DFLY_CORRECTION_ENORM, ".weight"), + "hidden_correction.gate_proj.weight": (gguf.MODEL_TENSOR.DFLY_CORRECTION_GATE, ".weight"), + "hidden_correction.up_proj.weight": (gguf.MODEL_TENSOR.DFLY_CORRECTION_UP, ".weight"), + "hidden_correction.down_proj.weight": (gguf.MODEL_TENSOR.DFLY_CORRECTION_DOWN, ".weight"), + "confidence_head.proj.weight": (gguf.MODEL_TENSOR.DFLY_CONFIDENCE, ".weight"), + "confidence_head.proj.bias": (gguf.MODEL_TENSOR.DFLY_CONFIDENCE, ".bias"), + } + + # copies of the target's tensors (manifest label, target key): checked against the target, never written + SHARED_COPIES: dict[str, tuple[str, str]] = { + "embed_tokens.weight": ("embedding", "model.embed_tokens.weight"), + "lm_head.weight": ("lm_head", "lm_head.weight"), + } + + # 2-D tensors written F32; every 1-D tensor is F32 too + F32_OUTPUTS = ("dfly_confidence.weight",) + + def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, fname_out: Path, *, dfly_block_size: int, dfly_causal: bool, + accept_embedding_mismatch: bool = False, block_size_source: str | None = None, causal_source: str | None = None, + **kwargs: Any): + if ftype not in (gguf.LlamaFileType.MOSTLY_BF16, gguf.LlamaFileType.MOSTLY_F16): + raise ValueError(f"DFly: --outtype must be bf16 or f16, got {ftype.name}") + if type(dfly_block_size) is not int or not 2 <= dfly_block_size < 2**32: + raise ValueError(f"DFly: --dfly-block-size must be an integer in [2, 2**32), got {dfly_block_size!r}") + if dfly_causal is not True: + raise ValueError("DFly: --dfly-causal must be true, schema v1 does not support non-causal DFly") + for flag, text in (("--dfly-block-size-source", block_size_source), ("--dfly-causal-source", causal_source)): + if text is not None and not text.strip(): + raise ValueError(f"DFly: {flag} must not be empty") + target_dir = kwargs.get("target_model_dir") + if target_dir is None or not Path(target_dir).is_dir(): + raise ValueError(f"DFly: --target-model-dir must be the target model directory, got {target_dir}") + out = Path(fname_out) + if out.suffix != ".gguf" or "{" in out.name or "}" in out.name or out.is_dir(): + raise ValueError(f"DFly: the output must be a .gguf file path without a name template, got {fname_out}") + + self._source_dir = Path(dir_model) + self._target_dir = Path(target_dir) + self._block_size = dfly_block_size + self._accept_mismatch = accept_embedding_mismatch + self._block_size_source = block_size_source or DEFAULT_SOURCE + self._causal_source = causal_source or DEFAULT_SOURCE + + # everything below reads only config.json, the index and the safetensors headers + self._check_source_files() + self._cfg = _load_json(self._source_dir / "config.json") + self._check_config() + cfg = self._cfg + self._dims = { + "L": cfg["num_hidden_layers"], "D": cfg["hidden_size"], "F": cfg["intermediate_size"], "H": cfg["num_attention_heads"], + "Rq": cfg["q_lora_rank"], "Rkv": cfg["kv_lora_rank"], "Dn": cfg["qk_nope_head_dim"], "Dr": cfg["qk_rope_head_dim"], + "Dv": cfg["v_head_dim"], "V": cfg["vocab_size"], + # null means the full hidden size + "C": cfg.get("hidden_correction_intermediate_size") or cfg["hidden_size"], + } + self._check_target() + self._src = self._scan_source() + + super().__init__(dir_model, ftype, fname_out, hparams=copy.deepcopy(cfg), **kwargs) + self._consumed: dict[str, list[str]] = {} + self._copies: dict[str, Any] = {} + self._f16_check: dict[str, Any] | None = None + self._dtype_summary: dict[str, dict[str, int]] = {} + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + # keep every source tensor under its own name; completeness is checked against the headers + return item + + def _check_source_files(self): + names = os.listdir(self._source_dir) + bins = sorted(n for n in names if n.startswith("pytorch_model") and n.endswith(".bin")) + if bins: + raise ValueError(f"DFly source {self._source_dir}: {bins} not supported, only model.safetensors") + for name in ("hadamard_packing.json", "hf_quant_config.json"): + if name in names: + raise ValueError(f"DFly source {self._source_dir}: {name} found, prism or quantized drafts are not supported") + if "model.safetensors" not in names and "model.safetensors.index.json" not in names: + raise ValueError(f"DFly source {self._source_dir}: no model.safetensors or model.safetensors.index.json") + + def _check_config(self): + cfg = self._cfg + where = f"DFly config {self._source_dir / 'config.json'}" + if not isinstance(cfg, dict): + raise ValueError(f"{where}: not a JSON object") + + errors: list[str] = [] + if "quantization_config" in cfg: + errors.append("quantization_config is set, quantized (FP8) drafts are not supported") + # TextModel would merge it over the checked fields + if "text_config" in cfg: + errors.append("text_config is set, a DFly draft config has no nested text config") + for field in ("dflash_block_size", "block_size"): + if field in cfg and not _same(cfg[field], self._block_size): + errors.append(f"{field} = {cfg[field]!r} conflicts with --dfly-block-size {self._block_size}") + for field in ("dflash_causal_attn", "causal", "is_causal"): + if field in cfg and cfg[field] is not True: + errors.append(f"{field} = {cfg[field]!r} conflicts with --dfly-causal true") + n_ctx = cfg.get("max_position_embeddings") + if type(n_ctx) is not int or n_ctx <= 0: + errors.append(f"max_position_embeddings must be a positive integer (it is context_length), got {n_ctx!r}") + if "target_kv_layers" not in cfg: + hint = f"; target_layer_ids {cfg['target_layer_ids']} are training taps, not KV layer ids" if "target_layer_ids" in cfg else "" + errors.append(f"target_kv_layers is required{hint}") + if "target_index_layer" not in cfg: + errors.append("target_index_layer is required") + for field in ("target_kv_layers", "target_index_layer"): + layers = cfg.get(field) + if field not in cfg: + continue + if not isinstance(layers, list) or not all(type(i) is int for i in layers): + errors.append(f"{field} must be a list of integers, got {layers!r}") + elif len(set(layers)) != len(layers): + errors.append(f"{field} {layers} has duplicate layer ids") + if "target_kv_layers" in cfg and "target_index_layer" in cfg and cfg["target_index_layer"] != cfg["target_kv_layers"]: + errors.append(f"target_index_layer {cfg['target_index_layer']} differs from target_kv_layers {cfg['target_kv_layers']}") + if errors: + raise ValueError(f"{where}: " + "; ".join(errors)) + + self._profile_check: list[dict[str, Any]] = [] + + def expect(field: str, actual: Any, expected: Any, ok: bool): + self._profile_check.append({"field": field, "expected": expected, "actual": actual, "result": "ok" if ok else "mismatch"}) + if not ok: + errors.append(f"{field} = {actual!r}, expected {expected!r}") + + for field, expected in self.PROFILE.items(): + actual = cfg.get(field, ABSENT) + expect(field, actual, expected, field in cfg and _same(actual, expected, field in FLOAT_FIELDS)) + for field, allowed in self.PROFILE_UNSET.items(): + actual = cfg.get(field, ABSENT) + expect(field, actual, f"absent or one of {list(allowed)}", field not in cfg or any(_same(actual, a) for a in allowed)) + for field in ("rope_theta", "rope_scaling"): + expect(field, cfg.get(field, ABSENT), ABSENT, field not in cfg) + if errors: + raise ValueError(f"{where} does not match the schema v1 production profile: " + "; ".join(errors)) + + # rules that need the dims checked above + D, V = cfg["hidden_size"], cfg["vocab_size"] + for field, allowed in ( + ("hidden_correction_intermediate_size", (None, D)), + ("draft_mlp_type", ("dense",)), + ("draft_vocab_size", (V,)), + ("qk_head_dim", (cfg["qk_nope_head_dim"] + cfg["qk_rope_head_dim"],)), + ): + actual = cfg.get(field, ABSENT) + expect(field, actual, f"absent or one of {list(allowed)}", field not in cfg or any(_same(actual, a) for a in allowed)) + if errors: + raise ValueError(f"{where} does not match the schema v1 production profile: " + "; ".join(errors)) + logger.info(f"DFly: config matches the schema v1 production profile ({len(self._profile_check)} checks)") + + def _target_tensor_files(self) -> dict[str, str]: + index = self._target_dir / "model.safetensors.index.json" + if index.is_file(): + return _weight_map(index) + names: dict[str, str] = {} + for part in ModelBase.get_model_part_names(self._target_dir, "model", ".safetensors"): + names.update(dict.fromkeys(_scan_safetensors(self._target_dir / part), part)) + return names + + def _target_tensor(self, name: str) -> tuple[gguf.LocalTensor, str]: + part = self._target_files.get(name) + tensors = _scan_safetensors(self._target_dir / part) if part is not None else {} + if name not in tensors: + raise ValueError(f"DFly target {self._target_dir}: no {name}" + (f" in {part}" if part is not None else "")) + return tensors[name], part + + def _check_target(self): + cfg, d = self._cfg, self._dims + top = _load_json(self._target_dir / "config.json") + tc = top.get("text_config", top) if isinstance(top, dict) else None + if not isinstance(tc, dict): + raise ValueError(f"DFly target {self._target_dir}: config.json has no text config") + self._target_config = top + arches = top.get("architectures") + for field, value in (("architectures", arches), ("text_config.architectures", tc.get("architectures", arches))): + if not (isinstance(value, list) and value and all(isinstance(a, str) for a in value)): + raise ValueError(f"DFly target {self._target_dir}: {field} must be a non-empty list of names, got {value!r}") + self._target_arch = get_model_architecture(top, ModelType.TEXT) + self._target_files = self._target_tensor_files() + self._structure_check: list[dict[str, Any]] = [] + errors: list[str] = [] + + def expect(field: str, actual: Any, expected: Any, ok: bool): + self._structure_check.append({"field": field, "expected": expected, "actual": actual, "result": "ok" if ok else "mismatch"}) + if not ok: + errors.append(f"{field} = {actual!r}, expected {expected!r}") + + expect("hadamard_packing.json", (self._target_dir / "hadamard_packing.json").is_file(), False, + not (self._target_dir / "hadamard_packing.json").is_file()) + expect("architectures", arches, f"first entry in {list(TARGET_ARCHES)}", arches[0] in TARGET_ARCHES) + expect("text architecture", self._target_arch, list(TARGET_ARCHES), self._target_arch in TARGET_ARCHES) + n_target = cfg.get("target_num_hidden_layers", ABSENT) + expect("draft target_num_hidden_layers", n_target, "an integer", type(n_target) is int) + expect("draft target_hidden_size", cfg.get("target_hidden_size", ABSENT), d["D"], _same(cfg.get("target_hidden_size"), d["D"])) + for field, expected in (("hidden_size", d["D"]), ("vocab_size", d["V"]), ("kv_lora_rank", d["Rkv"]), ("qk_rope_head_dim", d["Dr"]), + ("num_hidden_layers", n_target), ("index_topk", cfg["target_index_topk"])): + expect(f"text_config.{field}", tc.get(field, ABSENT), expected, _same(tc.get(field, ABSENT), expected)) + + n_layer = tc.get("num_hidden_layers") + layer_types, swa = tc.get("layer_types"), tc.get("swa_pattern") + for L in cfg["target_kv_layers"]: + in_range = type(n_layer) is int and 0 <= L < n_layer + expect(f"target layer {L} index", L, f"0 <= L < {n_layer}", in_range) + if not in_range: + continue + lt = layer_types[L] if isinstance(layer_types, list) and L < len(layer_types) else ABSENT + expect(f"text_config.layer_types[{L}]", lt, "sparse_attention", lt == "sparse_attention") + if swa is not None: + sp = swa[L] if isinstance(swa, list) and L < len(swa) else ABSENT + expect(f"text_config.swa_pattern[{L}]", sp, 0, _same(sp, 0)) + name = f"model.layers.{L}.self_attn.compressed_indexer.query_projection.weight" + expect(f"target tensor {name}", name in self._target_files, True, name in self._target_files) + + rope = tc.get("rope_parameters") + sparse = rope.get("sparse_attention") if isinstance(rope, dict) else None + theta = sparse.get("rope_theta", ABSENT) if isinstance(sparse, dict) else ABSENT + expect("text_config.rope_parameters.sparse_attention.rope_theta", theta, cfg["rope_parameters"]["rope_theta"], + _same(theta, float(cfg["rope_parameters"]["rope_theta"]), numeric=True)) + ratio, group = tc.get("compressed_indexer_compress_ratio", ABSENT), tc.get("compressed_indexer_group_topk", ABSENT) + expect("text_config.compressed_indexer_compress_ratio", ratio, 4, _same(ratio, 4)) + expect("text_config.compressed_indexer_group_topk", group, cfg["target_index_topk"] // 4, + type(group) is int and group * 4 == cfg["target_index_topk"]) + mask = cfg["mask_token_id"] + expect("mask_token_id", mask, f"0 <= id < {tc.get('vocab_size')}", type(tc.get("vocab_size")) is int and 0 <= mask < tc["vocab_size"]) + for field in ("bos_token_id", "eos_token_id", "pad_token_id"): + if field in cfg and field in tc: + expect(f"text_config.{field}", tc[field], cfg[field], _same(tc[field], cfg[field])) + name = self.SHARED_COPIES["embed_tokens.weight"][1] + expect(f"target tensor {name}", name in self._target_files, True, name in self._target_files) + if errors: + raise ValueError(f"DFly target {self._target_dir} does not fit this draft: " + "; ".join(errors)) + logger.info(f"DFly: target structure matches the draft ({len(self._structure_check)} checks)") + + def _source_shapes(self) -> dict[str, list[int]]: + d = self._dims + D, F, H, Rq, Rkv, Dn, Dr, Dv, C = (d[k] for k in ("D", "F", "H", "Rq", "Rkv", "Dn", "Dr", "Dv", "C")) + layer = { + "input_layernorm.weight": [D], + "self_attn.q_a_proj.weight": [Rq, D], + "self_attn.q_a_layernorm.weight": [Rq], + "self_attn.q_b_proj.weight": [H * (Dn + Dr), Rq], + "self_attn.kv_a_proj_with_mqa.weight": [Rkv + Dr, D], + "self_attn.kv_a_layernorm.weight": [Rkv], + self.KV_B: [H * (Dn + Dv), Rkv], + "self_attn.learnable_sink_param": [H], + "self_attn.linear_gate.weight": [H * Dv, D], + "self_attn.o_proj.weight": [D, H * Dv], + "self_attn.post_proj_norm.weight": [D], + "post_attention_layernorm.weight": [D], + "mlp.gate_proj.weight": [F, D], + "mlp.up_proj.weight": [F, D], + "mlp.down_proj.weight": [D, F], + } + shapes = {f"layers.{i}.{k}": v for i in range(d["L"]) for k, v in layer.items()} + shapes.update({ + "final_norm.weight": [D], + "mtp_fusion.enorm.weight": [D], + "mtp_fusion.hnorm.weight": [D], + "mtp_fusion.eh_proj.weight": [D, 2 * D], + "mtp_fusion.gate": [D], + "hidden_correction.hidden_norm.weight": [D], + "hidden_correction.embed_norm.weight": [D], + "hidden_correction.gate_proj.weight": [C, 2 * D], + "hidden_correction.up_proj.weight": [C, 2 * D], + "hidden_correction.down_proj.weight": [D, C], + "confidence_head.proj.weight": [1, D], + "confidence_head.proj.bias": [1], + }) + return shapes + + def _scan_source(self) -> dict[str, gguf.LocalTensor]: + index = self._source_dir / "model.safetensors.index.json" + weight_map = None + if index.is_file(): + weight_map = _weight_map(index) + self._parts = sorted(set(weight_map.values())) + else: + self._parts = ModelBase.get_model_part_names(self._source_dir, "model", ".safetensors") + tensors: dict[str, gguf.LocalTensor] = {} + found_in: dict[str, str] = {} + repeated: set[str] = set() + for part in self._parts: + for name, t in _scan_safetensors(self._source_dir / part).items(): + if name in tensors: + repeated.add(name) + tensors[name] = t + found_in[name] = part + if repeated: + raise ValueError(f"DFly source {self._source_dir}: tensors found in more than one shard: {sorted(repeated)}") + if weight_map is not None and weight_map != found_in: + diff = sorted(n for n in set(weight_map) | set(found_in) if weight_map.get(n) != found_in.get(n)) + raise ValueError(f"DFly source {index}: weight_map disagrees with the shard headers for {diff}") + + expected = self._source_shapes() + expected.update(dict.fromkeys(self.SHARED_COPIES, [self._dims["V"], self._dims["D"]])) + unknown = sorted(set(tensors) - set(expected)) + missing = sorted(set(expected) - set(tensors) - set(self.SHARED_COPIES)) + if unknown or missing: + raise ValueError(f"DFly source {self._source_dir}: unknown tensors {unknown}, missing tensors {missing}") + not_bf16 = [f"{n} ({t.dtype})" for n, t in sorted(tensors.items()) if t.dtype != "BF16"] + if not_bf16: + raise ValueError(f"DFly source {self._source_dir}: only BF16 tensors are supported, got {not_bf16}") + bad_shape = [f"{n} {list(t.shape)} (expected {expected[n]})" for n, t in sorted(tensors.items()) if list(t.shape) != expected[n]] + if bad_shape: + raise ValueError(f"DFly source {self._source_dir}: tensors with an unexpected shape: {bad_shape}") + return tensors + + def set_vocab(self): + self._set_target_vocab() + self.gguf_writer.add_mask_token_id(self._cfg["mask_token_id"]) + + def _set_target_vocab(self): + # the target's own vocab handler, run with dir_model pointing at the target + from . import get_model_class + target_cls = get_model_class(self._target_arch) + original_dir = self.dir_model + try: + self.dir_model = self._target_dir + target_cls.set_vocab(self) # ty: ignore[unresolved-attribute] + finally: + self.dir_model = original_dir + + def set_gguf_parameters(self): + # every key is written here: the base class would also write the GQA head_dim / num_key_value_heads + cfg, d, w = self._cfg, self._dims, self.gguf_writer + w.add_dfly_schema_version(1) + w.add_block_size(self._block_size) + w.add_causal_attention(True) + w.add_block_count(d["L"]) + w.add_context_length(cfg["max_position_embeddings"]) + w.add_embedding_length(d["D"]) + w.add_feed_forward_length(d["F"]) + w.add_head_count(d["H"]) + # absorbed MLA: one shared latent "head" + w.add_head_count_kv(1) + w.add_q_lora_rank(d["Rq"]) + w.add_kv_lora_rank(d["Rkv"]) + w.add_key_length(d["Rkv"] + d["Dr"]) + w.add_value_length(d["Rkv"]) + w.add_key_length_mla(d["Dn"] + d["Dr"]) + w.add_value_length_mla(d["Dv"]) + w.add_rope_dimension_count(d["Dr"]) + w.add_rope_freq_base(float(cfg["rope_parameters"]["rope_theta"])) + w.add_layer_norm_rms_eps(float(cfg["rms_norm_eps"])) + w.add_dfly_target_kv_layers(cfg["target_kv_layers"]) + w.add_dfly_target_index_layers(cfg["target_index_layer"]) + w.add_dfly_target_index_top_k(cfg["target_index_topk"]) + w.add_dfly_hidden_correction_length(d["C"]) + w.add_has_confidence_head(True) + w.add_dfly_mtp_fusion(cfg["mtp_fusion"]) + # the rope rows are written as they are; the graph rotates adjacent pairs like the target + w.add_dfly_rope_layout("norm_adjacent") + w.add_dfly_source_mrope_sections(cfg["rope_parameters"]["mrope_section"]) + w.add_file_type(self.ftype) + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool: + if new_name in self.F32_OUTPUTS: + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def _output_names(self, name: str) -> list[str]: + """GGUF names written for a source tensor: none for a shared copy, K and V for kv_b.""" + if name in self.SHARED_COPIES: + return [] + if name in self.GLOBAL_MAP: + key, suffix = self.GLOBAL_MAP[name] + return [self.format_tensor_name(key, suffix=suffix)] + parts = name.split(".", 2) + if len(parts) == 3 and parts[0] == "layers" and parts[1].isdecimal() and int(parts[1]) < self._dims["L"]: + bid, suffix = int(parts[1]), parts[2] + if suffix == self.KV_B: + return [self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_K_B, bid), self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_V_B, bid)] + if suffix in self.LAYER_MAP: + return [self.format_tensor_name(self.LAYER_MAP[suffix], bid)] + raise ValueError(f"DFly: no mapping for source tensor {name}") + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + names = self._output_names(name) + self._consumed[name] = names + if bid is not None and name == f"layers.{bid}.{self.KV_B}": + # per head: the first Dn rows are K, the next Dv rows are V + H, Dn, Dv = self._dims["H"], self._dims["Dn"], self._dims["Dv"] + kv_b = data_torch.view(H, Dn + Dv, data_torch.shape[-1]) + k_b, v_b = torch.split(kv_b, [Dn, Dv], dim=1) + return [(names[0], k_b.transpose(1, 2)), (names[1], v_b)] + return [(n, data_torch) for n in names] + + def _check_shared_copies(self): + copies: dict[str, Any] = {"accept_embedding_mismatch": self._accept_mismatch} + for src_name, (label, target_name) in self.SHARED_COPIES.items(): + rec: dict[str, Any] = {"source_key": src_name, "target_key": target_name} + copies[label] = rec + t = self._src.get(src_name) + if t is None: + rec["status"] = "absent" + logger.info(f"DFly: no {src_name} copy in the draft (absent)") + continue + tt, part = self._target_tensor(target_name) + rec.update({"shape": list(t.shape), "dtype": t.dtype, "target_file": part}) + if tt.shape != t.shape or tt.dtype != t.dtype: + raise ValueError(f"DFly shared copy {src_name} is {t.dtype} {list(t.shape)} but the target {target_name} is " + f"{tt.dtype} {list(tt.shape)}; this is not accepted even with --dfly-accept-embedding-mismatch") + # raw stored bytes, not converted values + rec["sha256"] = _payload_sha256(t) + rec["target_sha256"] = _payload_sha256(tt) + if rec["sha256"] == rec["target_sha256"]: + rec["status"] = "match" + logger.info(f"DFly: {src_name} copy matches the target {target_name}") + continue + if not self._accept_mismatch: + raise ValueError(f"DFly shared copy {src_name} differs from the target {target_name}: draft sha256 {rec['sha256']}, " + f"target sha256 {rec['target_sha256']}. The copy is never written; pass " + "--dfly-accept-embedding-mismatch to convert anyway and record it in the manifest") + rec["status"] = "mismatch_accepted" + rec.update(_copy_diff(t, tt, f"{src_name} or its target {target_name}")) + logger.warning(f"DFly: {src_name} copy differs from the target {target_name} (relL2 {rec['rel_l2']}, " + f"{rec['identical_rows']}/{rec['rows']} identical rows); accepted, recorded in the manifest") + self._copies = copies + + def _check_payloads(self): + nan_inf: list[str] = [] + overflow: list[str] = [] + stats: dict[str, dict[str, int]] = {} + to_f16 = self.ftype == gguf.LlamaFileType.MOSTLY_F16 + for name, t in self._src.items(): + if name in self.SHARED_COPIES: + continue + bits = _bf16(t) + # an all-ones exponent is NaN or Inf + if n := int(np.count_nonzero((bits & 0x7F80) == 0x7F80)): + nan_inf.append(f"{name} ({n})") + continue + outs = self._output_names(name) + if not to_f16 or len(t.shape) < 2 or outs[0] in self.F32_OUTPUTS: + continue + x = _bf16_to_f32(bits) + with np.errstate(over="ignore"): + y = x.astype(np.float16) + changed = y.astype(np.float32) != x + flushed = (y == 0) & (x != 0) + inf = np.isinf(y) + if len(outs) == 2: + # kv_b: K and V are disjoint row ranges of every head + H, Dn, Dv = self._dims["H"], self._dims["Dn"], self._dims["Dv"] + parts = [(outs[0], (slice(None), slice(0, Dn))), (outs[1], (slice(None), slice(Dn, Dn + Dv)))] + changed, flushed, inf = (m.reshape(H, Dn + Dv, -1) for m in (changed, flushed, inf)) + else: + parts = [(outs[0], (Ellipsis,))] + for out_name, sel in parts: + if n := int(np.count_nonzero(inf[sel])): + overflow.append(f"{out_name} ({n})") + stats[out_name] = {"rounded": int(np.count_nonzero(changed[sel])), "flushed_to_zero": int(np.count_nonzero(flushed[sel]))} + if nan_inf: + raise ValueError(f"DFly source tensors with NaN or Inf values: {nan_inf}") + if overflow: + raise ValueError(f"DFly: --outtype f16 would turn finite values into inf: {overflow}") + if to_f16: + self._f16_check = { + "rule": "rounded counts every element whose value changes, flushed_to_zero is included in it", + "tensors": stats, + "total": {"rounded": sum(s["rounded"] for s in stats.values()), + "flushed_to_zero": sum(s["flushed_to_zero"] for s in stats.values()), "overflow": 0}, + } + logger.info(f"DFly: BF16 -> F16 changes {self._f16_check['total']['rounded']} values, " + f"{self._f16_check['total']['flushed_to_zero']} of them to zero") + + def _check_outputs(self): + if len(self.gguf_writer.tensors) != 1: + raise ValueError("DFly: the output must be a single GGUF file") + written = self.gguf_writer.tensors[0] + d = self._dims + L, D, F, H, Rq, Rkv, Dn, Dr, Dv, C = (d[k] for k in ("L", "D", "F", "H", "Rq", "Rkv", "Dn", "Dr", "Dv", "C")) + mat = gguf.GGMLQuantizationType.BF16 if self.ftype == gguf.LlamaFileType.MOSTLY_BF16 else gguf.GGMLQuantizationType.F16 + + # numpy order, the reverse of the ggml ne + shapes = self._source_shapes() + expected: dict[str, list[int]] = {} + for i in range(L): + for suffix, key in self.LAYER_MAP.items(): + expected[self.format_tensor_name(key, i)] = shapes[f"layers.{i}.{suffix}"] + expected[self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_K_B, i)] = [H, Rkv, Dn] + expected[self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_V_B, i)] = [H, Dv, Rkv] + for src_name, (key, suffix) in self.GLOBAL_MAP.items(): + expected[self.format_tensor_name(key, suffix=suffix)] = shapes[src_name] + + missing, extra = sorted(set(expected) - set(written)), sorted(set(written) - set(expected)) + if missing or extra: + raise ValueError(f"DFly: output tensors differ from the schema: missing {missing}, extra {extra}") + bad = [] + for name, ti in written.items(): + want = gguf.GGMLQuantizationType.F32 if len(expected[name]) == 1 or name in self.F32_OUTPUTS else mat + if list(ti.shape) != expected[name] or ti.dtype != want: + bad.append(f"{name} {list(ti.shape)} {ti.dtype.name} (expected {expected[name]} {want.name})") + if bad: + raise ValueError(f"DFly: output tensors with an unexpected shape or type: {bad}") + unconsumed = sorted(set(self._src) - set(self._consumed)) + if unconsumed: + raise ValueError(f"DFly: source tensors that were never converted: {unconsumed}") + + # expected counts, from the config dims alone + per_layer = (3 * D + Rq * D + Rq + H * (Dn + Dr) * Rq + (Rkv + Dr) * D + Rkv + H * (Dn + Dv) * Rkv + H + + 2 * H * Dv * D + 3 * F * D) + want_counts = {"tensors": 16 * L + 12, "params": L * per_layer + 7 * D + 1 + 2 * D * D + 5 * C * D, + "f32_tensors": 6 * L + 8, "f32_params": L * (3 * D + Rq + Rkv + H) + 7 * D + 1} + f32 = [ti for ti in written.values() if ti.dtype == gguf.GGMLQuantizationType.F32] + counts = {"tensors": len(written), "params": sum(math.prod(ti.shape) for ti in written.values()), + "f32_tensors": len(f32), "f32_params": sum(math.prod(ti.shape) for ti in f32)} + if counts != want_counts: + raise ValueError(f"DFly: output counts {counts} differ from the config dims {want_counts}") + + for ti in written.values(): + s = self._dtype_summary.setdefault(ti.dtype.name, {"tensors": 0, "params": 0}) + s["tensors"] += 1 + s["params"] += math.prod(ti.shape) + logger.info(f"DFly: {counts['tensors']} tensors, {counts['params']} params, " + f"{counts['f32_tensors']} F32 tensors with {counts['f32_params']} params") + + def prepare_tensors(self): + self._check_shared_copies() + self._check_payloads() + super().prepare_tensors() + self._check_outputs() + + def _manifest_path(self) -> Path: + return self.fname_out.with_name(self.fname_out.name.removesuffix(".gguf") + ".manifest.json") + + def write(self): + # both files are written under temporary names, so a failed run keeps an earlier GGUF/manifest pair + out, manifest = self.fname_out, self._manifest_path() + part, tmp = out.with_name(out.name + ".part"), manifest.with_name(manifest.name + ".tmp") + self.fname_out = part + try: + super().write() + self._check_written(part) + self._write_manifest(tmp, part, out.name) + manifest.unlink(missing_ok=True) + os.replace(part, out) + os.replace(tmp, manifest) + except BaseException: + with contextlib.suppress(Exception): + self.gguf_writer.close() + for path in (part, tmp): + path.unlink(missing_ok=True) + raise + finally: + self.fname_out = out + logger.info(f"DFly: manifest written to {manifest}") + + def _check_written(self, path: Path): + # numpy's tofile does not report a failed final flush, so read the file back + reader = gguf.GGUFReader(path) + n_tensors = len(reader.tensors) + end = max((int(t.data_offset) + int(t.n_bytes) for t in reader.tensors), default=0) + del reader + if n_tensors != len(self.gguf_writer.tensors[0]) or end > path.stat().st_size: + raise ValueError(f"DFly: {path} is incomplete after writing") + + def _write_manifest(self, path: Path, gguf_path: Path, gguf_name: str): + written = self.gguf_writer.tensors[0] + kv = self.gguf_writer.kv_data[0] + commit, dirty = _repo_state() + target_index = self._target_dir / "model.safetensors.index.json" + + tensor_map = [] + for name, t in self._src.items(): + outs = self._consumed.get(name, []) + entry: dict[str, Any] = { + "source": name, "dtype": t.dtype, "shape": list(t.shape), "written": bool(outs), + "outputs": [{"name": n, "type": written[n].dtype.name, "ne": list(reversed(written[n].shape))} for n in outs], + } + if name in self.SHARED_COPIES: + entry["note"] = "shared copy: checked against the target, not written" + tensor_map.append(entry) + + manifest = { + "format": "hy_v4_next_dfly-manifest-1", + "converter": { + "repo_commit": commit, + "repo_dirty": dirty, + "design_baselines": { + "angelspec": ANGELSPEC_COMMIT, + "vllm": VLLM_COMMIT, + "note": "frozen references of plan section 2.1, not detected at conversion time", + }, + }, + "command": list(sys.argv), + "source": { + "dir": str(self._source_dir.resolve()), + "config": {"path": str((self._source_dir / "config.json").resolve()), "sha256": _sha256(self._source_dir / "config.json")}, + "weight_files": [{"file": p, "size": (self._source_dir / p).stat().st_size, "sha256": _sha256(self._source_dir / p)} + for p in self._parts], + "profile_check": self._profile_check, + }, + "block_size": {"value": self._block_size, "source": self._block_size_source}, + "causal": {"value": True, "source": self._causal_source}, + "target": { + "dir": str(self._target_dir.resolve()), + "architectures": self._target_config.get("architectures"), + "text_architecture": self._target_arch, + "config_sha256": _sha256(self._target_dir / "config.json"), + "index_sha256": _sha256(target_index) if target_index.is_file() else None, + "structure_check": self._structure_check, + }, + "tokenizer": { + "files": {f: _sha256(self._target_dir / f) for f in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja") + if (self._target_dir / f).is_file()}, + "pre": kv[gguf.Keys.Tokenizer.PRE].value if gguf.Keys.Tokenizer.PRE in kv else None, + "n_tokens": len(kv[gguf.Keys.Tokenizer.LIST].value) if gguf.Keys.Tokenizer.LIST in kv else None, + }, + "outtype": "bf16" if self.ftype == gguf.LlamaFileType.MOSTLY_BF16 else "f16", + "dtype_summary": self._dtype_summary, + "f16_check": self._f16_check, + "tensor_map": tensor_map, + "shared_copies": self._copies, + "output": {"file": gguf_name, "size": gguf_path.stat().st_size, "sha256": _sha256(gguf_path)}, + "training_pairing": "unverified", + "pairing_note": ("the structure checks passed; they do not prove that the draft was trained against this target, " + "and the hashes above only identify the files that were read"), + } + with open(path, "w", encoding="utf-8") as f: + json.dump(manifest, f, indent=2, allow_nan=False) + f.write("\n") diff --git a/convert_hf_to_gguf.py b/convert_hf_to_gguf.py index b863bccc5a242785912c84fb650fc45dd66ffef1..5ce87a980e6371df72aeb06a1292d55f4e86bf73 100755 --- a/convert_hf_to_gguf.py +++ b/convert_hf_to_gguf.py @@ -6,6 +6,7 @@ from __future__ import annotations import argparse import logging import os +import re import sys from pathlib import Path @@ -45,6 +46,68 @@ def split_str_to_n_bytes(split_str: str) -> int: return n +def dfly_block_size(value: str) -> int: + # int() would also take "8_0", "+8" or " 8" + if not re.fullmatch(r"[0-9]+", value) or not 2 <= int(value) < 2**32: + raise argparse.ArgumentTypeError(f"expected a decimal integer in [2, {2**32 - 1}], got {value!r}") + return int(value) + + +def check_dfly_args(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: + dfly_only = { + "--dfly-block-size": args.dfly_block_size is not None, + "--dfly-causal": args.dfly_causal is not None, + "--dfly-accept-embedding-mismatch": args.dfly_accept_embedding_mismatch, + "--dfly-block-size-source": args.dfly_block_size_source is not None, + "--dfly-causal-source": args.dfly_causal_source is not None, + } + if not args.dfly: + if given := [flag for flag, present in dfly_only.items() if present]: + parser.error(f"{', '.join(given)} can only be used with --dfly") + return + + errors = [f"--dfly requires {flag}" for flag, value in ( + ("--dfly-block-size", args.dfly_block_size), + ("--dfly-causal", args.dfly_causal), + ("--target-model-dir", args.target_model_dir), + ) if value is None] + if args.dfly_causal == "false": + errors.append("--dfly-causal false: schema v1 does not support non-causal DFly") + for flag, text in (("--dfly-block-size-source", args.dfly_block_size_source), ("--dfly-causal-source", args.dfly_causal_source)): + if text is not None and not text.strip(): + errors.append(f"{flag} must not be empty") + for flag, path in (("model", args.model), ("--target-model-dir", args.target_model_dir)): + # Path("") would be the current directory + if path is not None and not (path and Path(path).is_dir()): + errors.append(f"{flag} must be an existing directory, got {path!r}") + conflicts = { + "--mtp": args.mtp, "--dspark": args.dspark, "--no-mtp/--no-nextn": args.no_mtp, "--mmproj": args.mmproj, + "--remote": args.remote, "--mistral-format": args.mistral_format, "--vocab-only": args.vocab_only, + "--dry-run": args.dry_run, "--bigendian": args.bigendian, "--fuse-qkv": args.fuse_qkv, + "--fuse-gate-up-exps": args.fuse_gate_up_exps, "--fp8-as-q8": args.fp8_as_q8, + # writes an empty first shard, so the output becomes two files + "--no-tensor-first-split": args.no_tensor_first_split, + "--split-max-tensors": args.split_max_tensors != 0, "--split-max-size": args.split_max_size != "0", + } + errors += [f"--dfly cannot be combined with {flag}" for flag, present in conflicts.items() if present] + if args.outtype not in ("bf16", "f16"): + errors.append(f"--dfly needs --outtype bf16 or f16, got {args.outtype}") + # the manifest needs a plain file path; without --outfile the GGUF would land in the model directory + if args.outfile is None: + errors.append("--dfly requires --outfile") + elif args.outfile.suffix != ".gguf" or "{" in args.outfile.name or "}" in args.outfile.name or args.outfile.is_dir(): + errors.append(f"--outfile must be a .gguf file path without a name template, got {args.outfile}") + elif not args.outfile.parent.is_dir(): + errors.append(f"--outfile directory {args.outfile.parent} does not exist") + else: + out = args.outfile.resolve() + for flag, model_dir in (("model", args.model), ("--target-model-dir", args.target_model_dir)): + if model_dir is not None and out.is_relative_to(Path(model_dir).resolve()): + errors.append(f"--outfile {args.outfile} is inside the {flag} directory {model_dir}") + if errors: + parser.error("; ".join(errors)) + + def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Convert a huggingface model to a GGML compatible file") @@ -169,10 +232,35 @@ def parse_args() -> argparse.Namespace: "layer count to populate its GGUF." ), ) + parser.add_argument( + "--dfly", action="store_true", + help="Convert a HY4-Next DFly draft (DSparkDraftModel with MLA) as a hy_v4_next_dfly GGUF plus a .manifest.json. Needs --dfly-block-size, --dfly-causal, --target-model-dir, --outtype bf16|f16 and --outfile.", + ) + parser.add_argument( + "--dfly-block-size", type=dfly_block_size, default=None, + help="DFly: the training block size B, anchor included. Required with --dfly, no default.", + ) + parser.add_argument( + "--dfly-causal", choices=["true", "false"], default=None, + help="DFly: whether the draft was trained with causal block attention. Required with --dfly; only true is supported.", + ) + parser.add_argument( + "--dfly-accept-embedding-mismatch", action="store_true", + help="DFly: convert even if the draft's embedding/lm_head copy differs from the target's. The copy is never written; the mismatch is recorded in the manifest.", + ) + parser.add_argument( + "--dfly-block-size-source", type=str, default=None, + help="DFly: where --dfly-block-size comes from, written to the manifest", + ) + parser.add_argument( + "--dfly-causal-source", type=str, default=None, + help="DFly: where --dfly-causal comes from, written to the manifest", + ) args = parser.parse_args() if not args.print_supported_models and args.model is None: parser.error("the following arguments are required: model") + check_dfly_args(parser, args) return args @@ -286,6 +374,26 @@ def main() -> None: from conversion.deepseek import DeepseekV4DSparkModel model_class = DeepseekV4DSparkModel + dfly_kwargs = {} + if args.dfly: + if model_architecture != "DSparkDraftModel": + logger.error("--dfly is only supported for the HY4-Next DFly draft (DSparkDraftModel), got %s", model_architecture) + sys.exit(1) + from conversion.hy_v4_next_dfly import HYV4NextDFlyModel + model_class = HYV4NextDFlyModel + dfly_kwargs = dict( + dfly_block_size=args.dfly_block_size, + dfly_causal=args.dfly_causal == "true", + accept_embedding_mismatch=args.dfly_accept_embedding_mismatch, + block_size_source=args.dfly_block_size_source, + causal_source=args.dfly_causal_source, + ) + elif not is_mistral_format and model_architecture == "DSparkDraftModel": + from conversion.hy_v4_next_dfly import is_hy4_dfly_config + if is_hy4_dfly_config(hparams): + logger.error("this is a HY4-Next DFly draft; convert it with --dfly") + sys.exit(1) + if args.mtp or args.no_mtp: if not model_class.supports_mtp_export: logger.error("--mtp / --no-nextn are not supported for %s", model_architecture) @@ -308,6 +416,7 @@ def main() -> None: fuse_gate_up_exps=args.fuse_gate_up_exps, fp8_as_q8=args.fp8_as_q8, fuse_qkv=args.fuse_qkv, + **dfly_kwargs, ) if args.vocab_only: diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp index e4a878b828423957772250e19a9b4e2a100ccc3e..fc89fe7b9dca67d7d7c2120e241b4bde827152f5 100644 --- a/examples/speculative-simple/speculative-simple.cpp +++ b/examples/speculative-simple/speculative-simple.cpp @@ -25,6 +25,12 @@ int main(int argc, char ** argv) { return 1; } + // this loop decodes the draft as a plain model; draft-dfly runs in llama-server only + if (common_dfly_requested(params)) { + LOG_ERR("%s: draft-dfly is not supported here, use llama-server --spec-type draft-dfly\n", __func__); + return 1; + } + if (params.n_predict < -1) { LOG_ERR("%s: --n-predict must be >= -1\n", __func__); return 1; diff --git a/examples/speculative/speculative.cpp b/examples/speculative/speculative.cpp index 8f347b0d4eeedf27df83e31dcea7b9d94cb340d4..a51568abca35b338f963461b69fcff495392008a 100644 --- a/examples/speculative/speculative.cpp +++ b/examples/speculative/speculative.cpp @@ -45,6 +45,12 @@ int main(int argc, char ** argv) { return 1; } + // this loop decodes the draft as a plain model; draft-dfly runs in llama-server only + if (common_dfly_requested(params)) { + LOG_ERR("%s: draft-dfly is not supported here, use llama-server --spec-type draft-dfly\n", __func__); + return 1; + } + if (params.n_predict < -1) { LOG_ERR("%s: --n-predict must be >= -1\n", __func__); return 1; diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 3520b434918d5a33ce423f7b916747c01427e3cf..dfb09f9dd982a18735473c064e845a470684de6a 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -2125,6 +2125,8 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t sched) { GGML_ASSERT(sched); struct ggml_backend_sched_split * splits = sched->splits; + const char * batch_inputs_env = getenv("GGML_SCHED_BATCH_HOST_INPUTS"); + const int batch_host_inputs = batch_inputs_env ? atoi(batch_inputs_env) : 0; int prev_backend_id = -1; @@ -2132,6 +2134,9 @@ static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t s struct ggml_backend_sched_split * split = &splits[split_id]; int split_backend_id = split->backend_id; ggml_backend_t split_backend = sched->backends[split_backend_id]; + const auto split_device_type = batch_host_inputs ? ggml_backend_dev_type(ggml_backend_get_device(split_backend)) : GGML_BACKEND_DEVICE_TYPE_CPU; + const bool batch_split_inputs = batch_host_inputs && + (split_device_type == GGML_BACKEND_DEVICE_TYPE_GPU || split_device_type == GGML_BACKEND_DEVICE_TYPE_IGPU); // ensure the previous split's async work has completed before we start // this split, the allocator may have reused buffer regions across splits @@ -2146,6 +2151,42 @@ static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t s // copy the input tensors to the split backend // the weights in host memory are copied last, so that the copy callback can read the other inputs of the split for (int input_id = 0; input_id < split->n_inputs; input_id++) { + if (batch_split_inputs) { + std::vector srcs; + std::vector dsts; + for (int j = input_id; j < split->n_inputs; ++j) { + ggml_tensor * input = split->inputs[j]; + ggml_backend_buffer_t buf = input->view_src ? input->view_src->buffer : input->buffer; + if (ggml_backend_sched_is_host_weight(input) || !buf || !ggml_backend_buffer_is_host(buf)) { + break; + } + ggml_backend_t input_backend = ggml_backend_sched_get_tensor_backend(sched, input); + if (!(input->flags & GGML_TENSOR_FLAG_INPUT) && + (batch_host_inputs < 2 || !input_backend || + ggml_backend_dev_type(ggml_backend_get_device(input_backend)) != GGML_BACKEND_DEVICE_TYPE_CPU)) { + break; + } + srcs.push_back(input); + dsts.push_back(tensor_copy(input, split_backend_id, sched->cur_copy)); + } + if (srcs.size() > 1) { + for (size_t j = 0; j < srcs.size(); ++j) { + ggml_tensor * input = split->inputs[input_id + j]; + if (!(input->flags & GGML_TENSOR_FLAG_INPUT)) { + ggml_backend_synchronize(ggml_backend_sched_get_tensor_backend(sched, input)); + } + } + if (sched->events[split_backend_id][sched->cur_copy] != NULL) { + ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]); + } else { + ggml_backend_synchronize(split_backend); + } + // Finish all copies before the caller can change these inputs. + ggml_backend_tensor_copy_n(srcs.data(), dsts.data(), srcs.size()); + input_id += (int) srcs.size() - 1; + continue; + } + } if (!ggml_backend_sched_is_host_weight(split->inputs[input_id])) { ggml_backend_sched_copy_input(sched, split, split->inputs[input_id]); } diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index a46c4d3f096fb4e00bd0a6f000a545fd3fd33be3..6702a5d01ca295e4409340c07dd45c0cd45873b0 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -1271,36 +1271,6 @@ struct ggml_tensor_extra_gpu { #define USE_CUDA_GRAPH #endif -struct ggml_cuda_graph { -#ifdef USE_CUDA_GRAPH - ~ggml_cuda_graph() { - for (cudaGraphExec_t instance : instances) { - CUDA_CHECK(cudaGraphExecDestroy(instance)); - } - } - // the ggml graph is captured as a series of CUDA graphs, so the GPU can run one chunk while the next is enqueued - std::vector instances; - size_t num_nodes = 0; - std::vector nodes; - bool disable_due_to_gpu_arch = false; - bool warmup_complete = false; - uint64_t uid = 0; - int64_t last_used_time = 0; - struct node_properties { - ggml_tensor node; - void * node_src_data_ptrs[GGML_MAX_SRC]; - int64_t node_src_ne[GGML_MAX_SRC][GGML_MAX_DIMS]; - size_t node_src_nb[GGML_MAX_SRC][GGML_MAX_DIMS]; - }; - std::vector node_props; - - bool is_enabled() const { - static const bool disable_cuda_graphs_due_to_env = (getenv("GGML_CUDA_DISABLE_GRAPHS") != nullptr); - return !(disable_due_to_gpu_arch || disable_cuda_graphs_due_to_env); - } -#endif -}; - struct ggml_cuda_concurrent_event { std::vector join_events; cudaEvent_t fork_event = nullptr; @@ -1445,13 +1415,46 @@ struct ggml_cuda_concurrent_event { }; struct ggml_cuda_stream_context { + bool moe_initialized = false; std::unordered_map concurrent_events; void reset() { + moe_initialized = false; concurrent_events.clear(); } }; +struct ggml_cuda_graph { + ggml_cuda_stream_context concurrent_stream_context; +#ifdef USE_CUDA_GRAPH + ~ggml_cuda_graph() { + for (cudaGraphExec_t instance : instances) { + CUDA_CHECK(cudaGraphExecDestroy(instance)); + } + } + // the ggml graph is captured as a series of CUDA graphs, so the GPU can run one chunk while the next is enqueued + std::vector instances; + size_t num_nodes = 0; + std::vector nodes; + bool disable_due_to_gpu_arch = false; + bool warmup_complete = false; + uint64_t uid = 0; + int64_t last_used_time = 0; + struct node_properties { + ggml_tensor node; + void * node_src_data_ptrs[GGML_MAX_SRC]; + int64_t node_src_ne[GGML_MAX_SRC][GGML_MAX_DIMS]; + size_t node_src_nb[GGML_MAX_SRC][GGML_MAX_DIMS]; + }; + std::vector node_props; + + bool is_enabled() const { + static const bool disable_cuda_graphs_due_to_env = (getenv("GGML_CUDA_DISABLE_GRAPHS") != nullptr); + return !(disable_due_to_gpu_arch || disable_cuda_graphs_due_to_env); + } +#endif +}; + struct ggml_backend_cuda_context { int device; std::string name; @@ -1535,7 +1538,17 @@ struct ggml_backend_cuda_context { cudaStream_t stream() { return stream(device, curr_stream_no); } - ggml_cuda_stream_context & stream_context() { return concurrent_stream_context; } + ggml_cuda_stream_context & stream_context(const void * graph_key = nullptr) { +#ifdef USE_CUDA_GRAPH + static const bool per_graph = [] { const char * v = getenv("GGML_CUDA_MOE_CONCURRENT"); return v && atoi(v) != 0; }(); + if (per_graph && graph_key) { + return cuda_graph(graph_key)->concurrent_stream_context; + } +#else + GGML_UNUSED(graph_key); +#endif + return concurrent_stream_context; + } cublasHandle_t cublas_handle() { if (cublas_handles[device][curr_stream_no] == nullptr) { diff --git a/ggml/src/ggml-cuda/cpy.cu b/ggml/src/ggml-cuda/cpy.cu index 90a06b97bbc6e9f3936827cbf61e8c191303e043..22c4f70e0322e13d93ed381df7cd877994129caa 100644 --- a/ggml/src/ggml-cuda/cpy.cu +++ b/ggml/src/ggml-cuda/cpy.cu @@ -41,6 +41,21 @@ static __global__ void cpy_scalar(const char * cx, char * cdst, const int64_t ne cpy_1(cx + x_offset, cdst + dst_offset); } +static __global__ void cpy_f32_rows_vec4(const char * src, float4 * dst, const uint32_t nvec, + const uint3 ne0_vec, const uint3 ne1, const uint3 ne2, const size_t nb1, const size_t nb2, const size_t nb3) { + ggml_cuda_pdl_lc(); + const uint32_t i = blockIdx.x*blockDim.x + threadIdx.x; + if (i >= nvec) { + return; + } + const uint2 p0 = fast_div_modulo(i, ne0_vec); + const uint2 p1 = fast_div_modulo(p0.x, ne1); + const uint2 p2 = fast_div_modulo(p1.x, ne2); + const size_t offset = size_t(p0.y)*sizeof(float4) + size_t(p1.y)*nb1 + size_t(p2.y)*nb2 + size_t(p2.x)*nb3; + ggml_cuda_pdl_sync(); + dst[i] = *(const float4 *) (src + offset); +} + template static __global__ void cpy_scalar_transpose(const char * cx, char * cdst, const int64_t ne, const int64_t ne00, const int64_t ne01, const int64_t ne02, const int64_t nb00, const int64_t nb01, const int64_t nb02, @@ -478,7 +493,19 @@ void ggml_cuda_cpy(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, gg CUDA_CHECK(cudaMemcpy2DAsync(src1_ddc, mc_dpitch, src0_ddc, mc_spitch, mc_width, mc_height, cudaMemcpyDeviceToDevice, main_stream)); } else if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32) { - if (can_be_transposed) { + static const bool use_vec = [] { + const char * value = getenv("GGML_CUDA_CPY_F32_VEC"); + return value && atoi(value) != 0; + }(); + if (use_vec && ne >= 4096 && ne/4 <= INT_MAX && nb00 == sizeof(float) && ne00 % 4 == 0 && + ne01 <= INT_MAX && ne02 <= INT_MAX && ggml_is_contiguous(src1) && + (nb01 | nb02 | nb03 | (uintptr_t) src0_ddc | (uintptr_t) src1_ddc) % sizeof(float4) == 0) { + const uint32_t nvec = ne/4; + const dim3 blocks((nvec + CUDA_CPY_BLOCK_SIZE - 1)/CUDA_CPY_BLOCK_SIZE); + const ggml_cuda_kernel_launch_params params(blocks, CUDA_CPY_BLOCK_SIZE, 0, main_stream); + ggml_cuda_kernel_launch(cpy_f32_rows_vec4, params, src0_ddc, (float4 *) src1_ddc, nvec, + init_fastdiv_values(ne00/4), init_fastdiv_values(ne01), init_fastdiv_values(ne02), size_t(nb01), size_t(nb02), size_t(nb03)); + } else if (can_be_transposed) { ggml_cpy_scalar_cuda (src0_ddc, src1_ddc, ne, ne00, ne01, ne02, nb00, nb01, nb02, nb03, ne10, ne11, ne12, nb10, nb11, nb12, nb13, main_stream); } else { diff --git a/ggml/src/ggml-cuda/dsv4-hc.cu b/ggml/src/ggml-cuda/dsv4-hc.cu index 2d0b3cfeaed7b07bb5467d150c98e410beb1ea1a..f40605b8fd6b6726a3a2106dd960501eaad46d0b 100644 --- a/ggml/src/ggml-cuda/dsv4-hc.cu +++ b/ggml/src/ggml-cuda/dsv4-hc.cu @@ -4,6 +4,110 @@ static constexpr int DSV4_HC = 4; +template +static __global__ void dsv4_hc_gate_consumer_f32(const float * mixes, const float * factor, const float * bias, + const float * x, const float * residual, float * dst, int n_embd, + float s0, float b0, float s1, float b1, bool extra, float output_scale) { + __shared__ float gates[DSV4_HC]; + ggml_cuda_pdl_lc(); + ggml_cuda_pdl_sync(); + if (threadIdx.x < DSV4_HC) { + const int i = threadIdx.x; + const float z = __fadd_rn(__fmul_rn(mixes[i], factor[0]), bias[i]); + float v = 1.0f / (1.0f + expf(-z)); + v = fmaf(s0, v, b0); + gates[i] = extra ? fmaf(s1, v, b1) : v; + } + __syncthreads(); + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if constexpr (post) { + if (i < DSV4_HC*n_embd) { + float sum = x[i % n_embd] * gates[i / n_embd]; + sum += residual[i]; + dst[i] = sum; + } + } else { + if (i < n_embd) { + float sum = 0.0f; + for (int h = 0; h < DSV4_HC; ++h) { + sum += x[i + h*n_embd] * gates[h]; + } + dst[i] = output_scale * sum; + } + } +} + +bool ggml_cuda_op_dsv4_hc_gate_consumer(ggml_backend_cuda_context & ctx, const ggml_tensor * mul, + const ggml_tensor * add, const ggml_tensor * scale, const ggml_tensor * scale_extra, ggml_tensor * dst) { + const bool post = dst->op == GGML_OP_DSV4_HC_POST; + if (!post && dst->op != GGML_OP_DSV4_HC_PRE) { + return false; + } + const ggml_tensor * gate = scale_extra ? scale_extra : scale; + const ggml_tensor * x = dst->src[0]; + const ggml_tensor * residual = post ? dst->src[1] : nullptr; + const int64_t n_embd = x->ne[0]; + if (ggml_nelements(gate) != DSV4_HC || n_embd > INT_MAX / DSV4_HC || + dst->src[post ? 2 : 1] != gate || dst->type != GGML_TYPE_F32 || x->type != GGML_TYPE_F32 || + !ggml_is_contiguous(x) || !ggml_is_contiguous(dst)) { + return false; + } + if (post) { + if (dst->src[3] || ggml_nelements(x) != n_embd || residual->type != GGML_TYPE_F32 || + !ggml_is_contiguous(residual) || residual->ne[0] != n_embd || residual->ne[1] != DSV4_HC || + ggml_nelements(residual) != DSV4_HC*n_embd || ggml_nelements(dst) != DSV4_HC*n_embd) { + return false; + } + } else if (ggml_get_op_params_i32(dst, 1) != 0 || x->ne[1] != DSV4_HC || + ggml_nelements(x) != DSV4_HC*n_embd || ggml_nelements(dst) != n_embd) { + return false; + } + const int64_t n = ggml_nelements(dst); + const ggml_cuda_kernel_launch_params params((n + 255) / 256, 256, 0, ctx.stream()); + auto kernel = post ? dsv4_hc_gate_consumer_f32 : dsv4_hc_gate_consumer_f32; + ggml_cuda_kernel_launch(kernel, params, + (const float *) mul->src[0]->data, (const float *) mul->src[1]->data, (const float *) add->src[1]->data, + (const float *) x->data, residual ? (const float *) residual->data : nullptr, (float *) dst->data, (int) n_embd, + ggml_get_op_params_f32(scale, 0), ggml_get_op_params_f32(scale, 1), + scale_extra ? ggml_get_op_params_f32(scale_extra, 0) : 1.0f, + scale_extra ? ggml_get_op_params_f32(scale_extra, 1) : 0.0f, scale_extra != nullptr, + post ? 1.0f : ggml_get_op_params_f32(dst, 0)); + return true; +} + +static __global__ void dsv4_hc_gate_f32(const float * x, const float * scale, const float * bias, + float * dst, int64_t n, int64_t stride, float s0, float b0, float s1, float b1, bool extra) { + ggml_cuda_pdl_lc(); + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) { + return; + } + ggml_cuda_pdl_sync(); + const int64_t col = i % DSV4_HC; + // Keep the rounding of the separate MUL and ADD kernels. + const float z = __fadd_rn(__fmul_rn(x[(i / DSV4_HC)*stride + col], scale[0]), bias[col]); + float v = 1.0f / (1.0f + expf(-z)); + v = fmaf(s0, v, b0); + if (extra) { + v = fmaf(s1, v, b1); + } + dst[i] = v; +} + +void ggml_cuda_op_dsv4_hc_gate(ggml_backend_cuda_context & ctx, const ggml_tensor * mul, + const ggml_tensor * add, ggml_tensor * scale, ggml_tensor * scale_extra) { + const ggml_tensor * x = mul->src[0]; + ggml_tensor * dst = scale_extra ? scale_extra : scale; + const int64_t n = ggml_nelements(dst); + const ggml_cuda_kernel_launch_params params((n + 255) / 256, 256, 0, ctx.stream()); + ggml_cuda_kernel_launch(dsv4_hc_gate_f32, params, + (const float *) x->data, (const float *) mul->src[1]->data, (const float *) add->src[1]->data, + (float *) dst->data, n, x->nb[1] / sizeof(float), + ggml_get_op_params_f32(scale, 0), ggml_get_op_params_f32(scale, 1), + scale_extra ? ggml_get_op_params_f32(scale_extra, 0) : 1.0f, + scale_extra ? ggml_get_op_params_f32(scale_extra, 1) : 0.0f, scale_extra != nullptr); +} + static __device__ void dsv4_hc_comb_norm_cols(float * comb, float eps) { for (int idst = 0; idst < DSV4_HC; ++idst) { diff --git a/ggml/src/ggml-cuda/dsv4-hc.cuh b/ggml/src/ggml-cuda/dsv4-hc.cuh index 1885e76659d5a67bbc5c829e91f1df0ffecf6099..af2516a240cfcdd15c9135cfa91d3cfb65ffd23b 100644 --- a/ggml/src/ggml-cuda/dsv4-hc.cuh +++ b/ggml/src/ggml-cuda/dsv4-hc.cuh @@ -3,6 +3,10 @@ void ggml_cuda_op_dsv4_hc_comb(ggml_backend_cuda_context & ctx, ggml_tensor * dst); void ggml_cuda_op_dsv4_hc_pre(ggml_backend_cuda_context & ctx, ggml_tensor * dst); +void ggml_cuda_op_dsv4_hc_gate(ggml_backend_cuda_context & ctx, const ggml_tensor * mul, + const ggml_tensor * add, ggml_tensor * scale, ggml_tensor * scale_extra); +bool ggml_cuda_op_dsv4_hc_gate_consumer(ggml_backend_cuda_context & ctx, const ggml_tensor * mul, + const ggml_tensor * add, const ggml_tensor * scale, const ggml_tensor * scale_extra, ggml_tensor * dst); // gate_scale_in/gate_scale_out: the SCALE nodes of a fused SCALE -> SIGMOID -> SCALE chain feeding src[2] void ggml_cuda_op_dsv4_hc_post(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const ggml_tensor * gate_scale_in = nullptr, const ggml_tensor * gate_scale_out = nullptr); diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index beb877941c75ef8646f87c61d0e75d1da65b881a..9b06591930db2aa518a095c3d3e0e114fac122ff 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -1156,7 +1156,13 @@ void launch_fattn( dim3 blocks_num; if (stream_k) { // Stream-K splits the work before the mask scan is applied, so skipped KV tiles make the blocks uneven. - const bool prefer_whole_tiles = GGML_CUDA_CC_IS_NVIDIA(cc) && cc == GGML_CUDA_CC_DGX_SPARK && async_kv_preload && scan_mask; + static const bool whole_tiles_576 = [] { + const char * value = getenv("GGML_CUDA_FA_576_WHOLE_TILES"); + return value && atoi(value) != 0; + }(); + const bool prefer_whole_tiles = GGML_CUDA_CC_IS_NVIDIA(cc) && scan_mask && + ((cc == GGML_CUDA_CC_DGX_SPARK && async_kv_preload) || + (whole_tiles_576 && (cc == GGML_CUDA_CC_BLACKWELL || cc == GGML_CUDA_CC_DGX_SPARK) && Q->ne[0] == 576 && Q->ne[1] > 16 && !use_sparse)); auto should_use_stream_k = [prefer_whole_tiles](const int cc, const int ntiles_dst, const int max_blocks, const int DKQ) { const int tiles_nwaves = (ntiles_dst + max_blocks - 1) / max_blocks; diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 06956ce7a3d9f5651735b89513bbdb9097b647a4..2f358d02ab5009e8a7160bf0fe0783eb0f0c4e12 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -929,6 +929,22 @@ static bool ggml_backend_cuda_buffer_cpy_tensor(ggml_backend_buffer_t buffer, co static bool ggml_backend_cuda_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const struct ggml_tensor * const * srcs, struct ggml_tensor * const * dsts, size_t n_tensors) { ggml_backend_cuda_buffer_context * dst_ctx = (ggml_backend_cuda_buffer_context *)buffer->context; + bool all_host = true; + for (size_t i = 0; i < n_tensors; i++) { + ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer; + all_host &= ggml_backend_buffer_is_host(src_buf); + } + if (all_host) { + ggml_cuda_set_device(dst_ctx->device); + for (size_t i = 0; i < n_tensors; i++) { + if (ggml_nbytes(srcs[i]) != 0) { + CUDA_CHECK(cudaMemcpyAsync(dsts[i]->data, srcs[i]->data, ggml_nbytes(srcs[i]), cudaMemcpyHostToDevice, cudaStreamPerThread)); + } + } + CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); + return true; + } + for (size_t i = 0; i < n_tensors; i++) { ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer; if (!ggml_backend_buffer_is_cuda(src_buf)) { @@ -2057,6 +2073,13 @@ static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggm return false; } + if (x_up->type == GGML_TYPE_NVFP4) { + static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_SPARK_MMQ_FUSION"); + if (!enabled || up->op != GGML_OP_MUL_MAT_ID || !blackwell_mma_available(ggml_cuda_info().devices[device].cc)) { + return false; + } + } + // The fused kernel is only compiled for weights whose rows fill whole tiles (no fallback). if (ggml_cuda_mmq_needs_fallback(x_up->ne[1])) { return false; @@ -2105,11 +2128,15 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t return false; } + if (x_up->type == GGML_TYPE_NVFP4) { + return ggml_cuda_mmq_spark_fusion_supported(up, gate); + } + // The fused kernel needs one block per tile (no stream-k split), so only fuse if the tiling is efficient. return ggml_cuda_mmq_fusion_is_efficient(x_up->type, x_up->ne[1], ncols, nchannels, device); } -static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { +static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, ggml_cuda_mmvq_cache * cache = nullptr) { GGML_TENSOR_BINARY_OP_LOCALS if (ggml_cuda_op_mul_mat_use_fwht(dst) && ggml_cuda_op_fwht(ctx, src1, dst)) { @@ -2154,7 +2181,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor return; } if (ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) { - ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst); + ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst, nullptr, cache); return; } if (ggml_cuda_should_use_mmq(src0->type, cc, ne11, /*n_experts =*/ 0)) { @@ -2197,7 +2224,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return true; } -static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { +static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_cuda_mmvq_cache * cache) { const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * src1 = dst->src[1]; const ggml_tensor * ids = dst->src[2]; @@ -2217,7 +2244,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * if (ggml_is_quantized(src0->type)) { const int mmvq_mmid_max = get_mmvq_mmid_max_batch(src0->type, cc); if (ne2 <= mmvq_mmid_max) { - ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst); + ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst, nullptr, cache); return; } } else { @@ -2356,7 +2383,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * nb1, nb2, nb3, stream); } -static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct ggml_tensor * dst) { +static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct ggml_tensor * dst, ggml_cuda_mmvq_cache * cache) { switch (dst->op) { case GGML_OP_ARGMAX: ggml_cuda_argmax(ctx, dst); @@ -2549,10 +2576,10 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg ggml_cuda_op_rms_norm_back(ctx, dst); break; case GGML_OP_MUL_MAT: - ggml_cuda_mul_mat(ctx, dst->src[0], dst->src[1], dst); + ggml_cuda_mul_mat(ctx, dst->src[0], dst->src[1], dst, cache); break; case GGML_OP_MUL_MAT_ID: - ggml_cuda_mul_mat_id(ctx, dst); + ggml_cuda_mul_mat_id(ctx, dst, cache); break; case GGML_OP_OUT_PROD: ggml_cuda_out_prod(ctx, dst); @@ -3940,7 +3967,7 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, } // try and fuse nodes and return the number of nodes to skip -static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { +static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i, ggml_cuda_mmvq_cache * cache) { if (ggml_cuda_fusion_disabled()) { return 0; @@ -3948,7 +3975,51 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph ggml_tensor * node = cgraph->nodes[i]; - if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && + static const bool fuse_hc_gate = ggml_cuda_env_flag("GGML_CUDA_FUSE_HC_GATE"); + if (fuse_hc_gate && node->op == GGML_OP_MUL) { + // A bias view can be visited between MUL and ADD; it has no device work. + const int view = i + 1 < cgraph->n_nodes && cgraph->nodes[i + 1]->op == GGML_OP_VIEW ? 1 : 0; + const int idxs[] = { i, i + 1 + view, i + 2 + view, i + 3 + view, i + 4 + view }; + const ggml_op ops[] = { GGML_OP_MUL, GGML_OP_ADD, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_SCALE }; + const bool extra = ggml_can_fuse_ext(cgraph, idxs, ops, 5); + if (extra || ggml_can_fuse_ext(cgraph, idxs, ops, 4)) { + ggml_tensor * add = cgraph->nodes[idxs[1]]; + ggml_tensor * sigmoid = cgraph->nodes[idxs[2]]; + ggml_tensor * scale = cgraph->nodes[idxs[3]]; + const int output_idx = idxs[extra ? 4 : 3]; + ggml_tensor * dst = cgraph->nodes[output_idx]; + const ggml_tensor * x = node->src[0]; + const ggml_tensor * factor = node->src[1]; + const ggml_tensor * bias = add->src[1]; + if (add->src[0] == node && sigmoid->src[0] == add && scale->src[0] == sigmoid && + (!extra || dst->src[0] == scale) && ggml_get_unary_op(sigmoid) == GGML_UNARY_OP_SIGMOID && + x->type == GGML_TYPE_F32 && factor->type == GGML_TYPE_F32 && bias->type == GGML_TYPE_F32 && + node->type == GGML_TYPE_F32 && add->type == GGML_TYPE_F32 && sigmoid->type == GGML_TYPE_F32 && + scale->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && + x->ne[0] == 4 && x->ne[2] == 1 && x->ne[3] == 1 && ggml_is_contiguous_rows(x) && + ggml_nelements(factor) == 1 && bias->ne[0] == 4 && ggml_nelements(bias) == 4 && ggml_is_contiguous(bias) && + ggml_are_same_shape(x, dst) && ggml_is_contiguous(dst) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, output_idx - i + 1, &output_idx, 1)) { + static const bool fuse_consumer = ggml_cuda_env_flag("GGML_CUDA_FUSE_HC_CONSUMER"); + const int consumer_idx = output_idx + 1; + if (fuse_consumer && consumer_idx < cgraph->n_nodes) { + ggml_tensor * consumer = cgraph->nodes[consumer_idx]; + if (consumer->op == GGML_OP_DSV4_HC_PRE || consumer->op == GGML_OP_DSV4_HC_POST) { + if (ggml_node_has_n_uses(cgraph, output_idx, 1) && + (consumer->flags & GGML_TENSOR_FLAG_COMPUTE) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, consumer_idx - i + 1, &consumer_idx, 1) && + ggml_cuda_op_dsv4_hc_gate_consumer(*cuda_ctx, node, add, scale, extra ? dst : nullptr, consumer)) { + return consumer_idx - i; + } + } + } + ggml_cuda_op_dsv4_hc_gate(*cuda_ctx, node, add, scale, extra ? dst : nullptr); + return output_idx - i; + } + } + } + + if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context(cgraph->n_nodes ? cgraph->nodes[0] : nullptr).concurrent_events.empty() && ggml_cuda_match_shared_expert(cgraph, i, i + 3) && ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) { const int outputs[] = { i + 2, i + 5 }; @@ -3963,7 +4034,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph fusion.shared_up = shared->src[1]->src[0]; fusion.shared_gate = shared->src[0]->src[0]; fusion.shared_dst = shared; - ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion, cache); return 5; } } @@ -4311,7 +4382,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data, cache); fused_mul_mat_vec = true; fused_node_count = n_ops; break; @@ -4404,8 +4475,15 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph fusion_data.glu_op = ggml_get_glu_op(glu); fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + if (!with_bias && ggml_cuda_mmq_spark_fusion_supported(up_n, gate_n)) { + ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data, cache); fused_mul_mat_vec = true; fused_node_count = n_ops; break; @@ -4475,7 +4553,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph fusion_data.glu_op = ggml_get_glu_op(glu); fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data, cache); fused_mul_mat_vec = true; fused_node_count = 5; break; @@ -4514,7 +4592,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph fusion_data.glu_op = ggml_get_glu_op(glu); fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data, cache); fused_mul_mat_vec = true; fused_node_count = 3; break; @@ -4614,7 +4692,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph fusion_data.x_scale = scale; if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data, cache); fused_mul_mat_vec = true; fused_node_count = n_ops; break; @@ -4679,7 +4757,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data); + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data, cache); fused_mul_mat_vec = true; fused_node_count = 2; break; @@ -4750,13 +4828,83 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph return 0; } +// Reuse only vectors whose storage is unchanged between all consumers in this graph. +static void ggml_cuda_prepare_mmvq_cache(ggml_backend_cuda_context & ctx, const ggml_cgraph * graph, ggml_cuda_mmvq_cache & cache, + const std::unordered_map * stream_mapping = nullptr, int stream = 0) { + struct uses { int first; int last; }; + std::unordered_map inputs; + for (int i = 0; i < graph->n_nodes; ++i) { + const ggml_tensor * node = graph->nodes[i]; + if (stream_mapping) { + auto it = stream_mapping->find(node); + if ((it == stream_mapping->end() ? 0 : it->second) != stream) { + continue; + } + } + if (node->op != GGML_OP_MUL_MAT && node->op != GGML_OP_MUL_MAT_ID) { + continue; + } + const ggml_tensor * x = node->src[1]; + if (!ggml_is_quantized(node->src[0]->type) || x->type != GGML_TYPE_F32 || + x->ne[0] < 32 || x->ne[0] > 65536 || ggml_nelements(x) != x->ne[0] || !ggml_is_contiguous(x)) { + continue; + } + auto result = inputs.emplace(ggml_cuda_mmvq_cache_key(x), uses{i, i}); + result.first->second.last = i; + } + size_t size = 0; + for (const auto & input : inputs) { + const ggml_tensor * x = input.first; + const uses range = input.second; + if (range.first == range.last) { + continue; + } + const uintptr_t start = (uintptr_t) x->data; + const size_t bytes = ggml_nbytes(x); + auto overlaps = [&](const ggml_tensor * dst) { + const uintptr_t other = (uintptr_t) dst->data; + const size_t other_bytes = ggml_nbytes(dst); + return other <= start ? start - other < other_bytes : other - start < bytes; + }; + bool unchanged = true; + for (int i = range.first; i <= range.last && unchanged; ++i) { + const ggml_tensor * node = graph->nodes[i]; + if (ggml_cuda_is_view_or_noop(node)) { + continue; + } + unchanged = !overlaps(node); + // These operations write through an explicit destination source. + if (node->op == GGML_OP_CPY || node->op == GGML_OP_SET_ROWS) { + unchanged = unchanged && !overlaps(node->src[node->op == GGML_OP_CPY ? 1 : 2]); + } + // MMVQ can clear the allocation padding of temporary weights. + if ((node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) && + ggml_backend_buffer_get_usage(node->src[0]->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && + ggml_is_quantized(node->src[0]->type)) { + unchanged = false; + } + } + if (unchanged) { + const size_t quantized_bytes = GGML_PAD(x->ne[0], MATRIX_ROW_PADDING) / QK8_1 * sizeof(block_q8_1); + if (size + quantized_bytes > 8*1024*1024) { + break; + } + cache.entries.emplace(x, ggml_cuda_mmvq_cache::entry{size}); + size += quantized_bytes; + } + } + if (size) { + cache.data.alloc(ctx.pool(), size); + } +} + static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, const bool use_cuda_graph, const bool cuda_graph_update_required, const void * graph_key) { bool graph_evaluated_or_captured = false; // flag used to determine whether it is an integrated_gpu const bool integrated = ggml_cuda_info().devices[cuda_ctx->device].integrated; - ggml_cuda_stream_context & stream_ctx = cuda_ctx->stream_context(); + ggml_cuda_stream_context & stream_ctx = cuda_ctx->stream_context(cgraph->n_nodes ? cgraph->nodes[0] : nullptr); bool is_concurrent_event_active = false; ggml_cuda_concurrent_event * concurrent_event = nullptr; bool should_launch_concurrent_events = false; @@ -4855,6 +5003,27 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud stream_ctx.concurrent_events.clear(); } + std::array mmvq_caches; + static const bool reuse_q8 = ggml_cuda_env_flag("GGML_CUDA_REUSE_Q8"); + static const bool moe_concurrent = ggml_cuda_env_flag("GGML_CUDA_MOE_CONCURRENT"); + const bool prepare_cache = reuse_q8 && (!should_launch_concurrent_events || moe_concurrent); + ggml_cuda_mmvq_cache * cache = nullptr; + if (prepare_cache) { + std::unordered_map node_streams; + int streams = 1; + if (should_launch_concurrent_events) { + for (const auto & item : stream_ctx.concurrent_events) { + streams = std::max(streams, item.second.n_streams + 1); + node_streams.insert(item.second.stream_mapping.begin(), item.second.stream_mapping.end()); + } + } + GGML_ASSERT(streams <= GGML_CUDA_MAX_STREAMS); + for (int stream = 0; stream < streams; ++stream) { + ggml_cuda_prepare_mmvq_cache(*cuda_ctx, cgraph, mmvq_caches[stream], &node_streams, stream); + } + cache = &mmvq_caches[0]; + } + for (int i = 0; i < cgraph->n_nodes; i++) { ggml_tensor * node = cgraph->nodes[i]; #ifdef USE_CUDA_GRAPH @@ -4906,7 +5075,20 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud continue; } - int nodes_to_skip = ggml_cuda_try_fuse(cuda_ctx, cgraph, i); + if (prepare_cache) { + cache = &mmvq_caches[cuda_ctx->curr_stream_no]; + } + ggml_cgraph fusion_graph = *cgraph; + if (is_concurrent_event_active) { + for (int j = i + 1; j < cgraph->n_nodes; ++j) { + auto mapping = concurrent_event->stream_mapping.find(cgraph->nodes[j]); + if (mapping == concurrent_event->stream_mapping.end() || mapping->second != cuda_ctx->curr_stream_no) { + fusion_graph.n_nodes = j; + break; + } + } + } + int nodes_to_skip = ggml_cuda_try_fuse(cuda_ctx, &fusion_graph, i, cache); if (nodes_to_skip != 0) { #ifdef GGML_CUDA_DEBUG @@ -4935,7 +5117,7 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud GGML_UNUSED(integrated); #endif // NDEBUG - bool ok = ggml_cuda_compute_forward(*cuda_ctx, node); + bool ok = ggml_cuda_compute_forward(*cuda_ctx, node, cache); if (!ok) { GGML_LOG_ERROR("%s: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op)); } @@ -4996,6 +5178,142 @@ static bool ggml_cuda_graph_set_enabled(ggml_backend_cuda_context * cuda_ctx, co } #endif // USE_CUDA_GRAPH +// Graph eviction drops stream metadata. Rebuild only when the existing allocation is safe. +static bool ggml_cuda_moe_stream_ranges_safe(const ggml_cuda_concurrent_event & event) { + const auto overlaps = [](const ggml_tensor * a, const ggml_tensor * b) { + if (!a || !b || !a->data || !b->data || ggml_is_empty(a) || ggml_is_empty(b)) { + return false; + } + const uintptr_t x = (uintptr_t) a->data; + const uintptr_t y = (uintptr_t) b->data; + return x <= y ? y - x < ggml_nbytes(a) : x - y < ggml_nbytes(b); + }; + for (const auto & [writer, stream] : event.stream_mapping) { + if (ggml_is_empty(writer) || writer->op == GGML_OP_NONE || writer->op == GGML_OP_VIEW || + writer->op == GGML_OP_RESHAPE || writer->op == GGML_OP_TRANSPOSE || writer->op == GGML_OP_PERMUTE) { + continue; + } + if (!writer->data || writer->op == GGML_OP_CPY || writer->op == GGML_OP_SET_ROWS) { + return false; + } + for (const auto & [other, other_stream] : event.stream_mapping) { + if (stream == other_stream) { + continue; + } + if (overlaps(writer, other)) { + return false; + } + for (const ggml_tensor * input : other->src) { + if (overlaps(writer, input)) { + return false; + } + } + } + } + return true; +} + +static void ggml_cuda_prepare_moe_concurrency(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, + ggml_backend_graph_optimize_params * params) { + auto & stream_context = cuda_ctx->stream_context(cgraph->n_nodes ? cgraph->nodes[0] : nullptr); + stream_context.moe_initialized = true; + std::unordered_map node_indices; + for (int i = 0; i < cgraph->n_nodes; ++i) { + node_indices[cgraph->nodes[i]] = i; + } + const auto is_noop = [](const ggml_tensor * node) { + return ggml_is_empty(node) || node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || + node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE; + }; + std::vector> concurrent_node_ranges; + for (int join_idx = 0; join_idx < cgraph->n_nodes; ++join_idx) { + ggml_tensor * join = cgraph->nodes[join_idx]; + if (join->op != GGML_OP_ADD || ggml_nrows(join) != 1) { + continue; + } + const ggml_tensor * shared = join->src[1]; + if (!shared || shared->op != GGML_OP_MUL_MAT || !strstr(shared->name, "ffn_shexp")) { + continue; + } + const ggml_tensor * glu = shared->src[1]; + if (glu->op != GGML_OP_GLU || !glu->src[0] || !glu->src[1] || + glu->src[0]->op != GGML_OP_MUL_MAT || glu->src[1]->op != GGML_OP_MUL_MAT || + glu->src[0]->src[1] != glu->src[1]->src[1]) { + continue; + } + const ggml_tensor * root = glu->src[0]->src[1]; + auto root_it = node_indices.find(root); + if (root_it == node_indices.end() || ggml_nrows(root) != 1) { + continue; + } + const int fork_idx = root_it->second; + if (fork_idx >= join_idx || (!concurrent_node_ranges.empty() && fork_idx <= concurrent_node_ranges.back().second)) { + continue; + } + std::unordered_map branches; + bool indexed = false; + for (int branch = 0; branch < 2; ++branch) { + std::vector pending{join->src[branch]}; + while (!pending.empty()) { + const ggml_tensor * node = pending.back(); + pending.pop_back(); + auto pos = node_indices.find(node); + if (pos == node_indices.end() || pos->second <= fork_idx || pos->second >= join_idx) { + continue; + } + int & mask = branches[node]; + if (mask & (1 << branch)) { + continue; + } + mask |= 1 << branch; + indexed = indexed || (branch == 0 && node->op == GGML_OP_MUL_MAT_ID); + for (const ggml_tensor * input : node->src) { + if (input) { + pending.push_back(input); + } + } + } + } + if (!indexed) { + continue; + } + bool valid = true; + ggml_cuda_concurrent_event event(2); + event.join_node = join; + for (int j = fork_idx + 1; j < join_idx; ++j) { + const ggml_tensor * node = cgraph->nodes[j]; + const int mask = branches[node]; + if (mask == 3 || (mask == 0 && !is_noop(node))) { + valid = false; + break; + } + event.stream_mapping[node] = mask == 2 ? 2 : 1; + event.original_order.push_back(node); + } + if (!valid) { + continue; + } + // Both branches retain their intermediates until the join, including view sources. + if (params) { + for (int j = fork_idx; j < join_idx; ++j) { + params->add_alloc_dep(params->user_data, cgraph->nodes[j], join); + for (ggml_tensor * input : cgraph->nodes[j]->src) { + if (input) { + params->add_alloc_dep(params->user_data, input, join); + } + } + } + } else if (!ggml_cuda_moe_stream_ranges_safe(event)) { + continue; + } + stream_context.concurrent_events.emplace(root, std::move(event)); + concurrent_node_ranges.emplace_back(fork_idx, join_idx); + } + if (!params) { + GGML_LOG_DEBUG("%s: restored %zu concurrent MoE regions\n", __func__, stream_context.concurrent_events.size()); + } +} + static enum ggml_status ggml_backend_cuda_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context; @@ -5014,6 +5332,9 @@ static enum ggml_status ggml_backend_cuda_graph_compute(ggml_backend_t backend, if (graph->is_enabled()) { const bool graph_compatible = ggml_cuda_graph_check_compability(cgraph); if (graph_compatible) { + if (ggml_cuda_env_flag("GGML_CUDA_MOE_CONCURRENT") && !graph->concurrent_stream_context.moe_initialized) { + ggml_cuda_prepare_moe_concurrency(cuda_ctx, cgraph, nullptr); + } const bool properties_changed = ggml_cuda_graph_update_required(cuda_ctx, cgraph); if (!graph->warmup_complete) { @@ -5224,11 +5545,12 @@ static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph return env != nullptr && atoi(env) == 1; }(); - if (!enable_graph_optimization) { + static const bool enable_moe_concurrent = ggml_cuda_env_flag("GGML_CUDA_MOE_CONCURRENT"); + if (!enable_graph_optimization && !enable_moe_concurrent) { return; } - ggml_cuda_stream_context & stream_context = cuda_ctx->stream_context(); + ggml_cuda_stream_context & stream_context = cuda_ctx->stream_context(cgraph->n_nodes ? cgraph->nodes[0] : nullptr); stream_context.reset(); if (!use_cuda_graph) { @@ -5293,6 +5615,16 @@ static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph // store {fork_idx, join_idx} std::vector> concurrent_node_ranges; + if (enable_moe_concurrent) { + ggml_cuda_prepare_moe_concurrency(cuda_ctx, cgraph, params); + for (const auto & [root, event] : stream_context.concurrent_events) { + concurrent_node_ranges.emplace_back(node_indices.at(root), node_indices.at(event.join_node)); + } + } + if (!enable_graph_optimization) { + return; + } + for (const auto & [root_node, count] : fan_out) { if (count >= min_fan_out && count <= max_fan_out) { const int root_node_idx = node_indices[root_node]; @@ -5410,7 +5742,7 @@ static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph concurrent_event.original_order.push_back(cgraph->nodes[i]); } - std::unordered_map & concurrent_events = cuda_ctx->stream_context().concurrent_events; + std::unordered_map & concurrent_events = cuda_ctx->stream_context(cgraph->n_nodes ? cgraph->nodes[0] : nullptr).concurrent_events; GGML_ASSERT(concurrent_events.find(root_node) == concurrent_events.end()); concurrent_events.emplace(root_node, std::move(concurrent_event)); GGML_LOG_DEBUG("Adding stream at node %s %p\n", root_node->name, root_node); diff --git a/ggml/src/ggml-cuda/lightning-indexer.cu b/ggml/src/ggml-cuda/lightning-indexer.cu index 429d2e200c8405a223887e27d103c5ab6e643ad2..be3e2d4ebb8301f70ce6a22abd0a84ddc5c7cdd0 100644 --- a/ggml/src/ggml-cuda/lightning-indexer.cu +++ b/ggml/src/ggml-cuda/lightning-indexer.cu @@ -697,6 +697,49 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 32, k, GGML_TYPE_F32) GGML_ABORT("fatal error"); } + } else if (n_embd == 128 && n_head == 16) { + // hy_v4_flash: 16 indexer heads, which both the 8-head wmma tile and the N_HEAD/4 inner + // loop of the vector kernel still cover +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + if (GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_BF16) { + // use wmma kernel + constexpr int K_VECS_PER_BLOCK = 32; + constexpr int WARPS_PER_BLOCK = 8; + + dim3 block(32, WARPS_PER_BLOCK); + int num_kv_blocks = (n_kv + (K_VECS_PER_BLOCK) - 1) / (K_VECS_PER_BLOCK); + dim3 grid(num_kv_blocks, n_batch, n_stream); + + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_wmma, 128, 16, k, GGML_TYPE_F16) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_wmma, 128, 16, k, GGML_TYPE_Q4_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_wmma, 128, 16, k, GGML_TYPE_Q4_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_wmma, 128, 16, k, GGML_TYPE_Q5_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_wmma, 128, 16, k, GGML_TYPE_Q5_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_wmma, 128, 16, k, GGML_TYPE_Q8_0) + GGML_ABORT("fatal error"); + } else { +#else // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + { +#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + // use vector kernel + constexpr int K_VECS_PER_WARP = 8; + constexpr int WARPS_PER_BLOCK = 8; + constexpr int K_VECS_PER_BLOCK = K_VECS_PER_WARP * WARPS_PER_BLOCK; + + dim3 block(32, WARPS_PER_BLOCK); + int num_kv_blocks = (n_kv + (K_VECS_PER_BLOCK) - 1) / (K_VECS_PER_BLOCK); + dim3 grid(num_kv_blocks, n_batch, n_stream); + + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_F16) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q4_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q4_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q5_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q5_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q8_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_BF16) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_F32) + GGML_ABORT("fatal error"); + } } else if (n_embd == 128 && n_head == 4 && n_batch >= LIGHTNING_INDEXER_TILE_TOKENS) { // too few heads for a wmma tile, the tile kernel shares the keys across the tokens constexpr int WARPS_PER_BLOCK = 8; @@ -763,7 +806,7 @@ bool ggml_cuda_lightning_indexer_supported(int device, const ggml_tensor * dst) return false; } - if (neq1 != 64 && neq1 != 32 && neq1 != 4) { + if (neq1 != 64 && neq1 != 32 && neq1 != 16 && neq1 != 4) { return false; } diff --git a/ggml/src/ggml-cuda/mmq-config-blackwell.cuh b/ggml/src/ggml-cuda/mmq-config-blackwell.cuh index 9fbe32b6972b706baee8e9218dcf1570419d9f20..e0a84630ec9e4aff38bfdd14b0b9b92f69d2eb61 100644 --- a/ggml/src/ggml-cuda/mmq-config-blackwell.cuh +++ b/ggml/src/ggml-cuda/mmq-config-blackwell.cuh @@ -19,7 +19,7 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_NVFP4, 256, 1, 128, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, true); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, true); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, true); - CASE(GGML_TYPE_NVFP4, 256, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, true); + CASE(GGML_TYPE_NVFP4, 128, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, true); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, true); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); @@ -27,7 +27,7 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_NVFP4, 256, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); - CASE(GGML_TYPE_NVFP4, 256, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); + CASE(GGML_TYPE_NVFP4, 128, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 80, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 96, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); CASE(GGML_TYPE_NVFP4, 256, 1, 128, 112, GGML_CUDA_MMQ_SRAM_LAYOUT_FP4, MMQ_ITER_K_FP4, true, false); diff --git a/ggml/src/ggml-cuda/mmq-load-tiles.cuh b/ggml/src/ggml-cuda/mmq-load-tiles.cuh index 4951db72ebfc9a795a8602cac911bf181f132ddf..1e8f564e0bdbc6f13a2bfd73fb8e2fd29321c5e0 100644 --- a/ggml/src/ggml-cuda/mmq-load-tiles.cuh +++ b/ggml/src/ggml-cuda/mmq-load-tiles.cuh @@ -1782,9 +1782,8 @@ template static __de } } -template static __device__ __forceinline__ void ggml_cuda_mmq_load_tiles_nvfp4_nvfp4( +template static __device__ __forceinline__ void ggml_cuda_mmq_load_tiles_nvfp4_nvfp4( const char * __restrict__ x, const char * __restrict__ x_gate, int * __restrict__ x_tile, const int kbx0, const int i_max, const int stride) { - GGML_UNUSED(x_gate); constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, fallback, GGML_PREC_Q4) / warp_size; @@ -1800,7 +1799,6 @@ template static __device__ __forceinline_ const int kbx = txi % threads_per_row; const int row_in_warp = txi / threads_per_row; - const block_nvfp4 * bxi_base = (const block_nvfp4 *) x + kbx0 + kbx; uint32_t * x_u32_scale = x_u32 + 64 + kbx; #pragma unroll @@ -1811,7 +1809,7 @@ template static __device__ __forceinline_ i = min(i, i_max); } - const block_nvfp4 * bxi = bxi_base + i * stride; + const block_nvfp4 * bxi = ggml_cuda_mmq_x_row(x, x_gate, kbx0 + kbx, i, stride); const uint32_t * src_qs = reinterpret_cast(bxi->qs); diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu index 49e0ce9050c021f4ffa03924f7bc510f4a96cc41..71cf86debf65dc9d926ab87147f6226d677ca507 100644 --- a/ggml/src/ggml-cuda/mmq.cu +++ b/ggml/src/ggml-cuda/mmq.cu @@ -1,5 +1,6 @@ #include "common.cuh" #include "mmq.cuh" +#include "mmvq.cuh" #include "quantize.cuh" #include "mmid.cuh" @@ -172,7 +173,10 @@ void ggml_cuda_mul_mat_q( const ggml_tensor * gate = fusion ? fusion->gate : nullptr; ggml_cuda_mm_fusion_args_device fusion_device = {}; if (fusion) { - GGML_ASSERT(gate && !fusion->x_bias && !fusion->gate_bias && !fusion->x_scale && !fusion->gate_scale); + GGML_ASSERT(gate && !fusion->x_bias && !fusion->gate_bias); + GGML_ASSERT(src0->type == GGML_TYPE_NVFP4 || (!fusion->x_scale && !fusion->gate_scale)); + fusion_device.x_scale = fusion->x_scale ? fusion->x_scale->data : nullptr; + fusion_device.gate_scale = fusion->gate_scale ? fusion->gate_scale->data : nullptr; GGML_ASSERT(gate->type == src0->type && ggml_are_same_shape(gate, src0) && ggml_are_same_stride(gate, src0)); fusion_device.gate = gate->data; fusion_device.glu_op = fusion->glu_op; @@ -224,9 +228,9 @@ void ggml_cuda_mul_mat_q( const bool fallback = ggml_cuda_mmq_needs_fallback(ne01); - // With fusion dst is the GLU output, not a MUL_MAT; the fused types always quantize src1 to Q8_1. - // TODO support for Q4 precision if both tensors allow it - const ggml_prec prec_src1 = gate ? GGML_PREC_Q8 : ggml_cuda_mmq_get_prec_src1(src0, dst, cc); + // Native FP4 fusion is selected only after checking both matmul precision settings. + const ggml_prec prec_src1 = gate ? (src0->type == GGML_TYPE_NVFP4 ? GGML_PREC_Q4 : GGML_PREC_Q8) : + ggml_cuda_mmq_get_prec_src1(src0, dst, cc); const bool use_native_fp4 = prec_src1 == GGML_PREC_Q4; const size_t y_block_size = use_native_fp4 ? sizeof(block_fp4_mmq) : sizeof(block_q8_1_mmq); @@ -245,9 +249,48 @@ void ggml_cuda_mul_mat_q( if (GGML_CUDA_CC_IS_RDNA3(cc) || GGML_CUDA_CC_IS_RDNA4_M(cc) || GGML_CUDA_CC_IS_RDNA4(cc)) { ncols_opt = (ne12*n_expert_used + ne02 - 1) / ne02; } + + if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) { + static const auto read_tile_hint = [](const char * name, int fallback) { + const char * env = getenv(name); + if (!env) { + return fallback; + } + char * end = nullptr; + const long value = strtol(env, &end, 10); + if (end == env || *end || (value != -1 && value != 0 && (value < 8 || value > 128 || value % 8))) { + GGML_LOG_WARN("Invalid %s: %s; using %d\n", name, env, fallback); + return fallback; + } + return (int) value; + }; + static const int tile_plain = read_tile_hint("GGML_CUDA_SPARK_MMQ_TILE", 0); + static const int tile_fused = read_tile_hint("GGML_CUDA_SPARK_MMQ_TILE_FUSED", tile_plain); + const int tile_hint = gate ? tile_fused : tile_plain; + if (tile_hint == -1) { + const int64_t hint = (8*ne12*n_expert_used + 3*ne02 - 1) / (3*ne02); + ncols_opt = std::min(128, std::max(32, GGML_PAD(hint, 8))); + } else if (tile_hint > 0) { + ncols_opt = tile_hint; + } + } + } + + if (!ids && src0->type == GGML_TYPE_Q8_0 && cc == GGML_CUDA_CC_BLACKWELL && ne11 > 128) { + static const int tile_q8 = [] { + const char * value = getenv("GGML_CUDA_Q8_MMQ_TILE"); + return value ? atoi(value) : 0; + }(); + if (tile_q8 >= 8 && tile_q8 <= 128 && tile_q8 % 8 == 0) { + ncols_opt = tile_q8; + } } J_best = ggml_cuda_mmq_get_J_best(src0->type, ncols_opt, fallback, cc, smpbo, prec_src1, &nthreads_best); + if (ids && src0->type == GGML_TYPE_NVFP4 && getenv("GGML_CUDA_SPARK_MMQ_TRACE")) { + GGML_LOG_INFO("SPARK_MMQ weight=%s tokens=%lld opt=%lld J=%d threads=%d fused=%d\n", src0->name, + (long long) ne12, (long long) ncols_opt, J_best, nthreads_best, gate != nullptr); + } } GGML_ASSERT(J_best > 0); @@ -531,3 +574,30 @@ bool ggml_cuda_mmq_fusion_is_efficient(const ggml_type type, const int64_t nrows const int64_t tiles_efficiency_percent = 100 * ntiles / (nsm*tiles_nwaves); return tiles_efficiency_percent >= 90; } + +bool ggml_cuda_mmq_spark_fusion_supported(const ggml_tensor * up, const ggml_tensor * gate) { + static const bool enabled = []() { + const char * env = getenv("GGML_CUDA_SPARK_MMQ_FUSION"); + return env && std::atoi(env) != 0; + }(); + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + if (!enabled || !blackwell_mma_available(cc) || up->op != GGML_OP_MUL_MAT_ID || + up->src[0]->type != GGML_TYPE_NVFP4 || gate->src[0]->type != GGML_TYPE_NVFP4 || + up->src[1]->type != GGML_TYPE_F32 || ggml_cuda_mmq_needs_fallback(up->src[0]->ne[1]) || + up->src[1]->ne[2] <= get_mmvq_mmid_max_batch(GGML_TYPE_NVFP4, cc)) { + return false; + } + if (!ggml_cuda_should_use_mmq(GGML_TYPE_NVFP4, cc, up->src[1]->ne[2], up->src[0]->ne[2])) { + return false; + } + for (const ggml_tensor * mm : {up, gate}) { + const ggml_tensor * weight = mm->src[0]; + if (ggml_get_op_params_i32(mm, 1) != GGML_HINT_NONE || + ggml_cuda_mmq_get_prec_src1(weight, mm, cc) != GGML_PREC_Q4 || + (ggml_backend_buffer_get_usage(weight->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && + ggml_nbytes(weight) != ggml_backend_buffer_get_alloc_size(weight->buffer, weight) && weight->view_src)) { + return false; + } + } + return true; +} diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index 308968be9dcb5c6cc2dcc410b4ae3f91d8e7830c..4e0be7ecbfe0fabe8dc2bd97c6e75d2893f75702 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -16,7 +16,7 @@ typedef void (*ggml_cuda_mmq_load_tiles_t)(const char * __restrict__ x, const ch typedef void (*ggml_cuda_mmq_vec_dot_t)(const int * __restrict__ x, const int * __restrict__ y, float * __restrict__ sum, const int k00); typedef void (*ggml_cuda_mmq_write_back_t)(const float * __restrict__ sum, const int32_t * __restrict__ get_rows_to_sorted, float * __restrict__ dst, const float * __restrict__ y_scale, const int stride, const int i_max, const int j_max, - const ggml_glu_op glu_op, const float glu_limit); + const ggml_glu_op glu_op, const float glu_limit, const float2 lane_scale); enum mmq_q8_1_ds_layout { MMQ_Q8_1_DS_LAYOUT_D4, @@ -434,9 +434,9 @@ static __host__ int ggml_cuda_mmq_get_nbytes_shared_x(const ggml_cuda_mmq_config // ------------------------------------------------------------ -// Weight types with a fused gate/up/GLU path (see ggml_cuda_mmq_get_util_funcs). +// Weight types with a fused gate/up/GLU path. SPARK-4Bit requires native Q4 activations. static constexpr __host__ __device__ bool ggml_cuda_mmq_fusion_supported(const ggml_type type) { - return type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K || type == GGML_TYPE_Q6_K || type == GGML_TYPE_Q8_0 || type == GGML_TYPE_IQ4_XS; + return type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K || type == GGML_TYPE_Q6_K || type == GGML_TYPE_Q8_0 || type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_NVFP4; } // Fused gate/up/GLU: the weight tile alternates chunks of this many up and gate rows, so rows r and r + 8 of an MMA tile (same thread) pair up. @@ -462,8 +462,8 @@ static __device__ __forceinline__ const block_t * ggml_cuda_mmq_x_row( template static __device__ __forceinline__ void ggml_cuda_mmq_write_back_dp4a( const float * __restrict__ sum, const int32_t * __restrict__ ids_dst, float * __restrict__ dst, const float * __restrict__ y_scale, const int stride, const int i_max, const int j_max, - const ggml_glu_op glu_op, const float glu_limit) { - GGML_UNUSED_VARS(glu_op, glu_limit); + const ggml_glu_op glu_op, const float glu_limit, const float2 lane_scale) { + GGML_UNUSED_VARS(glu_op, glu_limit, lane_scale); constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, fallback, prec_src1) / warp_size; @@ -507,7 +507,7 @@ template tile_C; @@ -543,7 +543,13 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma( if constexpr (has_fusion) { const int sum_index = (j0/tile_C::J + n)*tile_C::ne + l; - dst[ids_dst[j]*stride + i] = ggml_cuda_op_glu_single(glu_op, sum[sum_index + tile_C::ne/2], sum[sum_index], glu_limit); + float up = sum[sum_index]; + float gate = sum[sum_index + tile_C::ne/2]; + if constexpr (type == GGML_TYPE_NVFP4) { + up = (up * y_scale[j]) * lane_scale.x; + gate = (gate * y_scale[j]) * lane_scale.y; + } + dst[ids_dst[j]*stride + i] = ggml_cuda_op_glu_single(glu_op, gate, up, glu_limit); } else if constexpr (type == GGML_TYPE_NVFP4) { if (y_scale_used) { dst[ids_dst[j]*stride + i] = y_scale[j] * sum[(j0/tile_C::J + n)*tile_C::ne + l]; @@ -558,7 +564,7 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma( } } - GGML_UNUSED_VARS(y_scale_used, glu_op, glu_limit); + GGML_UNUSED_VARS(y_scale_used, glu_op, glu_limit, lane_scale); } // ------------------------------------------------------------------------------------------------------------------------------------- @@ -737,9 +743,9 @@ static constexpr __device__ ggml_cuda_mmq_util_funcs ggml_cuda_mmq_get_util_func if (prec_src1 == GGML_PREC_Q4) { return ggml_cuda_mmq_util_funcs( -1, - ggml_cuda_mmq_load_tiles_nvfp4_nvfp4, + ggml_cuda_mmq_load_tiles_nvfp4_nvfp4, ggml_cuda_mmq_vec_dot_fp4_fp4_mma, - ggml_cuda_mmq_write_back_mma); + ggml_cuda_mmq_write_back_mma); } break; default: @@ -919,7 +925,7 @@ static __device__ __forceinline__ void mul_mat_q_process_tile( const int * __restrict__ ids_dst, float * __restrict__ dst, float * __restrict__ tmp_fixup, const float * __restrict__ y_scale, const ggml_glu_op glu_op, const float glu_limit, const int stride_row_x, const int ncols_y, const int stride_col_dst, - const int tile_x_max_i, const int tile_y_max_j, const int kb0_start, const int kb0_stop) { + const int tile_x_max_i, const int tile_y_max_j, const int kb0_start, const int kb0_stop, const float2 lane_scale = {1.0f, 1.0f}) { static_assert(!(fixup && has_fusion), "the fused gate/up path does not split K"); static_assert(!(fallback && has_fusion), "the fused gate/up path needs nrows_x % 128 == 0"); @@ -987,16 +993,16 @@ static __device__ __forceinline__ void mul_mat_q_process_tile( } if (fixup) { - write_back(sum, ids_dst, tmp_fixup + blockIdx.x*(J*I), y_scale, I, I, J, glu_op, glu_limit); + write_back(sum, ids_dst, tmp_fixup + blockIdx.x*(J*I), y_scale, I, I, J, glu_op, glu_limit, lane_scale); } else { - write_back(sum, ids_dst, dst, y_scale, stride_col_dst, tile_x_max_i, tile_y_max_j, glu_op, glu_limit); + write_back(sum, ids_dst, dst, y_scale, stride_col_dst, tile_x_max_i, tile_y_max_j, glu_op, glu_limit, lane_scale); } } // The mul_mat_q kernel implements "stream-k" work partitioning as described in https://arxiv.org/abs/2301.03598 -template +template __launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, fallback, prec_src1), ggml_cuda_mmq_get_occupancy(type, J, fallback, prec_src1)) static __global__ void mul_mat_q( const char * __restrict__ x, const char * __restrict__ x_gate, const int * __restrict__ y, const int32_t * __restrict__ ids_dst, @@ -1005,7 +1011,7 @@ static __global__ void mul_mat_q( const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst, const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst, - const uint3 ntx) { + const uint3 ntx, const float * x_scale, const float * gate_scale) { #ifdef TURING_MMA_AVAILABLE constexpr bool fusion_available = true; @@ -1043,76 +1049,89 @@ static __global__ void mul_mat_q( __syncthreads(); // The fused kernel needs the whole K range of a tile in one block, so it always uses tiling. - if constexpr (has_fusion || !ggml_cuda_mmq_get_stream_k(type, J, fallback, prec_src1)) { + if constexpr (has_fusion || !ggml_cuda_mmq_get_stream_k(type, J, fallback, prec_src1) || compact_grid) { // The fused kernel writes the GLU of I/2 up rows and I/2 gate rows per tile. constexpr int I_dst = has_fusion ? I/2 : I; const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y); const int wt = tmp2.x; const int zt = tmp2.y; - const int jt = blockIdx.x; const int it = blockIdx.y; + const int col_count = ids_dst ? expert_bounds[zt + 1] - expert_bounds[zt] : ncols_dst; + const int jt_stop = compact_grid ? (col_count + J - 1)/J : blockIdx.x + 1; + for (int jt = blockIdx.x; jt < jt_stop; jt += gridDim.x) { + if constexpr (compact_grid) { + __syncthreads(); + } - // Defaults for regular matrix multiplication: - int col_low = 0; - int col_high = ncols_dst; - int col_diff = ncols_dst; - int offset_y = wt*stride_sample_y + zt*stride_channel_y; - int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; - int offset_y_scale; - if constexpr (type == GGML_TYPE_NVFP4) { - offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; - } else { - GGML_UNUSED(offset_y_scale); - } - - if (ids_dst) { - col_low = expert_bounds[zt + 0]; - col_high = expert_bounds[zt + 1]; - col_diff = col_high - col_low; - - offset_y = 0; - offset_dst = 0; + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; if constexpr (type == GGML_TYPE_NVFP4) { - offset_y_scale = 0; + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); } - if (jt*J >= col_diff) { - return; - } + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; - // __syncthreads(); // There is no previous tile that could cause a race condition. -#pragma unroll - for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { - const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } - if (j0 + nwarps*warp_size > J && j >= J) { - break; + if (jt*J >= col_diff) { + return; } - ids_dst_shared[j] = ids_dst[col_low + jt*J + j]; +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = jt*J + j < col_diff ? ids_dst[col_low + jt*J + j] : 0; + } + __syncthreads(); } - __syncthreads(); - } - offset_y += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int)); - offset_dst += it*I_dst; - const float * y_scale_tile = nullptr; - if constexpr (type == GGML_TYPE_NVFP4) { - offset_y_scale += col_low + jt*J; - y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; - } + offset_y += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int)); + offset_dst += it*I_dst; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt*J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } - const int tile_x_max_i = nrows_x - it*I_dst - 1; - const int tile_y_max_j = col_diff - jt*J - 1; + const int tile_x_max_i = nrows_x - it*I_dst - 1; + const int tile_y_max_j = col_diff - jt*J - 1; - const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I_dst*stride_row_x; + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I_dst*stride_row_x; - constexpr bool fixup = false; - mul_mat_q_process_tile - (x, x_gate, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, - glu_op, glu_limit, stride_row_x, ncols_y, stride_col_dst, - tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z); + float2 lane_scale = {1.0f, 1.0f}; + if constexpr (has_fusion && type == GGML_TYPE_NVFP4) { + const int expert = fastdiv(zt, channel_ratio); + lane_scale = {x_scale ? x_scale[expert] : 1.0f, gate_scale ? gate_scale[expert] : 1.0f}; + } + constexpr bool fixup = false; + mul_mat_q_process_tile + (x, x_gate, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + glu_op, glu_limit, stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z, lane_scale); + if constexpr (!compact_grid) { + break; + } + } return; } @@ -1473,7 +1492,14 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const int ntx = (args.ncols_max + config.J - 1) / config.J; const int ntzw = args.nchannels_y * args.nsamples_y; // Column tiles innermost so that the concurrently running blocks share the same tile of x and read it from L2. - const dim3 block_nums_xy_tiling(ntx, nty, ntzw); + static const int compact_hint = [] { + const char * value = getenv("GGML_CUDA_SPARK_MMQ_COMPACT_GRID"); + return value ? atoi(value) : 0; + }(); + const bool compact_grid = type == GGML_TYPE_NVFP4 && prec_src1 == GGML_PREC_Q4 && + blackwell_mma_available(cc) && args.ids_dst && compact_hint > 0; + const int grid_x = compact_grid ? std::min(ntx, compact_hint) : ntx; + const dim3 block_nums_xy_tiling(grid_x, nty, ntzw); GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0); GGML_ASSERT(args.nsamples_y % args.nsamples_x == 0); @@ -1487,14 +1513,21 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const uint3 channel_ratio_fd = init_fastdiv_values(channel_ratio); const uint3 sample_ratio_fd = init_fastdiv_values(sample_ratio); - if (has_fusion || !config.stream_k) { + if (has_fusion || !config.stream_k || compact_grid) { GGML_ASSERT(nty <= 65535); // gridDim.y limit - mul_mat_q<<>> + auto kernel = mul_mat_q; + if constexpr (type == GGML_TYPE_NVFP4 && prec_src1 == GGML_PREC_Q4) { + if (compact_grid) { + CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q), nbytes_shared); + kernel = mul_mat_q; + } + } + kernel<<>> (args.x, (const char *) args.fusion.gate, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale, args.fusion.glu_op, args.fusion.glu_limit, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, - ntx_fd); + ntx_fd, (const float *) args.fusion.x_scale, (const float *) args.fusion.gate_scale); return; } @@ -1525,7 +1558,7 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, - ntx_fd); + ntx_fd, (const float *) args.fusion.x_scale, (const float *) args.fusion.gate_scale); if (!fixup_needed) { return; @@ -1597,7 +1630,7 @@ void mul_mat_q_switch_J(ggml_backend_cuda_context & ctx, const mmq_args & args, template static void mul_mat_q_switch_fusion(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) { - if constexpr (!fallback && ggml_cuda_mmq_fusion_supported(type)) { + if constexpr (!fallback && ggml_cuda_mmq_fusion_supported(type) && (type != GGML_TYPE_NVFP4 || prec_src1 == GGML_PREC_Q4)) { if (args.fusion.gate) { mul_mat_q_switch_J(ctx, args, stream); return; @@ -1662,3 +1695,5 @@ void ggml_cuda_mul_mat_q( bool ggml_cuda_should_use_mmq(enum ggml_type type, int cc, int64_t ne11, int64_t n_experts); bool ggml_cuda_mmq_fusion_is_efficient(ggml_type type, int64_t nrows_x, int64_t ncols, int64_t nchannels, int device); + +bool ggml_cuda_mmq_spark_fusion_supported(const ggml_tensor * up, const ggml_tensor * gate); diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 1a9cf55cb9158e601c3b96db1f5b724aae442039..ceb86796e6315390142c7c67769e05584b5f145c 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -618,8 +618,8 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int return 1; } -template -__launch_bounds__(calc_nwarps(type, ncols_dst, get_device_table_id(), small_k, halve_iters)*ggml_cuda_get_physical_warp_size(), 1) +template +__launch_bounds__((spark_2w ? 2 : calc_nwarps(type, ncols_dst, get_device_table_id(), small_k, halve_iters))*ggml_cuda_get_physical_warp_size(), 1) static __global__ void mul_mat_vec_q( const void * vx_ptr, const void * vy_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr, const uint32_t ncols_x, const uint3 nchannels_y, const uint32_t stride_row_x, const uint32_t stride_col_y, @@ -636,8 +636,8 @@ static __global__ void mul_mat_vec_q( constexpr int qi = ggml_cuda_type_traits::qi; constexpr int vdr = get_vdr_mmvq(type); constexpr mmvq_parameter_table_id table_id = get_device_table_id(); - constexpr int nwarps = calc_nwarps(type, ncols_dst, table_id, small_k, halve_iters); - constexpr int rows_per_cuda_block = calc_rows_per_block(type, ncols_dst, table_id, small_k, nwarps); + constexpr int nwarps = spark_2w ? 2 : calc_nwarps(type, ncols_dst, table_id, small_k, halve_iters); + constexpr int rows_per_cuda_block = spark_2w ? 1 : calc_rows_per_block(type, ncols_dst, table_id, small_k, nwarps); constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr vec_dot_q_cuda_t vec_dot_q_cuda = get_vec_dot_q_cuda(type); @@ -1198,6 +1198,27 @@ static void mul_mat_vec_q_switch_ncols_dst( return idle * 8 <= iters_wide * 2; }; + if constexpr (type == GGML_TYPE_NVFP4) { + static const bool use_2w = [] { const char * v = getenv("GGML_CUDA_SPARK_MMVQ_2W"); return v && atoi(v) != 0; }(); + if (use_2w && cc >= GGML_CUDA_CC_BLACKWELL && cc < GGML_CUDA_CC_RUBIN && has_ids && ncols_dst == 1 && + ncols_x == 1536 && !fusion.shared_up) { + const ggml_cuda_kernel_launch_params params(dim3(nrows_x, nchannels_dst, nsamples_dst), dim3(warp_size, 2), 0, stream); + const bool fused = fusion.gate || fusion.x_bias || fusion.gate_bias || fusion.x_scale || fusion.gate_scale; + if (fused) { + ggml_cuda_kernel_launch(mul_mat_vec_q, params, + vx, vy, ids, fusion, dst, ncols_x, nchannels_y_fd, stride_row_x, stride_col_y, stride_col_dst, + channel_ratio_fd, stride_channel_x, stride_channel_y, stride_channel_dst, + sample_ratio_fd, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride); + } else { + ggml_cuda_kernel_launch(mul_mat_vec_q, params, + vx, vy, ids, fusion, dst, ncols_x, nchannels_y_fd, stride_row_x, stride_col_y, stride_col_dst, + channel_ratio_fd, stride_channel_x, stride_channel_y, stride_channel_dst, + sample_ratio_fd, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride); + } + return; + } + } + if (has_ids && ncols_dst > 1) { // Multi-token MUL_MAT_ID path - dedicated MoE kernel mul_mat_vec_q_moe_launch( @@ -1454,7 +1475,7 @@ static void mul_mat_vec_q_switch_type( void ggml_cuda_mul_mat_vec_q( ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, - const ggml_cuda_mm_fusion_args_host * fusion) { + const ggml_cuda_mm_fusion_args_host * fusion, ggml_cuda_mmvq_cache * cache) { GGML_ASSERT( src1->type == GGML_TYPE_F32); GGML_ASSERT( dst->type == GGML_TYPE_F32); GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID. @@ -1549,12 +1570,25 @@ void ggml_cuda_mul_mat_vec_q( } const int64_t ne10_padded = GGML_PAD(ne10, MATRIX_ROW_PADDING); - ggml_cuda_pool_alloc src1_q8_1(ctx.pool(), ne13*ne12 * ne11*ne10_padded * sizeof(block_q8_1)/QK8_1); - { + ggml_cuda_pool_alloc src1_q8_1(ctx.pool()); + char * src1_quantized = nullptr; + bool quantize = true; + if (cache) { + auto it = cache->entries.find(ggml_cuda_mmvq_cache_key(src1)); + if (it != cache->entries.end()) { + src1_quantized = cache->data.get() + it->second.offset; + quantize = !it->second.ready; + it->second.ready = true; + } + } + if (!src1_quantized) { + src1_quantized = src1_q8_1.alloc(ne13*ne12 * ne11*ne10_padded * sizeof(block_q8_1)/QK8_1); + } + if (quantize) { const int64_t s11 = src1->nb[1] / ts_src1; const int64_t s12 = src1->nb[2] / ts_src1; const int64_t s13 = src1->nb[3] / ts_src1; - quantize_row_q8_1_cuda(src1_d, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream); + quantize_row_q8_1_cuda(src1_d, nullptr, src1_quantized, src0->type, ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream); } const int64_t s01 = src0->nb[1] / ts_src0; @@ -1580,7 +1614,7 @@ void ggml_cuda_mul_mat_vec_q( const int64_t ids_stride = ids ? ids->nb[1] / ggml_type_size(ids->type) : 0; mul_mat_vec_q_switch_type( - src0->data, src0->type, src1_q8_1.get(), ids_d, fusion_local, dst_d, ne00, + src0->data, src0->type, src1_quantized, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst, ne03, ne3, s03, s13, s3, ids_stride, stream); diff --git a/ggml/src/ggml-cuda/mmvq.cuh b/ggml/src/ggml-cuda/mmvq.cuh index 5605bf7a4e60348c047844c771e7171849ba2eec..b5a39a6b191b5eeee7a49bdc9758c6f0ed1b0a09 100644 --- a/ggml/src/ggml-cuda/mmvq.cuh +++ b/ggml/src/ggml-cuda/mmvq.cuh @@ -8,8 +8,25 @@ bool ggml_cuda_should_use_mmvq(enum ggml_type type, int cc, int64_t ne11); // based on the quantization type and GPU architecture (compute capability). int get_mmvq_mmid_max_batch(ggml_type type, int cc); +static inline const ggml_tensor * ggml_cuda_mmvq_cache_key(const ggml_tensor * x) { + while (x->view_src && x->data == x->view_src->data && x->type == x->view_src->type && + ggml_are_same_shape(x, x->view_src) && ggml_is_contiguous(x->view_src)) { + x = x->view_src; + } + return x; +} + +struct ggml_cuda_mmvq_cache { + struct entry { + size_t offset; + bool ready = false; + }; + std::unordered_map entries; + ggml_cuda_pool_alloc data; +}; + void ggml_cuda_mul_mat_vec_q(ggml_backend_cuda_context & ctx, - const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion = nullptr); + const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion = nullptr, ggml_cuda_mmvq_cache * cache = nullptr); void ggml_cuda_op_mul_mat_vec_q( ggml_backend_cuda_context & ctx, diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 4d057295c128c2b47f45564c635f597bd1f392ea..4645f2ffc6a2fd3bf44b86e272d826542c87ae4d 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -341,6 +341,16 @@ class Keys: VECTOR_EPS = "lilicorr.vector_eps" LOGIT_SCALE = "lilicorr.logit_scale" + class DFly: + SCHEMA_VERSION = "{arch}.schema_version" + TARGET_KV_LAYERS = "{arch}.target_kv_layers" + TARGET_INDEX_LAYERS = "{arch}.target_index_layers" + TARGET_INDEX_TOP_K = "{arch}.target_index_top_k" + HIDDEN_CORRECTION_LENGTH = "{arch}.hidden_correction_length" + MTP_FUSION = "{arch}.mtp_fusion" + ROPE_LAYOUT = "{arch}.rope_layout" + SOURCE_MROPE_SECTIONS = "{arch}.source_mrope_sections" + class PosNet: EMBEDDING_LENGTH = "{arch}.posnet.embedding_length" BLOCK_COUNT = "{arch}.posnet.block_count" @@ -702,6 +712,8 @@ class MODEL_ARCH(IntEnum): HUNYUAN_VL = auto() HY_V3 = auto() HY_V4 = auto() + HY_V4_FLASH = auto() + HY_V4_NEXT_DFLY = auto() SMOLLM3 = auto() GPT_OSS = auto() LFM2 = auto() @@ -1050,6 +1062,8 @@ class MODEL_TENSOR(IntEnum): INDEXER_COMPRESSOR_NORM = auto() INDEXER_KPOOL_GATE = auto() INDEXER_KPOOL_APE = auto() + INDEXER_KPOOL_VALUE = auto() + INDEXER_KPOOL_NORM = auto() ATTN_V_GATE = auto() # k2-horizon MoVA router ATTN_V_EXP = auto() # k2-horizon MoVA value experts # vision @@ -1377,6 +1391,10 @@ class MODEL_TENSOR(IntEnum): DSPARK_MASK_EMBD = auto() # per-slot mask embeddings ENGRAM_KV = auto() ENGRAM_GATE = auto() + ENGRAM_KV_B = auto() + ENGRAM_LOOKUP_NORM = auto() + ENGRAM_PRE_GAMMA = auto() + ENGRAM_HC_SCALE = auto() DFLASH_ATTN_CONV_BASE = auto() DFLASH_ATTN_CONV_PROJ = auto() DFLASH_FFN_CONV_BASE = auto() @@ -1384,6 +1402,16 @@ class MODEL_TENSOR(IntEnum): DFLASH_SELECTOR_PREV = auto() DFLASH_SELECTOR_NEXT = auto() DFLASH_SELECTOR_HIDDEN = auto() + DFLY_FUSION_ENORM = auto() + DFLY_FUSION_HNORM = auto() + DFLY_FUSION_EH = auto() + DFLY_FUSION_GATE = auto() + DFLY_CORRECTION_HNORM = auto() + DFLY_CORRECTION_ENORM = auto() + DFLY_CORRECTION_GATE = auto() + DFLY_CORRECTION_UP = auto() + DFLY_CORRECTION_DOWN = auto() + DFLY_CONFIDENCE = auto() LILICORR_TOKEN_PROJ = auto() LILICORR_PASS_HIDDEN_PROJ = auto() LILICORR_SLOT_EMBD = auto() @@ -1562,6 +1590,8 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = { MODEL_ARCH.HUNYUAN_VL: "hunyuan_vl", MODEL_ARCH.HY_V3: "hy_v3", MODEL_ARCH.HY_V4: "hy_v4", + MODEL_ARCH.HY_V4_FLASH: "hy_v4_flash", + MODEL_ARCH.HY_V4_NEXT_DFLY: "hy_v4_next_dfly", MODEL_ARCH.SMOLLM3: "smollm3", MODEL_ARCH.GPT_OSS: "gpt-oss", MODEL_ARCH.LFM2: "lfm2", @@ -1908,6 +1938,8 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = { MODEL_TENSOR.INDEXER_COMPRESSOR_NORM: "blk.{bid}.indexer_compressor_norm", MODEL_TENSOR.INDEXER_KPOOL_GATE: "blk.{bid}.indexer_compressor_gate", MODEL_TENSOR.INDEXER_KPOOL_APE: "blk.{bid}.indexer_compressor_ape", + MODEL_TENSOR.INDEXER_KPOOL_VALUE: "blk.{bid}.indexer_compressor_value", + MODEL_TENSOR.INDEXER_KPOOL_NORM: "blk.{bid}.indexer_compressor_norm", # vision MODEL_TENSOR.V_MMPROJ: "mm.{bid}", MODEL_TENSOR.V_MMPROJ_FC: "mm.model.fc", @@ -2259,6 +2291,10 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = { MODEL_TENSOR.DSPARK_MASK_EMBD: "mask_embd", MODEL_TENSOR.ENGRAM_KV: "blk.{bid}.engram_kv", MODEL_TENSOR.ENGRAM_GATE: "blk.{bid}.engram_gate", + MODEL_TENSOR.ENGRAM_KV_B: "blk.{bid}.engram_kv_b", + MODEL_TENSOR.ENGRAM_LOOKUP_NORM: "blk.{bid}.engram_lookup_norm", + MODEL_TENSOR.ENGRAM_PRE_GAMMA: "blk.{bid}.engram_pre_gamma", + MODEL_TENSOR.ENGRAM_HC_SCALE: "blk.{bid}.engram_hc_scale", MODEL_TENSOR.DFLASH_ATTN_CONV_BASE: "blk.{bid}.attn_conv_base", MODEL_TENSOR.DFLASH_ATTN_CONV_PROJ: "blk.{bid}.attn_conv_proj", MODEL_TENSOR.DFLASH_FFN_CONV_BASE: "blk.{bid}.ffn_conv_base", @@ -2266,6 +2302,16 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = { MODEL_TENSOR.DFLASH_SELECTOR_PREV: "selector_predecessor", MODEL_TENSOR.DFLASH_SELECTOR_NEXT: "selector_successor", MODEL_TENSOR.DFLASH_SELECTOR_HIDDEN: "selector_hidden", + MODEL_TENSOR.DFLY_FUSION_ENORM: "dfly_fusion_enorm", + MODEL_TENSOR.DFLY_FUSION_HNORM: "dfly_fusion_hnorm", + MODEL_TENSOR.DFLY_FUSION_EH: "dfly_fusion_eh", + MODEL_TENSOR.DFLY_FUSION_GATE: "dfly_fusion_gate", + MODEL_TENSOR.DFLY_CORRECTION_HNORM: "dfly_correction_hnorm", + MODEL_TENSOR.DFLY_CORRECTION_ENORM: "dfly_correction_enorm", + MODEL_TENSOR.DFLY_CORRECTION_GATE: "dfly_correction_gate", + MODEL_TENSOR.DFLY_CORRECTION_UP: "dfly_correction_up", + MODEL_TENSOR.DFLY_CORRECTION_DOWN: "dfly_correction_down", + MODEL_TENSOR.DFLY_CONFIDENCE: "dfly_confidence", MODEL_TENSOR.LILICORR_TOKEN_PROJ: "lilicorr.token_proj", MODEL_TENSOR.LILICORR_PASS_HIDDEN_PROJ: "lilicorr.pass_hidden_proj", MODEL_TENSOR.LILICORR_SLOT_EMBD: "lilicorr.slot_embedding", @@ -5553,6 +5599,96 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = { MODEL_TENSOR.FFN_DOWN_SHEXP, MODEL_TENSOR.FFN_UP_SHEXP, ], + MODEL_ARCH.HY_V4_FLASH: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ROPE_FREQS, + MODEL_TENSOR.HC_HEAD_FN, + MODEL_TENSOR.HC_HEAD_BASE, + MODEL_TENSOR.HC_HEAD_SCALE, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_SINKS, + MODEL_TENSOR.ATTN_Q_A, + MODEL_TENSOR.ATTN_Q_A_NORM, + MODEL_TENSOR.ATTN_Q_B, + MODEL_TENSOR.ATTN_KV_A_MQA, + MODEL_TENSOR.ATTN_KV_A_NORM, + MODEL_TENSOR.ATTN_K_B, + MODEL_TENSOR.ATTN_V_B, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.INDEXER_K_NORM, + MODEL_TENSOR.INDEXER_PROJ, + MODEL_TENSOR.INDEXER_ATTN_K, + MODEL_TENSOR.INDEXER_ATTN_Q_B, + MODEL_TENSOR.HC_ATTN_FN, + MODEL_TENSOR.HC_ATTN_BASE, + MODEL_TENSOR.HC_ATTN_SCALE, + MODEL_TENSOR.HC_FFN_FN, + MODEL_TENSOR.HC_FFN_BASE, + MODEL_TENSOR.HC_FFN_SCALE, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_SHEXP, + MODEL_TENSOR.FFN_DOWN_SHEXP, + MODEL_TENSOR.FFN_UP_SHEXP, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_POST_NORM, + MODEL_TENSOR.FFN_ROUTED_DOWN, + MODEL_TENSOR.FFN_ROUTED_UP, + MODEL_TENSOR.PER_LAYER_TOKEN_EMBD, + MODEL_TENSOR.ENGRAM_KV, + MODEL_TENSOR.ENGRAM_GATE, + MODEL_TENSOR.ENGRAM_KV_B, + MODEL_TENSOR.ENGRAM_LOOKUP_NORM, + MODEL_TENSOR.ENGRAM_PRE_GAMMA, + MODEL_TENSOR.ENGRAM_HC_SCALE, + MODEL_TENSOR.INDEXER_KPOOL_GATE, + MODEL_TENSOR.INDEXER_KPOOL_APE, + MODEL_TENSOR.INDEXER_KPOOL_VALUE, + MODEL_TENSOR.INDEXER_KPOOL_NORM, + MODEL_TENSOR.NEXTN_EH_PROJ, + MODEL_TENSOR.NEXTN_ENORM, + MODEL_TENSOR.NEXTN_HNORM, + MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM, + ], + MODEL_ARCH.HY_V4_NEXT_DFLY: [ + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q_A, + MODEL_TENSOR.ATTN_Q_A_NORM, + MODEL_TENSOR.ATTN_Q_B, + MODEL_TENSOR.ATTN_KV_A_MQA, + MODEL_TENSOR.ATTN_KV_A_NORM, + MODEL_TENSOR.ATTN_K_B, + MODEL_TENSOR.ATTN_V_B, + MODEL_TENSOR.ATTN_SINKS, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.DFLY_FUSION_ENORM, + MODEL_TENSOR.DFLY_FUSION_HNORM, + MODEL_TENSOR.DFLY_FUSION_EH, + MODEL_TENSOR.DFLY_FUSION_GATE, + MODEL_TENSOR.DFLY_CORRECTION_HNORM, + MODEL_TENSOR.DFLY_CORRECTION_ENORM, + MODEL_TENSOR.DFLY_CORRECTION_GATE, + MODEL_TENSOR.DFLY_CORRECTION_UP, + MODEL_TENSOR.DFLY_CORRECTION_DOWN, + MODEL_TENSOR.DFLY_CONFIDENCE, + ], MODEL_ARCH.SMOLLM3: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -6468,6 +6604,10 @@ MODEL_TENSOR_SKIP: dict[MODEL_ARCH, list[MODEL_TENSOR]] = { MODEL_TENSOR.ROPE_FREQS, MODEL_TENSOR.ATTN_ROT_EMBD, ], + MODEL_ARCH.HY_V4_FLASH: [ + MODEL_TENSOR.ROPE_FREQS, + MODEL_TENSOR.ATTN_ROT_EMBD, + ], MODEL_ARCH.CHATGLM: [ MODEL_TENSOR.ROPE_FREQS, ], @@ -6734,6 +6874,7 @@ class VisionProjectorType: POCKETTTS_GEN = "pockettts_gen" # audio generation: flow-matching decoder + mimi decoder SOPRANO = "soprano" # audio generation: Vocos decoder HUNYUANVL = "hunyuanvl" + HY_V4_FLASH = "hy_v4_flash" PARAKEET = "parakeet" # audio MINIMAXM3 = "minimax_m3" MINICPMV4_6 = "minicpmv4_6" diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index a0800e24c0a68e78ebd6a7a6e3fbfb2119ff29c3..a872a4bce870829f941bb0fad98fa948402f1d5f 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -1312,6 +1312,51 @@ class GGUFWriter: def add_lilicorr_logit_scale(self, value: float) -> None: self.add_float32(Keys.LiliCorr.LOGIT_SCALE, value) + @staticmethod + def _is_uint32(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and 0 <= value < 2**32 + + def _add_dfly_uint32(self, key: str, value: int) -> None: + if not self._is_uint32(value): + raise ValueError(f"{key} must be a uint32, got {value!r}") + self.add_uint32(key, value) + + def _add_dfly_uint32_array(self, key: str, values: Sequence[int]) -> None: + # add_array would infer INT32 from Python ints + if not isinstance(values, (list, tuple)) or not values or not all(self._is_uint32(v) for v in values): + raise ValueError(f"{key} must be a non-empty list of uint32, got {values!r}") + self.add_key_value(key, list(values), GGUFValueType.ARRAY, sub_type=GGUFValueType.UINT32) + + def _add_dfly_string(self, key: str, value: str) -> None: + # add_string silently skips an empty string + if not isinstance(value, str) or not value: + raise ValueError(f"{key} must be a non-empty string, got {value!r}") + self.add_string(key, value) + + def add_dfly_schema_version(self, value: int) -> None: + self._add_dfly_uint32(Keys.DFly.SCHEMA_VERSION.format(arch=self.arch), value) + + def add_dfly_target_kv_layers(self, value: Sequence[int]) -> None: + self._add_dfly_uint32_array(Keys.DFly.TARGET_KV_LAYERS.format(arch=self.arch), value) + + def add_dfly_target_index_layers(self, value: Sequence[int]) -> None: + self._add_dfly_uint32_array(Keys.DFly.TARGET_INDEX_LAYERS.format(arch=self.arch), value) + + def add_dfly_target_index_top_k(self, value: int) -> None: + self._add_dfly_uint32(Keys.DFly.TARGET_INDEX_TOP_K.format(arch=self.arch), value) + + def add_dfly_hidden_correction_length(self, value: int) -> None: + self._add_dfly_uint32(Keys.DFly.HIDDEN_CORRECTION_LENGTH.format(arch=self.arch), value) + + def add_dfly_mtp_fusion(self, value: str) -> None: + self._add_dfly_string(Keys.DFly.MTP_FUSION.format(arch=self.arch), value) + + def add_dfly_rope_layout(self, value: str) -> None: + self._add_dfly_string(Keys.DFly.ROPE_LAYOUT.format(arch=self.arch), value) + + def add_dfly_source_mrope_sections(self, value: Sequence[int]) -> None: + self._add_dfly_uint32_array(Keys.DFly.SOURCE_MROPE_SECTIONS.format(arch=self.arch), value) + def add_tokenizer_model(self, model: str) -> None: self.add_string(Keys.Tokenizer.MODEL, model) diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index d06dc4ec5fdcd3c1f7b5aa75025a095ac0a1db07..325ea6ec0fe75a65e2403147fcccd8020fd6a8e1 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -219,6 +219,36 @@ class TensorNameMap: MODEL_TENSOR.LILICORR_ANCHOR_OUT_HEAD: ( "model.lilicorr.anchor_out_head", ), + MODEL_TENSOR.DFLY_FUSION_ENORM: ( + "mtp_fusion.enorm", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_FUSION_HNORM: ( + "mtp_fusion.hnorm", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_FUSION_EH: ( + "mtp_fusion.eh_proj", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_FUSION_GATE: ( + "mtp_fusion.gate", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_CORRECTION_HNORM: ( + "hidden_correction.hidden_norm", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_CORRECTION_ENORM: ( + "hidden_correction.embed_norm", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_CORRECTION_GATE: ( + "hidden_correction.gate_proj", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_CORRECTION_UP: ( + "hidden_correction.up_proj", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_CORRECTION_DOWN: ( + "hidden_correction.down_proj", # hy_v4_next_dfly + ), + MODEL_TENSOR.DFLY_CONFIDENCE: ( + "confidence_head.proj", # hy_v4_next_dfly + ), } block_mappings_cfg: dict[MODEL_TENSOR, tuple[str, ...]] = { @@ -420,6 +450,7 @@ class TensorNameMap: "model.layers.{bid}.post_attn_norm", # kolibri1 "model.layers.layers.{bid}.post_mixer_norm.weight", # plamo2 "model.layers.{bid}.post_operator_norm", # lfm3 + "model.layers.{bid}.self_attn.post_proj_norm", # hy-v4-flash ), # Rotary embeddings @@ -504,6 +535,8 @@ class TensorNameMap: "model.layers.{bid}.post_mlp_layernorm", # glm-4-0414 "model.layers.{bid}.post_ffn_norm", # kolibri1 "model.layers.layers.{bid}.post_mlp_norm.weight", # plamo2 + "model.layers.{bid}.mlp.combine_output_norm", # hy-v4-flash (MoE layers) + "model.layers.{bid}.mlp.post_fc2_norm", # hy-v4-flash (dense layers) "model.layers.{bid}.feed_forward.up_proj", "model.layers.{bid}.post_moe_norm", # grok-2 "model.layers.{bid}.post_ffn_norm", # lfm3 @@ -1026,10 +1059,12 @@ class TensorNameMap: # Kimi K3 latent MoE: routed experts operate in a down-projected space MODEL_TENSOR.FFN_ROUTED_DOWN: ( "model.layers.{bid}.block_sparse_moe.routed_expert_down_proj", + "model.layers.{bid}.mlp.routed_expert_down_proj", # hy-v4-flash ), MODEL_TENSOR.FFN_ROUTED_UP: ( "model.layers.{bid}.block_sparse_moe.routed_expert_up_proj", + "model.layers.{bid}.mlp.routed_expert_up_proj", # hy-v4-flash ), MODEL_TENSOR.FFN_ROUTED_NORM: ( @@ -2406,6 +2441,7 @@ class TensorNameMap: MODEL_TENSOR.V_MM_PRE_NORM: ( "vit.perceive.before_rms", # HunyuanVL + "vit.perceive.norm", # hy-v4-flash ), MODEL_TENSOR.V_TOK_IMG_BEGIN: ( diff --git a/gguf-py/tests/test_dfly_constants.py b/gguf-py/tests/test_dfly_constants.py new file mode 100755 index 0000000000000000000000000000000000000000..df905a0b1b7de09fb3d1a01153fc336456bf2a6a --- /dev/null +++ b/gguf-py/tests/test_dfly_constants.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 + +import unittest +from pathlib import Path +import os +import sys + +# Necessary to load the local gguf package +if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent / 'gguf-py').exists(): + sys.path.insert(0, str(Path(__file__).parent.parent)) + +from gguf.constants import Keys, MODEL_ARCH, MODEL_ARCH_NAMES, MODEL_TENSOR, MODEL_TENSORS, TENSOR_NAMES + +ARCH = "hy_v4_next_dfly" + +# written out on purpose, same lists as tests/test-dfly.cpp +EXPECTED_TENSOR_NAMES = [ + "blk.0.attn_norm.weight", + "blk.0.attn_q_a.weight", + "blk.0.attn_q_a_norm.weight", + "blk.0.attn_q_b.weight", + "blk.0.attn_kv_a_mqa.weight", + "blk.0.attn_kv_a_norm.weight", + "blk.0.attn_k_b.weight", + "blk.0.attn_v_b.weight", + "blk.0.attn_sinks.weight", + "blk.0.attn_gate.weight", + "blk.0.attn_output.weight", + "blk.0.post_attention_norm.weight", + "blk.0.ffn_norm.weight", + "blk.0.ffn_gate.weight", + "blk.0.ffn_up.weight", + "blk.0.ffn_down.weight", + "blk.1.attn_norm.weight", + "blk.1.attn_q_a.weight", + "blk.1.attn_q_a_norm.weight", + "blk.1.attn_q_b.weight", + "blk.1.attn_kv_a_mqa.weight", + "blk.1.attn_kv_a_norm.weight", + "blk.1.attn_k_b.weight", + "blk.1.attn_v_b.weight", + "blk.1.attn_sinks.weight", + "blk.1.attn_gate.weight", + "blk.1.attn_output.weight", + "blk.1.post_attention_norm.weight", + "blk.1.ffn_norm.weight", + "blk.1.ffn_gate.weight", + "blk.1.ffn_up.weight", + "blk.1.ffn_down.weight", + "blk.2.attn_norm.weight", + "blk.2.attn_q_a.weight", + "blk.2.attn_q_a_norm.weight", + "blk.2.attn_q_b.weight", + "blk.2.attn_kv_a_mqa.weight", + "blk.2.attn_kv_a_norm.weight", + "blk.2.attn_k_b.weight", + "blk.2.attn_v_b.weight", + "blk.2.attn_sinks.weight", + "blk.2.attn_gate.weight", + "blk.2.attn_output.weight", + "blk.2.post_attention_norm.weight", + "blk.2.ffn_norm.weight", + "blk.2.ffn_gate.weight", + "blk.2.ffn_up.weight", + "blk.2.ffn_down.weight", + "blk.3.attn_norm.weight", + "blk.3.attn_q_a.weight", + "blk.3.attn_q_a_norm.weight", + "blk.3.attn_q_b.weight", + "blk.3.attn_kv_a_mqa.weight", + "blk.3.attn_kv_a_norm.weight", + "blk.3.attn_k_b.weight", + "blk.3.attn_v_b.weight", + "blk.3.attn_sinks.weight", + "blk.3.attn_gate.weight", + "blk.3.attn_output.weight", + "blk.3.post_attention_norm.weight", + "blk.3.ffn_norm.weight", + "blk.3.ffn_gate.weight", + "blk.3.ffn_up.weight", + "blk.3.ffn_down.weight", + "blk.4.attn_norm.weight", + "blk.4.attn_q_a.weight", + "blk.4.attn_q_a_norm.weight", + "blk.4.attn_q_b.weight", + "blk.4.attn_kv_a_mqa.weight", + "blk.4.attn_kv_a_norm.weight", + "blk.4.attn_k_b.weight", + "blk.4.attn_v_b.weight", + "blk.4.attn_sinks.weight", + "blk.4.attn_gate.weight", + "blk.4.attn_output.weight", + "blk.4.post_attention_norm.weight", + "blk.4.ffn_norm.weight", + "blk.4.ffn_gate.weight", + "blk.4.ffn_up.weight", + "blk.4.ffn_down.weight", + "output_norm.weight", + "dfly_fusion_enorm.weight", + "dfly_fusion_hnorm.weight", + "dfly_fusion_eh.weight", + "dfly_fusion_gate.weight", + "dfly_correction_hnorm.weight", + "dfly_correction_enorm.weight", + "dfly_correction_gate.weight", + "dfly_correction_up.weight", + "dfly_correction_down.weight", + "dfly_confidence.weight", + "dfly_confidence.bias", +] + +EXPECTED_KEYS = [ + (Keys.General.ARCHITECTURE, "general.architecture"), + (Keys.DFly.SCHEMA_VERSION, "hy_v4_next_dfly.schema_version"), + (Keys.LLM.BLOCK_SIZE, "hy_v4_next_dfly.block_size"), + (Keys.Attention.CAUSAL, "hy_v4_next_dfly.attention.causal"), + (Keys.LLM.BLOCK_COUNT, "hy_v4_next_dfly.block_count"), + (Keys.LLM.CONTEXT_LENGTH, "hy_v4_next_dfly.context_length"), + (Keys.LLM.EMBEDDING_LENGTH, "hy_v4_next_dfly.embedding_length"), + (Keys.LLM.FEED_FORWARD_LENGTH, "hy_v4_next_dfly.feed_forward_length"), + (Keys.Attention.HEAD_COUNT, "hy_v4_next_dfly.attention.head_count"), + (Keys.Attention.HEAD_COUNT_KV, "hy_v4_next_dfly.attention.head_count_kv"), + (Keys.Attention.Q_LORA_RANK, "hy_v4_next_dfly.attention.q_lora_rank"), + (Keys.Attention.KV_LORA_RANK, "hy_v4_next_dfly.attention.kv_lora_rank"), + (Keys.Attention.KEY_LENGTH, "hy_v4_next_dfly.attention.key_length"), + (Keys.Attention.VALUE_LENGTH, "hy_v4_next_dfly.attention.value_length"), + (Keys.Attention.KEY_LENGTH_MLA, "hy_v4_next_dfly.attention.key_length_mla"), + (Keys.Attention.VALUE_LENGTH_MLA, "hy_v4_next_dfly.attention.value_length_mla"), + (Keys.Rope.DIMENSION_COUNT, "hy_v4_next_dfly.rope.dimension_count"), + (Keys.Rope.FREQ_BASE, "hy_v4_next_dfly.rope.freq_base"), + (Keys.Attention.LAYERNORM_RMS_EPS, "hy_v4_next_dfly.attention.layer_norm_rms_epsilon"), + (Keys.DFly.TARGET_KV_LAYERS, "hy_v4_next_dfly.target_kv_layers"), + (Keys.DFly.TARGET_INDEX_LAYERS, "hy_v4_next_dfly.target_index_layers"), + (Keys.DFly.TARGET_INDEX_TOP_K, "hy_v4_next_dfly.target_index_top_k"), + (Keys.DFly.HIDDEN_CORRECTION_LENGTH, "hy_v4_next_dfly.hidden_correction_length"), + (Keys.LLM.HAS_CONFIDENCE_HEAD, "hy_v4_next_dfly.has_confidence_head"), + (Keys.DFly.MTP_FUSION, "hy_v4_next_dfly.mtp_fusion"), + (Keys.DFly.ROPE_LAYOUT, "hy_v4_next_dfly.rope_layout"), + (Keys.DFly.SOURCE_MROPE_SECTIONS, "hy_v4_next_dfly.source_mrope_sections"), + (Keys.Tokenizer.MASK_ID, "tokenizer.ggml.mask_token_id"), +] + +EXPECTED_NEW_TENSOR_NAMES = { + MODEL_TENSOR.DFLY_FUSION_ENORM: "dfly_fusion_enorm", + MODEL_TENSOR.DFLY_FUSION_HNORM: "dfly_fusion_hnorm", + MODEL_TENSOR.DFLY_FUSION_EH: "dfly_fusion_eh", + MODEL_TENSOR.DFLY_FUSION_GATE: "dfly_fusion_gate", + MODEL_TENSOR.DFLY_CORRECTION_HNORM: "dfly_correction_hnorm", + MODEL_TENSOR.DFLY_CORRECTION_ENORM: "dfly_correction_enorm", + MODEL_TENSOR.DFLY_CORRECTION_GATE: "dfly_correction_gate", + MODEL_TENSOR.DFLY_CORRECTION_UP: "dfly_correction_up", + MODEL_TENSOR.DFLY_CORRECTION_DOWN: "dfly_correction_down", + MODEL_TENSOR.DFLY_CONFIDENCE: "dfly_confidence", +} + +# exact members: ATTN_KV_NORM and FFN_PRE_NORM have the same names as ATTN_KV_A_NORM and FFN_NORM +EXPECTED_TENSOR_TYPES = { + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q_A, + MODEL_TENSOR.ATTN_Q_A_NORM, + MODEL_TENSOR.ATTN_Q_B, + MODEL_TENSOR.ATTN_KV_A_MQA, + MODEL_TENSOR.ATTN_KV_A_NORM, + MODEL_TENSOR.ATTN_K_B, + MODEL_TENSOR.ATTN_V_B, + MODEL_TENSOR.ATTN_SINKS, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.OUTPUT_NORM, + *EXPECTED_NEW_TENSOR_NAMES, +} + + +class TestDFlyConstants(unittest.TestCase): + maxDiff = None + + def test_arch_name(self): + self.assertEqual(MODEL_ARCH_NAMES[MODEL_ARCH.HY_V4_NEXT_DFLY], ARCH) + + def test_tensor_types(self): + types = MODEL_TENSORS[MODEL_ARCH.HY_V4_NEXT_DFLY] + self.assertEqual(len(types), 27) + self.assertEqual(len(set(types)), len(types)) + self.assertEqual(set(types), EXPECTED_TENSOR_TYPES) + # borrowed from the target, never written to a DFly GGUF + self.assertNotIn(MODEL_TENSOR.TOKEN_EMBD, types) + self.assertNotIn(MODEL_TENSOR.OUTPUT, types) + + def test_tensor_names(self): + self.assertEqual(len(EXPECTED_TENSOR_NAMES), 92) + names = [] + for t in MODEL_TENSORS[MODEL_ARCH.HY_V4_NEXT_DFLY]: + name = TENSOR_NAMES[t] + if "{bid}" in name: + names += [name.format(bid=i) + ".weight" for i in range(5)] + else: + names.append(name + ".weight") + if t == MODEL_TENSOR.DFLY_CONFIDENCE: + names.append(name + ".bias") + self.assertCountEqual(names, EXPECTED_TENSOR_NAMES) + + def test_keys(self): + self.assertEqual(len(EXPECTED_KEYS), 28) + for key, expected in EXPECTED_KEYS: + with self.subTest(key=expected): + self.assertEqual(key.format(arch=ARCH), expected) + + def test_new_tensor_names(self): + for t, expected in EXPECTED_NEW_TENSOR_NAMES.items(): + with self.subTest(tensor=t.name): + self.assertEqual(TENSOR_NAMES[t], expected) + + +if __name__ == '__main__': + unittest.main() diff --git a/gguf-py/tests/test_dfly_writer.py b/gguf-py/tests/test_dfly_writer.py new file mode 100755 index 0000000000000000000000000000000000000000..e723f0d0dd61edb623ab815b412154f3782ba7d6 --- /dev/null +++ b/gguf-py/tests/test_dfly_writer.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 + +import tempfile +import unittest +from pathlib import Path +import os +import sys + +# Necessary to load the local gguf package +if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent / 'gguf-py').exists(): + sys.path.insert(0, str(Path(__file__).parent.parent)) + +from gguf import GGUFReader, GGUFValueType, GGUFWriter + +ARCH = "hy_v4_next_dfly" + + +def write_and_read(path: Path, fill) -> GGUFReader: + writer = GGUFWriter(path, ARCH) + fill(writer) + writer.write_header_to_file() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + return GGUFReader(path) + + +class TestDFlyWriter(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.path = Path(tmp.name) / "dfly.gguf" + + def test_keys(self): + def fill(w: GGUFWriter): + w.add_dfly_schema_version(1) + w.add_dfly_target_kv_layers([25, 29, 33, 37, 41]) + w.add_dfly_target_index_layers((25, 29, 33, 37, 41)) + w.add_dfly_target_index_top_k(2048) + w.add_dfly_hidden_correction_length(3072) + w.add_dfly_mtp_fusion("slot0") + w.add_dfly_rope_layout("norm_adjacent") + w.add_dfly_source_mrope_sections([12, 10, 10]) + + r = write_and_read(self.path, fill) + for key, types, value in ( + ("schema_version", [GGUFValueType.UINT32], 1), + ("target_kv_layers", [GGUFValueType.ARRAY, GGUFValueType.UINT32], [25, 29, 33, 37, 41]), + ("target_index_layers", [GGUFValueType.ARRAY, GGUFValueType.UINT32], [25, 29, 33, 37, 41]), + ("target_index_top_k", [GGUFValueType.UINT32], 2048), + ("hidden_correction_length", [GGUFValueType.UINT32], 3072), + ("mtp_fusion", [GGUFValueType.STRING], "slot0"), + ("rope_layout", [GGUFValueType.STRING], "norm_adjacent"), + ("source_mrope_sections", [GGUFValueType.ARRAY, GGUFValueType.UINT32], [12, 10, 10]), + ): + with self.subTest(key=key): + field = r.fields[f"{ARCH}.{key}"] + self.assertEqual(list(field.types), types) + self.assertEqual(field.contents(), value) + + def test_rejects(self): + writer = GGUFWriter(None, ARCH) + for name, call in ( + ("empty list", lambda: writer.add_dfly_target_kv_layers([])), + ("bool element", lambda: writer.add_dfly_target_index_layers([25, True])), + ("negative element", lambda: writer.add_dfly_source_mrope_sections([12, -1, 10])), + ("element too large", lambda: writer.add_dfly_target_kv_layers([2**32])), + ("float element", lambda: writer.add_dfly_target_kv_layers([25.0])), + ("not a list", lambda: writer.add_dfly_target_kv_layers(25)), + ("bool scalar", lambda: writer.add_dfly_schema_version(True)), + ("negative scalar", lambda: writer.add_dfly_target_index_top_k(-1)), + ("scalar too large", lambda: writer.add_dfly_hidden_correction_length(2**32)), + ("empty string", lambda: writer.add_dfly_mtp_fusion("")), + ("not a string", lambda: writer.add_dfly_rope_layout(None)), + ): + with self.subTest(case=name), self.assertRaises(ValueError): + call() + self.assertEqual([k for k in writer.kv_data[0] if k.startswith(ARCH + ".")], []) + + def test_target_layers_still_int32(self): + # other architectures rely on add_target_layers inferring INT32 + r = write_and_read(self.path, lambda w: w.add_target_layers([1, 2, 3])) + field = r.fields[f"{ARCH}.target_layers"] + self.assertEqual(list(field.types), [GGUFValueType.ARRAY, GGUFValueType.INT32]) + self.assertEqual(field.contents(), [1, 2, 3]) + + +if __name__ == '__main__': + unittest.main() diff --git a/include/llama.h b/include/llama.h index 3877b69e2d1e8559e4614ba61a7dcc0e4dc2343e..e705195216d96aad3a6e89b281f9e28d9c934871 100644 --- a/include/llama.h +++ b/include/llama.h @@ -606,6 +606,7 @@ extern "C" { LLAMA_API int32_t llama_model_n_head (const struct llama_model * model); LLAMA_API int32_t llama_model_n_head_kv (const struct llama_model * model); LLAMA_API int32_t llama_model_n_swa (const struct llama_model * model); + LLAMA_API int32_t llama_model_swa_type (const struct llama_model * model); // 0 none, 1 standard, 2 chunked, 3 symmetric // Get the model's RoPE frequency scaling factor LLAMA_API float llama_model_rope_freq_scale_train(const struct llama_model * model); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 97250c2e885645386702f516d1f00ff2c9b121f2..d15912560f4743ac1fd509c82b11c12f6b1b1b2f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -32,6 +32,7 @@ set(LLAMA_CORE_SOURCES llama-memory-hybrid.cpp llama-memory-hybrid-iswa.cpp llama-memory-hybrid-idx.cpp + llama-memory-idx-iswa.cpp llama-memory-recurrent.cpp llama-mmap.cpp llama-model-loader.cpp diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 40f608371c548107f2dcf24217a4d8c60be16a02..36a9995e76e5925f42122e647870f3c2ab8d5c66 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -132,6 +132,8 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_HUNYUAN_VL, "hunyuan_vl" }, { LLM_ARCH_HY_V3, "hy_v3" }, { LLM_ARCH_HY_V4, "hy_v4" }, + { LLM_ARCH_HY_V4_FLASH, "hy_v4_flash" }, + { LLM_ARCH_HY_V4_NEXT_DFLY, "hy_v4_next_dfly" }, { LLM_ARCH_SMOLLM3, "smollm3" }, { LLM_ARCH_OPENAI_MOE, "gpt-oss" }, { LLM_ARCH_LFM2, "lfm2" }, @@ -420,6 +422,16 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" }, { LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" }, + { LLM_KV_DFLY_SCHEMA_VERSION, "%s.schema_version" }, + { LLM_KV_DFLY_TARGET_KV_LAYERS, "%s.target_kv_layers" }, + { LLM_KV_DFLY_TARGET_INDEX_LAYERS, "%s.target_index_layers" }, + { LLM_KV_DFLY_TARGET_INDEX_TOP_K, "%s.target_index_top_k" }, + { LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, "%s.hidden_correction_length" }, + { LLM_KV_DFLY_MTP_FUSION, "%s.mtp_fusion" }, + { LLM_KV_DFLY_ROPE_LAYOUT, "%s.rope_layout" }, + { LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, "%s.source_mrope_sections" }, + { LLM_KV_HAS_CONFIDENCE_HEAD, "%s.has_confidence_head" }, + { LLM_KV_LILICORR_HIDDEN_SIZE, "lilicorr.hidden_size" }, { LLM_KV_LILICORR_CANDIDATE_TOPK, "lilicorr.candidate_topk" }, { LLM_KV_LILICORR_NUM_HEADS, "lilicorr.num_heads" }, @@ -808,6 +820,8 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_INDEXER_COMPRESSOR_NORM, "blk.%d.indexer_compressor_norm" }, { LLM_TENSOR_INDEXER_KPOOL_GATE, "blk.%d.indexer_compressor_gate" }, { LLM_TENSOR_INDEXER_KPOOL_APE, "blk.%d.indexer_compressor_ape" }, + { LLM_TENSOR_INDEXER_KPOOL_VALUE, "blk.%d.indexer_compressor_value" }, + { LLM_TENSOR_INDEXER_KPOOL_NORM, "blk.%d.indexer_compressor_norm" }, { LLM_TENSOR_FFN_GATE_TID2EID, "blk.%d.ffn_gate_tid2eid" }, { LLM_TENSOR_MASKED_EMBD_CENTROIDS, "masked_embd_centroids" }, { LLM_TENSOR_MASKED_EMBD_ORDERING, "masked_embd_ordering" }, @@ -820,6 +834,10 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_DSPARK_MASK_EMBD, "mask_embd" }, { LLM_TENSOR_ENGRAM_KV, "blk.%d.engram_kv" }, { LLM_TENSOR_ENGRAM_GATE, "blk.%d.engram_gate" }, + { LLM_TENSOR_ENGRAM_KV_B, "blk.%d.engram_kv_b" }, + { LLM_TENSOR_ENGRAM_LOOKUP_NORM, "blk.%d.engram_lookup_norm" }, + { LLM_TENSOR_ENGRAM_PRE_GAMMA, "blk.%d.engram_pre_gamma" }, + { LLM_TENSOR_ENGRAM_HC_SCALE, "blk.%d.engram_hc_scale" }, { LLM_TENSOR_DFLASH_ATTN_CONV_BASE, "blk.%d.attn_conv_base" }, { LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, "blk.%d.attn_conv_proj" }, { LLM_TENSOR_DFLASH_FFN_CONV_BASE, "blk.%d.ffn_conv_base" }, @@ -827,6 +845,16 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_DFLASH_SELECTOR_PREV, "selector_predecessor" }, { LLM_TENSOR_DFLASH_SELECTOR_NEXT, "selector_successor" }, { LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, "selector_hidden" }, + { LLM_TENSOR_DFLY_FUSION_ENORM, "dfly_fusion_enorm" }, + { LLM_TENSOR_DFLY_FUSION_HNORM, "dfly_fusion_hnorm" }, + { LLM_TENSOR_DFLY_FUSION_EH, "dfly_fusion_eh" }, + { LLM_TENSOR_DFLY_FUSION_GATE, "dfly_fusion_gate" }, + { LLM_TENSOR_DFLY_CORRECTION_HNORM, "dfly_correction_hnorm" }, + { LLM_TENSOR_DFLY_CORRECTION_ENORM, "dfly_correction_enorm" }, + { LLM_TENSOR_DFLY_CORRECTION_GATE, "dfly_correction_gate" }, + { LLM_TENSOR_DFLY_CORRECTION_UP, "dfly_correction_up" }, + { LLM_TENSOR_DFLY_CORRECTION_DOWN, "dfly_correction_down" }, + { LLM_TENSOR_DFLY_CONFIDENCE, "dfly_confidence" }, { LLM_TENSOR_LILICORR_TOKEN_PROJ, "lilicorr.token_proj" }, { LLM_TENSOR_LILICORR_PASS_HIDDEN_PROJ, "lilicorr.pass_hidden_proj" }, { LLM_TENSOR_LILICORR_SLOT_EMBD, "lilicorr.slot_embedding" }, @@ -1139,6 +1167,8 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_INDEXER_COMPRESSOR_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_INDEXER_KPOOL_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_INDEXER_KPOOL_APE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, + {LLM_TENSOR_INDEXER_KPOOL_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_INDEXER_KPOOL_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_FFN_GATE_TID2EID, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}}, {LLM_TENSOR_NEXTN_PROJ_PRE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_NEXTN_PROJ_POST, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, @@ -1175,6 +1205,10 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_DSPARK_MASK_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}}, {LLM_TENSOR_ENGRAM_KV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_ENGRAM_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_ENGRAM_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, + {LLM_TENSOR_ENGRAM_LOOKUP_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_ENGRAM_PRE_GAMMA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_ENGRAM_HC_SCALE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, {LLM_TENSOR_DFLASH_ATTN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_DFLASH_FFN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, @@ -1182,6 +1216,16 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_DFLASH_SELECTOR_PREV, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}}, {LLM_TENSOR_DFLASH_SELECTOR_NEXT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}}, {LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLY_FUSION_ENORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, + {LLM_TENSOR_DFLY_FUSION_HNORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, + {LLM_TENSOR_DFLY_FUSION_EH, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLY_FUSION_GATE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, + {LLM_TENSOR_DFLY_CORRECTION_HNORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, + {LLM_TENSOR_DFLY_CORRECTION_ENORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, + {LLM_TENSOR_DFLY_CORRECTION_GATE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLY_CORRECTION_UP, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLY_CORRECTION_DOWN, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLY_CONFIDENCE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_LILICORR_TOKEN_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_LILICORR_PASS_HIDDEN_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_LILICORR_SLOT_EMBD, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_ADD}}, @@ -1372,6 +1416,8 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { case LLM_ARCH_DEEPSEEK2: case LLM_ARCH_DEEPSEEK32: case LLM_ARCH_HY_V4: + case LLM_ARCH_HY_V4_FLASH: + case LLM_ARCH_HY_V4_NEXT_DFLY: case LLM_ARCH_DOTS3NOTE: case LLM_ARCH_GLM_DSA: case LLM_ARCH_BITNET: @@ -1409,6 +1455,7 @@ bool llama_arch_supports_save(llm_arch arch) { case LLM_ARCH_STEP35: case LLM_ARCH_CLEF: // the head tensors are not saved case LLM_ARCH_VLLM_DECISION2: + case LLM_ARCH_HY_V4_NEXT_DFLY: // the dfly keys and tensors are not saved return false; default: return true; diff --git a/src/llama-arch.h b/src/llama-arch.h index b98be40cf29bb7c6609a9531671cc73cb93b9b2c..1bdd35c936a57c6bb7bb5f19c67a964619d8e8dc 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -136,6 +136,8 @@ enum llm_arch { LLM_ARCH_HUNYUAN_VL, LLM_ARCH_HY_V3, LLM_ARCH_HY_V4, + LLM_ARCH_HY_V4_FLASH, + LLM_ARCH_HY_V4_NEXT_DFLY, LLM_ARCH_SMOLLM3, LLM_ARCH_OPENAI_MOE, LLM_ARCH_LFM2, @@ -465,6 +467,15 @@ enum llm_kv { LLM_KV_DFLASH_CONV_GROUP_SIZE, LLM_KV_DFLASH_SELECTOR_RANK, LLM_KV_DFLASH_SELECTOR_TOP_K, + LLM_KV_DFLY_SCHEMA_VERSION, + LLM_KV_DFLY_TARGET_KV_LAYERS, + LLM_KV_DFLY_TARGET_INDEX_LAYERS, + LLM_KV_DFLY_TARGET_INDEX_TOP_K, + LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, + LLM_KV_DFLY_MTP_FUSION, + LLM_KV_DFLY_ROPE_LAYOUT, + LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, + LLM_KV_HAS_CONFIDENCE_HEAD, LLM_KV_LILICORR_HIDDEN_SIZE, LLM_KV_LILICORR_CANDIDATE_TOPK, LLM_KV_LILICORR_NUM_HEADS, @@ -801,6 +812,8 @@ enum llm_tensor { LLM_TENSOR_INDEXER_COMPRESSOR_NORM, LLM_TENSOR_INDEXER_KPOOL_GATE, // glm5-next: k-pool gate scores LLM_TENSOR_INDEXER_KPOOL_APE, // glm5-next: k-pool position bias + LLM_TENSOR_INDEXER_KPOOL_VALUE, // hy_v4_flash: what the k-pool actually pools + LLM_TENSOR_INDEXER_KPOOL_NORM, // hy_v4_flash: norm of the pooled key LLM_TENSOR_FFN_GATE_TID2EID, LLM_TENSOR_NEXTN_PROJ_PRE, LLM_TENSOR_NEXTN_PROJ_POST, @@ -825,6 +838,10 @@ enum llm_tensor { LLM_TENSOR_DSPARK_MASK_EMBD, LLM_TENSOR_ENGRAM_KV, LLM_TENSOR_ENGRAM_GATE, + LLM_TENSOR_ENGRAM_KV_B, // hy_v4_flash: bias on the fused key/value projections + LLM_TENSOR_ENGRAM_LOOKUP_NORM, // hy_v4_flash: per-head RMSNorm of the looked-up rows + LLM_TENSOR_ENGRAM_PRE_GAMMA, // hy_v4_flash: scales the normed value before the gate + LLM_TENSOR_ENGRAM_HC_SCALE, // hy_v4_flash: per-hc per-channel additive gate offset LLM_TENSOR_DFLASH_ATTN_CONV_BASE, LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, LLM_TENSOR_DFLASH_FFN_CONV_BASE, @@ -832,6 +849,16 @@ enum llm_tensor { LLM_TENSOR_DFLASH_SELECTOR_PREV, LLM_TENSOR_DFLASH_SELECTOR_NEXT, LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, + LLM_TENSOR_DFLY_FUSION_ENORM, + LLM_TENSOR_DFLY_FUSION_HNORM, + LLM_TENSOR_DFLY_FUSION_EH, + LLM_TENSOR_DFLY_FUSION_GATE, + LLM_TENSOR_DFLY_CORRECTION_HNORM, + LLM_TENSOR_DFLY_CORRECTION_ENORM, + LLM_TENSOR_DFLY_CORRECTION_GATE, + LLM_TENSOR_DFLY_CORRECTION_UP, + LLM_TENSOR_DFLY_CORRECTION_DOWN, + LLM_TENSOR_DFLY_CONFIDENCE, LLM_TENSOR_LILICORR_TOKEN_PROJ, LLM_TENSOR_LILICORR_PASS_HIDDEN_PROJ, LLM_TENSOR_LILICORR_SLOT_EMBD, diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 0cd795a5690b31b55834f0e7ab3b4e7e3bf3fd7c..a12c45efb009d2d2dd785cd63b49dd43d7b6c04a 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -6,14 +6,19 @@ #include "llama-impl.h" #include "llama-batch.h" #include "llama-io.h" +#include "llama-kv-cache.h" +#include "llama-kv-cache-iswa.h" #include "llama-memory.h" #include "llama-mmap.h" #include "llama-model.h" #include "llama-moe-cache.h" #include "llama-ext.h" #include "llama-sampler.h" +#include "llama-vocab.h" +#include "models/hy-v4-next-dfly.h" #include "llama.h" +#include #include #include #include @@ -264,6 +269,15 @@ llama_context::llama_context( } } + // the DFly draft reads E, O and the K storage of the bound target + if (model.arch == LLM_ARCH_HY_V4_NEXT_DFLY) { + if (params.ctx_other == nullptr) { + throw std::runtime_error("hy_v4_next_dfly requires ctx_other to be the bound target"); + } + cparams.ctx_other = params.ctx_other; + cparams.dfly_inp = &dfly_inp; + } + if (cparams.rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) { cparams.rope_scaling_type = hparams.rope_scaling_type_train; } @@ -353,6 +367,16 @@ llama_context::llama_context( cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch); + if (model.arch == LLM_ARCH_HY_V4_NEXT_DFLY) { + // llama_init_from_model forces these before any reserve, a direct construction must not get past them either + if (cparams.flash_attn) { + throw std::runtime_error("hy_v4_next_dfly: flash attention must be disabled"); + } + if (cparams.n_ubatch != (params.n_ubatch == 0 ? params.n_batch : params.n_ubatch)) { + throw std::runtime_error(format("hy_v4_next_dfly: n_ubatch %u was cut to %u", params.n_ubatch, cparams.n_ubatch)); + } + } + cparams.n_outputs_max = params.n_outputs_max == 0 || llama_model_has_encoder(&model) ? cparams.n_batch : params.n_outputs_max; cparams.n_outputs_max_per_seq = params.n_outputs_max_per_seq == 0 ? cparams.n_outputs_max : std::min(params.n_outputs_max_per_seq, cparams.n_outputs_max); @@ -492,8 +516,8 @@ llama_context::llama_context( llama_set_abort_callback(this, params.abort_callback, params.abort_callback_data); - // graph outputs buffer - { + // graph outputs buffer; the DFly draft copies out only its few ids and probes + if (model.arch != LLM_ARCH_HY_V4_NEXT_DFLY) { if (output_reserve(params.n_seq_max) < params.n_seq_max) { throw std::runtime_error("failed to reserve initial output buffer"); } @@ -1391,6 +1415,770 @@ void llama_context::set_embeddings_nextn(bool value, bool masked) { cparams.embeddings_nextn_masked = masked; } +// ids of configured captures, never reused within the process +static std::atomic g_dfly_capture_ctx_id{0}; + +bool llama_context::dfly_capture_configure(const int32_t * layers, uint32_t n_layers, uint32_t dfly_top_k, std::string & err) { + if (dfly_cap_top_k > 0) { + const bool same = layers != nullptr && n_layers == cparams.dfly_capture_n_layer && dfly_top_k == dfly_cap_top_k && + std::equal(layers, layers + n_layers, cparams.dfly_capture_layers.begin()); + if (!same) { + err = "capture is already configured with other layers or S"; + return false; + } + return true; + } + + const auto & hparams = model.hparams; + + if (layers == nullptr || n_layers != LLAMA_DFLY_N_LAYER) { + err = format("expected %d target layers, got %u", LLAMA_DFLY_N_LAYER, layers ? n_layers : 0); + return false; + } + + const auto * mem = dynamic_cast(memory.get()); + if (model.arch != LLM_ARCH_HY_V4_FLASH || mem == nullptr) { + err = "capture needs a hy_v4_flash target with an indexer memory"; + return false; + } + if (mem->get_kpool() != 4 || mem->get_kpool_by_order() || !hparams.indexer_kpool_select_tail) { + err = format("capture needs pools of 4 positions and a selected tail, got kpool %u, by_order %d, select_tail %d", + mem->get_kpool(), (int) mem->get_kpool_by_order(), (int) hparams.indexer_kpool_select_tail); + return false; + } + + for (uint32_t k = 0; k < n_layers; ++k) { + const int32_t il = layers[k]; + if (il < 0 || (uint32_t) il >= hparams.n_layer()) { + err = format("layer %d: out of range [0, %u)", il, hparams.n_layer()); + return false; + } + if (hparams.is_swa(il) || !hparams.is_indexer_full(il)) { + err = format("layer %d: not a full attention layer with an indexer", il); + return false; + } + if (std::find(layers, layers + k, il) != layers + k) { + err = format("layer %d: listed twice", il); + return false; + } + } + + if (dfly_top_k < 4 || dfly_top_k > 2048 || dfly_top_k % 4 != 0 || dfly_top_k != hparams.indexer_top_k) { + err = format("S = %u must be a multiple of 4 in [4, 2048] and equal the target's indexer top_k %u", + dfly_top_k, hparams.indexer_top_k); + return false; + } + + if (cparams.ctx_type != LLAMA_CONTEXT_TYPE_DEFAULT || cparams.embeddings || cparams.pooling_type != LLAMA_POOLING_TYPE_NONE) { + err = "capture needs a default context without pooled embeddings"; + return false; + } + if (cparams.embeddings_nextn && !cparams.embeddings_nextn_masked) { + err = "capture cannot share the context with unmasked nextn embeddings (MTP/EAGLE3)"; + return false; + } + + cparams.dfly_capture_n_layer = n_layers; + std::copy(layers, layers + n_layers, cparams.dfly_capture_layers.begin()); + + dfly_cap_top_k = dfly_top_k; + dfly_cap_ctx_id = ++g_dfly_capture_ctx_id; + dfly_cap_decode_ok = false; + dfly_cap_n_rows = 0; + dfly_cap_err.clear(); + dfly_cap_stage.clear(); + dfly_cap_seq_decode.fill(0); + + set_embeddings_nextn(true, true); + + // the export changes the graph even when nextn was already masked + sched_need_reserve = true; + + return true; +} + +llama_dfly_capture_status llama_context::dfly_capture_take(uint64_t prefix_epoch, std::vector & out, std::string & err) { + out.clear(); + + if (dfly_cap_top_k == 0) { + err = "capture is not configured"; + return LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED; + } + if (!dfly_cap_decode_ok) { + err = "the last decode did not succeed"; + return LLAMA_DFLY_CAPTURE_STATUS_NO_ROWS; + } + if (!dfly_cap_err.empty()) { + err = dfly_cap_err; + return LLAMA_DFLY_CAPTURE_STATUS_ERROR; + } + if (dfly_cap_n_rows == 0) { + err = "the last decode has no output rows"; + return LLAMA_DFLY_CAPTURE_STATUS_NO_ROWS; + } + if (!cparams.embeddings_nextn || !cparams.embeddings_nextn_masked) { + err = "capture needs masked nextn embeddings"; + return LLAMA_DFLY_CAPTURE_STATUS_ERROR; + } + + int64_t n_staged = 0; + for (const auto & bl : dfly_cap_stage) { + n_staged += bl.n_rows; + } + if (n_staged != dfly_cap_n_rows) { + err = format("staged %" PRId64 " rows, the decode output %" PRId64, n_staged, dfly_cap_n_rows); + return LLAMA_DFLY_CAPTURE_STATUS_ERROR; + } + const auto * mem = dynamic_cast(memory.get()); + if (mem == nullptr) { + err = "the memory is not an indexer memory"; + return LLAMA_DFLY_CAPTURE_STATUS_ERROR; + } + + synchronize(); + + const uint32_t n_embd = model.hparams.n_embd_out(); + + std::vector res; + res.reserve(n_staged); + + llama_memory_idx_iswa::kpool_refs refs; + llama_dfly_ctx_set set; + std::string e; + + for (const auto & bl : dfly_cap_stage) { + for (int64_t r = 0; r < bl.n_rows; ++r) { + llama_dfly_snapshot s; + s.target_ctx_id = dfly_cap_ctx_id; + s.decode_id = dfly_cap_decode_id; + s.prefix_epoch = prefix_epoch; + s.seq_id = bl.seq[r]; + s.batch_row = bl.batch_row[r]; + s.query_pos = bl.pos[r]; + + const float * h = get_embeddings_nextn_ith(s.batch_row); + if (h == nullptr) { + err = format("row %d pos %d: no nextn embedding", s.batch_row, s.query_pos); + return LLAMA_DFLY_CAPTURE_STATUS_ERROR; + } + s.h_final.assign(h, h + n_embd); + + for (uint32_t k = 0; k < cparams.dfly_capture_n_layer; ++k) { + const int32_t il = cparams.dfly_capture_layers[k]; + const int32_t * ids = bl.ids[k].data() + r*bl.n_top; + const float * scores = bl.scores[k].data() + r*bl.n_top; + + llama_dfly_sel_status st = LLAMA_DFLY_SEL_STATUS_OK; + if (!mem->kpool_copy_refs(s.seq_id, s.query_pos, ids, bl.n_top, refs, e)) { + st = LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT; + } else { + st = llama_dfly_normalize_selection(ids, scores, bl.n_top, s.query_pos, dfly_cap_top_k, refs, set, e); + } + if (st != LLAMA_DFLY_SEL_STATUS_OK) { + err = format("row %d pos %d layer %d: %s", s.batch_row, s.query_pos, il, e.c_str()); + return LLAMA_DFLY_CAPTURE_STATUS_ERROR; + } + + auto & lc = s.layer[k]; + lc.target_layer = il; + lc.strm = set.strm; + lc.pos = std::move(set.pos); + lc.cell = std::move(set.cell); + } + + res.push_back(std::move(s)); + } + } + + out = std::move(res); + + return LLAMA_DFLY_CAPTURE_STATUS_OK; +} + +void llama_context::dfly_capture_stage(const llama_ubatch & ubatch, const llm_graph_result * res) { + if (!dfly_cap_err.empty()) { + return; + } + + const int64_t n_out = n_outputs; + + int64_t n_top = -1; + for (uint32_t k = 0; k < cparams.dfly_capture_n_layer; ++k) { + const int32_t il = cparams.dfly_capture_layers[k]; + const ggml_tensor * ti = res->t_dfly_ids[k]; + const ggml_tensor * ts = res->t_dfly_scores[k]; + if (ti == nullptr || ts == nullptr) { + dfly_cap_err = format("layer %d: export missing", il); + return; + } + if (ti->type != GGML_TYPE_I32 || ts->type != GGML_TYPE_F32 || + ti->ne[1] != n_out || ggml_nrows(ti) != n_out || ts->ne[1] != n_out || ggml_nrows(ts) != n_out || + ti->ne[0] != ts->ne[0] || (n_top >= 0 && ti->ne[0] != n_top)) { + dfly_cap_err = format("layer %d: export shape [%" PRId64 ", %" PRId64 "] does not match %" PRId64 " output rows", + il, ti->ne[0], ti->ne[1], n_out); + return; + } + if (!(ti->flags & GGML_TENSOR_FLAG_OUTPUT) || !(ts->flags & GGML_TENSOR_FLAG_OUTPUT)) { + dfly_cap_err = format("layer %d: export is not a graph output", il); + return; + } + if (ggml_backend_sched_get_tensor_backend(sched.get(), const_cast(ti)) == nullptr || + ggml_backend_sched_get_tensor_backend(sched.get(), const_cast(ts)) == nullptr) { + dfly_cap_err = format("layer %d: export has no backend", il); + return; + } + n_top = ti->ne[0]; + } + + if (ubatch.data == nullptr || ubatch.data->batch_idxs.size() != ubatch.n_tokens || + (n_out != (int64_t) ubatch.n_tokens && ubatch.output == nullptr)) { + dfly_cap_err = "the ubatch has no map to the batch rows"; + return; + } + + dfly_capture_block bl; + bl.n_top = n_top; + bl.n_rows = n_out; + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + if (n_out == (int64_t) ubatch.n_tokens || ubatch.output[i]) { + bl.batch_row.push_back(ubatch.data->batch_idxs[i]); + bl.pos .push_back(ubatch.pos[i]); + bl.seq .push_back(ubatch.seq_id[i][0]); + } + } + if ((int64_t) bl.batch_row.size() != n_out) { + dfly_cap_err = format("the ubatch marks %zu output rows, the graph %" PRId64, bl.batch_row.size(), n_out); + return; + } + + dfly_cap_stage.push_back(std::move(bl)); + auto & dst = dfly_cap_stage.back(); + + for (uint32_t k = 0; k < cparams.dfly_capture_n_layer; ++k) { + ggml_tensor * ti = res->t_dfly_ids[k]; + ggml_tensor * ts = res->t_dfly_scores[k]; + dst.ids[k].resize(n_out*n_top); + dst.scores[k].resize(n_out*n_top); + ggml_backend_tensor_get_async(ggml_backend_sched_get_tensor_backend(sched.get(), ti), ti, dst.ids[k].data(), 0, ggml_nbytes(ti)); + ggml_backend_tensor_get_async(ggml_backend_sched_get_tensor_backend(sched.get(), ts), ts, dst.scores[k].data(), 0, ggml_nbytes(ts)); + } +} + +size_t llama_context::dfly_stage_n_blocks_for_test() const { + return dfly_cap_stage.size(); +} + +const llama_context::dfly_capture_block & llama_context::dfly_stage_block_for_test(size_t b) const { + return dfly_cap_stage.at(b); +} + +size_t llama_context::dfly_stage_bytes_for_test() const { + size_t n = 0; + for (const auto & bl : dfly_cap_stage) { + for (size_t k = 0; k < bl.ids.size(); ++k) { + n += bl.ids[k].size()*sizeof(int32_t) + bl.scores[k].size()*sizeof(float); + } + n += bl.batch_row.size()*sizeof(int32_t) + bl.pos.size()*sizeof(llama_pos) + bl.seq.size()*sizeof(llama_seq_id); + } + return n; +} + +float * llama_context::dfly_stage_scores_for_test(size_t b, size_t k) { + return dfly_cap_stage.at(b).scores.at(k).data(); +} + +// host buffers count as the CPU, so that a CPU-only pair passes the device check +static std::string llama_dfly_dev_name(const ggml_tensor * t) { + if (t == nullptr || t->buffer == nullptr) { + return "none"; + } + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(t->buffer); + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + if (ggml_backend_buft_is_host(buft) || dev == nullptr || ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) { + return "CPU"; + } + return ggml_backend_dev_name(dev); +} + +static void llama_dfly_vocab_info(const llama_vocab & vocab, hy_v4_next_dfly_vocab_info & v) { + const int32_t n = vocab.n_tokens(); + + v.type = (int32_t) vocab.get_type(); + v.text.resize(n); + v.score.resize(n); + v.attr.resize(n); + for (int32_t i = 0; i < n; ++i) { + v.text[i] = vocab.token_get_text(i); + v.score[i] = vocab.token_get_score(i); + v.attr[i] = (int32_t) vocab.token_get_attr(i); + } + // the mask id is the draft's own, checked against the vocab size + v.special = { + { "tokenizer.ggml.bos_token_id", vocab.token_bos() }, + { "tokenizer.ggml.eos_token_id", vocab.token_eos() }, + { "tokenizer.ggml.eot_token_id", vocab.token_eot() }, + { "tokenizer.ggml.eom_token_id", vocab.token_eom() }, + { "tokenizer.ggml.seperator_token_id", vocab.token_sep() }, + { "tokenizer.ggml.padding_token_id", vocab.token_pad() }, + { "tokenizer.ggml.fim_pre_token_id", vocab.token_fim_pre() }, + { "tokenizer.ggml.fim_suf_token_id", vocab.token_fim_suf() }, + { "tokenizer.ggml.fim_mid_token_id", vocab.token_fim_mid() }, + { "tokenizer.ggml.fim_pad_token_id", vocab.token_fim_pad() }, + { "tokenizer.ggml.fim_rep_token_id", vocab.token_fim_rep() }, + { "tokenizer.ggml.fim_sep_token_id", vocab.token_fim_sep() }, + }; + v.add_bos = vocab.get_add_bos(); + v.add_eos = vocab.get_add_eos(); +} + +static void llama_dfly_fill_draft_binding(const llama_model & model, hy_v4_next_dfly_binding & b) { + const auto & hp = model.hparams; + + b.n_embd = hp.n_embd; + b.n_lora_kv = hp.n_lora_kv; + b.n_rot = hp.n_rot(); + b.top_k = hp.dfly_target_index_top_k; + b.mask_id = (uint32_t) model.vocab.token_mask(); + b.rope_base = hp.rope_freq_base_train; + b.kv_layers.assign(hp.dfly_target_kv_layers.begin(), hp.dfly_target_kv_layers.end()); + b.index_layers.assign(hp.dfly_target_index_layers.begin(), hp.dfly_target_index_layers.end()); + llama_dfly_vocab_info(model.vocab, b.vocab); + for (const auto & [name, t] : model.tensors_by_name) { + b.weight_dev.emplace_back(name, llama_dfly_dev_name(t)); + } +} + +void llama_context::dfly_fill_target_binding(hy_v4_next_dfly_binding & b) const { + const auto & hp = model.hparams; + + b.arch = llm_arch_name(model.arch); + b.t_n_embd = hp.n_embd; + b.t_n_lora_kv = hp.n_lora_kv; + b.t_n_rot = hp.n_rot(); + b.t_top_k = hp.indexer_top_k; + b.t_select_tail = hp.indexer_kpool_select_tail; + b.t_prism = !model.hdmd.rot.empty() || !model.hdmd.inv.empty(); + b.t_lora = !loras->empty(); + b.t_ext_factor = cparams.yarn_ext_factor; + b.t_attn_factor = cparams.yarn_attn_factor; + + b.t_layers.clear(); + for (uint32_t il = 0; il < hp.n_layer(); ++il) { + hy_v4_next_dfly_target_layer tl; + tl.swa = hp.is_swa(il); + tl.has_indexer = hp.indexer_top_k > 0 && hp.is_indexer_full(il); + tl.rope_base = model.get_rope_freq_base (cparams, il); + tl.rope_scale = model.get_rope_freq_scale(cparams, il); + b.t_layers.push_back(tl); + } + + llama_dfly_vocab_info(model.vocab, b.t_vocab); + + auto ne = [](const ggml_tensor * t) { + return t ? std::vector(t->ne, t->ne + GGML_MAX_DIMS) : std::vector(); + }; + b.e_ne = ne(model.tok_embd); + b.o_ne = ne(model.output); + b.e_dev = llama_dfly_dev_name(model.tok_embd); + b.o_dev = llama_dfly_dev_name(model.output); + + const auto * mem = dynamic_cast(memory.get()); + b.k.assign(b.kv_layers.size(), hy_v4_next_dfly_target_k()); + if (mem == nullptr) { + return; + } + b.t_kpool = mem->get_kpool(); + b.t_kpool_by_order = mem->get_kpool_by_order(); + + const llama_kv_cache * base = mem->get_mem_attn()->get_base(); + const auto k_rot = base->get_k_rot(); + for (size_t i = 0; i < b.kv_layers.size(); ++i) { + const int32_t il = (int32_t) b.kv_layers[i]; + ggml_tensor * k = nullptr; + try { + k = base->get_k_storage(il); + } catch (const std::out_of_range &) { + continue; + } + auto & bk = b.k[i]; + bk.found = k != nullptr; + bk.type = k ? (int32_t) k->type : -1; + bk.width = k ? k->ne[0] : 0; + bk.rotated = (size_t) il < k_rot.size() && k_rot[il] != nullptr; + bk.dev = llama_dfly_dev_name(k); + } +} + +bool llama_context::dfly_check_snapshot(const llama_dfly_snapshot & s, llama_seq_id seq_id, std::string & err) const { + const llama_context * tgt = cparams.ctx_other; + const auto & hp = model.hparams; + + if (seq_id < 0 || seq_id >= LLAMA_MAX_SEQ) { + err = format("seq %d is out of range", seq_id); + return false; + } + + const uint64_t ctx_id = tgt->dfly_capture_ctx_id(); + const uint64_t decode_id = tgt->dfly_capture_ok_decode_id(seq_id); + + if (ctx_id == 0 || s.target_ctx_id != ctx_id) { + err = format("target context %" PRIu64 ", the bound target is %" PRIu64, s.target_ctx_id, ctx_id); + return false; + } + if (s.prefix_epoch != dfly_epoch[seq_id]) { + err = format("epoch %" PRIu64 ", the current epoch is %" PRIu64, s.prefix_epoch, dfly_epoch[seq_id]); + return false; + } + if (decode_id == 0 || s.decode_id != decode_id) { + err = format("decode %" PRIu64 " is not the target's last successful decode %" PRIu64, s.decode_id, decode_id); + return false; + } + if (s.seq_id != seq_id) { + err = format("seq %d, the request is for seq %d", s.seq_id, seq_id); + return false; + } + if (s.h_final.size() != hp.n_embd) { + err = format("hidden state of %zu values, expected %u", s.h_final.size(), hp.n_embd); + return false; + } + + const auto * mem = dynamic_cast(llama_get_memory(cparams.ctx_other)); + const llama_kv_cache * base = mem->get_mem_attn()->get_base(); + const uint32_t strm = base->get_stream(seq_id); + const auto & cells = base->get_cells(seq_id); + const llama_pos p = s.query_pos; + + std::vector seen(cells.size()); + for (uint32_t i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + const auto & l = s.layer[i]; + const size_t n = l.pos.size(); + if (l.target_layer != (int32_t) hp.dfly_target_kv_layers[i]) { + err = format("layer %u is target layer %d, expected %u", i, l.target_layer, hp.dfly_target_kv_layers[i]); + return false; + } + if (l.strm != strm) { + err = format("layer %u: stream %u, seq %d is in stream %u", i, l.strm, seq_id, strm); + return false; + } + if (n < 1 || n > hp.dfly_target_index_top_k || l.cell.size() != n) { + err = format("layer %u: count %zu with %zu cells, expected 1 to %u", i, n, l.cell.size(), hp.dfly_target_index_top_k); + return false; + } + // increasing and ending at p: no repeated position, p is in, nothing after p + if (l.pos.back() != p) { + err = format("layer %u: the last position is %d, expected the query position %d", i, l.pos.back(), p); + return false; + } + std::fill(seen.begin(), seen.end(), false); + for (size_t k = 0; k < n; ++k) { + const uint32_t c = l.cell[k]; + if (k > 0 && l.pos[k - 1] >= l.pos[k]) { + err = format("layer %u: positions %d, %d are not increasing", i, l.pos[k - 1], l.pos[k]); + return false; + } + if (c >= cells.size() || seen[c]) { + err = format("layer %u: cell %u is out of range or repeated", i, c); + return false; + } + seen[c] = true; + if (dfly_test_skip_cells) { + continue; + } + if (cells.is_empty(c) || !cells.seq_has(c, seq_id) || cells.pos_get(c) != l.pos[k]) { + err = format("layer %u: cell %u no longer holds position %d of seq %d", i, c, l.pos[k], seq_id); + return false; + } + } + } + + return true; +} + +llama_dfly_status llama_context::dfly_propose(const llama_dfly_request & req, llama_dfly_result & out) { + out.n_tokens = 0; + + // every return syncs this context first, so that the target may write its cache again + auto done = [&](llama_dfly_status status) { + synchronize(); + return status; + }; + + const auto & hp = model.hparams; + const int32_t n_vocab = model.vocab.n_tokens(); + const int32_t K = req.k_step; + + // the seq is a target sequence, this context has none of its own + if (req.seq_id < 0 || (uint32_t) req.seq_id >= cparams.ctx_other->n_seq_max()) { + LLAMA_LOG_ERROR("%s: invalid seq_id = %d\n", __func__, req.seq_id); + return done(LLAMA_DFLY_BAD_REQUEST); + } + if (req.anchor_token < 0 || req.anchor_token >= n_vocab) { + LLAMA_LOG_ERROR("%s: anchor_token = %d is out of the vocab of %d\n", __func__, req.anchor_token, n_vocab); + return done(LLAMA_DFLY_BAD_REQUEST); + } + if (req.anchor_pos < 0) { + LLAMA_LOG_ERROR("%s: invalid anchor_pos = %d\n", __func__, req.anchor_pos); + return done(LLAMA_DFLY_BAD_REQUEST); + } + // K first: K + 1 must not overflow + if (K >= (int32_t) cparams.n_ubatch) { + LLAMA_LOG_ERROR("%s: k_step + 1 = %lld exceeds n_ubatch = %u\n", __func__, (long long) K + 1, cparams.n_ubatch); + return done(LLAMA_DFLY_BAD_REQUEST); + } + const int32_t W = K + 1; + + // the setters can turn these on after init, the draft graph has no such outputs + if (cparams.embeddings || cparams.embeddings_nextn || + std::any_of(cparams.embeddings_layer_inp.begin(), cparams.embeddings_layer_inp.end(), [](bool b) { return b; })) { + LLAMA_LOG_ERROR("%s: embeddings, nextn and layer input outputs are not supported by a DFly draft context\n", __func__); + return done(LLAMA_DFLY_BAD_REQUEST); + } + if (cparams.dfly_force_prev) { + const bool ok = (int32_t) dfly_test_prev.size() >= K && + std::all_of(dfly_test_prev.begin(), dfly_test_prev.begin() + K, [&](llama_token t) { return t >= 0 && t < n_vocab; }); + if (!ok) { + LLAMA_LOG_ERROR("%s: the forced prev chain is too short or out of the vocab, k_step = %d\n", __func__, K); + return done(LLAMA_DFLY_BAD_REQUEST); + } + } + if (K == 0) { + return done(LLAMA_DFLY_OK); + } + + const llama_pos p = req.anchor_pos - 1; + + // a snapshot serves one successful propose + const llama_dfly_snapshot * snap = nullptr; + size_t snap_idx = 0; + for (size_t i = 0; i < dfly_snaps.size(); ++i) { + if (dfly_snaps[i].seq_id == req.seq_id && dfly_snaps[i].query_pos == p && !dfly_consumed[i]) { + snap = &dfly_snaps[i]; + snap_idx = i; + break; + } + } + if (snap == nullptr) { + LLAMA_LOG_DEBUG("%s: seq %d: no snapshot for query position %d\n", __func__, req.seq_id, p); + return done(LLAMA_DFLY_NO_SNAPSHOT); + } + + { + std::string err; + if (!dfly_check_snapshot(*snap, req.seq_id, err)) { + LLAMA_LOG_ERROR("%s: seq %d pos %d decode %" PRIu64 ": bad snapshot: %s\n", __func__, req.seq_id, p, snap->decode_id, err.c_str()); + return done(LLAMA_DFLY_BAD_SNAPSHOT); + } + } + + // the target must be done writing the cells we read + cparams.ctx_other->synchronize(); + + // padding repeats the query's own cell and is masked; -1 never reaches get_rows + const int64_t S = hp.dfly_target_index_top_k; + dfly_inp.h_t = snap->h_final; + for (uint32_t i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + const auto & l = snap->layer[i]; + const int64_t n = (int64_t) l.cell.size(); + + auto & cell = dfly_inp.cell[i]; + cell.assign(S, (int32_t) l.cell.back()); + std::copy(l.cell.begin(), l.cell.end(), cell.begin()); + + auto & mask = dfly_inp.mask[i]; + mask.assign((S + W)*W, -INFINITY); + for (int32_t j = 0; j < W; ++j) { + float * row = mask.data() + j*(S + W); + std::fill(row, row + n, 0.0f); + std::fill(row + S, row + S + j + 1, 0.0f); + } + } + if (cparams.dfly_force_prev) { + dfly_inp.prev.assign(dfly_test_prev.begin(), dfly_test_prev.begin() + K); + } + + // [anchor, MASK, ...] at a..a+K, no outputs + llama_batch_ext batch(this); + for (int32_t j = 0; j < W; ++j) { + llama_token tok = model.vocab.token_mask(); + if (j == 0) { + tok = req.anchor_token; + } else if ((int32_t) dfly_test_block.size() >= j) { + tok = dfly_test_block[j - 1]; + } + const int32_t idx = batch.add_token(0); + if (idx < 0 || !batch.set_token_id(idx, tok)) { + LLAMA_LOG_ERROR("%s: failed to add slot %d to the batch\n", __func__, j); + return done(LLAMA_DFLY_BAD_REQUEST); + } + batch.tokens[idx].pos[0] = req.anchor_pos + j; + } + + try { + sched_reserve(); + + if (!balloc->init(batch, model.vocab, false)) { + LLAMA_LOG_ERROR("%s: failed to initialize the batch\n", __func__); + return done(LLAMA_DFLY_COMPUTE_FAILED); + } + const llama_ubatch ubatch = balloc->split_simple(W); + + n_outputs = 0; + + ggml_status status; + const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_DEFAULT, nullptr, status); + if (res == nullptr || (int32_t) res->t_dfly_tokens.size() != K || (int32_t) res->t_dfly_finite.size() != K) { + LLAMA_LOG_ERROR("%s: seq %d pos %d: the draft graph failed, status %d\n", __func__, req.seq_id, p, (int) status); + return done(LLAMA_DFLY_COMPUTE_FAILED); + } + + std::vector raw(K); + std::vector finite(K); + for (int32_t j = 0; j < K; ++j) { + ggml_tensor * tr = res->t_dfly_tokens[j]; + ggml_tensor * tf = res->t_dfly_finite[j]; + ggml_backend_tensor_get_async(ggml_backend_sched_get_tensor_backend(sched.get(), tr), tr, &raw[j], 0, sizeof(int32_t)); + ggml_backend_tensor_get_async(ggml_backend_sched_get_tensor_backend(sched.get(), tf), tf, &finite[j], 0, sizeof(float)); + } + synchronize(); + + std::string err; + if (!llama_dfly_check_draft(raw.data(), finite.data(), K, n_vocab, err)) { + LLAMA_LOG_ERROR("%s: seq %d pos %d decode %" PRIu64 ": draft dropped: %s\n", __func__, req.seq_id, p, snap->decode_id, err.c_str()); + return done(LLAMA_DFLY_BAD_TOKEN); + } + + std::copy(raw.begin(), raw.end(), out.tokens); + out.n_tokens = K; + dfly_consumed[snap_idx] = true; + } catch (const std::exception & e) { + LLAMA_LOG_ERROR("%s: seq %d pos %d: %s\n", __func__, req.seq_id, p, e.what()); + return done(LLAMA_DFLY_COMPUTE_FAILED); + } + + return done(LLAMA_DFLY_OK); +} + +llama_dfly_status llama_context::dfly_capture_enable() { + llama_context * tgt = cparams.ctx_other; + const auto & hp = model.hparams; + + llama_set_embeddings_nextn(tgt, true, true); + + const std::vector layers(hp.dfly_target_index_layers.begin(), hp.dfly_target_index_layers.end()); + std::string err; + if (!tgt->dfly_capture_configure(layers.data(), (uint32_t) layers.size(), hp.dfly_target_index_top_k, err)) { + LLAMA_LOG_ERROR("%s: %s\n", __func__, err.c_str()); + return LLAMA_DFLY_BAD_REQUEST; + } + return LLAMA_DFLY_OK; +} + +// keep the snapshots for which keep(s) holds, with their consumed state +template +static void dfly_keep_snapshots(std::vector & snaps, std::vector & consumed, F keep) { + size_t n = 0; + for (size_t i = 0; i < snaps.size(); ++i) { + if (!keep(snaps[i])) { + continue; + } + if (n != i) { + snaps[n] = std::move(snaps[i]); + consumed[n] = consumed[i]; + } + ++n; + } + snaps.resize(n); + consumed.resize(n); +} + +llama_dfly_status llama_context::dfly_capture_pull() { + const llama_context * tgt = cparams.ctx_other; + + std::vector snaps; + std::string err; + const llama_dfly_capture_status st = cparams.ctx_other->dfly_capture_take(0, snaps, err); + if (st == LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED) { + LLAMA_LOG_ERROR("%s: call llama_dfly_capture_enable first: %s\n", __func__, err.c_str()); + return LLAMA_DFLY_BAD_REQUEST; + } + + // the rows of a sequence are stale once a later decode or a state read touched it, the other sequences keep theirs + dfly_keep_snapshots(dfly_snaps, dfly_consumed, [&](const llama_dfly_snapshot & s) { + return s.decode_id == tgt->dfly_capture_ok_decode_id(s.seq_id); + }); + + if (st == LLAMA_DFLY_CAPTURE_STATUS_NO_ROWS) { + return LLAMA_DFLY_NO_SNAPSHOT; + } + if (st == LLAMA_DFLY_CAPTURE_STATUS_ERROR) { + LLAMA_LOG_ERROR("%s: the target capture failed, snapshots dropped: %s\n", __func__, err.c_str()); + return LLAMA_DFLY_BAD_SNAPSHOT; + } + + // each decode is published once: a second pull, or one after an invalidate, adds nothing + auto pulled = dfly_pulled; + for (auto & s : snaps) { + if (s.seq_id < 0 || s.seq_id >= LLAMA_MAX_SEQ || s.decode_id <= dfly_pulled[s.seq_id]) { + continue; + } + s.prefix_epoch = dfly_epoch[s.seq_id]; + pulled[s.seq_id] = s.decode_id; + dfly_snaps.push_back(std::move(s)); + dfly_consumed.push_back(false); + } + dfly_pulled = pulled; + + return LLAMA_DFLY_OK; +} + +void llama_context::dfly_invalidate(llama_seq_id seq_id) { + if (seq_id < 0 || seq_id >= LLAMA_MAX_SEQ) { + return; + } + ++dfly_epoch[seq_id]; + // the rows the target staged before this are not published later + if (cparams.ctx_other) { + dfly_pulled[seq_id] = std::max(dfly_pulled[seq_id], cparams.ctx_other->dfly_capture_decode_id()); + } + dfly_keep_snapshots(dfly_snaps, dfly_consumed, [&](const llama_dfly_snapshot & s) { return s.seq_id != seq_id; }); +} + +void llama_context::dfly_set_snapshots_for_test(std::vector snaps, uint64_t epoch) { + dfly_snaps = std::move(snaps); + dfly_consumed.assign(dfly_snaps.size(), false); + dfly_epoch.fill(epoch); + dfly_pulled.fill(0); +} + +void llama_context::dfly_set_block_tokens_for_test(std::vector tokens) { + dfly_test_block = std::move(tokens); +} + +void llama_context::dfly_set_prev_for_test(std::vector prev) { + dfly_test_prev = std::move(prev); + cparams.dfly_force_prev = !dfly_test_prev.empty(); +} + +void llama_context::dfly_skip_cell_check_for_test(bool skip) { + dfly_test_skip_cells = skip; +} + +const llama_dfly_propose_input & llama_context::dfly_input_for_test() const { + return dfly_inp; +} + +const std::vector & llama_context::dfly_snapshots_for_test() const { + return dfly_snaps; +} + +uint64_t llama_context::dfly_epoch_for_test(llama_seq_id seq_id) const { + return seq_id >= 0 && seq_id < LLAMA_MAX_SEQ ? dfly_epoch[seq_id] : 0; +} + +void llama_context::dfly_rearm_for_test() { + dfly_consumed.assign(dfly_snaps.size(), false); +} + void llama_context::set_embeddings_layer_inp(uint32_t lid, bool enable) { LLAMA_LOG_DEBUG("%s: lid = %d, enable = %d\n", __func__, lid, enable); @@ -1721,6 +2509,11 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll } int llama_context::encode(const llama_batch_ext & batch_inp) { + if (model.arch == LLM_ARCH_HY_V4_NEXT_DFLY) { + LLAMA_LOG_ERROR("%s: a DFly draft context runs only through llama_dfly_propose\n", __func__); + return -1; + } + if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; @@ -1968,7 +2761,27 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map 0 && cparams.n_seq_max > 1; + if (dfly_one_ubatch && (n_tokens_all > cparams.n_ubatch || embd_all)) { + LLAMA_LOG_ERROR("%s: DFly with several sequences: the batch of %u tokens is not one ubatch of at most %u\n", + __func__, n_tokens_all, cparams.n_ubatch); + return -1; + } + GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); // TODO: this clear of the buffer can easily be forgotten - need something better @@ -2120,12 +2941,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { break; } + // the plan must be a single ubatch as well, nothing is applied yet + if (dfly_one_ubatch && mctx->get_ubatch().n_tokens != n_tokens_all) { + LLAMA_LOG_ERROR("%s: DFly with several sequences: the batch of %u tokens is not one ubatch of at most %u\n", + __func__, n_tokens_all, cparams.n_ubatch); + return -1; + } + // reserve output buffer if (output_reserve(n_outputs_all) < n_outputs_all) { LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all); return -2; }; + // DFly: the sequences this decode writes, their earlier rows are stale from the first ubatch on + std::array dfly_touched = {}; + // start a new sampling transaction for this logical batch for (const auto & entry : sampling.samplers) { llama_sampler_backend_begin(entry.second); @@ -2173,6 +3004,13 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { ggml_status status; + if (dfly_cap_top_k > 0) { + for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { + dfly_cap_seq_decode[ubatch.seq_id_unq[s]] = 0; + dfly_touched[ubatch.seq_id_unq[s]] = true; + } + } + const auto * res = process_ubatch(ubatch, ctx_type_to_graph_type(cparams.ctx_type), mctx.get(), status); if (!res) { @@ -2317,6 +3155,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { } } + if (dfly_cap_top_k > 0 && n_outputs > 0) { + dfly_capture_stage(ubatch, res); + } + if (extract_all_idxs) { GGML_ASSERT(ubatch.data && ubatch.data->batch_idxs.size() == ubatch.n_tokens); GGML_ASSERT(embd_batch_idxs.size() == (size_t) n_tokens_prev); @@ -2390,6 +3232,11 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // remember the swaps and apply them lazily upon logits/embeddings access output_swaps.push_back({ i, j_min }); + + // the staged rows are not swapped along + if (dfly_cap_top_k > 0 && dfly_cap_err.empty()) { + dfly_cap_err = "output rows are reordered"; + } } std::fill(output_ids.begin(), output_ids.end(), -1); @@ -2403,6 +3250,16 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // wait for the computation to finish (automatically done when obtaining the model output) //synchronize(); + if (dfly_cap_top_k > 0) { + dfly_cap_decode_ok = true; + dfly_cap_n_rows = n_outputs_all; + for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { + if (dfly_touched[s]) { + dfly_cap_seq_decode[s] = dfly_cap_decode_id; + } + } + } + return 0; } @@ -2715,7 +3572,8 @@ uint32_t llama_context::graph_max_nodes(uint32_t n_tokens) const { model.arch == LLM_ARCH_NANBEIGE || model.arch == LLM_ARCH_MINIMAX_01 || model.arch == LLM_ARCH_MINIMAX_M3 || - model.arch == LLM_ARCH_HY_V4) { + model.arch == LLM_ARCH_HY_V4 || + model.arch == LLM_ARCH_HY_V4_FLASH) { res = std::max(n_tokens * 40, 32u * model.n_tensors()); } else if (model.arch == LLM_ARCH_DFLASH && model.hparams.dflash_selector_rank > 0) { // DFlash2's convolutions and selector are shape work rather than matmuls, @@ -3866,6 +4724,9 @@ size_t llama_context::state_write_data(llama_io_write_i & io) { size_t llama_context::state_read_data(llama_io_read_i & io) { LLAMA_LOG_DEBUG("%s: reading state\n", __func__); + dfly_capture_reset(); + dfly_cap_seq_decode.fill(0); + // read model info { LLAMA_LOG_DEBUG("%s: - reading model info\n", __func__); @@ -3898,6 +4759,14 @@ size_t llama_context::state_seq_write_data(llama_io_write_i & io, llama_seq_id s } size_t llama_context::state_seq_read_data(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { + dfly_capture_reset(); + // only this sequence's rows are stale + if (seq_id >= 0 && seq_id < LLAMA_MAX_SEQ) { + dfly_cap_seq_decode[seq_id] = 0; + } else { + dfly_cap_seq_decode.fill(0); + } + if (memory) { memory->state_read(io, seq_id, flags); } @@ -4256,6 +5125,97 @@ llama_context_params llama_context_default_params() { return result; } +// the DFly draft: checked and forced before anything is reserved, plan 8.7; false (logged) on bad input +static bool llama_dfly_init_params(const llama_model & model, llama_context_params & params) { + const char * func = "llama_init_from_model"; + auto fail = [&](const std::string & msg) { + LLAMA_LOG_ERROR("%s: %s\n", func, msg.c_str()); + return false; + }; + + const auto & hp = model.hparams; + + llama_context * tgt = params.ctx_other; + if (tgt == nullptr) { + return fail("hy_v4_next_dfly: ctx_other must be the bound target context"); + } + if (params.n_seq_max != 1) { + return fail(format("hy_v4_next_dfly: n_seq_max = %u must be 1", params.n_seq_max)); + } + if (params.ctx_type != LLAMA_CONTEXT_TYPE_DEFAULT) { + return fail("hy_v4_next_dfly: ctx_type must be LLAMA_CONTEXT_TYPE_DEFAULT"); + } + if (params.embeddings) { + return fail("hy_v4_next_dfly: embeddings must be false"); + } + if (params.pooling_type != LLAMA_POOLING_TYPE_UNSPECIFIED && params.pooling_type != LLAMA_POOLING_TYPE_NONE) { + return fail("hy_v4_next_dfly: pooling_type must be none"); + } + if (params.samplers != nullptr && params.n_samplers > 0) { + return fail("hy_v4_next_dfly: samplers (backend sampling) are not supported"); + } + if (params.attention_type == LLAMA_ATTENTION_TYPE_NON_CAUSAL) { + return fail("hy_v4_next_dfly: attention_type must be causal"); + } + // the graph rotates with the draft's own theta, an override would be ignored + if (params.rope_freq_base != 0.0f || params.rope_freq_scale != 0.0f || params.yarn_ext_factor > 0.0f || + (params.yarn_attn_factor >= 0.0f && params.yarn_attn_factor != 1.0f) || + (params.rope_scaling_type != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED && params.rope_scaling_type != LLAMA_ROPE_SCALING_TYPE_NONE)) { + return fail("hy_v4_next_dfly: rope_freq_base, rope_freq_scale, yarn_ext_factor, yarn_attn_factor and rope_scaling_type overrides are not supported"); + } + + const uint32_t n_ctx_tgt = llama_n_ctx(tgt); + if (params.n_ctx == 0) { + params.n_ctx = n_ctx_tgt; + } else if (params.n_ctx != n_ctx_tgt) { + return fail(format("hy_v4_next_dfly: n_ctx = %u must be 0 or the target's n_ctx %u", params.n_ctx, n_ctx_tgt)); + } + + // the width of a propose round is n_ubatch, check the value given and the one in effect + const uint32_t w_max = std::min(hp.dfly_block_size, 8); + const uint32_t n_ubatch = params.n_ubatch == 0 ? params.n_batch : params.n_ubatch; + if (n_ubatch < 1 || n_ubatch > w_max) { + return fail(format("hy_v4_next_dfly: n_ubatch = %u (given %u, n_batch %u) must be in [1, %u] = [1, min(block_size %u, 8)]", + n_ubatch, params.n_ubatch, params.n_batch, w_max, hp.dfly_block_size)); + } + if (params.n_batch < n_ubatch) { + return fail(format("hy_v4_next_dfly: n_batch = %u must be >= n_ubatch = %u", params.n_batch, n_ubatch)); + } + if (n_ubatch > n_ctx_tgt || n_ctx_tgt > hp.n_ctx_train) { + return fail(format("hy_v4_next_dfly: n_ubatch %u <= target n_ctx %u <= draft context_length %u does not hold", + n_ubatch, n_ctx_tgt, hp.n_ctx_train)); + } + + try { + hy_v4_next_dfly_binding b; + llama_dfly_fill_draft_binding(model, b); + tgt->dfly_fill_target_binding(b); + hy_v4_next_dfly_check_binding(b); + } catch (const std::exception & e) { + return fail(e.what()); + } + + // no KV and dense: these do not touch the target's cache or MoE settings + auto force = [&](const char * name, bool changed, const std::string & from, const char * to) { + if (changed) { + LLAMA_LOG_WARN("%s: hy_v4_next_dfly: forcing %s = %s (was %s)\n", func, name, to, from.c_str()); + } + }; + force("flash_attn_type", params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED, llama_flash_attn_type_name(params.flash_attn_type), "disabled"); + force("type_k", params.type_k != GGML_TYPE_F16, ggml_type_name(params.type_k), "f16"); + force("type_v", params.type_v != GGML_TYPE_F16, ggml_type_name(params.type_v), "f16"); + force("offload_kqv", !params.offload_kqv, "false", "true"); + force("moe_cache_size", params.moe_cache_size != 0, std::to_string(params.moe_cache_size), "0"); + + params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; + params.type_k = GGML_TYPE_F16; + params.type_v = GGML_TYPE_F16; + params.offload_kqv = true; + params.moe_cache_size = 0; + + return true; +} + llama_context * llama_init_from_model( llama_model * model, llama_context_params params) { @@ -4274,6 +5234,11 @@ llama_context * llama_init_from_model( return nullptr; } + // before the generic flash attention and cache type checks + if (model->arch == LLM_ARCH_HY_V4_NEXT_DFLY && !llama_dfly_init_params(*model, params)) { + return nullptr; + } + if (params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && model->arch == LLM_ARCH_GROK) { LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__); params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; @@ -4963,3 +5928,63 @@ llama_memory_breakdown llama_get_memory_breakdown(const struct llama_context * c llama_context * llama_get_ctx_other(struct llama_context * ctx) { return ctx->get_cparams().ctx_other; } + +static bool llama_dfly_check_ctx(const llama_context * ctx, const char * func) { + if (ctx == nullptr || ctx->get_model().arch != LLM_ARCH_HY_V4_NEXT_DFLY) { + LLAMA_LOG_ERROR("%s: ctx is not a DFly context\n", func); + return false; + } + return true; +} + +// after the target warmup and seq_rm probe: the masked nextn and the selection export of the draft's layers +llama_dfly_status llama_dfly_capture_enable(llama_context * ctx_dfly) { + if (!llama_dfly_check_ctx(ctx_dfly, __func__)) { + return LLAMA_DFLY_BAD_REQUEST; + } + return ctx_dfly->dfly_capture_enable(); +} + +// after the target decode returns and before any seq edit (a verify rollback): the take of an edited sequence fails +llama_dfly_status llama_dfly_capture_pull(llama_context * ctx_dfly) { + if (!llama_dfly_check_ctx(ctx_dfly, __func__)) { + return LLAMA_DFLY_BAD_REQUEST; + } + return ctx_dfly->dfly_capture_pull(); +} + +llama_dfly_status llama_dfly_propose( + llama_context * ctx_dfly, + const llama_dfly_request * request, + llama_dfly_result * result) { + if (result != nullptr) { + result->n_tokens = 0; + } + if (request == nullptr || result == nullptr) { + LLAMA_LOG_ERROR("%s: request and result must not be null\n", __func__); + return LLAMA_DFLY_BAD_REQUEST; + } + if (!llama_dfly_check_ctx(ctx_dfly, __func__)) { + return LLAMA_DFLY_BAD_REQUEST; + } + if (request->k_step < 0) { + LLAMA_LOG_ERROR("%s: invalid k_step = %d\n", __func__, request->k_step); + return LLAMA_DFLY_BAD_REQUEST; + } + if (result->capacity < request->k_step) { + LLAMA_LOG_ERROR("%s: capacity = %d is less than k_step = %d\n", __func__, result->capacity, request->k_step); + return LLAMA_DFLY_BAD_REQUEST; + } + if (request->k_step > 0 && result->tokens == nullptr) { + LLAMA_LOG_ERROR("%s: tokens must not be null for k_step = %d\n", __func__, request->k_step); + return LLAMA_DFLY_BAD_REQUEST; + } + return ctx_dfly->dfly_propose(*request, *result); +} + +void llama_dfly_invalidate(llama_context * ctx_dfly, llama_seq_id seq_id) { + if (ctx_dfly == nullptr || !llama_dfly_check_ctx(ctx_dfly, __func__)) { + return; + } + ctx_dfly->dfly_invalidate(seq_id); +} diff --git a/src/llama-context.h b/src/llama-context.h index 39c5619df67d881813f8624307423efa5bc0ec45..4bc4712870f5daa16f7ff48a345dfd67c2271b22 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -3,6 +3,7 @@ #include "llama.h" #include "llama-ext.h" #include "llama-cparams.h" +#include "llama-dfly.h" #include "llama-graph.h" #include "llama-adapter.h" #include "llama-impl.h" @@ -14,9 +15,11 @@ #include #include +#include #include struct llama_model; +struct hy_v4_next_dfly_binding; class llama_batch_allocr; class llama_moe_cache; @@ -121,6 +124,60 @@ struct llama_context { void set_embeddings (bool value); void set_embeddings_nextn(bool value, bool masked); + + // DFly target capture, internal: the public llama_dfly_capture_* wrap these (S5c) + // layers: the 5 target layers, in the draft's order; dfly_top_k: S from the draft + bool dfly_capture_configure(const int32_t * layers, uint32_t n_layers, uint32_t dfly_top_k, std::string & err); + + // copies every output row of the last decode into snapshots, all or nothing + llama_dfly_capture_status dfly_capture_take(uint64_t prefix_epoch, std::vector & out, std::string & err); + + // the exported selection of one ubatch with outputs, rows in batch order + struct dfly_capture_block { + int64_t n_top = 0; + int64_t n_rows = 0; + std::array, LLAMA_DFLY_N_LAYER> ids; // [n_rows*n_top] per slot + std::array, LLAMA_DFLY_N_LAYER> scores; // [n_rows*n_top] per slot + std::vector batch_row; // row in the logical batch + std::vector pos; + std::vector seq; + }; + + // DFly target: the capture id, the id of the last decode, and per sequence the last successful decode that wrote it + // (0 if a failed decode or a state read came after it) + uint64_t dfly_capture_ctx_id() const { return dfly_cap_ctx_id; } + uint64_t dfly_capture_decode_id() const { return dfly_cap_decode_id; } + uint64_t dfly_capture_ok_decode_id(llama_seq_id seq_id) const { + return seq_id >= 0 && seq_id < LLAMA_MAX_SEQ ? dfly_cap_seq_decode[seq_id] : 0; + } + + // DFly target: the target half of the binding check of a draft (layer 3 of the loader) + void dfly_fill_target_binding(hy_v4_next_dfly_binding & b) const; + + // DFly draft: one round from the snapshot at anchor_pos - 1; out.n_tokens is k_step on success, else 0 + llama_dfly_status dfly_propose(const llama_dfly_request & req, llama_dfly_result & out); + + // DFly draft, the public capture: turn on the target export, take the rows of its last decode, drop them + llama_dfly_status dfly_capture_enable(); + llama_dfly_status dfly_capture_pull(); + void dfly_invalidate(llama_seq_id seq_id); + + // test only, not called by the library + void dfly_set_snapshots_for_test(std::vector snaps, uint64_t epoch); + void dfly_set_block_tokens_for_test(std::vector tokens); // slots 1..K, empty: MASK + void dfly_set_prev_for_test(std::vector prev); // prev of slots 1..K, empty: the graph's chain + void dfly_skip_cell_check_for_test(bool skip); + const llama_dfly_propose_input & dfly_input_for_test() const; + const std::vector & dfly_snapshots_for_test() const; + uint64_t dfly_epoch_for_test(llama_seq_id seq_id = 0) const; + void dfly_rearm_for_test(); // the snapshots may be proposed from again + + // test only, not called by the library + size_t dfly_stage_n_blocks_for_test() const; + const dfly_capture_block & dfly_stage_block_for_test(size_t b) const; + size_t dfly_stage_bytes_for_test() const; + float * dfly_stage_scores_for_test(size_t b, size_t k); + void set_embeddings_layer_inp(uint32_t lid, bool enable); void set_embeddings_layer_inp_dev(bool value); @@ -375,6 +432,37 @@ private: std::vector output_swaps; + // DFly capture: S given at configure (0 = not configured) and the state of the last decode + uint32_t dfly_cap_top_k = 0; + uint64_t dfly_cap_ctx_id = 0; + uint64_t dfly_cap_decode_id = 0; + bool dfly_cap_decode_ok = false; + int64_t dfly_cap_n_rows = 0; + std::string dfly_cap_err; // first error recorded during the last decode + std::vector dfly_cap_stage; + std::array dfly_cap_seq_decode = {}; // per sequence, see dfly_capture_ok_decode_id + + // drop the staged rows; nothing staged before a decode or a state read may be taken after it + void dfly_capture_reset(); + + // queue the copy of this ubatch's export into a new staging block + void dfly_capture_stage(const llama_ubatch & ubatch, const llm_graph_result * res); + + // DFly draft: the snapshots of the bound target, the epoch of each target sequence and the propose staging + std::array dfly_epoch = {}; + std::array dfly_pulled = {}; // per sequence: the last target decode whose rows were published + std::vector dfly_snaps; // the rows of every sequence + std::vector dfly_consumed; // per snapshot: a successful propose used it + llama_dfly_propose_input dfly_inp; + + // test hooks + std::vector dfly_test_block; + std::vector dfly_test_prev; + bool dfly_test_skip_cells = false; + + // the identity checks of plan 6.3 item 5 on the selected snapshot + bool dfly_check_snapshot(const llama_dfly_snapshot & s, llama_seq_id seq_id, std::string & err) const; + ggml_backend_sched_ptr sched; bool sched_need_reserve = true; diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 9141cba3ea932caa3b9b67b6246bc23cf7125696..f9d971a21bb51b9c158f7baed3544855b7f8d57b 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -1,7 +1,9 @@ #pragma once #include "llama.h" +#include "llama-hparams.h" +#include #include #include @@ -72,4 +74,12 @@ struct llama_cparams { void * cb_eval_user_data; llama_context * ctx_other; + + // DFly target capture: export the selection of these layers for the output rows, 0 = off + uint32_t dfly_capture_n_layer = 0; + std::array dfly_capture_layers = {}; + + // DFly draft: the propose staging of the context, and a forced prev chain (test only) + const struct llama_dfly_propose_input * dfly_inp = nullptr; + bool dfly_force_prev = false; }; diff --git a/src/llama-dfly.h b/src/llama-dfly.h new file mode 100644 index 0000000000000000000000000000000000000000..8c529c2cf639c77767eaee60ccfc0635be930ae6 --- /dev/null +++ b/src/llama-dfly.h @@ -0,0 +1,249 @@ +#pragma once + +// hy_v4_next_dfly host helpers that need no graph or context types, so that tests can call them directly + +#include "llama-memory-idx-iswa.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +enum llama_dfly_sel_status { + LLAMA_DFLY_SEL_STATUS_OK = 0, + LLAMA_DFLY_SEL_STATUS_BAD_ARG, + LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT, + LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS, + LLAMA_DFLY_SEL_STATUS_NON_FINITE, + LLAMA_DFLY_SEL_STATUS_BAD_POOL, + LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP, + LLAMA_DFLY_SEL_STATUS_DUP_GROUP, + LLAMA_DFLY_SEL_STATUS_SHORT_EXPORT, + LLAMA_DFLY_SEL_STATUS_INTERNAL, +}; + +inline const char * llama_dfly_sel_status_name(llama_dfly_sel_status status) { + switch (status) { + case LLAMA_DFLY_SEL_STATUS_OK: return "ok"; + case LLAMA_DFLY_SEL_STATUS_BAD_ARG: return "bad_arg"; + case LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT: return "bad_layout"; + case LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS: return "not_contiguous"; + case LLAMA_DFLY_SEL_STATUS_NON_FINITE: return "non_finite"; + case LLAMA_DFLY_SEL_STATUS_BAD_POOL: return "bad_pool"; + case LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP: return "future_group"; + case LLAMA_DFLY_SEL_STATUS_DUP_GROUP: return "dup_group"; + case LLAMA_DFLY_SEL_STATUS_SHORT_EXPORT: return "short_export"; + case LLAMA_DFLY_SEL_STATUS_INTERNAL: return "internal"; + } + return "unknown"; +} + +// the DFly context of one query row in one target layer +struct llama_dfly_ctx_set { + uint32_t strm = 0; + std::vector pos; // strictly increasing, 1..top_k entries, ends at p + std::vector cell; // stream local, cell[i] holds pos[i] +}; + +// ids/scores: the target's top-k for this row and layer as exported, unordered, -inf for invisible items +// dfly_top_k: S from hy_v4_next_dfly.target_index_top_k, never the target's own indexer_top_k +// refs: kpool_copy_refs for the same sequence, p and ids +// keeps the S/4 - 1 best history groups (ties among the exported groups go to the lower group) plus every member of p's own group +// on error out is empty and err is one line ": p=

", with " i= id= score=" for an item +inline llama_dfly_sel_status llama_dfly_normalize_selection( + const int32_t * ids, const float * scores, size_t n_ids, llama_pos p, uint32_t dfly_top_k, + const llama_memory_idx_iswa::kpool_refs & refs, llama_dfly_ctx_set & out, std::string & err) { + // the group size the draft was trained with + const int64_t G = 4; + + auto fail = [&](llama_dfly_sel_status status, const char * item = "") { + out = llama_dfly_ctx_set(); + err = std::string(llama_dfly_sel_status_name(status)) + ": p=" + std::to_string(p) + item; + return status; + }; + auto fail_item = [&](llama_dfly_sel_status status, size_t i) { + char buf[96]; + snprintf(buf, sizeof(buf), " i=%zu id=%d score=%.9g", i, ids[i], (double) scores[i]); + return fail(status, buf); + }; + + const int64_t S = dfly_top_k; + if (S < G || S > 2048 || S % G != 0 || p < 0) { + return fail(LLAMA_DFLY_SEL_STATUS_BAD_ARG); + } + if (n_ids > 0 && (ids == nullptr || scores == nullptr)) { + return fail(LLAMA_DFLY_SEL_STATUS_BAD_ARG); + } + if (refs.found.size() != n_ids || refs.pos.size() != n_ids*refs.kpool || refs.cell.size() != n_ids*refs.kpool || + refs.cur_pos.size() != refs.cur_cell.size()) { + return fail(LLAMA_DFLY_SEL_STATUS_BAD_ARG); + } + + if (refs.kpool != G) { + return fail(LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT); + } + // groups are counted from position 0 + if (refs.pos_min != 0) { + return fail(LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT); + } + + const int64_t g = p / G; + const int64_t H = S/G - 1; + + // [0, p] must have no hole and no repeated position: p's own group then holds exactly 4g..p + if (refs.n_hist_avail != g || (int64_t) refs.n_cells_upto_p != (int64_t) p + 1) { + return fail(LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS); + } + bool cur_ok = (int64_t) refs.cur_pos.size() == p - G*g + 1; + for (size_t k = 0; cur_ok && k < refs.cur_pos.size(); ++k) { + cur_ok = refs.cur_pos[k] == G*g + (int64_t) k; + } + if (!cur_ok) { + return fail(LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS); + } + + struct cand { + float score; + int64_t h; + size_t i; + }; + std::vector hist; + std::unordered_set seen; + + // every finite item is checked in input order, before anything is sorted + for (size_t i = 0; i < n_ids; ++i) { + const float s = scores[i]; + if (s == -INFINITY) { + continue; + } + if (!std::isfinite(s)) { + return fail_item(LLAMA_DFLY_SEL_STATUS_NON_FINITE, i); + } + if (!refs.found[i]) { + return fail_item(LLAMA_DFLY_SEL_STATUS_BAD_POOL, i); + } + + // a pool must be one group: 4 consecutive positions from a multiple of 4 + const llama_pos * mp = refs.pos.data() + i*G; + bool aligned = mp[0] >= 0 && mp[0] % G == 0; + for (int64_t k = 1; aligned && k < G; ++k) { + aligned = (int64_t) mp[k] == (int64_t) mp[0] + k; + } + if (!aligned) { + char buf[96]; + snprintf(buf, sizeof(buf), " i=%zu id=%d pos=%d", i, ids[i], mp[0]); + return fail(LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT, buf); + } + + const int64_t h = mp[0] / G; + // by position: p's own group is in the future too while it is incomplete + if (G*h + G - 1 > p) { + return fail_item(LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP, i); + } + if (!seen.insert(h).second) { + return fail_item(LLAMA_DFLY_SEL_STATUS_DUP_GROUP, i); + } + // p's own complete group is added below with the rest of the group, it is not history + if (h < g) { + hist.push_back({ s, h, i }); + } + } + + // fewer than this means the target kept fewer groups than the draft needs, or the export lost some + if ((int64_t) hist.size() < std::min(H, g)) { + return fail(LLAMA_DFLY_SEL_STATUS_SHORT_EXPORT); + } + + // exact compare, no epsilon: ties among the exported groups go to the lower group + auto better = [](const cand & a, const cand & b) { + return a.score > b.score || (a.score == b.score && a.h < b.h); + }; + if ((int64_t) hist.size() > H) { + std::nth_element(hist.begin(), hist.begin() + H, hist.end(), better); + hist.resize(H); + } + std::sort(hist.begin(), hist.end(), [](const cand & a, const cand & b) { return a.h < b.h; }); + + llama_dfly_ctx_set res; + res.strm = refs.strm; + res.pos .reserve(hist.size()*G + refs.cur_pos.size()); + res.cell.reserve(hist.size()*G + refs.cur_pos.size()); + for (const auto & c : hist) { + for (int64_t k = 0; k < G; ++k) { + res.pos .push_back(refs.pos [c.i*G + k]); + res.cell.push_back(refs.cell[c.i*G + k]); + } + } + res.pos .insert(res.pos .end(), refs.cur_pos .begin(), refs.cur_pos .end()); + res.cell.insert(res.cell.end(), refs.cur_cell.begin(), refs.cur_cell.end()); + + bool ok = !res.pos.empty() && (int64_t) res.pos.size() <= S && res.pos.back() == p; + for (size_t k = 1; ok && k < res.pos.size(); ++k) { + ok = res.pos[k - 1] < res.pos[k]; + } + if (!ok) { + return fail(LLAMA_DFLY_SEL_STATUS_INTERNAL); + } + + out = std::move(res); + + return LLAMA_DFLY_SEL_STATUS_OK; +} + +enum llama_dfly_capture_status { + LLAMA_DFLY_CAPTURE_STATUS_OK = 0, + LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED, + LLAMA_DFLY_CAPTURE_STATUS_NO_ROWS, + LLAMA_DFLY_CAPTURE_STATUS_ERROR, +}; + +// the DFly context of one query row in one target layer, as copied out of the target +struct llama_dfly_layer_ctx { + int32_t target_layer = -1; + uint32_t strm = 0; + std::vector pos; // count = pos.size(), 1..S, strictly increasing, ends at query_pos + std::vector cell; // stream local, cell[i] holds pos[i] +}; + +// one output row of one target decode, owned by the reader +struct llama_dfly_snapshot { + uint64_t target_ctx_id = 0; + uint64_t decode_id = 0; + uint64_t prefix_epoch = 0; + llama_seq_id seq_id = -1; + int32_t batch_row = -1; + llama_pos query_pos = -1; + std::vector h_final; // n_embd, after the target's final norm + std::array layer; +}; + +// the inputs of one DFly propose, filled by the draft context and read by the graph at set_input +struct llama_dfly_propose_input { + std::vector h_t; // n_embd + std::array, LLAMA_DFLY_N_LAYER> cell; // S per layer, padded with the query's own cell + std::array, LLAMA_DFLY_N_LAYER> mask; // [W][S + W] per layer, 0 or -inf + std::vector prev; // K, only read when the graph is built with a forced prev chain (test only) +}; + +// the host check of a drafted round: every raw id in the vocab and every finite probe 0, else the round is dropped +// on error err names the first bad slot (1-based) +inline bool llama_dfly_check_draft(const int32_t * raw, const float * finite, int32_t n, int32_t n_vocab, std::string & err) { + for (int32_t j = 0; j < n; ++j) { + if (raw[j] < 0 || raw[j] >= n_vocab) { + err = "slot " + std::to_string(j + 1) + ": raw id " + std::to_string(raw[j]) + " is out of the vocab of " + std::to_string(n_vocab); + return false; + } + // NaN for any NaN or inf in the logits + if (!(finite[j] == 0.0f)) { + char buf[64]; + snprintf(buf, sizeof(buf), "%g", (double) finite[j]); + err = "slot " + std::to_string(j + 1) + ": the logits are not finite (probe " + buf + ")"; + return false; + } + } + return true; +} diff --git a/src/llama-ext.h b/src/llama-ext.h index 23a781404bd8bb55b5b889fb43ca75c20d82f4f6..9053900cb5b726054bcae652bdc4e8dcf7767b76 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -202,3 +202,44 @@ LLAMA_API uint32_t llama_model_get_tok_embd_rows(const struct llama_model * mode // realtime models: number of tokens the output lags behind the audio input, used by mtmd; 0 if not applicable LLAMA_API uint32_t llama_model_n_tokens_delay(const struct llama_model * model); + +// +// DFly draft model (hy_v4_next_dfly) staging +// + +enum llama_dfly_status : int32_t { + LLAMA_DFLY_OK = 0, + LLAMA_DFLY_NO_SNAPSHOT = 1, + LLAMA_DFLY_BAD_SNAPSHOT = 2, + LLAMA_DFLY_BAD_TOKEN = 3, + LLAMA_DFLY_COMPUTE_FAILED = 4, + LLAMA_DFLY_BAD_REQUEST = 5, +}; + +struct llama_dfly_request { + llama_seq_id seq_id; + llama_token anchor_token; + llama_pos anchor_pos; + int32_t k_step; +}; + +struct llama_dfly_result { + llama_token * tokens; // caller owned, [0, n_tokens) written on success + int32_t capacity; // must be >= request.k_step + int32_t n_tokens; // 0 on entry and on any failure, k_step on success +}; + +// call once at init, after target warmup and the seq_rm probe: turn on the masked target capture that DFly reads +LLAMA_API enum llama_dfly_status llama_dfly_capture_enable(struct llama_context * ctx_dfly); + +// call after each successful target decode: copy all output rows, NO_SNAPSHOT if there are none +LLAMA_API enum llama_dfly_status llama_dfly_capture_pull (struct llama_context * ctx_dfly); + +// call once per round: draft k_step tokens from the snapshot row at anchor_pos - 1 +LLAMA_API enum llama_dfly_status llama_dfly_propose( + struct llama_context * ctx_dfly, + const struct llama_dfly_request * request, + struct llama_dfly_result * result); + +// call before prefill and at end/clear/restore/prefix change: drop the snapshot of seq_id +LLAMA_API void llama_dfly_invalidate(struct llama_context * ctx_dfly, llama_seq_id seq_id); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index fe8bdebe5e2c7452375dfa01c364e0d48ebc198c..7277e5250a367c0a3e85bf69a58a498e02f4c140 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -5,6 +5,7 @@ #include "llama-moe-cache.h" #include "llama-batch.h" #include "llama-cparams.h" +#include "llama-dfly.h" #include "llama-sampler.h" #include "llama-kv-cache.h" @@ -15,6 +16,7 @@ #include "llama-kv-cache-dsv4.h" #include "llama-memory-hybrid.h" #include "llama-memory-hybrid-iswa.h" +#include "llama-memory-idx-iswa.h" #include "llama-memory-recurrent.h" #include @@ -834,8 +836,12 @@ void llm_graph_input_attn_k_iswa::set_input(const llama_ubatch * ubatch) { mctx->get_swa()->set_input_attn_mask(self_attn_mask_swa, ubatch, cparams.causal_attn); } +const llama_kv_cache_iswa_context * llm_graph_input_attn_k_iswa::mctx_of(const llm_graph_params & params) const { + return static_cast(params.mctx); +} + bool llm_graph_input_attn_k_iswa::can_reuse(const llm_graph_params & params) { - const auto * mctx = static_cast(params.mctx); + const auto * mctx = mctx_of(params); this->mctx = mctx; @@ -1388,6 +1394,65 @@ bool llm_graph_input_sampling::can_reuse(const llm_graph_params & params) { return true; } +bool llm_graph_dfly_k_storage(const llama_cparams & cparams, const llama_hparams & hparams, llama_seq_id seq_id, + std::array & k, uint32_t & strm) { + const auto * mem = cparams.ctx_other ? dynamic_cast(llama_get_memory(cparams.ctx_other)) : nullptr; + if (mem == nullptr) { + return false; + } + const llama_kv_cache * base = mem->get_mem_attn()->get_base(); + if (seq_id < 0 || (uint32_t) seq_id >= base->get_n_seq_max()) { + return false; + } + try { + for (uint32_t i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + k[i] = base->get_k_storage((int32_t) hparams.dfly_target_kv_layers[i]); + } + } catch (const std::out_of_range &) { + return false; + } + strm = base->get_stream(seq_id); + return true; +} + +void llm_graph_input_dfly::set_input(const llama_ubatch * ubatch) { + GGML_ASSERT(src != nullptr); + + const int64_t n_tokens = ubatch->n_tokens; + + GGML_ASSERT((int64_t) src->h_t.size() == h_t->ne[0]); + ggml_backend_tensor_set(h_t, src->h_t.data(), 0, ggml_nbytes(h_t)); + + for (uint32_t i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + GGML_ASSERT((int64_t) src->cell[i].size() == n_ctx_rows); + GGML_ASSERT((int64_t) src->mask[i].size() == (n_ctx_rows + n_tokens)*n_tokens); + ggml_backend_tensor_set(ctx_idx[i], src->cell[i].data(), 0, ggml_nbytes(ctx_idx[i])); + ggml_backend_tensor_set(kq_mask[i], src->mask[i].data(), 0, ggml_nbytes(kq_mask[i])); + } + + if (prev) { + GGML_ASSERT((int64_t) src->prev.size() == prev->ne[0]); + ggml_backend_tensor_set(prev, src->prev.data(), 0, ggml_nbytes(prev)); + } +} + +bool llm_graph_input_dfly::can_reuse(const llm_graph_params & params) { + std::array k = {}; + uint32_t s = 0; + if (!llm_graph_dfly_k_storage(params.cparams, params.hparams, params.ubatch.seq_id[0][0], k, s)) { + return false; + } + + bool res = true; + + res &= src == params.cparams.dfly_inp; + res &= force_prev == params.cparams.dfly_force_prev; + res &= k == k_storage && s == strm; + res &= kq_mask[0]->ne[1] == params.ubatch.n_tokens; + + return res; +} + // // llm_graph_result // @@ -1411,6 +1476,11 @@ void llm_graph_result::reset() { t_embd_pooled = nullptr; t_h_nextn = nullptr; + t_dfly_ids.fill(nullptr); + t_dfly_scores.fill(nullptr); + t_dfly_tokens.clear(); + t_dfly_finite.clear(); + t_layer_inp.resize(LLAMA_MAX_LAYERS + 1); std::fill(t_layer_inp.begin(), t_layer_inp.end(), nullptr); @@ -1457,6 +1527,18 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { if (t_h_nextn != nullptr) { ggml_set_output(t_h_nextn); } + for (size_t k = 0; k < t_dfly_ids.size(); ++k) { + if (t_dfly_ids[k] != nullptr) { + ggml_set_output(t_dfly_ids[k]); + } + if (t_dfly_scores[k] != nullptr) { + ggml_set_output(t_dfly_scores[k]); + } + } + for (size_t j = 0; j < t_dfly_tokens.size(); ++j) { + ggml_set_output(t_dfly_tokens[j]); + ggml_set_output(t_dfly_finite[j]); + } { const auto & embeddings_layer_inp = params.cparams.embeddings_layer_inp; for (size_t il = 0; il < embeddings_layer_inp.size() && !params.cparams.embeddings_layer_inp_dev; ++il) { @@ -2452,7 +2534,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( const float limit = hparams.swiglu_clamp_exp[il]; constexpr float eps = 1e-6f; if (limit > eps) { - if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41 || arch == LLM_ARCH_GLM5_NEXT || (arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0) || arch == LLM_ARCH_HY_V4) { + if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41 || arch == LLM_ARCH_GLM5_NEXT || (arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0) || arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH) { cur = ggml_swiglu_clamp(ctx0, cur, up, limit); } else { up = ggml_clamp(ctx0, up, -limit, limit); @@ -3868,7 +3950,13 @@ llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const llm_graph_input_attn_k_iswa * llm_graph_context::build_attn_inp_k_iswa() const { const auto * mctx_cur = static_cast(mctx); - auto inp = std::make_unique(hparams, cparams, mctx_cur); + return build_attn_inp_k_iswa( + std::make_unique(hparams, cparams, mctx_cur), mctx_cur); +} + +llm_graph_input_attn_k_iswa * llm_graph_context::build_attn_inp_k_iswa( + std::unique_ptr inp, + const llama_kv_cache_iswa_context * mctx_cur) const { { inp->self_k_idxs = mctx_cur->get_base()->build_input_k_idxs(ctx0, ubatch); diff --git a/src/llama-graph.h b/src/llama-graph.h index 37b47acbb30aca36007d90d87e8412adfd22f6b1..37988ecaa8106728e92c01ba6ba408c602d2a850 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -562,12 +562,17 @@ public: cparams(cparams), mctx(mctx) { } - ~llm_graph_input_attn_k_iswa() = default; + virtual ~llm_graph_input_attn_k_iswa() = default; void set_input(const llama_ubatch * ubatch) override; bool can_reuse(const llm_graph_params & params) override; + // Where this input finds its context in the next batch's params. The default is that the + // memory is the iSWA cache itself; an arch whose memory merely composes one overrides this, + // because params.mctx is then that outer context and the cast would be wrong. + virtual const llama_kv_cache_iswa_context * mctx_of(const llm_graph_params & params) const; + ggml_tensor * get_k_idxs() const { return self_k_idxs; } ggml_tensor * get_k_idxs_swa() const { return self_k_idxs_swa; } @@ -770,6 +775,39 @@ public: std::map samplers; }; +struct llama_dfly_propose_input; + +// the K storage of the 5 target layers a DFly draft reads, and the stream of seq_id; false if the target has none +bool llm_graph_dfly_k_storage(const llama_cparams & cparams, const llama_hparams & hparams, llama_seq_id seq_id, + std::array & k, uint32_t & strm); + +// DFly propose: the snapshot data of one round, read from the context staging at set_input +// tokens and positions come with the ubatch +class llm_graph_input_dfly : public llm_graph_input_i { +public: + llm_graph_input_dfly(const llama_dfly_propose_input * src, int64_t n_ctx_rows, bool force_prev) : + src(src), n_ctx_rows(n_ctx_rows), force_prev(force_prev) {} + virtual ~llm_graph_input_dfly() = default; + + void set_input(const llama_ubatch * ubatch) override; + bool can_reuse(const llm_graph_params & params) override; + + ggml_tensor * h_t = nullptr; // F32 [n_embd, 1] + ggml_tensor * prev = nullptr; // I32 [n_tokens - 1], forced prev chain (test only) + + std::array ctx_idx = {}; // I32 [S], cells of the target K storage + std::array kq_mask = {}; // F32 [S + n_tokens, n_tokens] + + // the target storage the graph reads + std::array k_storage = {}; + uint32_t strm = 0; + + const llama_dfly_propose_input * src; + + const int64_t n_ctx_rows; // S + const bool force_prev; +}; + // // llm_graph_result // @@ -972,6 +1010,14 @@ public: std::vector t_layer_inp; + // DFly capture, per configured slot: the top-k ids (I32) and their scores (F32), [n_top_pool, n_outputs] + std::array t_dfly_ids = {}; + std::array t_dfly_scores = {}; + + // DFly draft, one per slot 1..K: the raw argmax id (I32 [1]) and the finite probe of the logits (F32 [1]) + std::vector t_dfly_tokens; + std::vector t_dfly_finite; + std::vector t_sampled; std::vector t_sampled_probs; std::vector t_sampled_logits; @@ -1370,6 +1416,12 @@ struct llm_graph_context { llm_graph_input_attn_k_iswa * build_attn_inp_k_iswa() const; + // same, for a memory that composes an iSWA pair rather than being one: the arch supplies the + // input, so it can override mctx_of(), and the attention context out of its own + llm_graph_input_attn_k_iswa * build_attn_inp_k_iswa( + std::unique_ptr inp, + const llama_kv_cache_iswa_context * mctx_cur) const; + // note: if k_cur is not provided, it will not be stored in the memory // note: the K cache is used as V (MLA-style attention) ggml_tensor * build_attn( diff --git a/src/llama-hparams.h b/src/llama-hparams.h index 4d2cb89314d24fab9ca845f2469847c5912ef807..283563a9d1a57f29f6fee6b75b5d174734568901 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -10,8 +10,12 @@ // bump if necessary #define LLAMA_MAX_LAYERS 512 #define LLAMA_MAX_EXPERTS 1024 // Kimi K3 -#define LLAMA_MAX_PLE_NGRAM 8 // qwen4exp, deepseek41 (all hash modules) +// multipliers are stored flat as [module][ngram] and indexed at stride ple_ngram_size +// (deepseek41.cpp:247), so this bounds ple_n_modules*ple_ngram_size, not ngram_size alone. +// hy_v4_flash needs 4 modules x 3 = 12. +#define LLAMA_MAX_PLE_NGRAM 16 // qwen4exp, deepseek41, hy_v4_flash (all hash modules) #define LLAMA_MAX_PLE_HEADS 64 // qwen4exp, deepseek41 (all hash modules) +#define LLAMA_DFLY_N_LAYER 5 // hy_v4_next_dfly schema v1 enum llama_expert_gating_func_type { LLAMA_EXPERT_GATING_FUNC_TYPE_NONE = 0, @@ -284,6 +288,16 @@ struct llama_hparams { float lilicorr_vector_eps = 0.0f; float lilicorr_logit_scale = 0.0f; + // hy_v4_next_dfly + uint32_t dfly_schema_version = 0; + uint32_t dfly_block_size = 0; // B, includes the anchor + uint32_t dfly_target_index_top_k = 0; // S + uint32_t dfly_hidden_correction_length = 0; // C + bool dfly_has_confidence_head = false; + std::array dfly_target_kv_layers = {}; + std::array dfly_target_index_layers = {}; + std::array dfly_source_mrope_sections = {}; + // llama4 smallthinker uint32_t n_moe_layer_step = 0; uint32_t n_no_rope_layer_step = 4; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 84f547ae18d6c4f58586e8a384f5ae691e7b99ae..0dd9121af24eaaca5f73c449dd390552654b020e 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -6,6 +6,7 @@ #include "llama-context.h" #include +#include #include #include #include @@ -1017,6 +1018,12 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, uint32_t n_tokens = ubatch.n_tokens; uint32_t n_seqs = 1; + // the sequences that write in this ubatch, see the SWA mask below + std::array seq_writes = {}; + for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { + seq_writes[ubatch.seq_id_unq[s]] = true; + } + if (n_stream > 1) { GGML_ASSERT(n_tokens % ubatch.n_seqs_unq == 0); @@ -1104,8 +1111,10 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, if (!can_use) { const llama_seq_id seq_id_cell = cells.seq_get(idx); - // SWA mask - if (llama_hparams::is_masked_swa(n_swa, swa_type, pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) { + // SWA mask: a writing sequence may drop its oldest window row, the others keep their whole + // window, which a checkpoint, a state save and the replay at their pos_max need + const llama_pos p1 = cells.seq_pos_max(seq_id_cell) + (seq_writes[seq_id_cell] ? 1 : 0); + if (llama_hparams::is_masked_swa(n_swa, swa_type, pos_cell, p1)) { can_use = true; } } @@ -2105,14 +2114,18 @@ ggml_tensor * llama_kv_cache::build_rope_shift( tmp = ggml_cast(ctx, cur, GGML_TYPE_F32); // rotate back - tmp = llama_mul_mat_hadamard(ctx, tmp, rot); + if (rot) { + tmp = llama_mul_mat_hadamard(ctx, tmp, rot); + } tmp = ggml_rope_ext(ctx, tmp, shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow); // rotate fwd - tmp = llama_mul_mat_hadamard(ctx, tmp, rot); + if (rot) { + tmp = llama_mul_mat_hadamard(ctx, tmp, rot); + } tmp = ggml_cpy(ctx, tmp, cur); } else { diff --git a/src/llama-memory-idx-iswa.cpp b/src/llama-memory-idx-iswa.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3dae9bd6a05b9e87503c3f0a642bd6722c4ebb19 --- /dev/null +++ b/src/llama-memory-idx-iswa.cpp @@ -0,0 +1,1077 @@ +#include "llama-memory-idx-iswa.h" + +#include "llama-impl.h" +#include "llama-batch.h" +#include "llama-io.h" +#include "llama-model.h" + +#include +#include +#include +#include + +// +// llama_memory_idx_iswa +// + +llama_memory_idx_iswa::llama_memory_idx_iswa( + const llama_model & model, + bool no_alloc, + ggml_type type_k, + ggml_type type_v, + bool v_trans, + bool offload, + bool swa_full, + bool unified, + uint32_t kv_size, + uint32_t n_seq_max, + uint32_t n_ubatch, + const layer_filter_cb & filter, + const layer_filter_cb & filter_idx) : + hparams_idx(model.hparams), + mem_attn(new llama_kv_cache_iswa( + model, no_alloc, type_k, type_v, v_trans, offload, swa_full, unified, + kv_size, n_seq_max, n_ubatch, + nullptr, filter, nullptr, nullptr)), + mem_idx([&] { + // a model without an indexer uses llama_kv_cache_iswa directly, so there is no null case here + GGML_ASSERT(filter_idx != nullptr); + + // the indexer mirrors the base child alone, so a SWA layer has no cells of its own to index + for (uint32_t il = 0; il < model.hparams.n_layer_all; ++il) { + GGML_ASSERT(!(filter_idx(il) && model.hparams.is_swa(il)) && "an indexer layer cannot be a SWA layer"); + } + + // MQA with a single key head of indexer_head_size, as llama_kv_cache_dsa shapes its own + std::fill(hparams_idx.n_head_kv_arr.begin(), hparams_idx.n_head_kv_arr.end(), 1); + // a k-pool indexer caches its per-token rows and the pooled key side by side + // (glm5-next: key | gate | pooled, qwen4exp: key | pooled) + hparams_idx.n_embd_head_k_full = model.hparams.indexer_head_size * (model.hparams.indexer_kpool > 0 ? model.hparams.indexer_kpool_row : 1); + + // the cached indexer keys are raw, rotation happens after pooling at read time, so a + // K-shift must not rotate them while the stream copies in the same update still apply + hparams_idx.rope_type = LLAMA_ROPE_TYPE_NONE; + + // fool llama_kv_cache into thinking this is a MLA cache, so it won't cache V tensors + hparams_idx.n_embd_head_k_mla_impl = model.hparams.indexer_head_size; + hparams_idx.n_embd_head_v_mla_impl = model.hparams.indexer_head_size; + + LLAMA_LOG_INFO("%s: creating indexer KV cache, size = %u cells\n", __func__, kv_size); + + // the indexer mirrors the base child, so it takes its size and its (absent) SWA as well + return new llama_kv_cache( + model, no_alloc, hparams_idx, type_k, type_v, v_trans, offload, unified, + kv_size, n_seq_max, 0, LLAMA_SWA_TYPE_NONE, + nullptr, filter_idx, nullptr, nullptr, "idx_"); + }()) {} + +llama_memory_context_ptr llama_memory_idx_iswa::init_batch(llama_batch_allocr & balloc, uint32_t n_ubatch, bool embd_all) { + // note: repeats llama_kv_cache_iswa::init_batch, as the indexer needs the base slot infos that its context hides + // Use non-sequential split when KV cache is unified (needed for hellaswag/winogrande/multiple-choice) + const bool unified = (mem_attn->get_base()->get_n_stream() == 1); + + // several sequences in one stream: take the batch in order first, so that a batch that fits is one ubatch + // (an equal split cuts a DFly verify of one sequence apart); a single sequence keeps the equal split + const bool try_simple = unified && mem_attn->get_base()->get_n_seq_max() > 1; + + for (int attempt = try_simple ? 0 : 1; attempt < 2; ++attempt) { + balloc.split_reset(); + + std::vector ubatches; + + while (true) { + llama_ubatch ubatch; + + if (attempt == 0) { + ubatch = balloc.split_simple(n_ubatch); + } else if (embd_all) { + // if all tokens are output, split by sequence + ubatch = balloc.split_seq(n_ubatch); + } else { + ubatch = balloc.split_equal(n_ubatch, !unified, 0); + } + + if (ubatch.n_tokens == 0) { + break; + } + + ubatches.push_back(std::move(ubatch)); // NOLINT + } + + if (balloc.get_n_used() < balloc.get_n_tokens()) { + // failed to find a suitable split + continue; + } + + // the in-order split falls back to the equal split quietly, as in llama_kv_cache_iswa + auto sinfos_base = mem_attn->get_base()->prepare(ubatches); + if (sinfos_base.empty()) { + if (attempt == 1) { + LLAMA_LOG_ERROR("%s: failed to prepare non-SWA attention ubatches\n", __func__); + } + continue; + } + + auto sinfos_swa = mem_attn->get_swa()->prepare(ubatches); + if (sinfos_swa.empty()) { + if (attempt == 1) { + LLAMA_LOG_ERROR("%s: failed to prepare SWA attention ubatches\n", __func__); + } + continue; + } + + assert(sinfos_base.size() == sinfos_swa.size()); + + // the indexer uses the base cache's slot layout; a separate one can drift from it + llama_kv_cache::slot_info_vec_t sinfos_idx = sinfos_base; + + return std::make_unique( + this, std::move(sinfos_base), std::move(sinfos_swa), std::move(sinfos_idx), std::move(ubatches)); + } + + return std::make_unique(LLAMA_MEMORY_STATUS_FAILED_PREPARE); +} + +llama_memory_context_ptr llama_memory_idx_iswa::init_full() { + return std::make_unique(this); +} + +llama_memory_context_ptr llama_memory_idx_iswa::init_update(llama_context * lctx, bool optimize) { + return std::make_unique(this, lctx, optimize); +} + +bool llama_memory_idx_iswa::get_can_shift() const { + // the indexer holds raw keys, so a shift never has to rotate them: only attention can refuse one + return mem_attn->get_can_shift(); +} + +void llama_memory_idx_iswa::clear(bool data) { + mem_attn->clear(data); + mem_idx ->clear(data); + + mem_idx_stale_set(-1, 0); +} + +// A pooled key is only valid while the grouping that produced it holds. Grouping is sequence relative, +// so an edit at p0 leaves every pool that ends before p0 alone. +void llama_memory_idx_iswa::mem_idx_stale_set(llama_seq_id seq_id, llama_pos p0) { + p0 = std::max(p0, 0); + + if (seq_id < 0) { + for (auto & p : mem_idx_stale) { + p = std::min(p, p0); + } + + return; + } + + GGML_ASSERT(seq_id < (llama_seq_id) LLAMA_MAX_SEQ); + + mem_idx_stale[seq_id] = std::min(mem_idx_stale[seq_id], p0); +} + +// An edit at or below the first position moves pos_min, which regroups the whole sequence. +llama_pos llama_memory_idx_iswa::mem_idx_stale_pos(llama_seq_id seq_id, llama_pos p0) const { + if (seq_id < 0 || p0 <= mem_idx->seq_pos_min(seq_id)) { + return 0; + } + + return p0; +} + +bool llama_memory_idx_iswa::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { + // the stale position is relative to the first position the indexer still holds, so read it before the removal + const llama_pos stale = mem_idx_stale_pos(seq_id, p0); + + bool res = true; + + res = res & mem_attn->seq_rm(seq_id, p0, p1); + res = res & mem_idx ->seq_rm(seq_id, p0, p1); + + mem_idx_stale_set(seq_id, stale); + + return res; +} + +void llama_memory_idx_iswa::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { + // only whole sequences are copied: a shared cell holds a single pool grouping + GGML_ASSERT(p0 <= 0 && p1 < 0 && "partial seq_cp is not supported"); + + mem_attn->seq_cp(seq_id_src, seq_id_dst, p0, p1); + mem_idx ->seq_cp(seq_id_src, seq_id_dst, p0, p1); + + // a whole sequence copy gives the destination the source's pools, rep rows included: the source keeps its + // pooled keys, the destination rebuilds its layout and re-pools into the same rows + mem_idx_stale_set(seq_id_dst, 0); +} + +void llama_memory_idx_iswa::seq_keep(llama_seq_id seq_id) { + mem_attn->seq_keep(seq_id); + mem_idx ->seq_keep(seq_id); + + // every other sequence loses its cells, so their layouts must rebuild + mem_idx_stale_set(-1, 0); +} + +void llama_memory_idx_iswa::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { + // a negative shift moves the cells below p0, so they regroup as well + const llama_pos stale = mem_idx_stale_pos(seq_id, shift < 0 ? p0 + shift : p0); + + mem_attn->seq_add(seq_id, p0, p1, shift); + mem_idx ->seq_add(seq_id, p0, p1, shift); + + mem_idx_stale_set(seq_id, stale); +} + +void llama_memory_idx_iswa::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) { + mem_attn->seq_div(seq_id, p0, p1, d); + mem_idx ->seq_div(seq_id, p0, p1, d); + + mem_idx_stale_set(seq_id, 0); +} + +llama_pos llama_memory_idx_iswa::seq_pos_min(llama_seq_id seq_id) const { + return mem_attn->seq_pos_min(seq_id); +} + +llama_pos llama_memory_idx_iswa::seq_pos_max(llama_seq_id seq_id) const { + return mem_attn->seq_pos_max(seq_id); +} + +std::map llama_memory_idx_iswa::memory_breakdown() const { + std::map mb = mem_attn->memory_breakdown(); + + for (const auto & buft_size : mem_idx->memory_breakdown()) { + mb[buft_size.first] += buft_size.second; + } + + return mb; +} + +void llama_memory_idx_iswa::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { + mem_attn->state_write(io, seq_id, flags); + + // the indexer section goes last, so it is a pure suffix: an iSWA-only reader stops early instead of misparsing it + mem_idx->state_write(io, seq_id, flags); +} + +void llama_memory_idx_iswa::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { + // note: repeats llama_kv_cache_iswa::state_read + // the indexer needs the base cache's cells, and a half-failed restore must leave both caches alike + + // the indexer restore adopts the base cache's layout instead of searching for cells of its own + // two find_slot calls agree only while both caches see the same occupancy, which a restore cannot promise + llama_kv_cache::slot_info_vec_t sinfos_base; + + try { + mem_attn->get_base()->state_read_sinfo(io, seq_id, flags, &sinfos_base, nullptr); + mem_attn->get_swa ()->state_read(io, seq_id, flags); + + // must mirror the write order in state_write + // the indexer has the SWA type of the base child, so both read the same partial state + mem_idx->state_read_sinfo(io, seq_id, flags, nullptr, &sinfos_base); + + // a restore that rewrites cells does it behind the pool layout's back + if (!sinfos_base.empty()) { + mem_idx_stale_set(seq_id, 0); + } + } catch (...) { + // a half-restored context is the one state the indexer cannot fix by itself: attention holds new cells, the indexer old ones + // drop what was being restored from both of them, which is a state they do agree on. + state_drop(seq_id); + + throw; + } +} + +void llama_memory_idx_iswa::state_drop(llama_seq_id seq_id) { + if (seq_id < 0) { + clear(true); + + return; + } + + mem_attn->get_base()->state_clear(seq_id); + mem_attn->get_swa ()->state_clear(seq_id); + + mem_idx->state_clear(seq_id); + mem_idx_stale_set(seq_id, 0); +} + +llama_kv_cache_iswa * llama_memory_idx_iswa::get_mem_attn() const { + return mem_attn.get(); +} + +llama_kv_cache * llama_memory_idx_iswa::get_mem_idx() const { + return mem_idx.get(); +} + +// +// llama_memory_idx_iswa_context +// + +// streams in each ubatch's slot info, matching get_k/get_v's `ns` +static std::vector llama_memory_idx_iswa_ns(const llama_kv_cache::slot_info_vec_t & sinfos) { + std::vector res; + res.reserve(sinfos.size()); + + for (const auto & sinfo : sinfos) { + res.push_back(sinfo.s1 - sinfo.s0 + 1); + } + + return res; +} + +// Which cells of a sequence make up which pool, for the whole cache. +struct llama_memory_idx_iswa::kpool_layout { + struct seq { + llama_pos pos_min = 0; + uint32_t strm = 0; // Stream holding this sequence's cells + std::vector> cells; // Position and stream local cell pairs, sorted by position. + std::vector pools; + + // Where the pool scan stopped, so an append resumes instead of starting over. + size_t j_next = 0; + }; + + std::array seqs; + + uint32_t n_pool_real = 0; +}; + +// Which pools of the layout the current ubatch must re-pool, in the layout's pool order. +struct llama_memory_idx_iswa_context::kpool_state { + std::vector is_new; + std::vector rep_gen; // per global cell, the generation that last marked a pool with that rep + uint32_t generation = 0; + + uint32_t n_pool_real = 0; + uint32_t n_new = 0; + uint32_t n_new_g = 1; // graph size of the new pool list, stable across decode steps +}; + +namespace { + +// The last padded pool is always unused. +uint32_t kpool_pad(uint32_t n_pool) { + return std::max(64u, GGML_PAD(n_pool + 1, 64u)); +} + +// Rank of (pos, cell) in a sequence's cells sorted by position then cell, or -1 when absent. +// In order mode the rank alone places a token: cells sharing a position (M-RoPE images) have distinct ranks. +int64_t kpool_rank(const std::vector> & cells, llama_pos pos, uint32_t cell) { + auto it = std::lower_bound(cells.begin(), cells.end(), std::make_pair(pos, cell)); + return it != cells.end() && it->second == cell && it->first == pos ? it - cells.begin() : -1; +} + +} + +llama_memory_idx_iswa::~llama_memory_idx_iswa() = default; + +const llama_memory_idx_iswa::kpool_layout & llama_memory_idx_iswa::kpool_layout_get() const { + GGML_ASSERT(kpool_lay != nullptr); + + return *kpool_lay; +} + +// Pools are fixed by the positions relative to the sequence's first one, so the layout survives a plain +// append. A sequence edit can regroup them, and mem_idx_stale tells us it happened. +const llama_memory_idx_iswa::kpool_layout & llama_memory_idx_iswa::kpool_layout_update() { + if (!kpool_lay) { + kpool_lay = std::make_unique(); + } + + auto & lay = *kpool_lay; + + const uint32_t kpool = get_kpool(); + const uint32_t n_stream_kv = mem_idx->get_n_stream(); + const bool unified = n_stream_kv == 1; + + lay.n_pool_real = 0; + + for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { + auto & sq = lay.seqs[s]; + + // a non unified cache gives each sequence its own stream, with stream local cell indices + if (!unified && s >= (llama_seq_id) n_stream_kv) { + sq = kpool_layout::seq(); + continue; + } + + const auto & cells = mem_idx->get_cells(unified ? 0 : s); + const auto & sp = cells.seq_pos_get(s); + + sq.strm = unified ? 0 : mem_idx->get_stream(s); + + if (mem_idx_stale[s] == POS_CLEAN && !sq.cells.empty() && !sp.empty() && + sq.pos_min == sp.begin()->first) { + for (auto it = sp.upper_bound(sq.cells.back()); it != sp.end(); ++it) { + sq.cells.push_back(*it); + } + } + + // the appended tail accounts for every cell only if nothing before it was dropped, but an edit can + // regroup a sequence without changing its cell count, so a stale sequence must rebuild regardless + if (sq.cells.size() != sp.size() || mem_idx_stale[s] != POS_CLEAN) { + sq.cells.assign(sp.begin(), sp.end()); + sq.pools.clear(); + sq.j_next = 0; + sq.pos_min = sp.empty() ? 0 : sp.begin()->first; + } + + // Pools start at the first valid token + size_t j = sq.j_next; + if (hparams_idx.indexer_kpool_by_order) { + // consecutive cells in sequence order, whatever their positions + for (; j + kpool <= sq.cells.size(); j += kpool) { + sq.pools.push_back((uint32_t) j); + } + } else { + while (j + kpool <= sq.cells.size()) { + const llama_pos p0 = sq.cells[j].first; + if ((p0 - sq.pos_min) % (llama_pos) kpool != 0) { + ++j; + continue; + } + bool ok = true; + for (uint32_t k = 1; k < kpool; ++k) { + if (sq.cells[j + k].first != p0 + (llama_pos) k) { + ok = false; + break; + } + } + if (ok) { + sq.pools.push_back((uint32_t) j); + j += kpool; + } else { + ++j; + } + } + } + sq.j_next = j; + + lay.n_pool_real += (uint32_t) sq.pools.size(); + } + + return lay; +} + +// Only reads the layout, so the numbering is the one set_input_kpool used for the latest ubatch. +// A stale sequence is refused: its layout may still point at removed cells until the next batch succeeds. +bool llama_memory_idx_iswa::kpool_copy_refs(llama_seq_id seq_id, llama_pos p, const int32_t * ids, size_t n_ids, + kpool_refs & out, std::string & err) const { + out = kpool_refs(); + + if (!kpool_lay || get_kpool() == 0) { + err = format("%s: there is no k-pool layout", __func__); + return false; + } + if (seq_id < 0 || seq_id >= (llama_seq_id) LLAMA_MAX_SEQ) { + err = format("%s: seq_id = %d is out of range", __func__, seq_id); + return false; + } + if (p < 0) { + err = format("%s: p = %d is negative", __func__, p); + return false; + } + if (n_ids > 0 && ids == nullptr) { + err = format("%s: ids is null for n_ids = %zu", __func__, n_ids); + return false; + } + if (mem_idx_stale[seq_id] != POS_CLEAN) { + err = format("%s: seq_id = %d was edited since the last batch", __func__, seq_id); + return false; + } + + const auto & lay = *kpool_lay; + const auto & sq = lay.seqs[seq_id]; + const uint32_t kpool = get_kpool(); + + uint32_t pool_begin = 0; + for (llama_seq_id s = 0; s < seq_id; ++s) { + pool_begin += (uint32_t) lay.seqs[s].pools.size(); + } + + out.kpool = kpool; + out.strm = sq.strm; + out.pos_min = sq.pos_min; + out.pool_begin = pool_begin; + out.n_pools = (uint32_t) sq.pools.size(); + + out.found.assign(n_ids, 0); + out.pos .assign(n_ids*kpool, 0); + out.cell .assign(n_ids*kpool, 0); + + for (size_t i = 0; i < n_ids; ++i) { + const int64_t k = (int64_t) ids[i] - pool_begin; + if (k < 0 || k >= (int64_t) sq.pools.size()) { + continue; + } + const uint32_t j = sq.pools[k]; + out.found[i] = 1; + for (uint32_t m = 0; m < kpool; ++m) { + out.pos [i*kpool + m] = sq.cells[j + m].first; + out.cell[i*kpool + m] = sq.cells[j + m].second; + } + } + + const auto & cells = sq.cells; + const size_t i_end = std::upper_bound(cells.begin(), cells.end(), std::make_pair(p, UINT32_MAX)) - cells.begin(); + out.n_cells_upto_p = (uint32_t) i_end; + + if (p < sq.pos_min) { + return true; + } + + // the start of p's own pool + const llama_pos c0 = (llama_pos) (sq.pos_min + (int64_t) kpool*(((int64_t) p - sq.pos_min) / kpool)); + + out.n_hist_avail = (uint32_t) (std::lower_bound(sq.pools.begin(), sq.pools.end(), c0, + [&](uint32_t j, llama_pos c) { return cells[j].first < c; }) - sq.pools.begin()); + + const size_t i_cur = std::lower_bound(cells.begin(), cells.end(), std::make_pair(c0, 0u)) - cells.begin(); + for (size_t i = i_cur; i < i_end; ++i) { + out.cur_pos .push_back(cells[i].first); + out.cur_cell.push_back(cells[i].second); + } + + return true; +} + +llama_memory_idx_iswa_context::llama_memory_idx_iswa_context(llama_memory_status status) : status(status) {} + +llama_memory_idx_iswa_context::llama_memory_idx_iswa_context(llama_memory_idx_iswa * mem) : + mem(mem), + // graph reservation walks a full context, and the sparse attention is built only when this is set + // without it the reserved worst case is the dense graph, so ggml-alloc must grow the buffer on the first decode + ns_ubatch(std::vector{ mem->get_mem_idx()->get_n_stream() }), + ctx_attn(mem->get_mem_attn()->init_full()), + ctx_idx (mem->get_mem_idx ()->init_full()), + status(llama_memory_status_combine(ctx_attn->get_status(), ctx_idx->get_status())) { + if (kpool_track()) { + mem->kpool_layout_update(); + auto st = kpool_build_sizes(); + const auto * idx = mem->get_mem_idx(); + const uint64_t n_pool_max = uint64_t(idx->get_size() / mem->get_kpool()) * idx->get_n_seq_max(); + GGML_ASSERT(n_pool_max <= UINT32_MAX - 64); + st.n_pool_real = std::max(st.n_pool_real, uint32_t(n_pool_max)); + st.n_new = st.n_pool_real; + st.n_new_g = std::max(st.n_new, 1u); + kpool_st = std::make_unique(std::move(st)); + i_kpool = 0; + } +} + +llama_memory_idx_iswa_context::llama_memory_idx_iswa_context( + llama_memory_idx_iswa * mem, + llama_context * lctx, + bool optimize) : + mem(mem), + ctx_attn(mem->get_mem_attn()->init_update(lctx, optimize)), + // update() applies a pending cross-stream seq_cp, else the copy keeps stale indexer keys + ctx_idx (mem->get_mem_idx ()->init_update(lctx, optimize)), + status(llama_memory_status_combine(ctx_attn->get_status(), ctx_idx->get_status())) {} + +llama_memory_idx_iswa_context::llama_memory_idx_iswa_context( + llama_memory_idx_iswa * mem, + slot_info_vec_t sinfos_base, + slot_info_vec_t sinfos_swa, + slot_info_vec_t sinfos_idx, + std::vector ubatches) : + mem(mem), + ubatches(std::move(ubatches)), + ns_ubatch(llama_memory_idx_iswa_ns(sinfos_idx)), + sinfos_kpool(mem->get_kpool() > 0 && mem->get_kpool_by_order() ? sinfos_idx : slot_info_vec_t()), + // note: the children copy the ubatches; ctx_idx gets a copy of its own + ctx_attn(new llama_kv_cache_iswa_context(mem->get_mem_attn(), std::move(sinfos_base), std::move(sinfos_swa), this->ubatches)), + ctx_idx (new llama_kv_cache_context(mem->get_mem_idx(), std::move(sinfos_idx), this->ubatches)), + status(llama_memory_status_combine(ctx_attn->get_status(), ctx_idx->get_status())) { + // Sequence edits force the touched positions to re-pool. + mem_idx_stale_batch = mem->mem_idx_stale_get(); +} + +llama_memory_idx_iswa_context::~llama_memory_idx_iswa_context() = default; + +bool llama_memory_idx_iswa_context::next() { + assert(status == LLAMA_MEMORY_STATUS_SUCCESS); + + // Clear only after a successful ubatch. + if (i_next == 0 && mem != nullptr) { + mem->mem_idx_stale_clear(); + } + + ctx_attn->next(); + ctx_idx ->next(); + + if (++i_next >= ubatches.size()) { + return false; + } + + return true; +} + +bool llama_memory_idx_iswa_context::apply() { + assert(!llama_memory_status_is_fail(status)); + + bool res = true; + + res = res & ctx_attn->apply(); + res = res & ctx_idx ->apply(); + + // Extend the pool layout with this ubatch's cells, then pick what it must re-pool. + if (res && kpool_track()) { + mem->kpool_layout_update(); + if (!kpool_st) { + kpool_st = std::make_unique(); + } + kpool_build_state(get_ubatch()); + i_kpool = i_next; + } + + return res; +} + +llama_memory_status llama_memory_idx_iswa_context::get_status() const { + return status; +} + +const llama_ubatch & llama_memory_idx_iswa_context::get_ubatch() const { + assert(status == LLAMA_MEMORY_STATUS_SUCCESS); + + return ubatches[i_next]; +} + +bool llama_memory_idx_iswa_context::kpool_track() const { + // Derived from mem instead of being cached. + return mem != nullptr && mem->get_kpool() > 0 && !ns_ubatch.empty(); +} + +const llama_kv_cache_iswa_context * llama_memory_idx_iswa_context::get_attn() const { + return static_cast(ctx_attn.get()); +} + +const llama_kv_cache_context * llama_memory_idx_iswa_context::get_base() const { + return get_attn()->get_base(); +} + +const llama_kv_cache_context * llama_memory_idx_iswa_context::get_swa() const { + return get_attn()->get_swa(); +} + +const llama_kv_cache_context * llama_memory_idx_iswa_context::get_idx() const { + return static_cast(ctx_idx.get()); +} + +uint32_t llama_memory_idx_iswa_context::get_n_stream() const { + GGML_ASSERT(i_next < ns_ubatch.size()); + + return ns_ubatch[i_next]; +} + +llama_memory_idx_iswa_context::kpool_access::kpool_access(ggml_context * ctx, ggml_tensor * k, int64_t n_embd) : ctx(ctx) { + // rows are the per-token part (glm5-next: key | gate, qwen4exp: key), then the pooled key + const int64_t n_tok = k->ne[0] - n_embd; + GGML_ASSERT(n_tok > 0 && n_tok % n_embd == 0); + + const int64_t n_cells = k->ne[1]*k->ne[2]; + + // Pool indices can refer to other streams. Revisit these full-storage views if that changes: + // https://github.com/ggml-org/llama.cpp/pull/27773#discussion_r4130905603 + key_gate = ggml_view_2d(ctx, k, n_tok, n_cells, k->nb[1], 0); + pooled = ggml_view_2d(ctx, k, n_embd, n_cells, k->nb[1], ggml_row_size(k->type, n_tok)); +} + +ggml_tensor * llama_memory_idx_iswa_context::kpool_access::gather_key_gate(ggml_tensor * idxs) const { + return ggml_get_rows(ctx, key_gate, idxs); +} + +ggml_tensor * llama_memory_idx_iswa_context::kpool_access::scatter_pooled(ggml_tensor * values, ggml_tensor * idxs) const { + return ggml_set_rows(ctx, pooled, values, idxs); +} + +ggml_tensor * llama_memory_idx_iswa_context::kpool_access::gather_pooled(ggml_tensor * idxs) const { + return ggml_get_rows(ctx, pooled, idxs); +} + +llama_memory_idx_iswa_context::kpool_access llama_memory_idx_iswa_context::get_kpool_access( + ggml_context * ctx, int32_t il, int64_t n_embd) const { + GGML_ASSERT(mem != nullptr); + + return kpool_access(ctx, mem->get_mem_idx()->get_k_storage(il), n_embd); +} + +// k-pool DSA indexer (hy_v4_flash, glm5-next, qwen4exp QSA) + +// Sizes only, used by the full cache context so get_n_kpool() works during graph reserve. +llama_memory_idx_iswa_context::kpool_state llama_memory_idx_iswa_context::kpool_build_sizes() const { + const auto & lay = mem->kpool_layout_get(); + + kpool_state st; + st.n_pool_real = lay.n_pool_real; + + return st; +} + +// Which pools this ubatch must re-pool. +// Pool cache lifecycle: +// 1. cpy_k writes each token's key | gate into its idx cache row, pooled slot are zeroed. +// 2. This marks the pools the ubatch touches or completes as new, during decode that's one pool every kpool tokens, zero elsewise. +// 3. The graph pools only the new pools and set_rows each result into the pooled slot of the pool's last member row. +// 4. All pools are gathered in one get_rows via pool_cells, fresh ones just written, older ones from whatever batch last wrote them. +// A seq_* edit regroups the pools from the edited position on, so it stales them and the first ubatch of the next batch +// rebuilds them from the still-valid key | gate rows, rewriting the (possibly different) rep rows. +// Orphaned pooled slots are never cleared, a slot is only ever read through pool_cells, which follows the current grouping. +void llama_memory_idx_iswa_context::kpool_build_state(const llama_ubatch & ubatch) { + const auto & lay = mem->kpool_layout_get(); + auto & st = *kpool_st; + + const auto * idx = mem->get_mem_idx(); + const uint32_t kv_size = idx->get_size(); + const uint32_t kpool = mem->get_kpool(); + + st.n_pool_real = lay.n_pool_real; + st.n_new = 0; + if (++st.generation == 0) { + std::fill(st.is_new.begin(), st.is_new.end(), 0); + std::fill(st.rep_gen.begin(), st.rep_gen.end(), 0); + st.generation = 1; + } + st.is_new.resize(lay.n_pool_real, 0); + st.rep_gen.resize((size_t) kv_size*idx->get_n_stream(), 0); + + std::array pool_start; + + // a pool is marked once per rep: sequences sharing cells (a seq_cp, or tokens decoded for several sequences) + // share their pools, whose single pooled row they all read through pool_cells, so the scatter rows stay unique + auto mark = [&](llama_seq_id s, size_t k) { + const auto & sq = lay.seqs[s]; + const size_t rep = (size_t) sq.strm*kv_size + sq.cells[sq.pools[k] + kpool - 1].second; + if (st.rep_gen[rep] != st.generation) { + st.rep_gen[rep] = st.generation; + st.is_new[pool_start[s] + k] = st.generation; + ++st.n_new; + } + }; + + uint32_t ip = 0; + for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { + const auto & sq = lay.seqs[s]; + pool_start[s] = ip; + ip += (uint32_t) sq.pools.size(); + + // A sequence edit invalidates only pools ending after the edited position. + const llama_pos stale_from = i_next == 0 ? + mem_idx_stale_batch[s] : llama_memory_idx_iswa::POS_CLEAN; + if (stale_from == llama_memory_idx_iswa::POS_CLEAN) { + continue; + } + + auto first = std::lower_bound(sq.pools.begin(), sq.pools.end(), stale_from, + [&](uint32_t j, llama_pos p) { return sq.cells[j + kpool - 1].first < p; }); + for (auto it = first; it != sq.pools.end(); ++it) { + mark(s, it - sq.pools.begin()); + } + } + GGML_ASSERT(ip == st.is_new.size()); + + // in order mode a token's cell gives its rank, and the rank its pool: positions cannot, as an image shares one + const bool by_order = mem->get_kpool_by_order(); + const auto * sinfo = by_order ? &sinfos_kpool[i_next] : nullptr; + const uint32_t n_tps = by_order ? (uint32_t) sinfo->size() : 0; + + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + const llama_pos p = ubatch.pos[i]; + for (int32_t k = 0; k < ubatch.n_seq_id[i]; ++k) { + const llama_seq_id s = ubatch.seq_id[i][k]; + const auto & sq = lay.seqs[s]; + if (by_order) { + const int64_t r = kpool_rank(sq.cells, p, sinfo->idxs[i / n_tps][i % n_tps]); + GGML_ASSERT(r >= 0); + if ((size_t) r / kpool < sq.pools.size()) { + mark(s, (size_t) r / kpool); + } + continue; + } + auto it = std::upper_bound(sq.pools.begin(), sq.pools.end(), p, + [&](llama_pos pos, uint32_t j) { return pos < sq.cells[j].first; }); + if (it == sq.pools.begin()) { + continue; + } + --it; + if (p <= sq.cells[*it + kpool - 1].first) { + mark(s, it - sq.pools.begin()); + } + } + } + + // a ubatch touches at most t_s/kpool + 1 pools per sequence, pad to that bound so the graph keeps its shape + // as the count moves; reserve sizes the list for every pool the cache can hold, so never pad past n_pool_max + const uint32_t n_pool_max = kv_size / kpool * idx->get_n_seq_max(); + const uint32_t bound = ubatch.n_tokens/kpool + ubatch.n_seqs_unq; + st.n_new_g = std::max({st.n_new, 1u, std::min({bound, kpool_pad(st.n_pool_real) - 1, n_pool_max})}); +} + +const llama_memory_idx_iswa_context::kpool_state & llama_memory_idx_iswa_context::kpool_cur() const { + GGML_ASSERT(kpool_st != nullptr && i_kpool == i_next && "k-pool state read before apply()"); + + return *kpool_st; +} + +uint32_t llama_memory_idx_iswa_context::get_n_kpool() const { + return kpool_pad(kpool_cur().n_pool_real); +} + +uint32_t llama_memory_idx_iswa_context::get_n_kpool_new() const { + return kpool_cur().n_new_g; +} + +void llama_memory_idx_iswa_context::set_input_kpool(ggml_tensor * pool_cells, ggml_tensor * pool_idxs, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + ggml_tensor * sel_mask, ggml_tensor * new_pool_idxs, ggml_tensor * new_pool_rep, + const llama_ubatch * ubatch, ggml_tensor * new_pool_pos) const { + GGML_ASSERT(mem != nullptr); + GGML_ASSERT(ggml_backend_buffer_is_host(pool_cells->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(pool_idxs->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(pool_mask->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(tail_idxs->buffer)); + + const uint32_t kpool = mem->get_kpool(); + const uint32_t n_kv = get_idx()->get_n_kv(); + + const auto & st = kpool_cur(); + const auto & lay = mem->kpool_layout_get(); + + const uint32_t n_tokens = ubatch->n_tokens; + const uint32_t n_pool = (uint32_t) pool_cells->ne[0]; + const uint32_t n_new = st.n_new; + // the graph always pools at least one entry, padded to a stable bound, see kpool_build_state + const uint32_t n_new_g = st.n_new_g; + + const bool by_order = mem->get_kpool_by_order(); + + const uint32_t n_tail_slots = (uint32_t) tail_idxs->ne[0]; + const bool tail_full = n_tail_slots == kpool; + + GGML_ASSERT(n_pool == kpool_pad(st.n_pool_real)); + GGML_ASSERT(st.is_new.size() == st.n_pool_real); + GGML_ASSERT(pool_mask->ne[0] == (int64_t) n_pool && pool_mask->ne[1] == (int64_t) n_tokens); + GGML_ASSERT((n_tail_slots == kpool - 1 || tail_full) && tail_idxs->ne[1] == (int64_t) n_tokens); + GGML_ASSERT(pool_idxs->ne[0] == (int64_t) kpool && pool_idxs->ne[1] == (int64_t) n_pool); + GGML_ASSERT(ggml_backend_buffer_is_host(new_pool_idxs->buffer)); + GGML_ASSERT(ggml_nelements(new_pool_idxs) == (int64_t) kpool*n_new_g); + // the graph always scatters the fresh pooled keys back into the cache + GGML_ASSERT(new_pool_rep != nullptr && ggml_backend_buffer_is_host(new_pool_rep->buffer)); + GGML_ASSERT(new_pool_rep->ne[0] == (int64_t) n_new_g); + if (new_pool_pos != nullptr) { + GGML_ASSERT(ggml_backend_buffer_is_host(new_pool_pos->buffer)); + GGML_ASSERT(new_pool_pos->ne[0] == 4*(int64_t) n_new_g); + } + + const uint32_t kv_size = mem->get_mem_idx()->get_size(); + const uint32_t n_stream_kv = mem->get_mem_idx()->get_n_stream(); + + auto gcell = [&](const llama_memory_idx_iswa::kpool_layout::seq & sq, uint32_t cell) { + return (int64_t) sq.strm*kv_size + cell; + }; + + // Sequences present in this ubatch, pools of absent sequences must fall on the scatter sentinel row. + std::vector seq_in_ub(LLAMA_MAX_SEQ, 0); + for (uint32_t i = 0; i < n_tokens; ++i) { + for (int32_t k = 0; k < ubatch->n_seq_id[i]; ++k) { + seq_in_ub[ubatch->seq_id[i][k]] = 1; + } + } + + // a cell of this ubatch, written before any read, so the padded pools read a finite K row + int64_t dummy_cell = 0; + { + const llama_seq_id s = ubatch->seq_id[0][0]; + const auto & sq = lay.seqs[s]; + auto it = std::lower_bound(sq.cells.begin(), sq.cells.end(), std::make_pair(ubatch->pos[0], 0u)); + GGML_ASSERT(it != sq.cells.end() && it->first == ubatch->pos[0]); + dummy_cell = gcell(sq, it->second); + } + + // in order mode a token sees the pools and the tail up to its own rank in the sequence, which its cell pins down + std::vector rank; + if (by_order) { + const auto & sinfo = sinfos_kpool[i_next]; + const uint32_t n_tps = (uint32_t) sinfo.size(); + + rank.resize(n_tokens); + for (uint32_t i = 0; i < n_tokens; ++i) { + rank[i] = kpool_rank(lay.seqs[ubatch->seq_id[i][0]].cells, ubatch->pos[i], sinfo.idxs[i / n_tps][i % n_tps]); + GGML_ASSERT(rank[i] >= 0); + } + } + + // padding and absent cells point at the n_kv sentinel row, one past the live cells + const int32_t sentinel = (int32_t) n_kv; + + float * gm = nullptr; + uint32_t n_sel = 0; + uint32_t n_top = 0; // Pools per token in the selection. + uint32_t n_tail_sel = 0; + if (sel_mask != nullptr) { + GGML_ASSERT(ggml_backend_buffer_is_host(sel_mask->buffer)); + GGML_ASSERT(sel_mask->type == GGML_TYPE_F32); + GGML_ASSERT(sel_mask->ne[3] == (int64_t) n_tokens && sel_mask->ne[1] == 1 && sel_mask->ne[2] == 1); + n_sel = (uint32_t) sel_mask->ne[0]; + n_tail_sel = tail_full ? kpool : n_sel % kpool; + GGML_ASSERT(n_sel >= n_tail_sel && (n_sel - n_tail_sel) % kpool == 0); + GGML_ASSERT(n_tail_sel == 0 || n_tail_sel == n_tail_slots); + n_top = (n_sel - n_tail_sel) / kpool; + gm = (float *) sel_mask->data; + } + + // pools are laid out per sequence + std::vector seq_pool_start(LLAMA_MAX_SEQ, 0); + std::vector pool_end; + pool_end.reserve(n_pool); + + int32_t * pcell = (int32_t *) pool_cells->data; + int32_t * pidx = (int32_t *) pool_idxs->data; + int32_t * nidx = (int32_t *) new_pool_idxs->data; + int64_t * nrep = (int64_t *) new_pool_rep->data; + int32_t * npos = new_pool_pos != nullptr ? (int32_t *) new_pool_pos->data : nullptr; + + if (npos != nullptr) { + std::fill(npos, npos + 4*n_new_g, 0); + } + + uint32_t i_new = 0; + for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { + const auto & sq = lay.seqs[s]; + seq_pool_start[s] = (uint32_t) pool_end.size(); + + const bool inert = n_stream_kv > 1 && !seq_in_ub[s]; + + for (size_t pi = 0; pi < sq.pools.size(); ++pi) { + const uint32_t j = sq.pools[pi]; + const uint32_t ip = (uint32_t) pool_end.size(); + GGML_ASSERT(ip + 1 < n_pool); + + // The pooled key lives in the last member's row. + const uint32_t rep = sq.cells[j + kpool - 1].second; + pcell[ip] = (int32_t) gcell(sq, rep); + + for (uint32_t k = 0; k < kpool; ++k) { + pidx[(size_t) ip*kpool + k] = inert ? sentinel : (int32_t) sq.cells[j + k].second; + } + + if (st.is_new[ip] == st.generation) { + GGML_ASSERT(i_new < n_new); + for (uint32_t k = 0; k < kpool; ++k) { + nidx[(size_t) i_new*kpool + k] = (int32_t) gcell(sq, sq.cells[j + k].second); + } + nrep[i_new] = gcell(sq, rep); + if (npos != nullptr) { + // a pooled key is rotated to the M-RoPE position of its first member + const uint32_t c = sq.cells[j].second; + const auto & e = mem->get_mem_idx()->get_cells(s).ext_get(c); + npos[0*n_new_g + i_new] = sq.cells[j].first; + npos[1*n_new_g + i_new] = e.y; + npos[2*n_new_g + i_new] = e.x; + npos[3*n_new_g + i_new] = sq.cells[j].first; + } + ++i_new; + } + + pool_end.push_back(sq.cells[j + kpool - 1].first); + } + } + GGML_ASSERT(i_new == n_new); + + // Padded entries re-pool cells whose pooled slot is never read: only the reps of complete pools are read. + // Each entry takes its own cell, entries sharing one would write it from several threads in the scatter. + if (n_new_g > n_new) { + std::vector reps(pcell, pcell + pool_end.size()); + std::sort(reps.begin(), reps.end()); + + int64_t pad_cell = 0; + for (uint32_t i = n_new; i < n_new_g; ++i, ++pad_cell) { + while (std::binary_search(reps.begin(), reps.end(), pad_cell)) { + ++pad_cell; + } + GGML_ASSERT(pad_cell < (int64_t) kv_size*n_stream_kv); + for (uint32_t k = 0; k < kpool; ++k) { + nidx[(size_t) i*kpool + k] = (int32_t) pad_cell; + } + nrep[i] = pad_cell; + } + } + + const uint32_t n_pool_real = (uint32_t) pool_end.size(); + for (uint32_t ip = n_pool_real; ip < n_pool; ++ip) { + pcell[ip] = (int32_t) dummy_cell; // pool_cells always addresses the K storage + for (uint32_t k = 0; k < kpool; ++k) { + pidx[(size_t) ip*kpool + k] = sentinel; + } + } + + // a pool is visible when it belongs to the token's sequence and ends at or before it, unless reserved by a full-width tail + auto fill_mask = [&](auto * data) { + using T = std::remove_pointer_t; + const T keep = llama_cast(0.0f); + const T drop = llama_cast(-INFINITY); + + for (uint32_t i = 0; i < n_tokens; ++i) { + const llama_seq_id s = ubatch->seq_id[i][0]; + const llama_pos p = ubatch->pos[i]; + + T * row = data + (size_t) i*n_pool; + std::fill(row, row + n_pool, drop); + + const uint32_t p0 = seq_pool_start[s]; + const uint32_t p1 = p0 + (uint32_t) lay.seqs[s].pools.size(); + const uint32_t nv = by_order ? std::min(p1 - p0, (uint32_t) ((rank[i] + !tail_full)/kpool)) : + (uint32_t) ((tail_full ? std::lower_bound(pool_end.begin() + p0, pool_end.begin() + p1, p) : + std::upper_bound(pool_end.begin() + p0, pool_end.begin() + p1, p)) - (pool_end.begin() + p0)); + std::fill(row + p0, row + p0 + nv, keep); + + // Finite visible pools occupy the first min(nv, n_top) ranked slots. + if (gm != nullptr) { + const uint32_t nvc = std::min(nv, n_top); + float * grow = gm + (size_t) i*n_sel; + std::fill(grow, grow + (size_t) nvc*kpool, 0.0f); + std::fill(grow + (size_t) nvc*kpool, grow + (size_t) n_top*kpool, -INFINITY); + } + } + }; + if (pool_mask->type == GGML_TYPE_F16) { + fill_mask((ggml_fp16_t *) pool_mask->data); + } else { + fill_mask((float *) pool_mask->data); + } + + int32_t * tidx = (int32_t *) tail_idxs->data; + for (uint32_t i = 0; i < n_tokens; ++i) { + const llama_seq_id s = ubatch->seq_id[i][0]; + const llama_pos p = ubatch->pos[i]; + const auto & sq = lay.seqs[s]; + + const int64_t pos = by_order ? rank[i] : p - sq.pos_min; + const uint32_t n_tail = tail_full ? (uint32_t) (pos % kpool) + 1 : (uint32_t) ((pos + 1) % kpool); + + for (uint32_t k = 0; k < n_tail_slots; ++k) { + int32_t cell = sentinel; + bool real = false; + if (k < n_tail && by_order) { + const uint32_t c = sq.cells[rank[i] - k].second; + cell = (int32_t) c; + real = true; + } else if (k < n_tail) { + const llama_pos pt = p - (llama_pos) k; + auto it = std::lower_bound(sq.cells.begin(), sq.cells.end(), std::make_pair(pt, 0u)); + if (it != sq.cells.end() && it->first == pt) { + cell = (int32_t) it->second; + real = true; + } + } + tidx[(size_t) i*n_tail_slots + k] = cell; + + if (gm != nullptr && n_tail_sel != 0) { + gm[(size_t) i*n_sel + (size_t) n_top*kpool + k] = real ? 0.0f : -INFINITY; + } + } + } +} diff --git a/src/llama-memory-idx-iswa.h b/src/llama-memory-idx-iswa.h new file mode 100644 index 0000000000000000000000000000000000000000..1e659368fceb6351d9e6dc0ed2a0cc85ab0693e9 --- /dev/null +++ b/src/llama-memory-idx-iswa.h @@ -0,0 +1,274 @@ +#pragma once + +#include "llama-kv-cache-iswa.h" + +#include +#include +#include +#include +#include + +// +// llama_memory_idx_iswa +// + +// llama_kv_cache_iswa plus a second cache with one indexer key per token, for block-sparse attention (hy_v4_flash) +// only the non-SWA layers own an indexer, so it mirrors the base child alone: same size, padding, streams and +// slots, so cell j is one token in both + +class llama_memory_idx_iswa : public llama_memory_i { +public: + llama_memory_idx_iswa( + const llama_model & model, + bool no_alloc, + ggml_type type_k, + ggml_type type_v, + bool v_trans, + bool offload, + bool swa_full, + bool unified, + uint32_t kv_size, + uint32_t n_seq_max, + uint32_t n_ubatch, + /* layer filters */ + const layer_filter_cb & filter, + /* the SWA layers never own an indexer, so this must select non-SWA layers only */ + const layer_filter_cb & filter_idx); + + // Defined out of line because kpool_layout is incomplete here. + ~llama_memory_idx_iswa(); + + // + // llama_memory_i + // + + llama_memory_context_ptr init_batch( + llama_batch_allocr & balloc, + uint32_t n_ubatch, + bool embd_all) override; + + llama_memory_context_ptr init_full() override; + + llama_memory_context_ptr init_update(llama_context * lctx, bool optimize) override; + + bool get_can_shift() const override; + + void clear(bool data) override; + + bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; + void seq_cp (llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) override; + void seq_keep(llama_seq_id seq_id) override; + void seq_add (llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) override; + void seq_div (llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) override; + + llama_pos seq_pos_min(llama_seq_id seq_id) const override; + llama_pos seq_pos_max(llama_seq_id seq_id) const override; + + std::map memory_breakdown() const override; + + // state write/load + + void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const override; + void state_read (llama_io_read_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) override; + + // + // llama_memory_idx_iswa specific API + // + + llama_kv_cache_iswa * get_mem_attn() const; + llama_kv_cache * get_mem_idx () const; + + // The model's indexer pool size. + uint32_t get_kpool() const { return hparams_idx.indexer_kpool; } + + // Whether pools are kpool consecutive cells in sequence order (qwen4exp) instead of kpool consecutive positions. + bool get_kpool_by_order() const { return hparams_idx.indexer_kpool_by_order; } + + // Which cells of a sequence make up which pool of kpool consecutive positions (or cells, in order mode). + // It is kept here because it outlives the batch: pools are fixed by the positions relative to the + // sequence's first one, so a ubatch only ever appends to it. Sequence edits drop it, see mem_idx_stale. + struct kpool_layout; + + const kpool_layout & kpool_layout_update(); + const kpool_layout & kpool_layout_get() const; + + // A copy of what one k-pool selection points at, for readers outside the graph. + struct kpool_refs { + uint32_t kpool = 0; + uint32_t strm = 0; // stream holding the sequence's cells + llama_pos pos_min = 0; // pools start from the sequence's first position + uint32_t pool_begin = 0; // global index of the sequence's first pool + uint32_t n_pools = 0; // complete pools of the sequence + uint32_t n_hist_avail = 0; // pools of the sequence that start before p's own pool + uint32_t n_cells_upto_p = 0; // cells of the sequence at positions <= p + + std::vector found; // [n_ids], 1 when ids[i] is a pool of the sequence + std::vector pos; // [n_ids*kpool], member positions of each found pool + std::vector cell; // [n_ids*kpool], stream local member cells of each found pool + + std::vector cur_pos; // the sequence's cells from p's pool start up to p, by position + std::vector cur_cell; + }; + + // ids are pool indices numbered as set_input_kpool numbers them against the layout of the latest apply(). + // ids of an earlier ubatch stay valid only if no lower seq_id gained pools since (always so with one sequence). + // Returns false with err when there is no layout or the sequence was edited since the last batch. + bool kpool_copy_refs(llama_seq_id seq_id, llama_pos p, const int32_t * ids, size_t n_ids, + kpool_refs & out, std::string & err) const; + + // The pooled keys persist in the idx cache across batches. A sequence edit can regroup the pools + // from some position on, which stales every pooled key at or after it. POS_CLEAN means none. + using stale_pos_t = std::array; + + static constexpr llama_pos POS_CLEAN = std::numeric_limits::max(); + + static stale_pos_t stale_pos_clean() { + stale_pos_t res; + res.fill(POS_CLEAN); + return res; + } + + const stale_pos_t & mem_idx_stale_get() const { return mem_idx_stale; } + void mem_idx_stale_clear() { mem_idx_stale.fill(POS_CLEAN); } + +private: + // forget seq_id (all of it if seq_id < 0) in both caches at once, so a failed restore cannot leave them out of step + // seq_id < 0 drops the whole context, as the caches themselves do on a failed restore + void state_drop(llama_seq_id seq_id); + + // the indexer cache holds one key head per layer, so it needs its own hparams: + // llama_kv_cache keeps a reference to what it is given + llama_hparams hparams_idx; + + const std::unique_ptr mem_attn; + const std::unique_ptr mem_idx; + + // unique_ptr because kpool_layout is incomplete here + std::unique_ptr kpool_lay; + + // seq_id < 0 stales every sequence, p0 < 0 stales the sequence from its first position + void mem_idx_stale_set(llama_seq_id seq_id, llama_pos p0); + + // the position an edit at p0 stales the sequence from + llama_pos mem_idx_stale_pos(llama_seq_id seq_id, llama_pos p0) const; + + stale_pos_t mem_idx_stale = stale_pos_clean(); +}; + +class llama_memory_idx_iswa_context : public llama_memory_context_i { +public: + class kpool_access { + public: + ggml_tensor * gather_key_gate(ggml_tensor * idxs) const; + ggml_tensor * scatter_pooled(ggml_tensor * values, ggml_tensor * idxs) const; + ggml_tensor * gather_pooled(ggml_tensor * idxs) const; + + private: + friend class llama_memory_idx_iswa_context; + + kpool_access(ggml_context * ctx, ggml_tensor * k, int64_t n_embd); + + ggml_context * ctx; + ggml_tensor * key_gate; + ggml_tensor * pooled; + }; + + using slot_info_vec_t = llama_kv_cache::slot_info_vec_t; + + // used for errors + explicit llama_memory_idx_iswa_context(llama_memory_status status); + + // used to create a full-cache context + explicit llama_memory_idx_iswa_context(llama_memory_idx_iswa * mem); + + // used to create an update context + llama_memory_idx_iswa_context( + llama_memory_idx_iswa * mem, + llama_context * lctx, + bool optimize); + + // used to create a batch processing context from a batch + llama_memory_idx_iswa_context( + llama_memory_idx_iswa * mem, + slot_info_vec_t sinfos_base, + slot_info_vec_t sinfos_swa, + slot_info_vec_t sinfos_idx, + std::vector ubatches); + + ~llama_memory_idx_iswa_context(); // Defined out of line because kpool_state is incomplete here. + + // + // llama_memory_context_i + // + + bool next() override; + bool apply() override; + + llama_memory_status get_status() const override; + const llama_ubatch & get_ubatch() const override; + + // + // llama_memory_idx_iswa_context specific API + // + + const llama_kv_cache_iswa_context * get_attn() const; + + // the per-layer attention context: base for the non-SWA layers, swa for the rest + const llama_kv_cache_context * get_base() const; + const llama_kv_cache_context * get_swa () const; + + const llama_kv_cache_context * get_idx () const; + + // streams in the current slot info, the `ns` of get_k/get_v; 1 if unified + uint32_t get_n_stream() const; + + // hy_v4_flash, complete pools of kpool cells per sequence, scored as whole pools. + uint32_t get_n_kpool () const; // Padded pool count, where the last pool is always unused. + uint32_t get_n_kpool_new() const; // Pools to re-pool this ubatch, padded to a stable bound, never below 1. + kpool_access get_kpool_access(ggml_context * ctx, int32_t il, int64_t n_embd) const; + // sel_mask (F32 [n_sel, 1, 1, n_tokens], can be null): 0 for the live selection slots, -inf for the dead ones + // new_pool_pos (I32 [4*n_new]): M-RoPE position of each new pool's first member, for pooled keys rotated at pooling time + // tail_idxs width: kpool reserves the current group; kpool - 1 keeps only the incomplete tail. + void set_input_kpool(ggml_tensor * pool_cells, ggml_tensor * pool_idxs, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + ggml_tensor * sel_mask, ggml_tensor * new_pool_idxs, ggml_tensor * new_pool_rep, + const llama_ubatch * ubatch, ggml_tensor * new_pool_pos = nullptr) const; + +private: + llama_memory_idx_iswa * mem = nullptr; + + // the index of the next ubatch to process + size_t i_next = 0; + + std::vector ubatches; + + // streams per ubatch, read from the slot infos before ctx_idx takes them + // declared before sinfos_kpool and ctx_idx, so it is initialised while sinfos_idx is still intact + const std::vector ns_ubatch; + + // the indexer cells of each ubatch, kept for pools in cache order (qwen4exp): token s*n + i of ubatch u + // sits in cell idxs[s][i] of stream strm[s] of sinfos_kpool[u], and several cells can share a position + const slot_info_vec_t sinfos_kpool; + + const llama_memory_context_ptr ctx_attn; + const llama_memory_context_ptr ctx_idx; + + const llama_memory_status status; + + // Which pools of the layout this ubatch must re-pool. The layout itself belongs to the memory. + struct kpool_state; + kpool_state kpool_build_sizes() const; + void kpool_build_state(const llama_ubatch & ubatch); + const kpool_state & kpool_cur() const; + + // unique_ptr because kpool_state is incomplete here. + std::unique_ptr kpool_st; + + // The ubatch kpool_st was built for, guards against reads before apply. + size_t i_kpool = SIZE_MAX; + + // Whether this context tracks k-pool states. + bool kpool_track() const; + + // Positions each sequence must re-pool from, cleared only after the first ubatch succeeds + llama_memory_idx_iswa::stale_pos_t mem_idx_stale_batch = llama_memory_idx_iswa::stale_pos_clean(); +}; diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index 36f3850d518019e4e9612b2fb1bbe1e41145c74f..1287e80519ddcf57149cbada2edce014b2cc2a8d 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -357,10 +357,14 @@ void llama_model_saver::add_kv_from_model() { add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_TOP_K_BLOCKS, hparams.dsv41_cand_topk_blocks); add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_BLOCK_SIZE, hparams.dsv41_cand_block_size); } - if (hparams.ple_n_heads > 0) { - add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); - add_kv(LLM_KV_ENGRAM_TOKEN_MAP, model->engram_token_map); - } + } + + // any arch with an Engram module needs these, not just deepseek41. The token map is what says + // the arch has one at all: qwen4exp sets ple_n_heads for a plain per-layer embedding and has no + // hashed n-gram table, so it must not pick up a stray pad id. + if (hparams.ple_n_heads > 0 && !model->engram_token_map.empty()) { + add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); + add_kv(LLM_KV_ENGRAM_TOKEN_MAP, model->engram_token_map); } // the PLE group only means anything whole: write all of it or none diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 7529f55c2025f259d10f18f1c59c34a62cb3a40d..5c2bb054e12515b9e6c561ab31a78323380e8793 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -17,6 +17,7 @@ #include "llama-memory-hybrid.h" #include "llama-memory-hybrid-iswa.h" #include "llama-memory-hybrid-idx.h" +#include "llama-memory-idx-iswa.h" #include "llama-memory-recurrent.h" #include "llama.h" @@ -306,6 +307,10 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_hy_v3(params); case LLM_ARCH_HY_V4: return new llama_model_hy_v4(params); + case LLM_ARCH_HY_V4_FLASH: + return new llama_model_hy_v4_flash(params); + case LLM_ARCH_HY_V4_NEXT_DFLY: + return new llama_model_hy_v4_next_dfly(params); case LLM_ARCH_SMOLLM3: return new llama_model_smollm3(params); case LLM_ARCH_OPENAI_MOE: @@ -2638,7 +2643,8 @@ void llama_model::print_info() const { if (arch == LLM_ARCH_DEEPSEEK2 || arch == LLM_ARCH_DEEPSEEK2OCR || arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_MISTRAL4 || - arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4) { + arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4 || + arch == LLM_ARCH_HY_V4_FLASH) { LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead); LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q); LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv); @@ -2651,6 +2657,23 @@ void llama_model::print_info() const { LLAMA_LOG_INFO("%s: expert_gating_func = %s\n", __func__, llama_expert_gating_func_name((llama_expert_gating_func_type) hparams.expert_gating_func)); } + if (arch == LLM_ARCH_HY_V4_NEXT_DFLY) { + const auto & s = hparams.dfly_source_mrope_sections; + LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q); + LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv); + LLAMA_LOG_INFO("%s: n_embd_head_k_mla = %d\n", __func__, hparams.n_embd_head_k_mla()); + LLAMA_LOG_INFO("%s: n_embd_head_v_mla = %d\n", __func__, hparams.n_embd_head_v_mla()); + LLAMA_LOG_INFO("%s: dfly_schema_version = %u\n", __func__, hparams.dfly_schema_version); + LLAMA_LOG_INFO("%s: dfly_block_size = %u\n", __func__, hparams.dfly_block_size); + LLAMA_LOG_INFO("%s: dfly_target_kv_layers = %s\n", __func__, print_f([&](uint32_t i) { return (int32_t) hparams.dfly_target_kv_layers[i]; }, LLAMA_DFLY_N_LAYER).c_str()); + LLAMA_LOG_INFO("%s: dfly_index_layers = %s\n", __func__, print_f([&](uint32_t i) { return (int32_t) hparams.dfly_target_index_layers[i]; }, LLAMA_DFLY_N_LAYER).c_str()); + LLAMA_LOG_INFO("%s: dfly_index_top_k = %u\n", __func__, hparams.dfly_target_index_top_k); + LLAMA_LOG_INFO("%s: dfly_correction_len = %u\n", __func__, hparams.dfly_hidden_correction_length); + LLAMA_LOG_INFO("%s: dfly_confidence_head = %s\n", __func__, hparams.dfly_has_confidence_head ? "present" : "absent"); + // only a record of the training rope, the graph uses NORM rope on text positions + LLAMA_LOG_INFO("%s: dfly_source_mrope = [%u, %u, %u]\n", __func__, s[0], s[1], s[2]); + } + if (arch == LLM_ARCH_QWEN2MOE) { LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp()); LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp); @@ -2839,6 +2862,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, case LLM_ARCH_LLADA_MOE: case LLM_ARCH_RND1: case LLM_ARCH_CLEF: + case LLM_ARCH_HY_V4_NEXT_DFLY: { res = nullptr; } break; @@ -3029,6 +3053,75 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, nullptr); } } break; + case LLM_ARCH_HY_V4_FLASH: + { + GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE); + + if (hparams.indexer_top_k == 0) { + // no indexer, so the sparse layers attend their whole context: a plain iSWA pair is enough + llama_kv_cache_iswa::layer_filter_cb filter = [&](uint32_t il) { + return il < hparams.n_layer(); + }; + + // the draft context holds the MTP block alone + if (params.ctx_type == LLAMA_CONTEXT_TYPE_MTP) { + if (hparams.n_layer_nextn == 0) { + throw std::runtime_error("hy_v4_flash MTP requires the draft block, convert without --no-mtp"); + } + filter = [&](uint32_t il) { return il >= hparams.n_layer(); }; + } + + res = new llama_kv_cache_iswa( + *this, + params.no_alloc, + params.type_k, + params.type_v, + !cparams.flash_attn, + cparams.offload_kqv, + params.swa_full, + cparams.kv_unified, + cparams.n_ctx_seq, + cparams.n_seq_max, + cparams.n_ubatch, + nullptr, + filter, + nullptr, + nullptr); + } else { + // the indexer lives on the sparse layers, which are the non-SWA ones + llama_memory_idx_iswa::layer_filter_cb filter = [&](uint32_t il) { + return il < hparams.n_layer(); + }; + llama_memory_idx_iswa::layer_filter_cb filter_idx = [&](uint32_t il) { + return il < hparams.n_layer() && !hparams.is_swa(il) && hparams.is_indexer_full(il); + }; + + // the draft context holds the MTP block alone, which is a sparse layer and so + // owns an indexer of its own + if (params.ctx_type == LLAMA_CONTEXT_TYPE_MTP) { + if (hparams.n_layer_nextn == 0) { + throw std::runtime_error("hy_v4_flash MTP requires the draft block, convert without --no-mtp"); + } + filter = [&](uint32_t il) { return il >= hparams.n_layer(); }; + filter_idx = [&](uint32_t il) { return il >= hparams.n_layer(); }; + } + + res = new llama_memory_idx_iswa( + *this, + params.no_alloc, + params.type_k, + params.type_v, + !cparams.flash_attn, + cparams.offload_kqv, + params.swa_full, + cparams.kv_unified, + cparams.n_ctx_seq, + cparams.n_seq_max, + cparams.n_ubatch, + std::move(filter), + std::move(filter_idx)); + } + } break; case LLM_ARCH_DOTS3NOTE: { GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE); @@ -3493,6 +3586,10 @@ int32_t llama_model_n_swa(const llama_model * model) { return model->hparams.n_swa; } +int32_t llama_model_swa_type(const llama_model * model) { + return model->hparams.swa_type; +} + uint32_t llama_model_n_cls_out(const struct llama_model * model) { return model->hparams.n_cls_out; @@ -3616,6 +3713,8 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { return model->hparams.use_mrope() ? LLAMA_ROPE_TYPE_MROPE : LLAMA_ROPE_TYPE_NORM; // HY_V4 rotates consecutive pairs, matching the reference implementation case LLM_ARCH_HY_V4: + case LLM_ARCH_HY_V4_FLASH: + case LLM_ARCH_HY_V4_NEXT_DFLY: return LLAMA_ROPE_TYPE_NORM; // the pairs of head values are offset by n_rot/2 diff --git a/src/llama-model.h b/src/llama-model.h index da4964c98f7aee145ad132e641d082f1fc4eed49..b812dfa9d765d09caa2f6351a3042f82ceaaab8e 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -612,10 +612,20 @@ struct llama_layer { // glm5-next k-pool indexer struct ggml_tensor * indexer_kpool_gate = nullptr; struct ggml_tensor * indexer_kpool_ape = nullptr; + // hy_v4_flash: the pool runs over a projection of the normed key, and the pooled result is + // normed again before it is scored + struct ggml_tensor * indexer_kpool_value = nullptr; + struct ggml_tensor * indexer_kpool_norm = nullptr; // deepseek41 struct ggml_tensor * engram_kv = nullptr; struct ggml_tensor * engram_gate = nullptr; // q_weight*k_weight folded + // hy_v4_flash only: biases on engram_kv, the per-head norm of the looked-up rows, and the + // scale/offset of the delta the module writes back + struct ggml_tensor * engram_kv_b = nullptr; + struct ggml_tensor * engram_lookup_norm = nullptr; + struct ggml_tensor * engram_pre_gamma = nullptr; + struct ggml_tensor * engram_hc_scale = nullptr; // MSA struct ggml_tensor * index_q_proj = nullptr; @@ -829,6 +839,19 @@ struct llama_model { struct ggml_tensor * dflash_selector_next = nullptr; struct ggml_tensor * dflash_selector_hidden = nullptr; + // hy_v4_next_dfly + struct ggml_tensor * dfly_fusion_enorm = nullptr; + struct ggml_tensor * dfly_fusion_hnorm = nullptr; + struct ggml_tensor * dfly_fusion_eh = nullptr; + struct ggml_tensor * dfly_fusion_gate = nullptr; + struct ggml_tensor * dfly_correction_hnorm = nullptr; + struct ggml_tensor * dfly_correction_enorm = nullptr; + struct ggml_tensor * dfly_correction_gate = nullptr; + struct ggml_tensor * dfly_correction_up = nullptr; + struct ggml_tensor * dfly_correction_down = nullptr; + struct ggml_tensor * dfly_confidence = nullptr; + struct ggml_tensor * dfly_confidence_b = nullptr; + struct ggml_tensor * lilicorr_token_proj = nullptr; struct ggml_tensor * lilicorr_token_proj_b = nullptr; struct ggml_tensor * lilicorr_token_proj_s = nullptr; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 34c24785818819bb5be9ef04939ce8b24be9d55d..3f1b58e008880915027e3fa7ed3719e914d685d8 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -326,6 +326,12 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param // Engram gate is an elementwise weight (ggml_mul), not a matmul operand quantize &= name.find("engram_gate.weight") == std::string::npos; + // same for these: they are the second operand of a ggml_add / ggml_mul, which has no + // quantized kernel, so quantizing them aborts at run time rather than degrading quality + quantize &= name.find("engram_kv_b.weight") == std::string::npos; + quantize &= name.find("engram_hc_scale.weight") == std::string::npos; + quantize &= name.find("indexer_compressor_ape.weight") == std::string::npos; + // these are very small (e.g. 4x4) quantize &= name.find("altup") == std::string::npos; quantize &= name.find("laurel") == std::string::npos; diff --git a/src/models/hy-v4-flash.cpp b/src/models/hy-v4-flash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..285c3a55074af5e9cb0c2168ea1b636afb95af0f --- /dev/null +++ b/src/models/hy-v4-flash.cpp @@ -0,0 +1,1368 @@ +#include "models.h" + +#include "llama-kv-cache.h" +#include "llama-kv-cache-iswa.h" +#include "llama-memory-idx-iswa.h" + +#include + +// HY_V4_FLASH reuses hy_v4's iHC, gated MLA and learnable sink. What it adds: +// - a hybrid stack: "sparse" full-attention layers and sliding-window layers, with their own +// head count and rope base, over one shared MLA latent geometry +// - sandwich norms after the attention output and after the FFN +// - routed experts that run at n_expert_latent instead of n_embd + +// a token that cannot be hashed: outside the map, or an embedding (image) position +static constexpr int64_t HY_V4_FLASH_ENGRAM_DEAD = -1; + +// The reference builds every Engram norm as an RMSNorm with eps left unset, which resolves to the +// fp32 machine epsilon rather than to the model's rms_norm_eps. +static constexpr float HY_V4_FLASH_ENGRAM_EPS = 1.1920929e-07f; + +static size_t hy_v4_flash_elem_offset(const ggml_tensor * t, int64_t i) { + return ggml_row_size(t->type, i); +} + +static ggml_tensor * hy_v4_flash_view_1d(ggml_context * ctx, ggml_tensor * t, int64_t ne0, int64_t i0) { + return ggml_view_1d(ctx, t, ne0, hy_v4_flash_elem_offset(t, i0)); +} + +static ggml_tensor * hy_v4_flash_view_2d(ggml_context * ctx, ggml_tensor * t, int64_t ne0, int64_t ne1, int64_t i0) { + return ggml_view_2d(ctx, t, ne0, ne1, t->nb[1], hy_v4_flash_elem_offset(t, i0)); +} + +void llama_model_hy_v4_flash::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead, false); + ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); + ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv); + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl); + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale, false); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm, false); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func, false); + ml.get_key(LLM_KV_EXPERT_LATENT_LENGTH, hparams.n_expert_latent, false); + + // routed experts only; the shared and dense FFNs are not clamped + ml.get_key_or_arr(LLM_KV_SWIGLU_CLAMP_EXP, hparams.swiglu_clamp_exp, hparams.n_layer_all, false); + + ml.get_key(LLM_KV_HYPER_CONNECTION_COUNT, hparams.dsv4_hc_mult); + ml.get_key(LLM_KV_HYPER_CONNECTION_EPSILON, hparams.dsv4_hc_eps); + ml.get_key(LLM_KV_HYPER_CONNECTION_MAGNITUDE, hparams.hc_magnitude); + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa); + ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + + // Compressed indexer, optional: present on the sparse layers only. A file without it falls + // back to those layers attending their whole context, which is what phase 1 shipped, so the + // keys are read only when indexer.top_k says there is an indexer at all. + ml.get_key(LLM_KV_ATTENTION_INDEXER_TOP_K, hparams.indexer_top_k, false); + if (hparams.indexer_top_k > 0) { + ml.get_key(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, hparams.indexer_n_head); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, hparams.indexer_head_size); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KPOOL, hparams.indexer_kpool); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KPOOL_SELECT_TAIL, hparams.indexer_kpool_select_tail, false); + ml.get_key_or_arr(LLM_KV_ATTENTION_INDEXER_TYPES, hparams.is_indexer_full_impl, hparams.n_layer(), false); + + // indexer.types is what says which layers own one. Without it nothing does, and a file that + // carries the other indexer keys anyway must not select a cache this graph cannot drive. + bool any = false; + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + any = any || hparams.is_indexer_full(il); + } + + if (!any) { + hparams.indexer_top_k = 0; + } else { + if (hparams.indexer_kpool < 2 || hparams.indexer_top_k % hparams.indexer_kpool != 0) { + throw std::runtime_error(format( + "hy_v4_flash: indexer top_k %u must be a multiple of the pool size %u", + hparams.indexer_top_k, hparams.indexer_kpool)); + } + if (hparams.indexer_kpool_select_tail && hparams.indexer_top_k / hparams.indexer_kpool < 2) { + throw std::runtime_error("hy_v4_flash: indexer top_k must reserve at least one history group and one tail group"); + } + // the indexer cache mirrors the full-attention child, so a window layer cannot own one + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + if (!hparams.is_indexer_full(il)) { + continue; + } + if (hparams.is_swa(il)) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u is a sliding-window layer and cannot own an indexer", il)); + } + // the indexer splits each head into a nope front and a rope tail, so the tail must fit + if (hparams.n_rot(il) >= hparams.indexer_head_size) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u indexer key length %u must be larger than the rope dimension %u", + il, hparams.indexer_head_size, hparams.n_rot(il))); + } + } + } + } + + GGML_ASSERT(hparams.is_mla()); + + if (!hparams.is_swa_any()) { + throw std::runtime_error("hy_v4_flash: no sliding-window layer, expected a hybrid stack"); + } + + // One latent geometry for both layer types: only the head count differs, so the graph keeps a + // single latent cache and reads one set of MLA dimensions. dots3note is the arch that varies + // these per layer, and a file written for that shape would be read here as if it did not, so + // refuse it instead of building mis-sized wk_b / wv_b / wo views. + uint32_t n_embd_head_k_mla_swa = 0; + uint32_t n_embd_head_v_mla_swa = 0; + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA_SWA, n_embd_head_k_mla_swa, false); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA_SWA, n_embd_head_v_mla_swa, false); + + if ((n_embd_head_k_mla_swa && n_embd_head_k_mla_swa != hparams.n_embd_head_k_mla()) || + (n_embd_head_v_mla_swa && n_embd_head_v_mla_swa != hparams.n_embd_head_v_mla())) { + throw std::runtime_error(format( + "hy_v4_flash: needs one MLA geometry for both layer types, but the " + "sliding-window layers declare key/value %u/%u against %u/%u", + n_embd_head_k_mla_swa, n_embd_head_v_mla_swa, + hparams.n_embd_head_k_mla(), hparams.n_embd_head_v_mla())); + } + + // MLA is driven as MQA here: one shared latent row per token, so a file claiming more + // key/value heads would silently disagree with the cache this graph builds + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + if (hparams.n_head_kv(il) != 1) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u has n_head_kv %u, expected 1 for MLA", + il, hparams.n_head_kv(il))); + } + } + + // Engram, optional: the same n-gram hash tables deepseek41 carries, with one module per Engram + // layer. Multipliers, primes and offsets are all stored flat as [module][...] and indexed at + // module stride, so their lengths pin down the module count. + std::vector e_layers; + ml.get_arr(LLM_KV_PLE_LAYERS, e_layers, false); + if (!e_layers.empty()) { + std::vector mult; + std::vector offsets; + std::vector primes; + ml.get_key(LLM_KV_PLE_NGRAM_SIZE, hparams.ple_ngram_size); + ml.get_key(LLM_KV_PLE_HEADS_PER_NGRAM, hparams.ple_heads_per_ngram); + ml.get_key(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, hparams.ple_head_dim); + ml.get_arr(LLM_KV_PLE_LAYER_MULTIPLIERS, mult); + ml.get_arr(LLM_KV_PLE_HEAD_OFFSETS, offsets); + ml.get_arr(LLM_KV_PLE_HEAD_VOCAB_SIZES, primes); + ml.get_key(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); + ml.get_arr(LLM_KV_ENGRAM_TOKEN_MAP, engram_token_map); + + const size_t n_e = e_layers.size(); + const size_t n_gram = hparams.ple_ngram_size; + const size_t n_cols = n_gram >= 2 ? (n_gram - 1)*hparams.ple_heads_per_ngram : 0; + if (n_cols == 0 || hparams.ple_head_dim == 0 || + mult.size() != n_e*n_gram || primes.size() != n_e*n_cols || offsets.size() != n_e*n_cols || + mult.size() > LLAMA_MAX_PLE_NGRAM || primes.size() > LLAMA_MAX_PLE_HEADS || + hparams.engram_pad_id >= engram_token_map.size()) { + throw std::runtime_error("hy_v4_flash engram metadata is inconsistent"); + } + for (size_t e = 0; e < n_e; ++e) { + if (e_layers[e] >= hparams.n_layer() || (e > 0 && e_layers[e] <= e_layers[e - 1])) { + throw std::runtime_error(format("hy_v4_flash engram layer %u is out of range or out of order", e_layers[e])); + } + hparams.is_ple_impl.set(e_layers[e]); + } + for (size_t c = 0; c < n_e*n_cols; ++c) { + // a bucket count of 0 traps in the hash; row ids are int32 + if (primes[c] < 2 || offsets[c] + primes[c] > (uint64_t) INT32_MAX) { + throw std::runtime_error(format("hy_v4_flash engram head %zu: bucket range out of range", c)); + } + hparams.ple_head_offsets[c] = (uint32_t) offsets[c]; + hparams.ple_head_vocab_sizes[c] = (uint32_t) primes[c]; + } + std::copy(mult.begin(), mult.end(), hparams.ple_layer_multipliers.begin()); + hparams.ple_n_heads = (uint32_t) n_cols; + hparams.ple_n_modules = (uint32_t) n_e; + } + + type = LLM_TYPE_UNKNOWN; +} + +void llama_model_hy_v4_flash::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + const int64_t n_embd_head_k_mla = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_v_mla = hparams.n_embd_head_v_mla(); + const int64_t n_embd_head_qk_rope = hparams.n_rot(); + const int64_t n_embd_head_qk_nope = n_embd_head_k_mla - n_embd_head_qk_rope; + GGML_ASSERT(n_embd_head_qk_nope >= 1); + + const int64_t q_lora_rank = hparams.n_lora_q; + const int64_t kv_lora_rank = hparams.n_lora_kv; + const int64_t n_ff_exp = hparams.n_ff_exp(); + const int64_t n_expert_shared = hparams.n_expert_shared; + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t n_embd_latent = hparams.n_expert_latent ? hparams.n_expert_latent : n_embd; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0); + + hc_head_fn = create_tensor(tn(LLM_TENSOR_HC_HEAD_FN, "weight"), {hc * n_embd, hc}, 0); + hc_head_base = create_tensor(tn(LLM_TENSOR_HC_HEAD_BASE, "weight"), {hc}, 0); + hc_head_scale = create_tensor(tn(LLM_TENSOR_HC_HEAD_SCALE, "weight"), {1}, 0); + + const int64_t ple_n_heads = hparams.ple_n_heads; + const int64_t ple_head_dim = hparams.ple_head_dim; + if (ple_n_heads > 0) { + // every module's buckets live in one table, with the converter rebasing each module's head + // offsets into it, so the row count is the end of the last bucket + int64_t n_rows = 0; + for (size_t c = 0; c < (size_t) hparams.ple_n_modules*ple_n_heads; ++c) { + n_rows = std::max(n_rows, (int64_t) hparams.ple_head_offsets[c] + hparams.ple_head_vocab_sizes[c]); + } + // 118 GiB at the full size: read lazily, so only the rows a batch hashes to are faulted in + per_layer_tok_embd = create_tensor(tn(LLM_TENSOR_PER_LAYER_TOKEN_EMBD, "weight"), {ple_head_dim, n_rows}, TENSOR_READ_LAZY); + } + + // the MTP block sits after the trunk and is a sparse layer in its own right, minus the + // hyper-connections: it is not part of the hc stack the trunk runs + for (int i = 0; i < (int) hparams.n_layer_all; ++i) { + auto & layer = layers[i]; + const bool is_nextn = i >= n_layer; + + // the sliding-window layers carry more heads over the same latent geometry + const int64_t n_head_l = hparams.n_head(i); + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_sinks = create_tensor(tn(LLM_TENSOR_ATTN_SINKS, "weight", i), {n_head_l}, 0); + + layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0); + layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0); + layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head_l * n_embd_head_k_mla}, 0); + layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + n_embd_head_qk_rope}, 0); + layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0); + layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {n_embd_head_qk_nope, kv_lora_rank, n_head_l}, 0); + layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v_mla, n_head_l}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head_l * n_embd_head_v_mla, n_embd}, 0); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head_l * n_embd_head_v_mla}, 0); + layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0); + + if (!is_nextn) { + layer.hc_attn_fn = create_tensor(tn(LLM_TENSOR_HC_ATTN_FN, "weight", i), {hc * n_embd, 2 * hc}, 0); + layer.hc_attn_base = create_tensor(tn(LLM_TENSOR_HC_ATTN_BASE, "weight", i), {2 * hc}, 0); + layer.hc_attn_scale = create_tensor(tn(LLM_TENSOR_HC_ATTN_SCALE, "weight", i), {2}, 0); + layer.hc_ffn_fn = create_tensor(tn(LLM_TENSOR_HC_FFN_FN, "weight", i), {hc * n_embd, 2 * hc}, 0); + layer.hc_ffn_base = create_tensor(tn(LLM_TENSOR_HC_FFN_BASE, "weight", i), {2 * hc}, 0); + layer.hc_ffn_scale = create_tensor(tn(LLM_TENSOR_HC_FFN_SCALE, "weight", i), {2}, 0); + } else { + // the draft block folds the next token's embedding into the trunk's final hidden state + layer.nextn.enorm = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), {n_embd}, 0); + layer.nextn.hnorm = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), {n_embd}, 0); + layer.nextn.eh_proj = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), {2 * n_embd, n_embd}, 0); + layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), {n_embd}, 0); + } + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0); + + // is_indexer_full() only covers the trunk, and the draft block always owns an indexer + if (hparams.indexer_top_k > 0 && (is_nextn || hparams.is_indexer_full(i))) { + const int64_t n_idx = hparams.indexer_head_size; + const int64_t n_idx_head = hparams.indexer_n_head; + const int64_t kpool = hparams.indexer_kpool; + + layer.indexer_attn_k = create_tensor(tn(LLM_TENSOR_INDEXER_ATTN_K, "weight", i), {n_embd, n_idx}, 0); + layer.indexer_k_norm = create_tensor(tn(LLM_TENSOR_INDEXER_K_NORM, "weight", i), {n_idx}, 0); + // the pooled quantity is a projection of the normed key, not the key itself, and the + // gate that weights the pooling is another one: both square at the indexer width + layer.indexer_kpool_value = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_VALUE, "weight", i), {n_idx, n_idx}, 0); + layer.indexer_kpool_gate = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_GATE, "weight", i), {n_idx, n_idx}, 0); + layer.indexer_kpool_ape = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_APE, "weight", i), {n_idx, kpool}, 0); + layer.indexer_kpool_norm = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_NORM, "weight", i), {n_idx}, 0); + layer.indexer_attn_q_b = create_tensor(tn(LLM_TENSOR_INDEXER_ATTN_Q_B, "weight", i), {q_lora_rank, n_idx*n_idx_head}, 0); + layer.indexer_proj = create_tensor(tn(LLM_TENSOR_INDEXER_PROJ, "weight", i), {n_embd, n_idx_head}, 0); + } + + if (!is_nextn && engram_index(i) >= 0) { + // the hc key projections and the single value projection are fused into one matmul, as + // deepseek41 does; unlike deepseek41 they carry a bias + layer.engram_kv = create_tensor(tn(LLM_TENSOR_ENGRAM_KV, "weight", i), {ple_n_heads * ple_head_dim, n_embd * (hc + 1)}, 0); + layer.engram_kv_b = create_tensor(tn(LLM_TENSOR_ENGRAM_KV_B, "weight", i), {n_embd, hc + 1}, 0); + layer.engram_gate = create_tensor(tn(LLM_TENSOR_ENGRAM_GATE, "weight", i), {n_embd, hc}, 0); + layer.engram_lookup_norm = create_tensor(tn(LLM_TENSOR_ENGRAM_LOOKUP_NORM, "weight", i), {ple_head_dim, ple_n_heads}, 0); + layer.engram_pre_gamma = create_tensor(tn(LLM_TENSOR_ENGRAM_PRE_GAMMA, "weight", i), {n_embd}, 0); + layer.engram_hc_scale = create_tensor(tn(LLM_TENSOR_ENGRAM_HC_SCALE, "weight", i), {n_embd, hc}, 0); + } + + if (!is_nextn && i < (int) hparams.n_layer_dense_lead) { + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + } else { + if (n_expert == 0 || n_expert_used == 0) { + throw std::runtime_error("hy_v4_flash: n_expert and n_expert_used must be > 0"); + } + + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); + + if (hparams.n_expert_latent) { + layer.ffn_routed_down = create_tensor(tn(LLM_TENSOR_FFN_ROUTED_DOWN, "weight", i), {n_embd, n_embd_latent}, 0); + layer.ffn_routed_up = create_tensor(tn(LLM_TENSOR_FFN_ROUTED_UP, "weight", i), {n_embd_latent, n_embd}, 0); + } + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd_latent, n_ff_exp, n_expert}, 0); + layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd_latent, n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd_latent, n_expert}, 0); + + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_exp * n_expert_shared, n_embd}, 0); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, 0); + } + } +} + +int llama_model_hy_v4_flash::engram_index(int il) const { + if (hparams.ple_n_heads == 0 || !hparams.is_ple(il)) { + return -1; + } + int e = 0; + for (int j = 0; j < il; ++j) { + e += hparams.is_ple(j); + } + return e; +} + +void llama_model_hy_v4_flash::engram_hash(int e, const llama_ubatch & ubatch, + const std::vector & prev, + std::vector & ids, std::vector & valid) const { + const int64_t n_gram = hparams.ple_ngram_size; + const int64_t n_prev = n_gram - 1; + const int64_t n_head = hparams.ple_heads_per_ngram; + const int64_t n_cols = hparams.ple_n_heads; + + const uint64_t * mult = hparams.ple_layer_multipliers.data() + (size_t) e*n_gram; + const uint32_t * primes = hparams.ple_head_vocab_sizes.data() + (size_t) e*n_cols; + const uint32_t * offs = hparams.ple_head_offsets.data() + (size_t) e*n_cols; + const int64_t pad = engram_token_map[hparams.engram_pad_id]; + + const auto cid = [&](llama_token t) -> int64_t { + return t < 0 || t >= (llama_token) engram_token_map.size() ? HY_V4_FLASH_ENGRAM_DEAD : engram_token_map[t]; + }; + + ids.resize(ubatch.n_tokens*n_cols); + valid.resize(ubatch.n_tokens*n_cols); + + std::vector toks(n_gram); + + for (int64_t i = 0; i < ubatch.n_tokens; ++i) { + // A history shorter than the n-gram is padded, not dropped: the reference shifts the token + // window and fills the overhang with the pad id, so a real row is looked up even at the + // start of a sequence. Only an embedding (image) position has no n-gram at all, and there + // the reference marks every column invalid and masks the whole contribution. + const bool is_embd = !ubatch.token || (ubatch.is_mixed() && ubatch.type[i]); + int64_t c = is_embd ? HY_V4_FLASH_ENGRAM_DEAD : cid(ubatch.token[i]); + const bool dead = c == HY_V4_FLASH_ENGRAM_DEAD; + toks[0] = dead ? pad : c; + for (int64_t s = 1; s < n_gram; ++s) { + c = ubatch.pos[i] - s < 0 ? HY_V4_FLASH_ENGRAM_DEAD : cid(prev[i*n_prev + (n_prev - s)]); + toks[s] = c == HY_V4_FLASH_ENGRAM_DEAD ? pad : c; + } + + uint64_t rolling = toks[0]*mult[0]; + for (int64_t o = 1; o < n_gram; ++o) { + rolling ^= toks[o]*mult[o]; + for (int64_t h = 0; h < n_head; ++h) { + const int64_t col = (o - 1)*n_head + h; + ids [i*n_cols + col] = (int32_t) (rolling % primes[col] + offs[col]); + valid[i*n_cols + col] = dead ? 0.0f : 1.0f; + } + } + } +} + +// the row ids and their validity are host-side, so they are graph inputs rather than computed +class llm_graph_input_hy_v4_flash : public llm_graph_input_i { +public: + llm_graph_input_hy_v4_flash(const llama_model_hy_v4_flash & model, + const llama_kv_cache_context * mctx) : model(model), mctx(mctx) {} + + void set_input(const llama_ubatch * ubatch) override; + bool can_reuse(const llm_graph_params & params) override; + + std::vector engram_ids; + std::vector engram_valid; + + const llama_model_hy_v4_flash & model; + const llama_kv_cache_context * mctx; +}; + +void llm_graph_input_hy_v4_flash::set_input(const llama_ubatch * ubatch) { + if (engram_ids.empty()) { + return; + } + + // a token shared by several sequences has the same history in each, so its first one resolves it + std::vector prev; + mctx->get_prev_tokens(*ubatch, model.hparams.ple_ngram_size - 1, prev); + + // hash every module before the first gather, so a lazily read table gets one batched readahead + std::vector> ids(engram_ids.size()); + std::vector> valid(engram_ids.size()); + std::vector all; + for (size_t e = 0; e < engram_ids.size(); ++e) { + model.engram_hash((int) e, *ubatch, prev, ids[e], valid[e]); + all.insert(all.end(), ids[e].begin(), ids[e].end()); + } + if (model.can_prefetch.count(model.per_layer_tok_embd)) { + llama_prefetch_rows(model.per_layer_tok_embd, all.data(), all.size()); + } + for (size_t e = 0; e < engram_ids.size(); ++e) { + if (engram_ids[e]->buffer) { + ggml_backend_tensor_set(engram_ids[e], ids[e].data(), 0, ids[e].size()*sizeof(int32_t)); + } + if (engram_valid[e]->buffer) { + ggml_backend_tensor_set(engram_valid[e], valid[e].data(), 0, valid[e].size()*sizeof(float)); + } + } +} + +bool llm_graph_input_hy_v4_flash::can_reuse(const llm_graph_params & params) { + // The memory context is rebuilt for every batch, so the one captured at graph build time is + // dangling by now and set_input would read freed memory. Re-fetch it, exactly as deepseek41 + // does for its own Engram input. + const auto * iswa = model.hparams.indexer_top_k > 0 + ? static_cast(params.mctx)->get_attn() + : static_cast(params.mctx); + mctx = iswa->get_base(); + + bool res = true; + for (auto * t : engram_ids) { + res &= t->ne[0] == (int64_t) (model.hparams.ple_n_heads*params.ubatch.n_tokens); + } + return res; +} + +std::unique_ptr llama_model_hy_v4_flash::build_arch_graph(const llm_graph_params & params) const { + if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) { + return std::make_unique(*this, params); + } + return std::make_unique(*this, params); +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_engram( + const llama_model & model, + ggml_tensor * x, + ggml_tensor * rows, + ggml_tensor * valid, + int il) const { + const auto & layer = model.layers[il]; + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + const int64_t n_cols = hparams.ple_n_heads; + const int64_t head_dim = hparams.ple_head_dim; + + GGML_ASSERT(rows->ne[0] == head_dim && rows->ne[1] == n_cols && rows->ne[2] == nt); + + // delta 1: each looked-up row is RMS-normed on its own and scaled by its head's weight. + // The per-column scale by valid is belt and braces: valid is uniform across a token's columns + // (a short history is padded, not invalidated), and the whole-token mask below is what actually + // suppresses an embedding position. + ggml_tensor * r = ggml_rms_norm(ctx0, rows, HY_V4_FLASH_ENGRAM_EPS); + r = ggml_mul(ctx0, r, layer.engram_lookup_norm); + r = ggml_mul(ctx0, r, ggml_reshape_3d(ctx0, valid, 1, n_cols, nt)); + r = ggml_reshape_2d(ctx0, r, head_dim*n_cols, nt); + cb(r, "engram_rows_normed", il); + + // delta 2: the fused key/value projection carries a bias + ggml_tensor * kv = build_lora_mm(layer.engram_kv, r); + kv = ggml_add(ctx0, ggml_reshape_3d(ctx0, kv, n_embd, hc + 1, nt), layer.engram_kv_b); + cb(kv, "engram_kv", il); + + ggml_tensor * key = ggml_cont(ctx0, ggml_view_3d(ctx0, kv, n_embd, hc, nt, kv->nb[1], kv->nb[2], 0)); + ggml_tensor * value = ggml_cont(ctx0, ggml_view_3d(ctx0, kv, n_embd, 1, nt, kv->nb[1], kv->nb[2], hc*kv->nb[1])); + + // the gate is deepseek41's: engram_gate folds norm_key.w * norm_query.w + ggml_tensor * egate = ggml_is_quantized(layer.engram_gate->type) ? ggml_cast(ctx0, layer.engram_gate, GGML_TYPE_F32) : layer.engram_gate; + ggml_tensor * dot = ggml_mul(ctx0, ggml_mul(ctx0, ggml_rms_norm(ctx0, x, HY_V4_FLASH_ENGRAM_EPS), ggml_rms_norm(ctx0, key, HY_V4_FLASH_ENGRAM_EPS)), egate); + dot = ggml_scale(ctx0, ggml_sum_rows(ctx0, dot), 1.0f/sqrtf((float) n_embd)); + cb(dot, "engram_dot", il); + + // sigmoid(copysign(sqrt(max(|dot|, 1e-6)), dot)); sign(0) = +1 as in copysign + ggml_tensor * mag = ggml_sqrt(ctx0, ggml_clamp(ctx0, ggml_abs(ctx0, dot), 1e-6f, INFINITY)); + ggml_tensor * sign = ggml_scale_bias(ctx0, ggml_step(ctx0, ggml_neg(ctx0, dot)), -2.0f, 1.0f); + ggml_tensor * gate = ggml_sigmoid(ctx0, ggml_mul(ctx0, mag, sign)); + cb(gate, "engram_gate", il); + + // delta 3: the delta is the normed value scaled by a learned gamma, not the raw value + ggml_tensor * signal = ggml_mul(ctx0, ggml_rms_norm(ctx0, value, HY_V4_FLASH_ENGRAM_EPS), layer.engram_pre_gamma); + // delta 4: the per-hc offset is additive and per channel, so it broadcasts over tokens only + ggml_tensor * scale = ggml_add(ctx0, ggml_repeat_4d(ctx0, gate, n_embd, hc, nt, 1), layer.engram_hc_scale); + cb(scale, "engram_scale", il); + + ggml_tensor * delta = ggml_mul(ctx0, ggml_repeat_4d(ctx0, signal, n_embd, hc, nt, 1), scale); + + // A token with no valid n-gram contributes nothing. Zeroing its columns is not enough: the + // projection bias would still put a constant through the value path. This is the first token + // of every sequence, and any embedding (image) position. + ggml_tensor * any = ggml_sum_rows(ctx0, ggml_reshape_2d(ctx0, valid, n_cols, nt)); + any = ggml_step(ctx0, any); + delta = ggml_mul(ctx0, delta, ggml_reshape_3d(ctx0, any, 1, 1, nt)); + cb(delta, "engram_delta", il); + + return ggml_add(ctx0, x, delta); +} + +// reduce hc streams x[:,i,:] weighted by w[i,:] -> [n_embd, n_tokens] +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_reduce( + ggml_tensor * x, + ggml_tensor * weights, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + GGML_ASSERT(x->ne[0] == n_embd); + GGML_ASSERT(x->ne[1] == hc); + + // the fused node is registered per layer, so the head reduce (il < 0) keeps the loop + if (cparams.fused_dsv4_hc_pre && il >= 0) { + ggml_tensor * result = ggml_dsv4_hc_pre(ctx0, x, weights); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_PRE, result, il}); + return result; + } + + ggml_tensor * result = nullptr; + for (int64_t ih = 0; ih < hc; ++ih) { + ggml_tensor * xh = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], ih * x->nb[1]); + ggml_tensor * wh = ggml_view_2d(ctx0, weights, 1, nt, weights->nb[1], ih * weights->nb[0]); + ggml_tensor * cur = ggml_mul(ctx0, xh, wh); + result = result ? ggml_add(ctx0, result, cur) : cur; + } + return result; +} + +llama_model_hy_v4_flash::graph::hc_pre +llama_model_hy_v4_flash::graph::build_hc_pre( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + GGML_ASSERT(x->ne[0] == n_embd && x->ne[1] == hc); + + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc * n_embd, nt); + ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, hparams.f_norm_rms_eps); + ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm); + cb(mixes, "hc_mixes", il); + + ggml_tensor * scale_pre = hy_v4_flash_view_1d(ctx0, hc_scale, 1, 0); + ggml_tensor * scale_post = hy_v4_flash_view_1d(ctx0, hc_scale, 1, 1); + ggml_tensor * base_pre = hy_v4_flash_view_1d(ctx0, hc_base, hc, 0); + ggml_tensor * base_post = hy_v4_flash_view_1d(ctx0, hc_base, hc, hc); + + ggml_tensor * pre = hy_v4_flash_view_2d(ctx0, mixes, hc, nt, 0); + pre = ggml_mul(ctx0, pre, scale_pre); + pre = ggml_add(ctx0, pre, base_pre); + pre = ggml_sigmoid(ctx0, pre); + pre = ggml_scale_bias(ctx0, pre, 1.0f, hparams.dsv4_hc_eps); + cb(pre, "hc_pre", il); + + ggml_tensor * post = hy_v4_flash_view_2d(ctx0, mixes, hc, nt, hc); + post = ggml_mul(ctx0, post, scale_post); + post = ggml_add(ctx0, post, base_post); + post = ggml_sigmoid(ctx0, post); + post = ggml_scale(ctx0, post, hparams.hc_magnitude); + post = ggml_scale_bias(ctx0, post, 1.0f, hparams.dsv4_hc_eps); + cb(post, "hc_post_gate", il); + + return { build_hc_reduce(x, pre, il), post }; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_post( + ggml_tensor * x, + ggml_tensor * residual, + ggml_tensor * post, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[1]; + GGML_ASSERT(x->ne[0] == n_embd); + GGML_ASSERT(residual->ne[1] == hc); + + // comb is the identity here: each stream keeps its own residual, hy_v4 has no cross-stream mix + if (cparams.fused_dsv4_hc_post) { + ggml_tensor * result = ggml_dsv4_hc_post(ctx0, x, residual, post, nullptr); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_POST, result, il}); + return result; + } + + ggml_tensor * out = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * res_i = ggml_view_2d(ctx0, residual, n_embd, nt, residual->nb[2], i * residual->nb[1]); + ggml_tensor * post_i = ggml_view_2d(ctx0, post, 1, nt, post->nb[1], i * post->nb[0]); + ggml_tensor * cur = ggml_add(ctx0, res_i, ggml_mul(ctx0, x, post_i)); + cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, nt); + out = out ? ggml_concat(ctx0, out, cur, 1) : cur; + } + + return out; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_head( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc * n_embd, nt); + ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, hparams.f_norm_rms_eps); + ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm); + cb(mixes, "hc_head_mixes", -1); + + ggml_tensor * pre = ggml_mul(ctx0, mixes, hc_scale); + pre = ggml_add(ctx0, pre, hc_base); + pre = ggml_sigmoid(ctx0, pre); + pre = ggml_scale_bias(ctx0, pre, 1.0f, hparams.dsv4_hc_eps); + cb(pre, "hc_head_pre", -1); + + return build_hc_reduce(x, pre, -1); +} + +// The memory composes an iSWA pair rather than being one, so the standard input cannot recover its +// context from params.mctx on its own. +class llama_model_hy_v4_flash::llm_graph_input_attn_idx : public llm_graph_input_attn_k_iswa { +public: + using llm_graph_input_attn_k_iswa::llm_graph_input_attn_k_iswa; + + const llama_kv_cache_iswa_context * mctx_of(const llm_graph_params & params) const override { + return static_cast(params.mctx)->get_attn(); + } +}; + +class llama_model_hy_v4_flash::llm_graph_input_kpool : public llm_graph_input_i { +public: + llm_graph_input_kpool(const llama_memory_idx_iswa_context * mctx, uint32_t kpool) : mctx(mctx), kpool(kpool) {} + virtual ~llm_graph_input_kpool() = default; + + void set_input(const llama_ubatch * ubatch) override { + mctx->get_idx()->set_input_k_idxs(k_idxs, ubatch); + mctx->set_input_kpool(pool_cells, pool_idxs, pool_mask, tail_idxs, sel_mask, + new_pool_idxs, new_pool_rep, ubatch, new_pool_pos); + } + + bool can_reuse(const llm_graph_params & params) override { + mctx = static_cast(params.mctx); + + bool res = true; + + res &= k_idxs->ne[0] == params.ubatch.n_tokens; + res &= pool_cells->ne[0] == mctx->get_n_kpool(); + res &= pool_mask->ne[1] == params.ubatch.n_tokens; + res &= tail_idxs->ne[1] == params.ubatch.n_tokens; + res &= n_kv == mctx->get_idx()->get_n_kv(); + res &= n_new == std::max(mctx->get_n_kpool_new(), 1u); + + return res; + } + + ggml_tensor * k_idxs = nullptr; // I64 [n_tokens] + ggml_tensor * pool_cells = nullptr; // I32 [n_pool] cell caching each pool's pooled key + ggml_tensor * pool_idxs = nullptr; // I32 [kpool, n_pool] member cells per pool + ggml_tensor * pool_mask = nullptr; // F32/F16 [n_pool, n_tokens] + ggml_tensor * tail_idxs = nullptr; // I32 [kpool, n_tokens] when the current group is forced + ggml_tensor * sel_mask = nullptr; // F32 [n_sel, 1, 1, n_tokens] + ggml_tensor * new_pool_idxs = nullptr; // I32 [kpool*n_new] + ggml_tensor * new_pool_rep = nullptr; // I64 [n_new] + ggml_tensor * new_pool_pos = nullptr; // I32 [4*n_new] first member's position per new pool + + const llama_memory_idx_iswa_context * mctx; + const uint32_t kpool; + uint32_t n_new = 0; + uint32_t n_sel = 0; + uint32_t n_kv = 0; +}; + +llama_model_hy_v4_flash::llm_graph_input_kpool * llama_model_hy_v4_flash::graph::build_inp_kpool( + const llama_memory_idx_iswa_context * mctx_idx) { + const auto * mctx_lid = mctx_idx->get_idx(); + + const uint32_t kpool = hparams.indexer_kpool; + const uint32_t n_pool = mctx_idx->get_n_kpool(); + // a ubatch that completes no pool still builds one dummy entry, so the graph does not change + // shape every kpool tokens + const uint32_t n_new = std::max(mctx_idx->get_n_kpool_new(), 1u); + + const auto type_mask = cparams.fused_lid ? GGML_TYPE_F16 : GGML_TYPE_F32; + + auto inp = std::make_unique(mctx_idx, kpool); + + inp->k_idxs = mctx_lid->build_input_k_idxs(ctx0, ubatch); + inp->pool_cells = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool); + inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); + inp->pool_mask = ggml_new_tensor_2d(ctx0, type_mask, n_pool, n_tokens); + inp->tail_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, hparams.indexer_kpool_select_tail ? kpool : kpool - 1, n_tokens); + ggml_set_input(inp->pool_cells); + ggml_set_input(inp->pool_idxs); + ggml_set_input(inp->pool_mask); + ggml_set_input(inp->tail_idxs); + + ggml_build_forward_expand(gf, inp->pool_cells); + ggml_build_forward_expand(gf, inp->pool_idxs); + ggml_build_forward_expand(gf, inp->pool_mask); + ggml_build_forward_expand(gf, inp->tail_idxs); + + inp->n_kv = mctx_lid->get_n_kv(); + + { + // The reference keeps group_topk - 1 scored groups and forces the one the current token + // sits in, which the tail covers even when that group is complete. + const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool - hparams.indexer_kpool_select_tail); + const int64_t n_sel = kpool*n_top_pool + (hparams.indexer_kpool_select_tail ? kpool : 0); + inp->n_sel = (uint32_t) n_sel; + + if (!cparams.fused_top_k_mask) { + inp->sel_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_sel, 1, 1, n_tokens); + ggml_set_input(inp->sel_mask); + ggml_build_forward_expand(gf, inp->sel_mask); + } + } + + inp->n_new = n_new; + + inp->new_pool_idxs = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kpool*n_new); + ggml_set_input(inp->new_pool_idxs); + inp->new_pool_rep = ggml_new_tensor_1d(ctx0, GGML_TYPE_I64, n_new); + ggml_set_input(inp->new_pool_rep); + // 4 planes so the vision case can rotate pooled keys with mrope; text uses plane 0 + inp->new_pool_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 4*n_new); + ggml_set_input(inp->new_pool_pos); + ggml_build_forward_expand(gf, inp->new_pool_pos); + + return (llm_graph_input_kpool *) res->add_input(std::move(inp)); +} + +// rotate only the trailing n_rot of each indexer head, leaving the head's front half untouched +ggml_tensor * llama_model_hy_v4_flash::graph::build_indexer_rope( + ggml_tensor * x, ggml_tensor * pos, int64_t n_idx, float freq_base, int il) const { + const int64_t n_nope = n_idx - n_rot; + GGML_ASSERT(n_nope > 0); + + ggml_tensor * front = ggml_view_3d(ctx0, x, n_nope, x->ne[1], x->ne[2], + x->nb[1], x->nb[2], 0); + ggml_tensor * back = ggml_view_3d(ctx0, x, n_rot, x->ne[1], x->ne[2], + x->nb[1], x->nb[2], ggml_row_size(x->type, n_nope)); + + // the same base the layer's own attention uses, so a cparams override reaches the indexer too + back = ggml_rope_ext(ctx0, ggml_cont(ctx0, back), pos, nullptr, n_rot, rope_type, n_ctx_orig, + freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow); + cb(back, "indexer_rope", il); + + return ggml_concat(ctx0, ggml_cont(ctx0, front), back, 0); +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_kpool_select( + ggml_tensor * cur, ggml_tensor * qr, ggml_tensor * inp_pos, float freq_base, + const llama_layer & layer, + const llama_memory_idx_iswa_context * mctx_idx, llm_graph_input_kpool * inp_kpool, int il) { + const auto * mctx_lid = mctx_idx->get_idx(); + + const int64_t n_idx_head = hparams.indexer_n_head; + const int64_t n_idx = hparams.indexer_head_size; + const int64_t kpool = hparams.indexer_kpool; + const int64_t n_pool = inp_kpool->pool_cells->ne[0]; + const int64_t n_new = inp_kpool->n_new; + const int64_t n_kv = mctx_lid->get_n_kv(); + + // the query comes off the same lora residual the main attention uses, and is rotated at the + // token's own position + ggml_tensor * iq = ggml_mul_mat(ctx0, layer.indexer_attn_q_b, qr); + iq = ggml_reshape_3d(ctx0, iq, n_idx, n_idx_head, n_tokens); + iq = build_indexer_rope(iq, inp_pos, n_idx, freq_base, il); + cb(iq, "indexer_q", il); + + // key side: weight-only RMSNorm, unlike glm5-next's LayerNorm with a bias this model lacks + ggml_tensor * ik = ggml_mul_mat(ctx0, layer.indexer_attn_k, cur); + ik = build_norm(ik, layer.indexer_k_norm, nullptr, LLM_NORM_RMS, il); + cb(ik, "indexer_k", il); + + // what the pool averages is a projection of the normed key, and the weights come from another + // projection of it: glm5-next pools the key itself and gates off the hidden state + ggml_tensor * iv = ggml_mul_mat(ctx0, layer.indexer_kpool_value, ik); + ggml_tensor * ig = ggml_mul_mat(ctx0, layer.indexer_kpool_gate, ik); + cb(ig, "indexer_gate", il); + + // cache rows hold value | gate | pooled + ggml_tensor * pzero = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_idx, n_tokens), 0.0f); + ggml_tensor * packed = ggml_concat(ctx0, ggml_concat(ctx0, iv, ig, 0), pzero, 0); + packed = ggml_reshape_3d(ctx0, packed, 3*n_idx, 1, n_tokens); + ggml_build_forward_expand(gf, mctx_lid->cpy_k(ctx0, packed, inp_kpool->k_idxs, il)); + + auto kpool_cache = mctx_idx->get_kpool_access(ctx0, il, n_idx); + + const ggml_type type_mask = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; + + // pool the groups this ubatch completed; the last entry is a dummy when it completed none + ggml_tensor * rows = kpool_cache.gather_key_gate(inp_kpool->new_pool_idxs); + rows = ggml_reshape_3d(ctx0, rows, 2*n_idx, kpool, n_new); + + ggml_tensor * pk = ggml_view_3d(ctx0, rows, n_idx, kpool, n_new, rows->nb[1], rows->nb[2], 0); + ggml_tensor * pg = ggml_view_3d(ctx0, rows, n_idx, kpool, n_new, rows->nb[1], rows->nb[2], + ggml_row_size(rows->type, n_idx)); + + ggml_tensor * logits = ggml_add(ctx0, pg, layer.indexer_kpool_ape); + logits = ggml_cont(ctx0, ggml_permute(ctx0, logits, 1, 0, 2, 3)); // [kpool, n_idx, n_new] + // fold the pool axis into rows: soft_max maps ne[2] to a CUDA gridDim.y that caps at 65535 + ggml_tensor * probs = ggml_soft_max(ctx0, ggml_reshape_2d(ctx0, logits, kpool, n_idx*n_new)); + probs = ggml_reshape_3d(ctx0, probs, kpool, n_idx, n_new); + + pk = ggml_cont(ctx0, ggml_permute(ctx0, pk, 1, 0, 2, 3)); + ggml_tensor * pooled_new = ggml_sum_rows(ctx0, ggml_mul(ctx0, probs, pk)); // [1, n_idx, n_new] + pooled_new = ggml_reshape_2d(ctx0, pooled_new, n_idx, n_new); + + // the pooled key is normed and then rotated at its group's first position, so the score keeps + // the same relative geometry as the main attention + pooled_new = build_norm(pooled_new, layer.indexer_kpool_norm, nullptr, LLM_NORM_RMS, il); + { + ggml_tensor * pos = ggml_view_1d(ctx0, inp_kpool->new_pool_pos, n_new, 0); + ggml_tensor * p3 = ggml_reshape_3d(ctx0, pooled_new, n_idx, 1, n_new); + pooled_new = ggml_reshape_2d(ctx0, build_indexer_rope(p3, pos, n_idx, freq_base, il), n_idx, n_new); + } + cb(pooled_new, "indexer_pool_k_new", il); + + // write the fresh pooled keys into their rep rows, then read every pool back by cell: the + // older ones come from the rows earlier ubatches wrote + ggml_build_forward_expand(gf, kpool_cache.scatter_pooled(pooled_new, inp_kpool->new_pool_rep)); + ggml_tensor * pooled = kpool_cache.gather_pooled(inp_kpool->pool_cells); + pooled = ggml_reshape_3d(ctx0, pooled, n_idx, 1, n_pool); + cb(pooled, "indexer_pool_k", il); + + ggml_tensor * weights = ggml_mul_mat(ctx0, layer.indexer_proj, cur); + weights = ggml_scale(ctx0, weights, 1.0f / sqrtf(float(n_idx * n_idx_head))); + cb(weights, "indexer_weights", il); + + ggml_tensor * score = nullptr; + if (cparams.fused_lid) { + score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_kpool->pool_mask); + res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); + } else { + ggml_tensor * q_p = ggml_permute(ctx0, iq, 0, 2, 1, 3); // [n_idx, n_tokens, n_head] + ggml_tensor * k_p = ggml_permute(ctx0, pooled, 0, 2, 1, 3); // [n_idx, n_pool, 1] + + ggml_tensor * kq = ggml_mul_mat(ctx0, k_p, q_p); // [n_pool, n_tokens, n_head] + kq = ggml_cont(ctx0, ggml_permute(ctx0, kq, 2, 1, 0, 3)); // [n_head, n_tokens, n_pool] + score = ggml_relu(ctx0, kq); + score = ggml_mul(ctx0, score, weights); + score = ggml_sum_rows(ctx0, score); // [1, n_tokens, n_pool] + score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); // [n_pool, n_tokens, 1] + score = ggml_add(ctx0, score, inp_kpool->pool_mask); + } + cb(score, "indexer_score", il); + + const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool - hparams.indexer_kpool_select_tail); + ggml_tensor * top_k = ggml_top_k(ctx0, score, n_top_pool); // [n_top_pool, n_tokens], unordered + + // DFly capture: the same top_k and its scores, for the output rows + for (uint32_t k = 0; dfly_out_ids && k < cparams.dfly_capture_n_layer; ++k) { + if (cparams.dfly_capture_layers[k] != il) { + continue; + } + ggml_tensor * ids = ggml_get_rows(ctx0, top_k, dfly_out_ids); + ggml_tensor * scores = ggml_get_rows(ctx0, ggml_reshape_2d(ctx0, + ggml_get_rows(ctx0, ggml_reshape_3d(ctx0, score, 1, n_pool, n_tokens), top_k), + n_top_pool, n_tokens), dfly_out_ids); + cb(ids, "dfly_sel_ids", il); + cb(scores, "dfly_sel_scores", il); + ggml_build_forward_expand(gf, ids); + ggml_build_forward_expand(gf, scores); + res->t_dfly_ids[k] = ids; + res->t_dfly_scores[k] = scores; + } + + // keep the cells of the picked pools and of the current group, -inf elsewhere; every + // retained cell is in the token's own sequence, so the kq_mask is not needed on top + ggml_tensor * tail = hparams.indexer_kpool_select_tail ? inp_kpool->tail_idxs : nullptr; + GGML_ASSERT(kpool*n_top_pool + (tail ? tail->ne[0] : 0) == (int64_t) inp_kpool->n_sel); + + if (cparams.fused_top_k_mask) { + ggml_tensor * keep = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, type_mask, n_kv), 0.0f); + ggml_tensor * sel = ggml_top_k_mask(ctx0, keep, top_k, score, inp_kpool->pool_idxs, tail); + res->add_fused_node({LLM_FUSED_OP_TOP_K_MASK, sel, il}); + cb(sel, "indexer_sel", il); + + return sel; + } + + // Backends without a fused top-k mask scatter the same selection by hand. Everything this arch + // changes about the indexer is upstream of score, so from here on it is glm5-next's path. + ggml_tensor * sel_idx = nullptr; + { + // sel_mask marks the first min(nv, n_top_pool) slots as the live pools, so put the picked + // set in descending score order to match it (ggml_top_k leaves it unordered) + ggml_tensor * sel_score = ggml_get_rows(ctx0, + ggml_reshape_3d(ctx0, score, 1, n_pool, n_tokens), top_k); // [1, n_top_pool, n_tokens] + ggml_tensor * sel_order = ggml_argsort(ctx0, + ggml_reshape_2d(ctx0, sel_score, n_top_pool, n_tokens), GGML_SORT_ORDER_DESC); + + ggml_tensor * ordered = ggml_get_rows(ctx0, + ggml_reshape_3d(ctx0, ggml_cast(ctx0, top_k, GGML_TYPE_F32), 1, n_top_pool, n_tokens), sel_order); + ordered = ggml_cast(ctx0, + ggml_cont(ctx0, ggml_reshape_2d(ctx0, ordered, n_top_pool, n_tokens)), GGML_TYPE_I32); + cb(ordered, "indexer_top_k", il); + + sel_idx = ggml_get_rows(ctx0, inp_kpool->pool_idxs, + ggml_reshape_1d(ctx0, ordered, n_top_pool*n_tokens)); // [kpool, n_top_pool*n_tokens] + sel_idx = ggml_reshape_2d(ctx0, sel_idx, kpool*n_top_pool, n_tokens); + + if (tail) { + // the tail, with n_kv standing in for the cells it does not have yet + sel_idx = ggml_concat(ctx0, sel_idx, tail, 0); + } + } + + const int64_t n_sel = sel_idx->ne[0]; + GGML_ASSERT(n_sel == (int64_t) inp_kpool->n_sel); + GGML_ASSERT(inp_kpool->sel_mask && inp_kpool->sel_mask->ne[0] == n_sel && + inp_kpool->sel_mask->ne[3] == n_tokens); + + ggml_build_forward_expand(gf, sel_idx); + + ggml_tensor * mask_all = ggml_new_tensor_4d(ctx0, type_mask, n_kv + n_sel, 1, 1, 1); + mask_all = ggml_fill(ctx0, mask_all, -INFINITY); + mask_all = ggml_repeat_4d(ctx0, mask_all, n_kv + n_sel, n_tokens, 1, 1); + mask_all = ggml_reshape_3d(ctx0, mask_all, 1, n_kv + n_sel, n_tokens); + + ggml_tensor * zeros = ggml_new_tensor_4d(ctx0, type_mask, n_sel, 1, 1, 1); + zeros = ggml_fill(ctx0, zeros, 0.0f); + zeros = ggml_repeat_4d(ctx0, zeros, n_sel, n_tokens, 1, 1); + zeros = ggml_reshape_3d(ctx0, zeros, 1, n_sel, n_tokens); + + // Live slots (visible pools, real tail cells) address disjoint cells, and each dead slot writes + // its own dump row n_kv + slot, so a token's scatter indices stay unique: + // idx = dump + live*(idx - dump), live = exp(mask). + ggml_tensor * live = ggml_reshape_2d(ctx0, ggml_exp(ctx0, inp_kpool->sel_mask), n_sel, n_tokens); + ggml_tensor * dump = ggml_arange(ctx0, (float) n_kv, (float) (n_kv + n_sel), 1.0f); + ggml_tensor * idx_f = ggml_cast(ctx0, sel_idx, GGML_TYPE_F32); + idx_f = ggml_add(ctx0, ggml_mul(ctx0, ggml_sub(ctx0, idx_f, dump), live), dump); + sel_idx = ggml_cast(ctx0, idx_f, GGML_TYPE_I32); + + ggml_tensor * sel = ggml_set_rows(ctx0, mask_all, zeros, + ggml_reshape_3d(ctx0, sel_idx, n_sel, n_tokens, 1)); + + sel = ggml_view_2d(ctx0, sel, n_kv, n_tokens, sel->nb[2], 0); + sel = ggml_cont(ctx0, sel); + cb(sel, "indexer_sel", il); + + return sel; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_attention( + const llama_model & model, + llm_graph_input_attn_k_iswa * inp_attn, + ggml_tensor * cur, + ggml_tensor * inp_pos, + const llama_memory_idx_iswa_context * mctx_idx, + llm_graph_input_kpool * inp_kpool, + int il) { + const auto & layer = model.layers[il]; + + const int64_t n_head_l = hparams.n_head(il); + const int64_t n_embd_head_k = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_qk_rope = hparams.n_rot(); + const int64_t n_embd_head_qk_nope = n_embd_head_k - n_embd_head_qk_rope; + const uint32_t kv_lora_rank = hparams.n_lora_kv; + + const float kq_scale = 1.0f / sqrtf(float(n_embd_head_k)); + const float freq_base_l = model.get_rope_freq_base(cparams, il); + + ggml_tensor * qr = ggml_mul_mat(ctx0, layer.wq_a, cur); + qr = build_norm(qr, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il); + cb(qr, "q_resid", il); + + ggml_tensor * q = ggml_mul_mat(ctx0, layer.wq_b, qr); + + ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head_l, n_tokens, + ggml_row_size(q->type, n_embd_head_k), ggml_row_size(q->type, n_embd_head_k) * n_head_l, 0); + ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head_l, n_tokens, + ggml_row_size(q->type, n_embd_head_k), ggml_row_size(q->type, n_embd_head_k) * n_head_l, + ggml_row_size(q->type, n_embd_head_qk_nope)); + + ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, layer.wkv_a_mqa, cur); + ggml_tensor * kv_cmpr = ggml_view_2d(ctx0, kv_cmpr_pe, kv_lora_rank, n_tokens, + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), 0); + ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_cmpr_pe, n_embd_head_qk_rope, 1, n_tokens, + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank)); + + q_pe = ggml_rope_ext(ctx0, q_pe, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig, freq_base_l, freq_scale, + ext_factor, attn_factor, beta_fast, beta_slow); + cb(q_pe, "q_pe", il); + k_pe = ggml_rope_ext(ctx0, k_pe, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig, freq_base_l, freq_scale, + ext_factor, attn_factor, beta_fast, beta_slow); + cb(k_pe, "k_pe", il); + + kv_cmpr = build_norm(kv_cmpr, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il); + cb(kv_cmpr, "kv_cmpr", il); + + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope); + q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3); + + // rope goes last so build_rope_shift() can shift the cache in place + ggml_tensor * Qcur = ggml_concat(ctx0, q_nope_absorbed, q_pe, 0); + + kv_cmpr = ggml_reshape_3d(ctx0, kv_cmpr, kv_lora_rank, 1, n_tokens); + ggml_tensor * Kcur = ggml_concat(ctx0, kv_cmpr, k_pe, 0); + ggml_tensor * Vcur = kv_cmpr; + + ggml_tensor * sel = nullptr; + // the draft block is a sparse layer and always owns an indexer, and is_indexer_full() only + // covers the trunk + if (inp_kpool != nullptr && + (il >= (int) hparams.n_layer() || hparams.is_indexer_full(il))) { + sel = build_kpool_select(cur, qr, inp_pos, freq_base_l, layer, mctx_idx, inp_kpool, il); + } + + // wo is applied below so the gate can sit in front of it + ggml_tensor * attn; + + // with a rotated K cache wv_b has to come after the de-rotation, so it is applied here and not in build_attn_mha + auto apply_wv_b = [&](ggml_tensor * a) { + a = ggml_reshape_3d(ctx0, a, kv_lora_rank, n_head_l, n_tokens); + a = ggml_permute(ctx0, a, 0, 2, 1, 3); + a = ggml_mul_mat(ctx0, layer.wv_b, a); + a = ggml_permute(ctx0, a, 0, 2, 1, 3); + a = ggml_cont(ctx0, a); + return ggml_reshape_2d(ctx0, a, a->ne[0]*a->ne[1], n_tokens); + }; + + if (sel != nullptr) { + const auto * mctx_base = mctx_idx->get_base(); + const int64_t n_sel = inp_kpool->n_sel; + + // this layer writes the cache itself, so it rotates q and k like build_attn does + ggml_tensor * k_rot = inp_attn->self_k_rot[il]; + if (k_rot) { + Qcur = llama_mul_mat_hadamard(ctx0, Qcur, k_rot); + Kcur = llama_mul_mat_hadamard(ctx0, Kcur, k_rot); + } + + // The indexer's selection replaces the kq_mask, so this layer cannot go through build_attn: + // write the latent row ourselves, then read the whole cache back and let the mask decide. + ggml_tensor * k = mctx_base->get_k(ctx0, il); + ggml_tensor * v = ggml_view_4d(ctx0, k, kv_lora_rank, k->ne[1], k->ne[2], k->ne[3], + k->nb[1], k->nb[2], k->nb[3], 0); + + ggml_build_forward_expand(gf, Qcur); + ggml_build_forward_expand(gf, Kcur); + ggml_build_forward_expand(gf, mctx_base->cpy_k(ctx0, Kcur, inp_attn->get_k_idxs(), il)); + + // split the selection into the streams the K view carries + const int64_t n_stream = k->ne[3]; + GGML_ASSERT(sel->ne[0] == k->ne[2] && sel->ne[1] % n_stream == 0); + sel = ggml_reshape_4d(ctx0, sel, sel->ne[0], sel->ne[1]/n_stream, 1, n_stream); + + attn = build_attn_mha(Qcur, k, v, nullptr, sel, nullptr, layer.attn_sinks, k_rot ? nullptr : layer.wv_b, + n_sel, kq_scale, il); + if (k_rot) { + attn = llama_mul_mat_hadamard(ctx0, attn, k_rot); + attn = apply_wv_b(attn); + } + } else { + // null unless the K cache is quantized + ggml_tensor * k_rot = hparams.is_swa(il) ? inp_attn->self_k_rot_swa[il] : inp_attn->self_k_rot[il]; + + attn = build_attn(inp_attn, + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, k_rot ? nullptr : layer.wv_b, kq_scale, il); + if (k_rot) { + attn = apply_wv_b(attn); + } + } + cb(attn, "attn_kqv", il); + + ggml_tensor * gate = ggml_mul_mat(ctx0, layer.wqkv_gate, cur); + gate = ggml_sigmoid(ctx0, gate); + attn = ggml_mul(ctx0, attn, gate); + cb(attn, "attn_gated", il); + + ggml_tensor * out = build_lora_mm(layer.wo, attn); + out = build_norm(out, layer.attn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(out, "attn_out", il); + + return out; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_latent_moe( + const llama_model & model, + ggml_tensor * cur, + int il) const { + const auto & layer = model.layers[il]; + + // the router scores the full-width input, the experts take the latent one + ggml_tensor * logits = ggml_mul_mat(ctx0, layer.ffn_gate_inp, cur); + cb(logits, "ffn_moe_logits", il); + + ggml_tensor * routed_in = layer.ffn_routed_down + ? ggml_mul_mat(ctx0, layer.ffn_routed_down, cur) + : cur; + + ggml_tensor * moe_out = build_moe_ffn(routed_in, + nullptr, + layer.ffn_up_exps, + layer.ffn_gate_exps, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + n_expert, n_expert_used, + LLM_FFN_SILU, hparams.expert_weights_norm, + hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il, + logits, + nullptr, + layer.ffn_up_exps_s, + layer.ffn_gate_exps_s, + layer.ffn_down_exps_s); + cb(moe_out, "ffn_moe_out", il); + + if (layer.ffn_routed_up) { + moe_out = ggml_mul_mat(ctx0, layer.ffn_routed_up, moe_out); + cb(moe_out, "ffn_moe_up", il); + } + + ggml_tensor * shexp = build_ffn(cur, + layer.ffn_up_shexp, NULL, NULL, + layer.ffn_gate_shexp, NULL, NULL, + layer.ffn_down_shexp, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(shexp, "ffn_shexp", il); + + return ggml_add(ctx0, moe_out, shexp); +} + +llama_model_hy_v4_flash::graph::graph(const llama_model & model, const llm_graph_params & params) : + llm_graph_context(params) { + const int64_t hc = hparams.dsv4_hc_mult; + + ggml_tensor * cur; + + ggml_tensor * inp = build_inp_embd(model.tok_embd); + ggml_tensor * inp_pos = build_inp_pos(); + + // With an indexer the memory is a composition, so the attention context has to be fetched out + // of it and the input told how to find it again on reuse. + const auto * mctx_idx = hparams.indexer_top_k > 0 + ? static_cast(mctx) : nullptr; + + llm_graph_input_attn_k_iswa * inp_attn = mctx_idx + ? build_attn_inp_k_iswa( + std::make_unique(hparams, cparams, mctx_idx->get_attn()), + mctx_idx->get_attn()) + : build_attn_inp_k_iswa(); + + llm_graph_input_kpool * inp_kpool = mctx_idx ? build_inp_kpool(mctx_idx) : nullptr; + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + if (cparams.dfly_capture_n_layer > 0 && n_outputs > 0) { + dfly_out_ids = inp_out_ids; + } + + // Engram gathers go right after the token embeddings so they share the first graph split and + // the lazily read table stays on the host. An embedding-only ubatch has no token ids to hash, + // which matches the reference skipping Engram at its masked (image) positions. + auto inp_eng = std::make_unique( + static_cast(model), inp_attn->mctx->get_base()); + std::vector engram_rows; + std::vector engram_valid; + for (int il = 0; ubatch.token && hparams.ple_n_heads > 0 && il < n_layer; ++il) { + if (!hparams.is_ple(il)) { + continue; + } + const int64_t n_cols = hparams.ple_n_heads; + + ggml_tensor * ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_cols*n_tokens); + ggml_set_input(ids); + ggml_set_name(ids, ("engram_ids-" + std::to_string(il)).c_str()); + inp_eng->engram_ids.push_back(ids); + + ggml_tensor * valid = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_cols*n_tokens); + ggml_set_input(valid); + ggml_set_name(valid, ("engram_valid-" + std::to_string(il)).c_str()); + inp_eng->engram_valid.push_back(valid); + engram_valid.push_back(valid); + + ggml_tensor * rows = ggml_get_rows(ctx0, model.per_layer_tok_embd, ids); + rows = ggml_reshape_3d(ctx0, rows, hparams.ple_head_dim, n_cols, n_tokens); + cb(rows, "engram_rows", il); + ggml_build_forward_expand(gf, rows); + engram_rows.push_back(rows); + } + res->add_input(std::move(inp_eng)); + + // one embedding feeds hc parallel residual streams + ggml_tensor * inpL = ggml_reshape_3d(ctx0, inp, n_embd, 1, n_tokens); + inpL = ggml_repeat_4d(ctx0, inpL, n_embd, hc, n_tokens, 1); + cb(inpL, "hc_init", -1); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + + // Engram writes into the streams before the attention pre-mix reads them + const int e = static_cast(model).engram_index(il); + if (e >= 0 && !engram_rows.empty()) { + inpL = build_engram(model, inpL, engram_rows[e], engram_valid[e], il); + cb(inpL, "engram_out", il); + } + + ggml_tensor * residual = inpL; + hc_pre attn_hc = build_hc_pre(inpL, layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base, il); + cur = build_norm(attn_hc.cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + cur = build_attention(model, inp_attn, cur, inp_pos, mctx_idx, inp_kpool, il); + + inpL = build_hc_post(cur, residual, attn_hc.post, il); + cb(inpL, "hc_attn_out", il); + + residual = inpL; + hc_pre ffn_hc = build_hc_pre(inpL, layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base, il); + cur = build_norm(ffn_hc.cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + if ((uint32_t) il < hparams.n_layer_dense_lead) { + cur = build_ffn(cur, + layer.ffn_up, NULL, NULL, + layer.ffn_gate, NULL, NULL, + layer.ffn_down, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + } else { + cur = build_latent_moe(model, cur, il); + } + + cur = build_norm(cur, layer.ffn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_out", il); + + inpL = build_hc_post(cur, residual, ffn_hc.post, il); + cb(inpL, "l_out", il); + } + + // prune to the requested rows once, after every stream is done. Unmasked nextn embeddings want + // one row per token, so in that mode the narrowing waits until the state has been captured. + if (crop_before_nextn(inp_out_ids)) { + ggml_tensor * flat = ggml_reshape_2d(ctx0, inpL, n_embd * hc, n_tokens); + flat = ggml_get_rows(ctx0, flat, inp_out_ids); + inpL = ggml_reshape_3d(ctx0, flat, n_embd, hc, n_outputs); + } + + cur = build_hc_head(inpL, model.hc_head_fn, model.hc_head_scale, model.hc_head_base); + cb(cur, "hc_head", -1); + + cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); + + // the draft block consumes this exact state through its hnorm, so expose it for the caller to + // hand back via llama_batch_ext_set_embd_state() + cb(cur, "h_nextn", -1); + res->t_h_nextn = cur; + + if (crop_after_nextn(inp_out_ids)) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + } + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur); + cb(cur, "result_output", -1); + res->t_logits = cur; +} + +llama_model_hy_v4_flash::graph_mtp::graph_mtp(const llama_model & model, const llm_graph_params & params) : + graph(params, no_build{}) { + GGML_ASSERT(hparams.n_layer_nextn > 0 && "hy_v4_flash MTP needs the draft block, convert without --no-mtp"); + GGML_ASSERT(cparams.nextn_layer_offset >= 0 && + cparams.nextn_layer_offset < (int) hparams.n_layer_nextn && + "nextn_layer_offset out of range [0, n_layer_nextn)"); + + const int il = hparams.n_layer() + cparams.nextn_layer_offset; + const auto & layer = model.layers[il]; + + GGML_ASSERT(layer.nextn.eh_proj && layer.nextn.enorm && layer.nextn.hnorm && + "hy_v4_flash MTP block is missing"); + + const auto * mctx_idx = hparams.indexer_top_k > 0 + ? static_cast(mctx) : nullptr; + + llm_graph_input_attn_k_iswa * inp_attn = mctx_idx + ? build_attn_inp_k_iswa( + std::make_unique(hparams, cparams, mctx_idx->get_attn()), + mctx_idx->get_attn()) + : build_attn_inp_k_iswa(); + + llm_graph_input_kpool * inp_kpool = mctx_idx ? build_inp_kpool(mctx_idx) : nullptr; + + ggml_tensor * inp_pos = build_inp_pos(); + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + // the draft takes the next token's embedding alongside the trunk's final hidden state, which + // is the same tensor the trunk's own output head reads: already collapsed over the hc streams + // and already passed through output_norm + auto inp = std::make_unique(hparams.n_embd_inp(), n_embd); + + inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens); + ggml_set_input(inp->tokens); + + inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd_inp(), n_tokens); + ggml_set_input(inp->embd); + + inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens); + ggml_set_input(inp->h); + ggml_set_name(inp->h, "mtp_h_input"); + + ggml_tensor * tok_embd = ubatch.token + ? ggml_get_rows(ctx0, model.tok_embd, inp->tokens) + : inp->embd; + ggml_tensor * prev_h = inp->h; + res->add_input(std::move(inp)); + + ggml_tensor * cur = ggml_concat(ctx0, + build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il), + build_norm(prev_h, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il), 0); + cur = ggml_mul_mat(ctx0, layer.nextn.eh_proj, cur); + cb(cur, "mtp_eh_proj", il); + + // from here it is an ordinary sparse layer, except that the residual is the plain hidden state + // rather than one of the trunk's hc streams + ggml_tensor * residual = cur; + cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cur = build_attention(model, inp_attn, cur, inp_pos, mctx_idx, inp_kpool, il); + cur = ggml_add(ctx0, cur, residual); + + if (crop_before_nextn(inp_out_ids)) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + } + + residual = cur; + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + cur = build_latent_moe(model, cur, il); + cur = build_norm(cur, layer.ffn_post_norm, nullptr, LLM_NORM_RMS, il); + cur = ggml_add(ctx0, cur, residual); + + cur = build_norm(cur, layer.nextn.shared_head_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "mtp_result_norm", -1); + + // the draft's own post-norm state, so a second draft step can be fed from this one + res->t_h_nextn = cur; + + if (crop_after_nextn(inp_out_ids)) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + } + + cur = build_lora_mm(model.output, cur); + cb(cur, "mtp_result_output", -1); + + res->t_logits = cur; + + ggml_build_forward_expand(gf, cur); +} diff --git a/src/models/hy-v4-next-dfly.cpp b/src/models/hy-v4-next-dfly.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cdd47b433ed1d5bd73c5d059c943230b0c3da9a --- /dev/null +++ b/src/models/hy-v4-next-dfly.cpp @@ -0,0 +1,593 @@ +#include "models.h" + +#include "hy-v4-next-dfly.h" + +#include +#include +#include +#include + +// HY_V4_NEXT_DFLY: the 5-layer DFly draft of hy_v4_flash, schema v1. It keeps no KV cache and +// borrows tok_embd and output from the target, so the file holds only its own 92 tensors. + +struct hy_v4_next_dfly_key { + llm_kv kv; + gguf_type type; // GGUF_TYPE_ARRAY means an array of UINT32 +}; + +// the exact hy_v4_next_dfly.* key set of schema v1, plus the mask id +static const hy_v4_next_dfly_key hy_v4_next_dfly_keys[] = { + { LLM_KV_DFLY_SCHEMA_VERSION, GGUF_TYPE_UINT32 }, + { LLM_KV_DFLASH_BLOCK_SIZE, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_CAUSAL, GGUF_TYPE_BOOL }, + { LLM_KV_BLOCK_COUNT, GGUF_TYPE_UINT32 }, + { LLM_KV_CONTEXT_LENGTH, GGUF_TYPE_UINT32 }, + { LLM_KV_EMBEDDING_LENGTH, GGUF_TYPE_UINT32 }, + { LLM_KV_FEED_FORWARD_LENGTH, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_HEAD_COUNT, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_HEAD_COUNT_KV, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_Q_LORA_RANK, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_KV_LORA_RANK, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_KEY_LENGTH, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_VALUE_LENGTH, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_KEY_LENGTH_MLA, GGUF_TYPE_UINT32 }, + { LLM_KV_ATTENTION_VALUE_LENGTH_MLA, GGUF_TYPE_UINT32 }, + { LLM_KV_ROPE_DIMENSION_COUNT, GGUF_TYPE_UINT32 }, + { LLM_KV_ROPE_FREQ_BASE, GGUF_TYPE_FLOAT32 }, + { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, GGUF_TYPE_FLOAT32 }, + { LLM_KV_DFLY_TARGET_KV_LAYERS, GGUF_TYPE_ARRAY }, + { LLM_KV_DFLY_TARGET_INDEX_LAYERS, GGUF_TYPE_ARRAY }, + { LLM_KV_DFLY_TARGET_INDEX_TOP_K, GGUF_TYPE_UINT32 }, + { LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, GGUF_TYPE_UINT32 }, + { LLM_KV_HAS_CONFIDENCE_HEAD, GGUF_TYPE_BOOL }, + { LLM_KV_DFLY_MTP_FUSION, GGUF_TYPE_STRING }, + { LLM_KV_DFLY_ROPE_LAYOUT, GGUF_TYPE_STRING }, + { LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, GGUF_TYPE_ARRAY }, + { LLM_KV_TOKENIZER_MASK_ID, GGUF_TYPE_UINT32 }, +}; + +static std::string hy_v4_next_dfly_type_name(const gguf_context * ctx, int64_t kid) { + const gguf_type type = gguf_get_kv_type(ctx, kid); + if (type == GGUF_TYPE_ARRAY) { + return std::string("arr[") + gguf_type_name(gguf_get_arr_type(ctx, kid)) + "]"; + } + return gguf_type_name(type); +} + +static void hy_v4_next_dfly_check_keys(llama_model_loader & ml) { + const gguf_context * ctx = ml.metadata; + const std::string prefix = std::string(llm_arch_name(LLM_ARCH_HY_V4_NEXT_DFLY)) + "."; + + std::vector errors; + std::set known; + + for (const auto & key : hy_v4_next_dfly_keys) { + const std::string name = ml.llm_kv(key.kv); + known.insert(name); + + const int64_t kid = gguf_find_key(ctx, name.c_str()); + if (kid < 0) { + errors.push_back("missing key " + name); + continue; + } + if (gguf_get_kv_type(ctx, kid) != key.type || + (key.type == GGUF_TYPE_ARRAY && gguf_get_arr_type(ctx, kid) != GGUF_TYPE_UINT32)) { + const std::string expected = key.type == GGUF_TYPE_ARRAY ? "arr[u32]" : gguf_type_name(key.type); + errors.push_back("key " + name + " has type " + hy_v4_next_dfly_type_name(ctx, kid) + ", expected " + expected); + } + } + + for (int64_t i = 0; i < gguf_get_n_kv(ctx); ++i) { + const std::string name = gguf_get_key(ctx, i); + if (name.rfind(prefix, 0) == 0 && known.count(name) == 0) { + errors.push_back("unknown key " + name); + } + if (name.rfind("prism.hadamard.", 0) == 0) { + errors.push_back("prism.hadamard is not supported: " + name); + } + } + + if (!errors.empty()) { + std::string msg = "hy_v4_next_dfly: " + errors[0]; + for (size_t i = 1; i < errors.size(); ++i) { + msg += "; " + errors[i]; + } + throw std::runtime_error(msg); + } + + // the generic loader asserts on a block count it cannot hold + uint32_t n_layer = 0; + ml.get_key(LLM_KV_BLOCK_COUNT, n_layer); + if (n_layer != LLAMA_DFLY_N_LAYER) { + throw std::runtime_error(format("hy_v4_next_dfly: %s = %u must be %d", + ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), n_layer, LLAMA_DFLY_N_LAYER)); + } +} + +void llama_model_hy_v4_next_dfly::load_hparams(llama_model_loader & ml) { + // before the generic loader: it reads optional keys silently and asserts on some of them + hy_v4_next_dfly_check_keys(ml); + llama_model_base::load_hparams(ml); +} + +void llama_model_hy_v4_next_dfly::load_arch_hparams(llama_model_loader & ml) { + uint32_t schema_version = 0; + uint32_t block_size = 0; + bool has_confidence = false; + std::string mtp_fusion; + std::string rope_layout; + + std::vector kv_layers; + std::vector index_layers; + std::vector mrope_sections; + + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); + ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv); + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl); + ml.get_key(LLM_KV_DFLY_TARGET_INDEX_TOP_K, hparams.dfly_target_index_top_k); + ml.get_key(LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, hparams.dfly_hidden_correction_length); + ml.get_key(LLM_KV_DFLY_SCHEMA_VERSION, schema_version); + ml.get_key(LLM_KV_DFLASH_BLOCK_SIZE, block_size); + ml.get_key(LLM_KV_HAS_CONFIDENCE_HEAD, has_confidence); + ml.get_key(LLM_KV_DFLY_MTP_FUSION, mtp_fusion); + ml.get_key(LLM_KV_DFLY_ROPE_LAYOUT, rope_layout); + ml.get_arr(LLM_KV_DFLY_TARGET_KV_LAYERS, kv_layers); + ml.get_arr(LLM_KV_DFLY_TARGET_INDEX_LAYERS, index_layers); + ml.get_arr(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, mrope_sections); + + // schema v1 semantics + if (schema_version != 1) { + throw std::runtime_error(format("hy_v4_next_dfly: unknown schema: %s = %u, expected 1", + ml.llm_kv(LLM_KV_DFLY_SCHEMA_VERSION).c_str(), schema_version)); + } + if (block_size < 2) { + throw std::runtime_error(format("hy_v4_next_dfly: %s = %u must be >= 2", + ml.llm_kv(LLM_KV_DFLASH_BLOCK_SIZE).c_str(), block_size)); + } + if (!hparams.causal_attn) { + throw std::runtime_error(format("hy_v4_next_dfly: %s = false, schema v1 does not support non-causal DFly", + ml.llm_kv(LLM_KV_ATTENTION_CAUSAL).c_str())); + } + if (!has_confidence) { + throw std::runtime_error(format("hy_v4_next_dfly: %s = false must be true", + ml.llm_kv(LLM_KV_HAS_CONFIDENCE_HEAD).c_str())); + } + if (mtp_fusion != "slot0") { + throw std::runtime_error(format("hy_v4_next_dfly: %s = '%s' must be 'slot0'", + ml.llm_kv(LLM_KV_DFLY_MTP_FUSION).c_str(), mtp_fusion.c_str())); + } + if (rope_layout != "norm_adjacent") { + throw std::runtime_error(format("hy_v4_next_dfly: %s = '%s' must be 'norm_adjacent'", + ml.llm_kv(LLM_KV_DFLY_ROPE_LAYOUT).c_str(), rope_layout.c_str())); + } + if (mrope_sections.size() != hparams.dfly_source_mrope_sections.size()) { + throw std::runtime_error(format("hy_v4_next_dfly: %s has %zu entries, expected %zu", + ml.llm_kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS).c_str(), mrope_sections.size(), hparams.dfly_source_mrope_sections.size())); + } + + hy_v4_next_dfly_dims d; + d.n_layer = hparams.n_layer_all; + d.n_ctx_train = hparams.n_ctx_train; + d.n_embd = hparams.n_embd; + d.n_ff = hparams.n_ff(); + d.n_head = hparams.n_head(); + d.n_head_kv = hparams.n_head_kv(); + d.n_lora_q = hparams.n_lora_q; + d.n_lora_kv = hparams.n_lora_kv; + d.n_embd_head_k = hparams.n_embd_head_k(); + d.n_embd_head_v = hparams.n_embd_head_v(); + d.n_embd_head_k_mla = hparams.n_embd_head_k_mla_impl; + d.n_embd_head_v_mla = hparams.n_embd_head_v_mla_impl; + d.n_rot = hparams.n_rot(); + d.rope_freq_base = hparams.rope_freq_base_train; + d.norm_rms_eps = hparams.f_norm_rms_eps; + d.target_kv_layers = kv_layers; + d.target_index_layers = index_layers; + d.source_mrope_sections = mrope_sections; + d.target_index_top_k = hparams.dfly_target_index_top_k; + d.hidden_correction_length = hparams.dfly_hidden_correction_length; + + const std::vector warnings = hy_v4_next_dfly_check_dims(d); + + // the lists hold block_count == LLAMA_DFLY_N_LAYER entries, checked above + hparams.dfly_schema_version = schema_version; + hparams.dfly_block_size = block_size; + hparams.dfly_has_confidence_head = has_confidence; + std::copy(kv_layers.begin(), kv_layers.end(), hparams.dfly_target_kv_layers.begin()); + std::copy(index_layers.begin(), index_layers.end(), hparams.dfly_target_index_layers.begin()); + std::copy(mrope_sections.begin(), mrope_sections.end(), hparams.dfly_source_mrope_sections.begin()); + + for (const auto & w : warnings) { + LLAMA_LOG_WARN("%s\n", w.c_str()); + } + + type = LLM_TYPE_UNKNOWN; +} + +void llama_model_hy_v4_next_dfly::load_arch_tensors(llama_model_loader & ml) { + LLAMA_LOAD_LOCALS; + + const std::vector bad_infos = hy_v4_next_dfly_check_tensor_infos(llm_tensor_info_for); + if (!bad_infos.empty()) { + std::string names; + for (llm_tensor type : bad_infos) { + const bool repeating = std::find(std::begin(hy_v4_next_dfly_layer_tensors), std::end(hy_v4_next_dfly_layer_tensors), type) != + std::end(hy_v4_next_dfly_layer_tensors); + names += (names.empty() ? "" : ", ") + (repeating ? tn(type, "weight", 0) : tn(type, "weight")).str(); + } + throw std::runtime_error("hy_v4_next_dfly: the tensor info table cannot place " + names); + } + + // the vocab is loaded by now; read the raw mask id, the vocab drops one that is out of range + uint32_t mask_id = 0; + ml.get_key(LLM_KV_TOKENIZER_MASK_ID, mask_id); + const std::vector vocab_warnings = hy_v4_next_dfly_check_vocab(vocab.n_tokens(), mask_id, vocab.token_mask()); + + // done_getting_tensors() only counts, so name any tensor outside the schema here + std::set known; + for (int i = 0; i < n_layer; ++i) { + for (llm_tensor type : hy_v4_next_dfly_layer_tensors) { + known.insert(tn(type, "weight", i).str()); + } + } + for (llm_tensor type : hy_v4_next_dfly_global_tensors) { + known.insert(tn(type, "weight").str()); + } + known.insert(tn(LLM_TENSOR_DFLY_CONFIDENCE, "bias").str()); + + std::string unknown; + for (const auto & it : ml.weights_map) { + if (known.count(it.first) == 0) { + unknown += (unknown.empty() ? "" : ", ") + it.first; + } + } + if (!unknown.empty()) { + throw std::runtime_error("hy_v4_next_dfly: unknown tensors: " + unknown); + } + + const int64_t n_lora_q = hparams.n_lora_q; + const int64_t n_lora_kv = hparams.n_lora_kv; + const int64_t n_qk = hparams.n_embd_head_k_mla(); // nope + rope + const int64_t n_nope = n_qk - n_rot; + const int64_t n_v = hparams.n_embd_head_v_mla(); + const int64_t n_corr = hparams.dfly_hidden_correction_length; + + // Norms, sinks and the confidence head are F32; matrices also support Q8_0. + std::vector> created; + auto create = [&](const LLM_TN_IMPL & name, const std::initializer_list & ne, bool f32) { + ggml_tensor * t = create_tensor(name, ne, 0); + if (t == nullptr) { + throw std::runtime_error(format("hy_v4_next_dfly: tensor %s was not created", name.str().c_str())); + } + created.emplace_back(t, f32); + return t; + }; + auto create_f32 = [&](const LLM_TN_IMPL & name, const std::initializer_list & ne) { return create(name, ne, true); }; + auto create_mat = [&](const LLM_TN_IMPL & name, const std::initializer_list & ne) { return create(name, ne, false); }; + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + + layer.attn_norm = create_f32(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}); + layer.wq_a = create_mat(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, n_lora_q}); + layer.attn_q_a_norm = create_f32(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {n_lora_q}); + layer.wq_b = create_mat(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {n_lora_q, n_head * n_qk}); + layer.wkv_a_mqa = create_mat(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, n_lora_kv + n_rot}); + layer.attn_kv_a_norm = create_f32(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {n_lora_kv}); + layer.wk_b = create_mat(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {n_nope, n_lora_kv, n_head}); + layer.wv_b = create_mat(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {n_lora_kv, n_v, n_head}); + layer.attn_sinks = create_f32(tn(LLM_TENSOR_ATTN_SINKS, "weight", i), {n_head}); + layer.wqkv_gate = create_mat(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head * n_v}); + layer.wo = create_mat(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head * n_v, n_embd}); + layer.attn_post_norm = create_f32(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}); + + layer.ffn_norm = create_f32(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}); + layer.ffn_gate = create_mat(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}); + layer.ffn_up = create_mat(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}); + layer.ffn_down = create_mat(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}); + } + + output_norm = create_f32(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}); + + // fusion input is [E, H], correction input is [H, E] + dfly_fusion_enorm = create_f32(tn(LLM_TENSOR_DFLY_FUSION_ENORM, "weight"), {n_embd}); + dfly_fusion_hnorm = create_f32(tn(LLM_TENSOR_DFLY_FUSION_HNORM, "weight"), {n_embd}); + dfly_fusion_eh = create_mat(tn(LLM_TENSOR_DFLY_FUSION_EH, "weight"), {2 * n_embd, n_embd}); + dfly_fusion_gate = create_f32(tn(LLM_TENSOR_DFLY_FUSION_GATE, "weight"), {n_embd}); + + dfly_correction_hnorm = create_f32(tn(LLM_TENSOR_DFLY_CORRECTION_HNORM, "weight"), {n_embd}); + dfly_correction_enorm = create_f32(tn(LLM_TENSOR_DFLY_CORRECTION_ENORM, "weight"), {n_embd}); + dfly_correction_gate = create_mat(tn(LLM_TENSOR_DFLY_CORRECTION_GATE, "weight"), {2 * n_embd, n_corr}); + dfly_correction_up = create_mat(tn(LLM_TENSOR_DFLY_CORRECTION_UP, "weight"), {2 * n_embd, n_corr}); + dfly_correction_down = create_mat(tn(LLM_TENSOR_DFLY_CORRECTION_DOWN, "weight"), {n_corr, n_embd}); + + dfly_confidence = create_f32(tn(LLM_TENSOR_DFLY_CONFIDENCE, "weight"), {n_embd, 1}); + dfly_confidence_b = create_f32(tn(LLM_TENSOR_DFLY_CONFIDENCE, "bias"), {1}); + + std::string bad_types; + for (const auto & [t, f32] : created) { + const bool ok = f32 ? t->type == GGML_TYPE_F32 : (t->type == GGML_TYPE_BF16 || t->type == GGML_TYPE_F16 || t->type == GGML_TYPE_Q8_0); + if (!ok) { + bad_types += format("%stensor %s has type %s, expected %s", bad_types.empty() ? "" : "; ", + t->name, ggml_type_name(t->type), f32 ? "f32" : "bf16, f16 or q8_0"); + } + } + if (!bad_types.empty()) { + throw std::runtime_error("hy_v4_next_dfly: " + bad_types); + } + + // appendix A of the plan: 5 x 155,920,928 + 66,081,793 = 845,686,433 at the production dims + const int64_t n_params_layer = + n_embd + n_embd*n_lora_q + n_lora_q + n_lora_q*n_head*n_qk + + n_embd*(n_lora_kv + n_rot) + n_lora_kv + n_nope*n_lora_kv*n_head + n_lora_kv*n_v*n_head + n_head + + 2*n_embd*n_head*n_v + 2*n_embd + 3*n_embd*n_ff; + const int64_t n_params_global = 7*n_embd + 2*n_embd*n_embd + 2*2*n_embd*n_corr + n_corr*n_embd + 1; + + int64_t n_params = 0; + for (const auto & it : created) { + n_params += ggml_nelements(it.first); + } + if (n_params != n_layer*n_params_layer + n_params_global) { + throw std::runtime_error(format("hy_v4_next_dfly: the tensors hold %" PRId64 " parameters, the hparams give %" PRId64, + n_params, n_layer*n_params_layer + n_params_global)); + } + + for (const auto & w : vocab_warnings) { + LLAMA_LOG_WARN("%s\n", w.c_str()); + } +} + +std::unique_ptr llama_model_hy_v4_next_dfly::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(*this, params); +} + +// W = n_tokens slots [anchor, MASK, ...] at positions a..a+W-1, then K = W - 1 serial heads. +// reserve builds this without a snapshot, so only the shapes are used here; the data comes at set_input. +llama_model_hy_v4_next_dfly::graph::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) { + if (cparams.ctx_other == nullptr) { + throw std::runtime_error("hy_v4_next_dfly: the graph needs the bound target (ctx_other)"); + } + + // E, O and the K storage belong to the target and are read in place + const llama_model * target = llama_get_model(cparams.ctx_other); + ggml_tensor * tok_embd = target->tok_embd; + ggml_tensor * output = target->output; + + const int64_t W = n_tokens; + const int64_t K = W - 1; + const int64_t S = hparams.dfly_target_index_top_k; + const int64_t n_rkv = hparams.n_lora_kv; + const int64_t n_qk = hparams.n_embd_head_k_mla(); // Dn + Dr + const int64_t n_nope = n_qk - n_rot; + const int64_t n_v = hparams.n_embd_head_v_mla(); + const int64_t n_kv_row = n_rkv + n_rot; + const int64_t n_vocab = tok_embd->ne[1]; + + // 1/sqrt(Dn + Dr), not 1/sqrt(Rkv + Dr); the sinks are not scaled + const float kq_scale = 1.0f/sqrtf(float(n_qk)); + const float theta = hparams.rope_freq_base_train; + + auto inp = std::make_unique(cparams.dfly_inp, S, cparams.dfly_force_prev); + if (!llm_graph_dfly_k_storage(cparams, hparams, ubatch.seq_id[0][0], inp->k_storage, inp->strm)) { + throw std::runtime_error("hy_v4_next_dfly: the bound target has no K storage for the draft layers"); + } + inp->h_t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, 1); + ggml_set_input(inp->h_t); + for (int il = 0; il < n_layer; ++il) { + inp->ctx_idx[il] = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, S); + ggml_set_input(inp->ctx_idx[il]); + inp->kq_mask[il] = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, S + W, W); + ggml_set_input(inp->kq_mask[il]); + cb(inp->kq_mask[il], "dfly_kq_mask", il); + } + if (cparams.dfly_force_prev && K > 0) { + inp->prev = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, K); + ggml_set_input(inp->prev); + } + auto * inp_dfly = static_cast(res->add_input(std::move(inp))); + + ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens); + ggml_set_input(inp_tokens); + res->t_inp_tokens = inp_tokens; + { + auto inp_embd = std::make_unique(n_embd); + inp_embd->tokens = inp_tokens; + res->add_input(std::move(inp_embd)); + } + + ggml_tensor * inp_pos = build_inp_pos(); + + // the gather runs on a backend of this scheduler that can read the target K buffer + auto gather_backend = [&](const ggml_tensor * k, ggml_tensor * node) -> ggml_backend_t { + if (k->buffer == nullptr) { + return nullptr; + } + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(k->buffer); + for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { + ggml_backend_t backend = ggml_backend_sched_get_backend(sched, i); + if (ggml_backend_supports_buft(backend, buft) && ggml_backend_supports_op(backend, node)) { + return backend; + } + } + return nullptr; + }; + + auto name_slot = [](ggml_tensor * t, int64_t j, const char * name) { + ggml_format_name(t, "dfly_s%d.%s", (int) j, name); + }; + + // slot 0 fusion: concat(enorm(e0), hnorm(H_T)), E first; the gate is the raw vector and touches slot 0 only + ggml_tensor * x_embd = ggml_get_rows(ctx0, tok_embd, inp_tokens); + cb(x_embd, "dfly_x_embd", -1); + + ggml_tensor * e0 = ggml_view_2d(ctx0, x_embd, n_embd, 1, x_embd->nb[1], 0); + + ggml_tensor * fusion_in = ggml_concat(ctx0, + build_norm(e0, model.dfly_fusion_enorm, nullptr, LLM_NORM_RMS, -1), + build_norm(inp_dfly->h_t, model.dfly_fusion_hnorm, nullptr, LLM_NORM_RMS, -1), 0); + cb(fusion_in, "dfly_fusion_in", -1); + + ggml_tensor * fusion_delta = ggml_mul_mat(ctx0, model.dfly_fusion_eh, fusion_in); + cb(fusion_delta, "dfly_fusion_delta", -1); + + ggml_tensor * x = ggml_add(ctx0, e0, ggml_mul(ctx0, fusion_delta, model.dfly_fusion_gate)); + if (W > 1) { + x = ggml_concat(ctx0, x, ggml_view_2d(ctx0, x_embd, n_embd, W - 1, x_embd->nb[1], x_embd->nb[1]), 1); + } + cb(x, "dfly_x0", -1); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + + ggml_tensor * u = build_norm(x, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cb(u, "dfly_u", il); + + ggml_tensor * qr = build_norm(ggml_mul_mat(ctx0, layer.wq_a, u), layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il); + cb(qr, "dfly_qr", il); + + ggml_tensor * q = ggml_mul_mat(ctx0, layer.wq_b, qr); + + ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_nope, n_head, W, + ggml_row_size(q->type, n_qk), ggml_row_size(q->type, n_qk)*n_head, 0); + ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_rot, n_head, W, + ggml_row_size(q->type, n_qk), ggml_row_size(q->type, n_qk)*n_head, ggml_row_size(q->type, n_nope)); + + q_pe = ggml_rope_ext(ctx0, q_pe, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig, theta, 1.0f, 0.0f, 1.0f, beta_fast, beta_slow); + cb(q_pe, "dfly_qp", il); + + // absorbed with this layer's own kv_b + ggml_tensor * q_abs = ggml_mul_mat(ctx0, layer.wk_b, ggml_permute(ctx0, q_nope, 0, 2, 1, 3)); + q_abs = ggml_permute(ctx0, q_abs, 0, 2, 1, 3); + + ggml_tensor * q_all = ggml_concat(ctx0, q_abs, q_pe, 0); // [Rkv + Dr, H, W] + cb(q_all, "dfly_q", il); + + // the private block latent of this layer + ggml_tensor * kv = ggml_mul_mat(ctx0, layer.wkv_a_mqa, u); + + ggml_tensor * c_blk = ggml_view_2d(ctx0, kv, n_rkv, W, kv->nb[1], 0); + ggml_tensor * kp_blk = ggml_view_3d(ctx0, kv, n_rot, 1, W, kv->nb[1], kv->nb[1], ggml_row_size(kv->type, n_rkv)); + + c_blk = build_norm(c_blk, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il); + cb(c_blk, "dfly_c_block", il); + + kp_blk = ggml_rope_ext(ctx0, kp_blk, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig, theta, 1.0f, 0.0f, 1.0f, beta_fast, beta_slow); + cb(kp_blk, "dfly_kp_block", il); + + ggml_tensor * k_blk = ggml_concat(ctx0, ggml_reshape_3d(ctx0, c_blk, n_rkv, 1, W), kp_blk, 0); + + // the target latent was normed and rotated by the target layer, it is used as is + ggml_tensor * k_store = inp_dfly->k_storage[il]; + ggml_tensor * k_view = ggml_view_2d(ctx0, k_store, k_store->ne[0], k_store->ne[1], k_store->nb[1], inp_dfly->strm*k_store->nb[2]); + + ggml_tensor * k_ctx = ggml_get_rows(ctx0, k_view, inp_dfly->ctx_idx[il]); // F32 [Rkv + Dr, S] + cb(k_ctx, "dfly_kctx", il); + + ggml_backend_t backend_k = gather_backend(k_store, k_ctx); + if (backend_k == nullptr) { + throw std::runtime_error(format("hy_v4_next_dfly: no backend of the draft can read the K storage of target layer %u", + hparams.dfly_target_kv_layers[il])); + } + ggml_backend_sched_set_tensor_backend(sched, k_ctx, backend_k); + + ggml_tensor * k_all = ggml_concat(ctx0, k_ctx, ggml_reshape_2d(ctx0, k_blk, n_kv_row, W), 1); // [Rkv + Dr, S + W] + + // two 2D GEMMs over the single latent head, plan 8.6 + const int64_t N = S + W; + + ggml_tensor * q2 = ggml_reshape_2d(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, q_all, 0, 2, 1, 3)), n_kv_row, W*n_head); + + ggml_tensor * kq = ggml_mul_mat(ctx0, k_all, q2); // [N, W*H] + ggml_prec_set_acc(kq, GGML_PREC_F32); + + // the sinks go on the head axis ne[2] + kq = ggml_reshape_3d(ctx0, kq, N, W, n_head); + kq = ggml_soft_max_ext(ctx0, kq, inp_dfly->kq_mask[il], kq_scale, 0.0f); + ggml_soft_max_add_sinks(kq, layer.attn_sinks); + cb(kq, "dfly_probs", il); + + ggml_tensor * v_t = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_view_2d(ctx0, k_all, n_rkv, N, k_all->nb[1], 0))); + + ggml_tensor * o_lat = ggml_mul_mat(ctx0, v_t, ggml_reshape_2d(ctx0, kq, N, W*n_head)); // [Rkv, W*H] + ggml_prec_set_acc(o_lat, GGML_PREC_F32); + cb(o_lat, "dfly_o_latent", il); + + ggml_tensor * o = ggml_mul_mat(ctx0, layer.wv_b, ggml_reshape_3d(ctx0, o_lat, n_rkv, W, n_head)); // [Dv, W, H] + cb(o, "dfly_o", il); + + ggml_tensor * attn = ggml_cont_2d(ctx0, ggml_permute(ctx0, o, 0, 2, 1, 3), n_v*n_head, W); + + // the gate reads U and sits after v_b, before o_proj + ggml_tensor * gate = ggml_sigmoid(ctx0, ggml_mul_mat(ctx0, layer.wqkv_gate, u)); + cb(gate, "dfly_gate", il); + + attn = ggml_mul_mat(ctx0, layer.wo, ggml_mul(ctx0, attn, gate)); + cb(attn, "dfly_attn_out", il); + + // post_attention_norm after o_proj, ffn_norm after the first residual + ggml_tensor * post = build_norm(attn, layer.attn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(post, "dfly_post_proj", il); + + x = ggml_add(ctx0, x, post); + cb(x, "dfly_x_mid", il); + + ggml_tensor * t = build_norm(x, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + + ggml_tensor * ffn = ggml_mul_mat(ctx0, layer.ffn_down, + ggml_swiglu_split(ctx0, ggml_mul_mat(ctx0, layer.ffn_gate, t), ggml_mul_mat(ctx0, layer.ffn_up, t))); + cb(ffn, "dfly_ffn_out", il); + + x = ggml_add(ctx0, x, ffn); + cb(x, "dfly_x_out", il); + } + + ggml_tensor * h_d = build_norm(x, model.output_norm, nullptr, LLM_NORM_RMS, -1); + cb(h_d, "dfly_h_d", -1); + + // W = 1 has no head, h_d keeps the graph non-empty + ggml_build_forward_expand(gf, h_d); + + // slot j reads E[prev]: the anchor for slot 1, then the clamped id of slot j - 1 + ggml_tensor * e_prev = e0; + for (int64_t j = 1; j <= K; ++j) { + if (inp_dfly->prev) { + e_prev = ggml_get_rows(ctx0, tok_embd, ggml_view_1d(ctx0, inp_dfly->prev, 1, (j - 1)*ggml_element_size(inp_dfly->prev))); + } + + ggml_tensor * h = ggml_view_2d(ctx0, h_d, n_embd, 1, h_d->nb[1], j*h_d->nb[1]); + + // H first, E second + ggml_tensor * corr_in = ggml_concat(ctx0, + build_norm(h, model.dfly_correction_hnorm, nullptr, LLM_NORM_RMS, -1), + build_norm(e_prev, model.dfly_correction_enorm, nullptr, LLM_NORM_RMS, -1), 0); + name_slot(corr_in, j, "corr_in"); + + ggml_tensor * corr_delta = ggml_mul_mat(ctx0, model.dfly_correction_down, + ggml_swiglu_split(ctx0, ggml_mul_mat(ctx0, model.dfly_correction_gate, corr_in), ggml_mul_mat(ctx0, model.dfly_correction_up, corr_in))); + name_slot(corr_delta, j, "corr_delta"); + + ggml_tensor * h_corr = ggml_add(ctx0, h, corr_delta); + name_slot(h_corr, j, "h_corr"); + + ggml_tensor * logits = ggml_mul_mat(ctx0, output, h_corr); + name_slot(logits, j, "logits"); + + const hy_v4_next_dfly_ids ids = hy_v4_next_dfly_build_ids(ctx0, logits, n_vocab); + name_slot(ids.raw, j, "raw_id"); + name_slot(ids.finite, j, "finite_probe"); + + ggml_build_forward_expand(gf, ids.raw); + ggml_build_forward_expand(gf, ids.finite); + + res->t_dfly_tokens.push_back(ids.raw); + res->t_dfly_finite.push_back(ids.finite); + + // the raw id may be -1 on CUDA, only the clamped one feeds get_rows + if (j < K && inp_dfly->prev == nullptr) { + name_slot(ids.safe, j, "safe_id"); + e_prev = ggml_get_rows(ctx0, tok_embd, ids.safe); + } + } +} diff --git a/src/models/hy-v4-next-dfly.h b/src/models/hy-v4-next-dfly.h new file mode 100644 index 0000000000000000000000000000000000000000..49f4b823d2d5decddcbee00db34a5b1b31f47146 --- /dev/null +++ b/src/models/hy-v4-next-dfly.h @@ -0,0 +1,509 @@ +#pragma once + +// hy_v4_next_dfly loader checks that need no loader types, so that tests can call them directly + +#include "../llama-arch.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +// schema v1: 16 tensor types in each layer and 11 global ones (dfly_confidence also has a bias) +inline constexpr llm_tensor hy_v4_next_dfly_layer_tensors[] = { + LLM_TENSOR_ATTN_NORM, + LLM_TENSOR_ATTN_Q_A, + LLM_TENSOR_ATTN_Q_A_NORM, + LLM_TENSOR_ATTN_Q_B, + LLM_TENSOR_ATTN_KV_A_MQA, + LLM_TENSOR_ATTN_KV_A_NORM, + LLM_TENSOR_ATTN_K_B, + LLM_TENSOR_ATTN_V_B, + LLM_TENSOR_ATTN_SINKS, + LLM_TENSOR_ATTN_GATE, + LLM_TENSOR_ATTN_OUT, + LLM_TENSOR_ATTN_POST_NORM, + LLM_TENSOR_FFN_NORM, + LLM_TENSOR_FFN_GATE, + LLM_TENSOR_FFN_UP, + LLM_TENSOR_FFN_DOWN, +}; + +inline constexpr llm_tensor hy_v4_next_dfly_global_tensors[] = { + LLM_TENSOR_OUTPUT_NORM, + LLM_TENSOR_DFLY_FUSION_ENORM, + LLM_TENSOR_DFLY_FUSION_HNORM, + LLM_TENSOR_DFLY_FUSION_EH, + LLM_TENSOR_DFLY_FUSION_GATE, + LLM_TENSOR_DFLY_CORRECTION_HNORM, + LLM_TENSOR_DFLY_CORRECTION_ENORM, + LLM_TENSOR_DFLY_CORRECTION_GATE, + LLM_TENSOR_DFLY_CORRECTION_UP, + LLM_TENSOR_DFLY_CORRECTION_DOWN, + LLM_TENSOR_DFLY_CONFIDENCE, +}; + +// returns the types that info_for cannot place: no entry, wrong layer kind, or op NONE (the loader would skip them) +inline std::vector hy_v4_next_dfly_check_tensor_infos(const std::function & info_for) { + std::vector bad; + + auto check = [&](llm_tensor type, llm_tensor_layer layer) { + try { + const llm_tensor_info info = info_for(type); + if (info.layer != layer || info.op == GGML_OP_NONE) { + bad.push_back(type); + } + } catch (const std::out_of_range &) { + bad.push_back(type); + } + }; + + for (llm_tensor type : hy_v4_next_dfly_layer_tensors) { + check(type, LLM_TENSOR_LAYER_REPEATING); + } + for (llm_tensor type : hy_v4_next_dfly_global_tensors) { + check(type, LLM_TENSOR_LAYER_OUTPUT); + } + + return bad; +} + +// the metadata checked by layer 2 of the loader +struct hy_v4_next_dfly_dims { + uint32_t n_layer = 0; // block_count + uint32_t n_ctx_train = 0; + uint32_t n_embd = 0; // D + uint32_t n_ff = 0; // F + uint32_t n_head = 0; // H + uint32_t n_head_kv = 0; + uint32_t n_lora_q = 0; // Rq + uint32_t n_lora_kv = 0; // Rkv + uint32_t n_embd_head_k = 0; // key_length + uint32_t n_embd_head_v = 0; // value_length + uint32_t n_embd_head_k_mla = 0; // Dn + Dr + uint32_t n_embd_head_v_mla = 0; // Dv + uint32_t n_rot = 0; // Dr + float rope_freq_base = 0.0f; + float norm_rms_eps = 0.0f; + + std::vector target_kv_layers; + std::vector target_index_layers; + std::vector source_mrope_sections; + + uint32_t target_index_top_k = 0; // S + uint32_t hidden_correction_length = 0; // C +}; + +inline std::string hy_v4_next_dfly_list_str(const std::vector & v) { + std::string s = "["; + for (size_t i = 0; i < v.size(); ++i) { + s += (i > 0 ? ", " : "") + std::to_string(v[i]); + } + return s + "]"; +} + +// throws on a broken rule, returns one warning per value that is not the production one +inline std::vector hy_v4_next_dfly_check_dims(const hy_v4_next_dfly_dims & d) { + const LLM_KV kv(LLM_ARCH_HY_V4_NEXT_DFLY); + + auto fail = [](const std::string & msg) { + throw std::runtime_error("hy_v4_next_dfly: " + msg); + }; + + const std::pair positive[] = { + { LLM_KV_CONTEXT_LENGTH, d.n_ctx_train }, + { LLM_KV_EMBEDDING_LENGTH, d.n_embd }, + { LLM_KV_FEED_FORWARD_LENGTH, d.n_ff }, + { LLM_KV_ATTENTION_HEAD_COUNT, d.n_head }, + { LLM_KV_ATTENTION_Q_LORA_RANK, d.n_lora_q }, + { LLM_KV_ATTENTION_KV_LORA_RANK, d.n_lora_kv }, + { LLM_KV_ATTENTION_VALUE_LENGTH_MLA, d.n_embd_head_v_mla }, + { LLM_KV_ROPE_DIMENSION_COUNT, d.n_rot }, + { LLM_KV_DFLY_TARGET_INDEX_TOP_K, d.target_index_top_k }, + { LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, d.hidden_correction_length }, + }; + for (const auto & [key, value] : positive) { + if (value == 0) { + fail(kv(key) + " = 0 must be > 0"); + } + } + + if (d.n_head_kv != 1) { + fail(kv(LLM_KV_ATTENTION_HEAD_COUNT_KV) + " = " + std::to_string(d.n_head_kv) + " must be 1"); + } + if (d.n_rot % 2 != 0) { + fail(kv(LLM_KV_ROPE_DIMENSION_COUNT) + " = " + std::to_string(d.n_rot) + " must be even"); + } + // the training M-RoPE splits the Dr/2 rotary pairs over its three axes + uint64_t n_mrope = 0; + for (uint32_t n : d.source_mrope_sections) { + n_mrope += n; + } + if (n_mrope != d.n_rot / 2) { + fail(kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS) + " = " + hy_v4_next_dfly_list_str(d.source_mrope_sections) + " sums to " + + std::to_string(n_mrope) + ", expected rope.dimension_count / 2 = " + std::to_string(d.n_rot / 2)); + } + if (d.n_embd_head_k != (uint64_t) d.n_lora_kv + d.n_rot) { + fail(kv(LLM_KV_ATTENTION_KEY_LENGTH) + " = " + std::to_string(d.n_embd_head_k) + + " must be kv_lora_rank + rope.dimension_count = " + std::to_string((uint64_t) d.n_lora_kv + d.n_rot)); + } + if (d.n_embd_head_v != d.n_lora_kv) { + fail(kv(LLM_KV_ATTENTION_VALUE_LENGTH) + " = " + std::to_string(d.n_embd_head_v) + + " must be kv_lora_rank = " + std::to_string(d.n_lora_kv)); + } + if (d.n_embd_head_k_mla <= d.n_rot) { + fail(kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA) + " = " + std::to_string(d.n_embd_head_k_mla) + + " must be larger than rope.dimension_count = " + std::to_string(d.n_rot)); + } + if (!std::isfinite(d.rope_freq_base) || d.rope_freq_base <= 0.0f) { + fail(kv(LLM_KV_ROPE_FREQ_BASE) + " = " + std::to_string(d.rope_freq_base) + " must be finite and > 0"); + } + if (!std::isfinite(d.norm_rms_eps) || d.norm_rms_eps <= 0.0f) { + fail(kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS) + " = " + std::to_string(d.norm_rms_eps) + " must be finite and > 0"); + } + + // one target layer per draft layer, in draft layer order + auto check_layers = [&](llm_kv key, const std::vector & layers) { + if (layers.size() != d.n_layer) { + fail(kv(key) + " has " + std::to_string(layers.size()) + " entries, expected block_count = " + std::to_string(d.n_layer)); + } + for (size_t i = 0; i < layers.size(); ++i) { + for (size_t j = 0; j < i; ++j) { + if (layers[j] == layers[i]) { + fail(kv(key) + " has duplicate layer " + std::to_string(layers[i])); + } + } + } + }; + check_layers(LLM_KV_DFLY_TARGET_KV_LAYERS, d.target_kv_layers); + check_layers(LLM_KV_DFLY_TARGET_INDEX_LAYERS, d.target_index_layers); + if (d.target_index_layers != d.target_kv_layers) { + fail(kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS) + " = " + hy_v4_next_dfly_list_str(d.target_index_layers) + + " must equal " + kv(LLM_KV_DFLY_TARGET_KV_LAYERS) + " = " + hy_v4_next_dfly_list_str(d.target_kv_layers)); + } + + // test fixtures use smaller dims, so values that differ from the production profile only warn + std::vector warnings; + + auto warn = [&](llm_kv key, uint32_t value, uint32_t prod) { + if (value != prod) { + warnings.push_back("hy_v4_next_dfly: " + kv(key) + " = " + std::to_string(value) + " differs from the production value " + std::to_string(prod)); + } + }; + warn(LLM_KV_EMBEDDING_LENGTH, d.n_embd, 3072); + warn(LLM_KV_FEED_FORWARD_LENGTH, d.n_ff, 9216); + warn(LLM_KV_ATTENTION_HEAD_COUNT, d.n_head, 32); + warn(LLM_KV_ATTENTION_Q_LORA_RANK, d.n_lora_q, 1024); + warn(LLM_KV_ATTENTION_KV_LORA_RANK, d.n_lora_kv, 512); + warn(LLM_KV_ROPE_DIMENSION_COUNT, d.n_rot, 64); + warn(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, d.n_embd_head_v_mla, 256); + warn(LLM_KV_DFLY_TARGET_INDEX_TOP_K, d.target_index_top_k, 2048); + + const uint32_t n_nope = d.n_embd_head_k_mla - d.n_rot; + if (n_nope != 192) { + warnings.push_back("hy_v4_next_dfly: " + kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA) + " = " + std::to_string(d.n_embd_head_k_mla) + + " gives Dn = " + std::to_string(n_nope) + ", the production Dn is 192"); + } + + const std::vector prod_layers = { 25, 29, 33, 37, 41 }; + for (const auto & [key, layers] : { std::make_pair(LLM_KV_DFLY_TARGET_KV_LAYERS, &d.target_kv_layers), + std::make_pair(LLM_KV_DFLY_TARGET_INDEX_LAYERS, &d.target_index_layers) }) { + if (*layers != prod_layers) { + warnings.push_back("hy_v4_next_dfly: " + kv(key) + " = " + hy_v4_next_dfly_list_str(*layers) + + " differs from the production value " + hy_v4_next_dfly_list_str(prod_layers)); + } + } + + return warnings; +} + +// V and the raw tokenizer.ggml.mask_token_id, checked once the vocab is loaded; returns the warnings +inline std::vector hy_v4_next_dfly_check_vocab(uint32_t n_vocab, uint32_t mask_id, int32_t token_mask) { + const LLM_KV kv(LLM_ARCH_HY_V4_NEXT_DFLY); + + const std::string tokens = kv(LLM_KV_TOKENIZER_LIST); + const std::string mask = kv(LLM_KV_TOKENIZER_MASK_ID); + + // draft token ids pass through F32 in the graph, which is exact up to 2^24 + const uint32_t n_vocab_max = 1u << 24; + if (n_vocab < 1 || n_vocab > n_vocab_max) { + throw std::runtime_error("hy_v4_next_dfly: " + tokens + " has " + std::to_string(n_vocab) + + " tokens, expected 1 to " + std::to_string(n_vocab_max)); + } + // the vocab only warns on a bad special token and drops it + if (mask_id >= n_vocab) { + throw std::runtime_error("hy_v4_next_dfly: " + mask + " = " + std::to_string(mask_id) + + " is out of the vocab of " + std::to_string(n_vocab) + " tokens"); + } + if ((int64_t) mask_id != token_mask) { + throw std::runtime_error("hy_v4_next_dfly: " + mask + " = " + std::to_string(mask_id) + + " does not match the vocab mask token " + std::to_string(token_mask)); + } + + std::vector warnings; + if (n_vocab != 120832) { + warnings.push_back("hy_v4_next_dfly: " + tokens + " has " + std::to_string(n_vocab) + " tokens, the production vocab has 120832"); + } + if (mask_id != 120009) { + warnings.push_back("hy_v4_next_dfly: " + mask + " = " + std::to_string(mask_id) + " differs from the production value 120009"); + } + return warnings; +} + +// one vocab as the binding check reads it +struct hy_v4_next_dfly_vocab_info { + int32_t type = 0; + std::vector text; + std::vector score; + std::vector attr; + std::vector> special; // key -> id, -1 if unset + bool add_bos = false; + bool add_eos = false; +}; + +// one trunk layer of the target +struct hy_v4_next_dfly_target_layer { + bool swa = false; + bool has_indexer = false; + float rope_base = 0.0f; // effective, after the context parameters + float rope_scale = 0.0f; +}; + +// the K storage of one target layer the draft reads +struct hy_v4_next_dfly_target_k { + bool found = false; // the layer is in the target's full attention cache + int32_t type = -1; // ggml_type + int64_t width = 0; // ne[0] + bool rotated = false; + std::string dev; +}; + +// what layer 3 of the loader checks: the draft bound to a real target +struct hy_v4_next_dfly_binding { + // draft + uint32_t n_embd = 0; + uint32_t n_lora_kv = 0; + uint32_t n_rot = 0; + uint32_t top_k = 0; // S + uint32_t mask_id = 0; + float rope_base = 0.0f; + std::vector kv_layers; + std::vector index_layers; + hy_v4_next_dfly_vocab_info vocab; + std::vector> weight_dev; // tensor name -> device, host buffers count as CPU + + // target + std::string arch; + uint32_t t_n_embd = 0; + uint32_t t_n_lora_kv = 0; + uint32_t t_n_rot = 0; + uint32_t t_top_k = 0; + uint32_t t_kpool = 0; + bool t_kpool_by_order = false; + bool t_select_tail = false; + bool t_prism = false; + bool t_lora = false; + float t_ext_factor = 0.0f; + float t_attn_factor = 1.0f; // scales the target's rotated k_pe + std::vector t_layers; // the trunk, without MTP layers + hy_v4_next_dfly_vocab_info t_vocab; + std::vector e_ne; // token_embd, empty if missing + std::vector o_ne; // output, empty if missing + std::string e_dev; + std::string o_dev; + std::vector k; // one per kv layer +}; + +// throws on the first broken rule, naming the field or tensor +inline void hy_v4_next_dfly_check_binding(const hy_v4_next_dfly_binding & b) { + const LLM_KV kv(LLM_ARCH_HY_V4_NEXT_DFLY); + + auto fail = [](const std::string & msg) { + throw std::runtime_error("hy_v4_next_dfly: target binding: " + msg); + }; + auto u = [](uint64_t v) { return std::to_string(v); }; + + if (b.arch != "hy_v4_flash") { + fail("general.architecture of the target is '" + b.arch + "', expected 'hy_v4_flash'"); + } + if (b.t_n_embd != b.n_embd) { + fail(kv(LLM_KV_EMBEDDING_LENGTH) + " = " + u(b.n_embd) + " differs from the target's " + u(b.t_n_embd)); + } + + // the draft reads E and O of the target, so both must speak the same vocab + const auto & dv = b.vocab; + const auto & tv = b.t_vocab; + const std::string tokens = kv(LLM_KV_TOKENIZER_LIST); + if (dv.text.size() != tv.text.size()) { + fail(tokens + " has " + u(dv.text.size()) + " tokens, the target has " + u(tv.text.size())); + } + if (dv.type != tv.type) { + fail(kv(LLM_KV_TOKENIZER_MODEL) + " differs from the target's (vocab type " + std::to_string(dv.type) + " vs " + std::to_string(tv.type) + ")"); + } + for (size_t i = 0; i < dv.text.size(); ++i) { + if (dv.text[i] != tv.text[i]) { + fail(tokens + "[" + u(i) + "] differs from the target's"); + } + if (i < dv.score.size() && i < tv.score.size() && !(dv.score[i] == tv.score[i])) { + fail(kv(LLM_KV_TOKENIZER_SCORES) + "[" + u(i) + "] differs from the target's"); + } + if (i < dv.attr.size() && i < tv.attr.size() && dv.attr[i] != tv.attr[i]) { + fail(kv(LLM_KV_TOKENIZER_TOKEN_TYPE) + "[" + u(i) + "] differs from the target's"); + } + } + if (dv.special != tv.special) { + for (size_t i = 0; i < dv.special.size() && i < tv.special.size(); ++i) { + if (dv.special[i] != tv.special[i]) { + fail(dv.special[i].first + " = " + std::to_string(dv.special[i].second) + " differs from the target's " + + std::to_string(tv.special[i].second)); + } + } + fail("the special token lists differ in length"); + } + if (dv.add_bos != tv.add_bos || dv.add_eos != tv.add_eos) { + fail(kv(LLM_KV_TOKENIZER_ADD_BOS) + "/" + kv(LLM_KV_TOKENIZER_ADD_EOS) + " differ from the target's"); + } + if (b.mask_id >= tv.text.size()) { + fail(kv(LLM_KV_TOKENIZER_MASK_ID) + " = " + u(b.mask_id) + " is out of the target vocab"); + } + + const int64_t n_vocab = (int64_t) tv.text.size(); + auto check_ne = [&](const char * name, const std::vector & ne) { + if (ne.size() < 2 || ne[0] != (int64_t) b.n_embd || ne[1] != n_vocab || + std::any_of(ne.begin() + 2, ne.end(), [](int64_t n) { return n != 1; })) { + std::string s = "["; + for (size_t i = 0; i < ne.size(); ++i) { + s += (i > 0 ? ", " : "") + std::to_string(ne[i]); + } + fail(std::string("target tensor ") + name + " has ne " + s + "], expected [" + u(b.n_embd) + ", " + u(n_vocab) + "]"); + } + }; + check_ne("token_embd.weight", b.e_ne); + check_ne("output.weight", b.o_ne); + + if (b.t_n_lora_kv != b.n_lora_kv) { + fail(kv(LLM_KV_ATTENTION_KV_LORA_RANK) + " = " + u(b.n_lora_kv) + " differs from the target's " + u(b.t_n_lora_kv)); + } + if (b.t_n_rot != b.n_rot) { + fail(kv(LLM_KV_ROPE_DIMENSION_COUNT) + " = " + u(b.n_rot) + " differs from the target's " + u(b.t_n_rot)); + } + if (b.t_ext_factor != 0.0f) { + fail("the target uses YaRN (ext_factor " + std::to_string(b.t_ext_factor) + "), the draft rotates without it"); + } + if (b.t_attn_factor != 1.0f) { + fail("the target rotates with attn_factor " + std::to_string(b.t_attn_factor) + ", the draft with 1"); + } + + for (const auto & [key, layers] : { std::make_pair(LLM_KV_DFLY_TARGET_KV_LAYERS, &b.kv_layers), + std::make_pair(LLM_KV_DFLY_TARGET_INDEX_LAYERS, &b.index_layers) }) { + for (size_t i = 0; i < layers->size(); ++i) { + const uint32_t il = (*layers)[i]; + const std::string where = kv(key) + "[" + u(i) + "] = " + u(il); + if (std::find(layers->begin(), layers->begin() + i, il) != layers->begin() + i) { + fail(where + " is listed twice"); + } + if (il >= b.t_layers.size()) { + fail(where + " is not a trunk layer of the target (" + u(b.t_layers.size()) + " layers)"); + } + const auto & tl = b.t_layers[il]; + if (tl.swa) { + fail(where + " is a sliding window layer of the target"); + } + if (!tl.has_indexer) { + fail(where + " has no indexer in the target"); + } + if (tl.rope_base != b.rope_base || tl.rope_scale != 1.0f) { + fail(where + ": the target rotates with theta " + std::to_string(tl.rope_base) + " scale " + std::to_string(tl.rope_scale) + + ", the draft's " + kv(LLM_KV_ROPE_FREQ_BASE) + " is " + std::to_string(b.rope_base)); + } + } + } + if (b.kv_layers != b.index_layers) { + fail(kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS) + " must equal " + kv(LLM_KV_DFLY_TARGET_KV_LAYERS)); + } + + const std::string top_k = kv(LLM_KV_DFLY_TARGET_INDEX_TOP_K); + if (b.top_k < 4 || b.top_k > 2048 || b.top_k % 4 != 0) { + fail(top_k + " = " + u(b.top_k) + " must be a multiple of 4 in [4, 2048]"); + } + if (b.top_k != b.t_top_k) { + fail(top_k + " = " + u(b.top_k) + " differs from the target's indexer top_k " + u(b.t_top_k)); + } + if (b.t_kpool != 4 || b.t_kpool_by_order) { + fail("the target's indexer kpool is " + u(b.t_kpool) + (b.t_kpool_by_order ? " by order" : "") + ", expected 4 by position"); + } + if (!b.t_select_tail) { + fail("the target's indexer kpool_select_tail is false, expected true"); + } + if (b.t_prism) { + fail("the target uses prism.hadamard, which changes the shared weights"); + } + if (b.t_lora) { + fail("the target has LoRA adapters"); + } + + if (b.k.size() != b.kv_layers.size()) { + fail("the K storage of " + u(b.k.size()) + " layers was given, expected " + u(b.kv_layers.size())); + } + for (size_t i = 0; i < b.k.size(); ++i) { + const auto & k = b.k[i]; + const std::string where = "the K storage of target layer " + u(b.kv_layers[i]); + if (!k.found) { + fail(where + " is not in the target's full attention cache"); + } + if (k.type != GGML_TYPE_F16 && k.type != GGML_TYPE_BF16) { + fail(where + " has type " + ggml_type_name((ggml_type) k.type) + ", expected f16 or bf16"); + } + if (k.width != (int64_t) b.n_lora_kv + b.n_rot) { + fail(where + " has rows of " + std::to_string(k.width) + ", expected kv_lora_rank + rope.dimension_count = " + + u((uint64_t) b.n_lora_kv + b.n_rot)); + } + if (k.rotated) { + fail(where + " is rotated (quantized K cache)"); + } + } + + // the draft, E, O and the 5 K storages on one device + if (b.weight_dev.empty()) { + fail("no draft weights"); + } + const std::string & dev = b.weight_dev[0].second; + auto check_dev = [&](const std::string & name, const std::string & d) { + if (d != dev) { + fail(name + " is on " + d + ", the draft weight " + b.weight_dev[0].first + " on " + dev); + } + }; + for (const auto & [name, d] : b.weight_dev) { + check_dev(name, d); + } + check_dev("target tensor token_embd.weight", b.e_dev); + check_dev("target tensor output.weight", b.o_dev); + for (size_t i = 0; i < b.k.size(); ++i) { + check_dev("the K storage of target layer " + u(b.kv_layers[i]), b.k[i].dev); + } +} + +// raw argmax id (I32 [n]) of logits [n_vocab, n], the clamped id that may feed get_rows, and the probe that is 0 only +// when all logits are finite (NaN otherwise); an argmax of all -inf or NaN logits can be -1 on CUDA +struct hy_v4_next_dfly_ids { + ggml_tensor * raw; + ggml_tensor * safe; + ggml_tensor * finite; +}; + +// clamp in F32, exact for V <= 2^24: ggml_clamp takes no I32 +inline ggml_tensor * hy_v4_next_dfly_build_safe_id(ggml_context * ctx, ggml_tensor * raw, int64_t n_vocab) { + return ggml_cast(ctx, ggml_clamp(ctx, ggml_cast(ctx, raw, GGML_TYPE_F32), 0.0f, float(n_vocab - 1)), GGML_TYPE_I32); +} + +inline hy_v4_next_dfly_ids hy_v4_next_dfly_build_ids(ggml_context * ctx, ggml_tensor * logits, int64_t n_vocab) { + hy_v4_next_dfly_ids res; + res.raw = ggml_argmax(ctx, logits); + res.safe = hy_v4_next_dfly_build_safe_id(ctx, res.raw, n_vocab); + res.finite = ggml_sum_rows(ctx, ggml_scale(ctx, logits, 0.0f)); + return res; +} diff --git a/src/models/models.h b/src/models/models.h index 1fc7cae1dff0c2e7ffea4e75bd7e94bd699cdf3c..3dddd727276bb2d9bd7799595f7743c74a4e6127 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -9,6 +9,7 @@ #include class llama_memory_hybrid_idx_context; +class llama_memory_idx_iswa_context; // ref: https://github.com/ggml-org/llama.cpp/pull/28068 static inline ggml_tensor * build_gdn_l2_norm(ggml_context * ctx, ggml_tensor * x, float eps) { @@ -2370,6 +2371,143 @@ struct llama_model_hy_v4 : public llama_model_base { }; +// HY_V4_FLASH: hy_v4's iHC + gated MLA + sinks, with a hybrid attention stack (sparse full +// layers alternating with sliding-window layers, each with its own head count and rope base), +// sandwich norms and routed experts that run in a latent space. +struct llama_model_hy_v4_flash : public llama_model_base { + llama_model_hy_v4_flash(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + // -1 when the layer has no Engram module, else its index among the Engram layers + int engram_index(int il) const; + + // n-gram hash of module e. Writes one row id per (token, column) into ids, and alongside it the + // per-column validity: a short history is padded, as in deepseek41, so only a position with no + // n-gram at all (an embedding position) is marked invalid. + void engram_hash(int e, const llama_ubatch & ubatch, const std::vector & prev, + std::vector & ids, std::vector & valid) const; + + class llm_graph_input_kpool; + + // the memory only composes an iSWA pair, so the standard input cannot find its context in + // params.mctx by itself + class llm_graph_input_attn_idx; + + struct graph : public llm_graph_context { + graph(const llama_model & model, const llm_graph_params & params); + + // the MTP graph reuses the helpers without running the trunk + struct no_build {}; + graph(const llm_graph_params & params, no_build) : llm_graph_context(params) {} + + // the trunk's output rows when DFly capture exports the selection, null otherwise (and in the MTP graph) + ggml_tensor * dfly_out_ids = nullptr; + + // iHC, same layout as hy_v4: pre reduces the hc streams to one and returns the per-stream + // post gates, post writes the sublayer output back, head collapses before the final norm. + struct hc_pre { + ggml_tensor * cur; + ggml_tensor * post; + }; + + // reduce the hc streams to one, weighted by the pre gates + ggml_tensor * build_hc_reduce( + ggml_tensor * x, + ggml_tensor * weights, + int il) const; + + hc_pre build_hc_pre( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base, + int il) const; + + ggml_tensor * build_hc_post( + ggml_tensor * x, + ggml_tensor * residual, + ggml_tensor * post, + int il) const; + + ggml_tensor * build_hc_head( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base) const; + + // mctx_idx and inp_kpool are null when the file carries no indexer, and the sparse layers + // then attend their whole context + ggml_tensor * build_attention( + const llama_model & model, + llm_graph_input_attn_k_iswa * inp_attn, + ggml_tensor * cur, + ggml_tensor * inp_pos, + const llama_memory_idx_iswa_context * mctx_idx, + llm_graph_input_kpool * inp_kpool, + int il); + + llm_graph_input_kpool * build_inp_kpool(const llama_memory_idx_iswa_context * mctx_idx); + + // rotate only the trailing n_rot of each indexer head + ggml_tensor * build_indexer_rope(ggml_tensor * x, ggml_tensor * pos, int64_t n_idx, + float freq_base, int il) const; + + // score the pooled keys against the query and keep the best groups, plus the group the + // current token sits in + ggml_tensor * build_kpool_select( + ggml_tensor * cur, + ggml_tensor * qr, + ggml_tensor * inp_pos, + float freq_base, + const llama_layer & layer, + const llama_memory_idx_iswa_context * mctx_idx, + llm_graph_input_kpool * inp_kpool, + int il); + + // routed experts run at n_expert_latent, the router and the shared expert at n_embd + ggml_tensor * build_latent_moe( + const llama_model & model, + ggml_tensor * cur, + int il) const; + + // Engram writes its delta into the hc residual streams before the layer's attention pre-mix + ggml_tensor * build_engram( + const llama_model & model, + ggml_tensor * x, + ggml_tensor * rows, + ggml_tensor * valid, + int il) const; + }; + + // the draft block: one sparse layer fed the next token's embedding and the trunk's final + // hidden state, with no hyper-connections of its own + struct graph_mtp : public graph { + graph_mtp(const llama_model & model, const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + + +// HY_V4_NEXT_DFLY: the DFly draft of hy_v4_flash (schema v1). It borrows tok_embd and output from +// the target and keeps no KV cache, so its file holds only the draft's own tensors. +struct llama_model_hy_v4_next_dfly : public llama_model_base { + llama_model_hy_v4_next_dfly(const struct llama_model_params & params) : llama_model_base(params) {} + // checks the key set before the generic loader reads any key + void load_hparams(llama_model_loader & ml) override; + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + // one propose round: the W slots of the block and the K = W - 1 serial heads (plan section 8) + struct graph : public llm_graph_context { + graph(const llama_model & model, const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + + struct llama_model_hunyuan_vl : public llama_model_base { llama_model_hunyuan_vl(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4224a15aef607f25d1676f804c2e7439f8dcf9f7..6734bffb6c3c788fe2d20995e9e5fb9474627227 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -190,6 +190,10 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) llama_build_and_test(test-grammar-integration.cpp LABEL behavior) llama_build_and_test(test-llama-grammar.cpp LABEL behavior LINK llama) llama_build_and_test(test-batch-alloc.cpp LABEL behavior LINK llama) + llama_build_and_test(test-dfly.cpp LABEL "main behavior") + llama_build_and_test(test-dfly-target.cpp LABEL "main behavior") + # needs the real 446 GB target, so it is built but not run by ctest + llama_build(test-dfly-real.cpp) llama_build_and_test(test-chat.cpp LABEL behavior WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) target_include_directories(test-chat PRIVATE ${PROJECT_SOURCE_DIR}/tools/server) target_link_libraries(test-chat PRIVATE server-context) @@ -296,6 +300,12 @@ llama_test_cmd(python3 WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} ARGS -m unittest discover -s tests -p test_conversion_fp8.py -v ) +llama_test_cmd(python3 + NAME test-conversion-dfly + LABEL "python behavior" + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ARGS -m unittest discover -s tests -p test_conversion_dfly.py -v +) llama_build_and_test(test-json-schema.cpp LABEL behavior) llama_build_and_test(test-chat-auto-parser.cpp LABEL behavior WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) llama_build_and_test(test-chat-template.cpp LABEL behavior) diff --git a/tests/dfly-server/README.md b/tests/dfly-server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f6de2bc3a388d39aa830172324ef12f475eda18c --- /dev/null +++ b/tests/dfly-server/README.md @@ -0,0 +1,112 @@ +# draft-dfly server tests + +Server-level tests of `--spec-type draft-dfly` on a tiny target/DFly pair, driven over HTTP. They are not part of +ctest: they need a `llama-server` built with the test hooks and the tiny pair on disk. + +## Build and run + +```bash +# the hooks exist only with this option; never set it for a production build +cmake -S . -B build-asan -DLLAMA_DFLY_TEST_HOOKS=ON +cmake --build build-asan --target llama-server test-dfly -j + +# the pair: tiny-target.gguf (10 layers, indexer top_k 8) and tiny-dfly-b{3,5,8}.gguf, EOS id 111 in both +LLAMA_DFLY_TEST_WRITE_PAIR=/tmp/dfly-pair LLAMA_DFLY_TEST_WRITE_PAIR_EOS=111 build-asan/bin/test-dfly write_pair + +python3 tests/dfly-server/run_dfly_server_tests.py --server build-asan/bin/llama-server \ + --pair /tmp/dfly-pair --work /tmp/dfly-e2e --summary /tmp/dfly-e2e/summary.txt [--cases L1,L4] [--cache-mode off|primed|carry] \ + [--cache-ram-mib N] [--port 18700] [--r12-n 50] +``` + +Python 3 with `requests`. The servers run on the CPU with `--parallel 1 --fit off --cache-ram 0 --no-context-shift`, +the L groups also with `--no-cache-prompt --ctx-checkpoints 0`, the C and P groups with the prompt cache and +`--ctx-checkpoints 32`, the R groups also with `--cache-ram 256` (or as the group says); their logs and round logs are written to the work directory, and every log is scanned for +ASan/UBSan reports at the end. + +`--cache-mode` (P11) runs only the L groups, with the prompt cache and the slot checkpoints on (the AR servers are then +K = 0 with the same cache): + +- `primed`: each request follows a full prefill of its prompt (`cache_prompt` false, `n_predict` 1), so a request and + its reference share one history and every assertion holds as it is; each request also gets the cache checks below. +- `carry`: the requests reuse the slot state of the one before. The expected reuse comes from a client side model of + the generic path (the slot tokens, the checkpoints from the server log, no SWA wrap); the state assertions and the + cache checks are judged, the comparisons with a reference sequence are recorded in `carry-ref-notes.txt` and not judged, + since a reference and a request then decode their last prompt tokens in batches of other widths. + +`--cache-ram-mib N` (R11) runs the servers that have the prompt cache with `--cache-ram N` and the default thresholds +instead of `--cache-ram 0`, with every existing expectation unchanged; a request that loads a cached prompt is then +judged by G10 alone, and the client model of `carry` counts the requests after it as unknown. The R groups do not run. + +`run_dfly_init_tests.py --bin build-asan/bin --pair

--work --summary ` checks the initialization: every +configuration that draft-dfly with K > 0 does not support fails the load and names the setting (K = 0 starts as the target +alone, even with `--fit on`), the prompt cache, the slot checkpoints and the RAM cache with K > 0 (they start, a repeated prompt +reuses the slot or a checkpoint, and a prompt comes back from the RAM cache through the checkpoint of its entry), bad DFly headers (`tiny-dfly-bad-*.gguf`, also written by `write_pair`), the startup line, a +sleep and resume, a large absolute position, the request checks, `llama-cli`, the router and `llama-speculative`. + +## Test hooks (`LLAMA_DFLY_TEST_HOOKS`) + +- `LLAMA_DFLY_TEST_SCRIPT=`: re-read at the start of every request. Lines: + - `ref ...`: the reference token of each absolute position (prompt included). + - `r ...`: per round, the drafts made to match. A round is a draft with K_step > 0 in the request, + counted from 0. After a successful propose, drafts 0..r-1 become `ref[a+1+j]` and draft r a token other than + `ref[a+1+r]`; the real propose runs and its status counts as usual. + - `wrong `: the rejected draft of that round. + - `propose_fail ...` (H2): these rounds return no draft and run as plain decoding. + - `verify_fail ` (H3): the n-th verify of the request (1-based) is not decoded, `llama_decode` returns `ret`. +- `LLAMA_DFLY_TEST_CKPT_CORRUPT=magic|trunc`: before a checkpoint restore, overwrite the magic of its target data or cut the data in half, so that the restore fails. +- `LLAMA_DFLY_TEST_META_DROP=`: at the release of a slot, drop the last n tokens of its metadata and keep the memory. +- `LLAMA_DFLY_TEST_RAM_SAVE=short|zero`: a RAM cache save writes one byte less than its size, or reports an empty state. +- `LLAMA_DFLY_TEST_RAM_CORRUPT=magic|trunc|drft`: the first RAM cache load of the process overwrites the magic of the + target state, reads half of it, or reads the draft state one byte short, so that the load fails. +- `test hook: prompt cache: exact = 0|1, by = sim|lru, n_tokens, lcp, r_after, slot n_tokens, pos_min, ckpts [...], entries n [...]`: + after the RAM cache update of a task (also with `--cache-ram 0`), the slot, `server_prompt_restorable()` of the slot + for the task (`r_after`, -1 if not computed) and every cached prompt as `E:swa_pos_min:main bytes:draft bytes:checkpoints`. +- Two log lines of the server: `test hook: checkpoint restored: ...` (the recorded range and the memory range after a restore) and `test hook: before prompt decode: q = ...` (the first position of a prompt batch and the memory range it attends to). For an iswa memory, `llama_memory_seq_pos_min` gives the SWA cache. +- The server prints one line per prompt: `prefix cache: prefix_match_tokens = L, prefix_reused_tokens = R, + prefix_replayed_tokens = N - R, restore_source = slot|checkpoint|ram|ram_checkpoint|none, cache_fallback_reason = ...` + (`entry_corrupt` when a RAM load failed), with the RAM cache on one line per task `prompt cache: cache_save_decision = + skipped|empty|refused|superseded|budget|write_failed|saved, n_drop, cache_save_ms, cache_load_decision = + not_tried|no_entry|low_gain|loaded|failed, r_slot, r_entry, cache_restore_ms, n_entries`, and the DFly + implementation one line `first_propose_status = (), pos = ` for the first propose with + K_step > 0 of a request (both also without the hooks). +- `LLAMA_DFLY_TEST_LOG=` (H4): one JSON line per round of the DFly slot: `kind` (`prefill`, `ar` or `spec`), + `a`, `anchor`, `K`, `W`, `r`, `M`, `n_sample`, `n_accept`, `propose` (status; -1 no propose, -2 forced failure), + `k_step`, `n_draft_max`, `query_pos`, `seq_pos_max` (after the rollback), `n_tokens`, `stopped`, `stop`, + `tokens` (the outputs) and `draft`. After the stopping round, one more line `{"kind": "release", "seq_pos_max", "n_tokens", "pos_next"}` gives the slot after `release()`. + +## Reference sequences + +The tiny target gives bit-identical logits for widths 2..8 of a prefix, but not for width 1 (TG-04b). The reference +of a prompt is therefore the output of a DFly request with the real tiny drafts; in the scripted requests every row of +a W >= 2 verify must equal it, a W = 1 token (first anchor, K_step = 0, failed propose) is recorded but not asserted. +The reference requests ask for more tokens than the scripted ones, so their final W = 1 rounds lie outside. + +## Groups + +| group | content | +| --- | --- | +| L1 | prefill 16, 40, 300 then 200 tokens with the real drafts: propose OK, `query_pos = a-1`, `a' = a+r+1`, `seq_pos_max = a+r`, `n_tokens = a+r+1` | +| L2 | B=5/K=4 and B=8/K=7: 24 rounds all rejected, all accepted, alternating, and r cycling 0..K | +| L3 | the table of plan 9.3 for r = 0..4 | +| L4 | the stops of plan 9.5, a rejected EOS draft, EOS as first anchor, `ignore_eos`, a stop string on an accepted token, `n_predict` 1 and 0 against AR | +| L5 | C=32 (`--kv-unified-per-slot 32`), K=4, a=26: as many tokens as AR; K_step near the end of the budget | +| L6 | H2 propose failures; H3 verify failures with ret 1, 2, -3 | +| L7 | capture enabled after warmup and seq_rm probe; the request after K_step=0, a failed propose, a cancel and an error starts from its own prefill | +| L8 | temperature, top-k/top-p, repeat penalty and a grammar: sample = accept = M every round | +| L9 | `draft_n`, `draft_n_accepted`, `predicted_n` and the printed sum M / rounds against the round logs | +| L10 | a stop on draft 1, draft 4, the correction and the bonus: after the release `seq_pos_max + 1 = n_tokens = a + M` | +| C1 | the target alone, prompt cache and checkpoints on, `-ub 32`: a full match whose length is a checkpoint `pos_max` (also after the SWA ring wrapped), a full match inside the first window, a partial match, `--swa-full`; the recorded checkpoint range equals the restored one, a restored `pos_max` is not after the first evaluated position q, and the SWA cache holds `max(0, q - n_swa + 1)` | +| C2 | the target alone: a checkpoint restore that fails (`magic`, `trunc`) logs the error, clears the slot, prefills from position 0, and the server keeps serving | +| C3 | the target alone, `--cache-ram 64`, `--slot-save-path`: with `LLAMA_DFLY_TEST_META_DROP=3` neither the RAM cache nor the slot file saves the slot; without it both save | +| P1-P12 | draft-dfly B=5 K=4 with the prompt cache and the slot checkpoints, `-ub 32`, each request checked against an R derived from the generic path (the derivation is in the code): exact repeat after a short and a long answer, without checkpoints, N=20; partial prefixes around the SWA window, the ubatch and 4m+-1; a shorter prompt, an edit before or after a checkpoint, zero match; a switch of session through the checkpoint at the end of a shared prefix; the continuation after a stop on draft 1, draft 4, the correction, the bonus and the limit; the cache off for the server or the request; sampling changes; N=1, `n_predict` 0/1, C=32, early returns; a failed checkpoint restore (P10); a sleep (P12). Each P1-P9 request also runs on K = 0, recorded in `ar-control.json` | + +| R1-R13 | the RAM cache, B=5 K=4 and K = 0, `--cache-ram 256 --cache-ram-min-drop 32 --cache-ram-min-gain 16` (the thresholds scaled to n_swa 32), each request against the R, the decisions and the cached prompts derived in the code: sessions that come back only through the RAM cache (`ram`, `ram_checkpoint`, a full match at the window edge) and the default thresholds (R1); the save by n_drop, the ratio rule and the LRU branch, 512 by default (R2); the T_load edge and the two selection traps, an entry with a larger LCP but no larger R, and one that restores nothing (R3); a short or empty save (R4); a failed load in the target or the draft state removes the entry and clears the slot (R5); the dedup by R (R6); the size limit and the eviction, fewer checkpoints (R7); the save after each stop (R8); an agent fan-out in turn and round robin (R9); a sleep (R10); random sequences of two seeds, checked by G10 (R12); a checkpoint made right after a resume is skipped (R13) | + +The cache checks of a P request: G1 `cache_n = R`, `prompt_n = N - R` and the metric line; G2 the first evaluated +position q = R, the memory ends at q - 1 and the SWA cache holds `max(0, q - n_swa + 1)`; G3 the expected checkpoint +restored with its recorded range; G4 the first propose with K_step > 0 at a = N, `query_pos = N - 1`, status OK; +G5 `check_rounds`; G6 after the release `seq_pos_max + 1 = n_tokens = pos_next`; G7 the erased checkpoints; G8 the +server keeps serving. Every request with the cache also gets: G9 the cached prompts after the update (E, swa_pos_min, +checkpoints), none empty, a loaded one gone; G10 `r_after` and the `r_slot` or `r_entry` of the loaded prompt equal R; +G11 the save and load decisions follow the thresholds and the values of the line; G12 after a load the slot has the +checkpoints and the SWA start of the entry. diff --git a/tests/dfly-server/run_dfly_init_tests.py b/tests/dfly-server/run_dfly_init_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..eeac8df7f036fd61a17aababf92276e4fb0a0b81 --- /dev/null +++ b/tests/dfly-server/run_dfly_init_tests.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +# Initialization-level tests of draft-dfly (S6b), see README.md. Not part of ctest. +# +# usage: run_dfly_init_tests.py --bin --pair --work --summary + +import argparse +import json +import os +import random +import re +import subprocess +import sys +import time + +import requests + +HTTP = requests.Session() +HTTP.trust_env = False + +SANITIZER = re.compile(r'AddressSanitizer|LeakSanitizer|UndefinedBehaviorSanitizer|runtime error:') +METRIC = re.compile(r'prefix cache: prefix_match_tokens = (\d+), prefix_reused_tokens = (\d+), prefix_replayed_tokens = (\d+), ' + r'restore_source = (\w+), cache_fallback_reason = (\w+)') + +# a configuration draft-dfly runs with K > 0, the caches off; plans 5.2 and 5.3 allow the prompt cache, the slot checkpoints and the RAM cache +GOOD = ['--parallel', '1', '--fit', 'off', '--no-cache-prompt', '--cache-ram', '0', '--ctx-checkpoints', '0', '--no-context-shift'] + + +def rand_prompt(seed, n): + rng = random.Random(seed) + return [rng.randrange(5, 120) for _ in range(n)] + + +class Ctx: + def __init__(self, opts): + self.opts = opts + self.rows = [] + self.port = 18800 + self.sanitizer = [] + + def add(self, case, ok, info): + self.rows.append((case, ok, info)) + print(('PASS ' if ok else 'FAIL ') + case + ': ' + info, flush=True) + + def path(self, name): + return os.path.join(self.opts.pair, name) + + def scan(self, name, text): + hits = [l for l in text.splitlines() if SANITIZER.search(l)] + if hits: + self.sanitizer.append((name, hits[:3])) + + def server(self, name, args, env=None, expect_start=True, keep=False, timeout=240): + """start llama-server; returns (started, proc or None, log text so far, log path)""" + self.port += 1 + log_path = os.path.join(self.opts.work, name + '.log') + logf = open(log_path, 'w') + e = dict(os.environ) + e['ASAN_OPTIONS'] = 'detect_leaks=0' + e.update(env or {}) + cmd = [os.path.join(self.opts.bin, 'llama-server'), '--port', str(self.port), '-t', '8', '-c', '1024'] + args + p = subprocess.Popen(cmd, stdout=logf, stderr=subprocess.STDOUT, env=e) + started = False + deadline = time.time() + timeout + while time.time() < deadline: + if p.poll() is not None: + break + try: + if HTTP.get(f'http://127.0.0.1:{self.port}/health', timeout=2).json().get('status') == 'ok': + started = True + break + except Exception: + pass + time.sleep(0.3) + if not keep or not started: + if p.poll() is None: + p.terminate() + try: + p.wait(60) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + logf.close() + text = open(log_path, errors='replace').read() + self.scan(name, text) + return started, None, text, p.returncode + return started, (p, logf, log_path), None, None + + def stop(self, name, h): + p, logf, log_path = h + p.terminate() + try: + p.wait(60) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + logf.close() + text = open(log_path, errors='replace').read() + self.scan(name, text) + return text + + def url(self, path): + return f'http://127.0.0.1:{self.port}{path}' + + def expect_fail(self, case, args, needles): + started, _, text, rc = self.server(case.replace(' ', '_').replace('/', '_'), args) + found = [n for n in needles if n in text] + ok = not started and rc not in (0, None) and len(found) == len(needles) + err = [l for l in text.splitlines() if (' E ' in l or 'error' in l.lower()) and ('dfly' in l.lower() or 'draft' in l.lower())] + self.add(case, ok, f'exit {rc}, needles {found}/{needles}; {err[-1][:300] if err else ""}') + + +def run(opts): + c = Ctx(opts) + T = ['-m', c.path('tiny-target.gguf')] + D5 = T + ['-md', c.path('tiny-dfly-b5.gguf')] + D8 = T + ['-md', c.path('tiny-dfly-b8.gguf')] + D3 = T + ['-md', c.path('tiny-dfly-b3.gguf')] + + # K = 0 with the default fit (on), parallel and caches: starts as the target alone + started, h, _, _ = c.server('k0_fit_on', D8 + ['--spec-draft-n-max', '0'], keep=True) + if started: + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(1, 16), 'n_predict': 8, 'temperature': 0}).json() + text = c.stop('k0_fit_on', h) + ok = ('DFly disabled, target-only: --spec-draft-n-max 0' in text and 'loading draft model' not in text + and 'DFly capture enabled' not in text and js.get('timings', {}).get('predicted_n') == 8) + c.add('K=0 with fit on', ok, f'started, "DFly disabled" logged, no draft loaded, {js.get("timings", {}).get("predicted_n")} tokens') + else: + c.add('K=0 with fit on', False, 'did not start') + + # K = 0 skips the K > 0 checks, also --swa-full and --slot-save-path + started, h, _, _ = c.server('k0_swa_full_slot_save', D8 + ['--spec-draft-n-max', '0', '--swa-full', '--slot-save-path', opts.work], keep=True) + if started: + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(4, 16), 'n_predict': 8, 'temperature': 0}).json() + text = c.stop('k0_swa_full_slot_save', h) + ok = 'DFly disabled, target-only: --spec-draft-n-max 0' in text and js.get('timings', {}).get('predicted_n') == 8 + c.add('K=0 with --swa-full and --slot-save-path', ok, f'started, {js.get("timings", {}).get("predicted_n")} tokens') + else: + c.add('K=0 with --swa-full and --slot-save-path', False, 'did not start') + + # K > 0: each missing setting fails the load and names the setting + def without(*drop): + a, i = [], 0 + while i < len(GOOD): + if GOOD[i] in drop: + i += 1 if GOOD[i].startswith('--no-') else 2 + continue + a.append(GOOD[i]) + i += 1 + return a + c.expect_fail('K>0 fit on', D8 + without('--fit'), ['--fit off']) + # design 4.2: several slots need one KV stream, one ubatch per decode and the slots within the pool (the server + # sets 4 slots and -kvu when --parallel is not given) + c.expect_fail('K>0 parallel unset', D8 + without('--parallel'), ['--batch-size equal to --ubatch-size', 'they are 2048 and 512']) + c.expect_fail('K>0 parallel 2', D8 + without('--parallel') + ['--parallel', '2'], ['-kvu (--kv-unified)', 'n_parallel is 2']) + c.expect_fail('K>0 parallel 2 -kvu -b 64 -ub 32', D8 + without('--parallel') + ['--parallel', '2', '-kvu', '-b', '64', '-ub', '32'], + ['--batch-size equal to --ubatch-size']) + c.expect_fail('K>0 parallel 16 -kvu -ub 64', D8 + without('--parallel') + ['--parallel', '16', '-kvu', '-b', '64', '-ub', '64'], + ['n_parallel * (1 + K) = 80']) + c.expect_fail('K>0 parallel 2 over the pool', D8 + without('--parallel') + ['--parallel', '2', '-kvu', '-b', '64', '-ub', '64'], + ['--kv-unified-per-slot of at most n_ctx / n_parallel = 512']) + for name, extra, n_slots in (('K>0 parallel 2 -kvu, 512 per slot', ['--parallel', '2', '-kvu', '--kv-unified-per-slot', '512'], 2), + ('K>0 parallel unset, 256 per slot', ['--kv-unified-per-slot', '256'], 4)): + started, h, _, _ = c.server(name.replace(' ', '_').replace(',', ''), D8 + without('--parallel') + extra + ['-b', '64', '-ub', '64'], keep=True) + if started: + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(5, 16), 'n_predict': 8, 'temperature': 0, 'ignore_eos': True}).json() + text = c.stop(name, h) + ok = f'initializing, n_slots = {n_slots}' in text and 'DFly capture enabled' in text and js.get('timings', {}).get('predicted_n') == 8 + c.add(name, ok, f'started, n_slots {n_slots} logged: {f"n_slots = {n_slots}" in text}, {js.get("timings", {}).get("predicted_n")} tokens') + else: + c.add(name, False, 'did not start') + + # plan 5.3: the RAM cache with the default size and thresholds. The entry of A = 400 (E 407, P 375) restores 395 for A + # again through (364, 395, 396): pos_eval 399, threshold 369; the gain over the slot (Z) is 395 >= 256 + started, h, _, _ = c.server('K0_cache_ram_on', D8 + without('--cache-ram', '--no-cache-prompt', '--ctx-checkpoints'), keep=True) + if started: + A, Z = rand_prompt(20, 400), rand_prompt(21, 60) + body = {'temperature': 0, 'ignore_eos': True, 'n_predict': 8} + rs = [HTTP.post(c.url('/completion'), json=dict(body, prompt=p)).json() for p in (A, Z, A)] + text = c.stop('K0_cache_ram_on', h) + m = METRIC.findall(text) + pc = re.findall(r'prompt cache: cache_save_decision = (\w+), .*cache_load_decision = (\w+), r_slot = (-?\d+), r_entry = (-?\d+)', text) + got = (rs[2].get('timings', {}).get('cache_n'), m[2] if len(m) == 3 else None, pc[2] if len(pc) == 3 else None) + exp = (395, ('400', '395', '5', 'ram_checkpoint', 'window_check'), ('saved', 'loaded', '0', '395')) + ok = got == exp and all(r.get('timings', {}).get('predicted_n') == 8 for r in rs) and 'DFly capture enabled' in text + c.add('K>0 cache_ram on', ok, f'third request cache_n {got[0]}, metric {got[1]}, prompt cache {got[2]}, expected {exp}') + else: + c.add('K>0 cache_ram on', False, 'did not start') + + # plan 5.2: the prompt cache and the slot checkpoints start, and a repeated prompt reuses the slot + # expected R (n_swa 32): a full match of N = 100 reuses N - 1 in the slot; after 300 generated tokens with -ub 32 + # the 256 SWA cells no longer hold position 68, so the checkpoint (64, 95, 96) made 4 tokens before the end gives 95 + def cache_case(case, args, G1, R_exp, src_exp, why_exp): + name = case.replace(' ', '_').replace('/', '_') + started, h, _, _ = c.server(name, args, keep=True) + if not started: + c.add(case, False, 'did not start') + return + p = rand_prompt(10, 100) + body = {'prompt': p, 'temperature': 0, 'ignore_eos': True} + r1 = HTTP.post(c.url('/completion'), json=dict(body, n_predict=G1)).json() + r2 = HTTP.post(c.url('/completion'), json=dict(body, n_predict=8)).json() + text = c.stop(name, h) + m = METRIC.findall(text) + got = (r2.get('timings', {}).get('cache_n'), m[-1] if len(m) == 2 else None) + exp = (R_exp, ('100', str(R_exp), str(100 - R_exp), src_exp, why_exp)) + ok = (got == exp and r1.get('timings', {}).get('predicted_n') == G1 and r2.get('timings', {}).get('predicted_n') == 8 + and 'DFly capture enabled' in text) + c.add(case, ok, f'second request cache_n {got[0]}, metric {got[1]}, expected {exp}') + cache_case('K>0 cache_prompt on', D8 + without('--no-cache-prompt'), 8, 99, 'slot', 'none') + cache_case('K>0 ctx_checkpoints 4', D8 + without('--no-cache-prompt', '--ctx-checkpoints') + ['--ctx-checkpoints', '4', '-ub', '32'], + 300, 95, 'checkpoint', 'window_check') + cache_case('K>0 ctx_checkpoints default', D8 + without('--no-cache-prompt', '--ctx-checkpoints') + ['-ub', '32'], + 300, 95, 'checkpoint', 'window_check') + c.expect_fail('K>0 swa_full', D8 + GOOD + ['--swa-full'], ['no --swa-full']) + c.expect_fail('K>0 slot_save_path', D8 + GOOD + ['--slot-save-path', opts.work], ['no --slot-save-path']) + c.expect_fail('K>0 context shift on', D8 + without('--no-context-shift') + ['--context-shift'], ['--no-context-shift']) + c.expect_fail('K>0 K/V types differ', D8 + GOOD + ['--cache-type-k', 'f16', '--cache-type-v', 'q8_0'], ['--cache-type-k and --cache-type-v']) + c.expect_fail('K=4 with -ub 4', D8 + GOOD + ['-ub', '4'], ['--ubatch-size of at least 5']) + c.expect_fail('K>0 mmproj', D8 + GOOD + ['--mmproj', c.path('tiny-dfly-b3.gguf')], ['--no-mmproj']) + c.expect_fail('draft-dfly on a non-DFly draft', T + ['-md', c.path('tiny-target.gguf'), '--spec-type', 'draft-dfly'] + GOOD, + ['needs a hy_v4_next_dfly draft model']) + c.expect_fail('draft-dflash on a DFly draft', D8 + GOOD + ['--spec-type', 'draft-dflash'], ['conflicts with the hy_v4_next_dfly draft']) + c.expect_fail('bad schema', T + ['-md', c.path('tiny-dfly-bad-schema.gguf')] + GOOD, ['hy_v4_next_dfly.schema_version']) + c.expect_fail('bad B', T + ['-md', c.path('tiny-dfly-bad-b.gguf')] + GOOD, ['hy_v4_next_dfly.block_size']) + c.expect_fail('missing B', T + ['-md', c.path('tiny-dfly-bad-nob.gguf')] + GOOD, ['hy_v4_next_dfly.block_size is missing']) + c.expect_fail('bad causal', T + ['-md', c.path('tiny-dfly-bad-causal.gguf')] + GOOD, ['hy_v4_next_dfly.attention.causal']) + + # K omitted: B = 8 gives 4, B = 3 gives 2; the log, the target outputs and the DFly ubatch agree + for name, args, k in (('B=8 K omitted', D8, 4), ('B=3 K omitted', D3, 2)): + started, h, _, _ = c.server(name.replace(' ', '_').replace('=', ''), args + GOOD, keep=True) + if not started: + c.add(name, False, 'did not start') + continue + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(2, 20), 'n_predict': 12, 'temperature': 0}).json() + text = c.stop(name.replace(' ', '_').replace('=', ''), h) + m = re.search(r'DFly: B = (\d+), causal = true, K_requested = 4 \(default\), K_effective = (\d+), W_max = (\d+), target layers = \[([^\]]*)\], ' + r'target K cache = (\S+), shared output = (\S+), target outputs = (\d+), DFly n_ubatch = (\d+), DFly attention = FA off', text) + ok = (m is not None and int(m.group(2)) == k and int(m.group(3)) == k + 1 and int(m.group(7)) == k + 1 and int(m.group(8)) == k + 1 + and js.get('timings', {}).get('predicted_n') == 12) + c.add(name, ok, (m.group(0)[:260] if m else 'no DFly startup line') + (f'; clipped warning {"exceeds the block size" in text}' if k == 2 else '')) + + # sleep and resume: B = 5, K = 7 stays requested 7, effective 4 + started, h, _, _ = c.server('sleep', D5 + GOOD + ['--spec-draft-n-max', '7', '--sleep-idle-seconds', '1'], keep=True) + if started: + time.sleep(4) + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(3, 20), 'n_predict': 12, 'temperature': 0}).json() + text = c.stop('sleep', h) + n_line = len(re.findall(r'K_requested = 7 \(cli\), K_effective = 4, W_max = 5', text)) + n_sleep = text.count('server is entering sleeping state') + ok = n_line >= 4 and n_sleep >= 1 and js.get('timings', {}).get('predicted_n') == 12 + c.add('sleep resume B=5 K=7', ok, f'{n_sleep} sleeps, {n_line} lines with requested 7 (cli) / effective 4 (prepare and startup, before and after), request {js.get("timings", {}).get("predicted_n")} tokens') + else: + c.add('sleep resume B=5 K=7', False, 'did not start') + + # a large absolute position: the propose graph stays W wide (hook log, build-asan) + h4 = os.path.join(opts.work, 'longpos.h4.jsonl') + if os.path.exists(h4): + os.remove(h4) + started, h, _, _ = c.server('longpos', D5 + GOOD, env={'LLAMA_DFLY_TEST_LOG': h4}, keep=True) + if started: + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(4, 1000), 'n_predict': 16, 'temperature': 0, 'ignore_eos': True}).json() + c.stop('longpos', h) + rounds = [json.loads(l) for l in open(h4)] if os.path.exists(h4) else [] + spec = [r for r in rounds if r['kind'] == 'spec'] + ok = bool(spec) and all(r['W'] <= 5 and r['propose'] == 0 for r in spec) and max(r['a'] for r in spec) > 1000 + c.add('large absolute position', ok, f'{len(spec)} spec rounds at a {spec[0]["a"] if spec else None}..{spec[-1]["a"] if spec else None}, ' + f'W {sorted(set(r["W"] for r in spec))}, all propose OK {all(r["propose"] == 0 for r in spec)}') + else: + c.add('large absolute position', False, 'did not start') + + # request checks: an error for the request, the server keeps serving + started, h, _, _ = c.server('requests', D5 + GOOD, keep=True) + if started: + res = {} + for name, extra in (('n_cmpl', {'n_cmpl': 2}), + ('n_cache_reuse', {'n_cache_reuse': 8}), ('backend_sampling', {'backend_sampling': True})): + r = HTTP.post(c.url('/completion'), json=dict({'prompt': rand_prompt(5, 16), 'n_predict': 8, 'temperature': 0}, **extra)) + js = r.json() + msg = js.get('error', {}).get('message', '') if isinstance(js.get('error'), dict) else '' + # n_cmpl > n_parallel (1) is already refused by the request schema + res[name] = (r.status_code != 200 and ('draft-dfly does not support' in msg or name == 'n_cmpl'), msg) + js = HTTP.post(c.url('/completion'), json={'prompt': rand_prompt(5, 16), 'n_predict': 8, 'temperature': 0, 'ignore_eos': True}).json() + # plan 5.2: cache_prompt is accepted; the server runs with --no-cache-prompt, so only the second request reuses + p = rand_prompt(6, 100) + body = {'prompt': p, 'n_predict': 8, 'temperature': 0, 'ignore_eos': True, 'cache_prompt': True} + rc1 = HTTP.post(c.url('/completion'), json=body) + rc2 = HTTP.post(c.url('/completion'), json=body) + c.stop('requests', h) + for name, (ok, msg) in res.items(): + c.add(f'request {name}', ok, msg[:160]) + c.add('request after the rejected ones', js.get('timings', {}).get('predicted_n') == 8, f'{js.get("timings", {}).get("predicted_n")} tokens') + n1 = rc1.json().get('timings', {}).get('cache_n') if rc1.status_code == 200 else None + n2 = rc2.json().get('timings', {}).get('cache_n') if rc2.status_code == 200 else None + c.add('request cache_prompt accepted', rc1.status_code == 200 and rc2.status_code == 200 and n2 == 99, + f'status {rc1.status_code}/{rc2.status_code}, cache_n {n1}/{n2} (expected 99 on the second)') + else: + c.add('request checks', False, 'did not start') + + # llama-cli: --no-cache-prompt is known, the embedded server runs DFly and exits + def cli(name, args): + log = os.path.join(opts.work, name + '.log') + # -lv 4: the CLI hides the server log otherwise + cmd = [os.path.join(opts.bin, 'llama-cli')] + D5 + ['--spec-type', 'draft-dfly', '-c', '1024', '-t', '8', '-n', '16', '--temp', '0', + '-p', 'hello world', '-st', '--simple-io', '-lv', '4'] + args + with open(log, 'w') as f: + try: + r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, timeout=600, + env=dict(os.environ, ASAN_OPTIONS='detect_leaks=0')) + rc = r.returncode + except subprocess.TimeoutExpired: + rc = 'timeout' + text = open(log, errors='replace').read() + c.scan(name, text) + return rc, text + rc, text = cli('cli', GOOD) + ok = (rc == 0 and 'invalid argument' not in text and 'DFly capture enabled' in text and 'K_effective = 4' in text + and 'tokens per round (sum M / rounds)' in text) + c.add('llama-cli --no-cache-prompt', ok, f'exit {rc}, DFly capture enabled {"DFly capture enabled" in text}, ' + f'round statistics printed {"tokens per round (sum M / rounds)" in text}') + rc, text = cli('cli-cache-prompt', without('--no-cache-prompt')) + ok = rc == 0 and 'does not support this configuration' not in text and 'DFly capture enabled' in text + c.add('llama-cli without --no-cache-prompt', ok, f'exit {rc}, DFly capture enabled {"DFly capture enabled" in text}') + rc, text = cli('cli-cache-ram', without('--no-cache-prompt', '--cache-ram')) + ok = rc == 0 and 'does not support this configuration' not in text and 'DFly capture enabled' in text + c.add('llama-cli with the default --cache-ram', ok, f'exit {rc}, DFly capture enabled {"DFly capture enabled" in text}') + + # router and llama-speculative refuse DFly + c.expect_fail('router with draft-dfly', ['--spec-type', 'draft-dfly', '-md', c.path('tiny-dfly-b5.gguf')], ['draft-dfly is not supported in router mode']) + c.expect_fail('router with a DFly draft', ['-md', c.path('tiny-dfly-b5.gguf')], ['draft-dfly is not supported in router mode']) + spec_log = os.path.join(opts.work, 'speculative.log') + with open(spec_log, 'w') as f: + r = subprocess.run([os.path.join(opts.bin, 'llama-speculative')] + D5 + ['-p', 'hello', '-n', '8'], stdout=f, stderr=subprocess.STDOUT, + timeout=300, env=dict(os.environ, ASAN_OPTIONS='detect_leaks=0')) + text = open(spec_log, errors='replace').read() + c.add('llama-speculative with a DFly draft', r.returncode != 0 and 'draft-dfly is not supported here' in text, f'exit {r.returncode}') + + c.add('sanitizer', not c.sanitizer, f'reports {c.sanitizer}' if c.sanitizer else 'no ASan/UBSan report') + lines = [('PASS ' if ok else 'FAIL ') + case + ': ' + info for case, ok, info in c.rows] + n_fail = sum(1 for _, ok, _ in c.rows if not ok) + lines.append(f'== {len(c.rows) - n_fail}/{len(c.rows)} passed') + with open(opts.summary, 'w') as f: + f.write('\n'.join(lines) + '\n') + print(lines[-1]) + return n_fail == 0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--bin', required=True) + ap.add_argument('--pair', required=True) + ap.add_argument('--work', required=True) + ap.add_argument('--summary', required=True) + opts = ap.parse_args() + os.makedirs(opts.work, exist_ok=True) + sys.exit(0 if run(opts) else 1) + + +if __name__ == '__main__': + main() diff --git a/tests/dfly-server/run_dfly_server_tests.py b/tests/dfly-server/run_dfly_server_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..d694eaee96feb4b04b29c36cb876d39712d1e789 --- /dev/null +++ b/tests/dfly-server/run_dfly_server_tests.py @@ -0,0 +1,2149 @@ +#!/usr/bin/env python3 +# Server-level tests of draft-dfly on the tiny pair (see README.md). Not part of ctest. +# +# usage: run_dfly_server_tests.py --server build-asan/bin/llama-server --pair --work --summary [--cases L1,L2,...] +# [--cache-mode off|primed|carry] + +import argparse +import json +import os +import random +import re +import subprocess +import sys +import threading +import time + +import requests + +EOS = 111 +CKPT_MADE = re.compile(r'created context checkpoint \d+ of \d+ \(pos_min = (-?\d+), pos_max = (-?\d+), n_tokens = (\d+)') +HOOK_RESTORED = re.compile(r'test hook: checkpoint restored: recorded pos_min = (-?\d+), pos_max = (-?\d+), memory pos_min = (-?\d+), pos_max = (-?\d+)') +HOOK_DECODE = re.compile(r'test hook: before prompt decode: q = (-?\d+), memory pos_min = (-?\d+), pos_max = (-?\d+), model n_swa = (\d+)') +SANITIZER = re.compile(r'AddressSanitizer|LeakSanitizer|UndefinedBehaviorSanitizer|runtime error:') +METRIC = re.compile(r'prefix cache: prefix_match_tokens = (\d+), prefix_reused_tokens = (\d+), prefix_replayed_tokens = (-?\d+), ' + r'restore_source = (\w+), cache_fallback_reason = (\w+)') +FIRST_PROPOSE = re.compile(r'first_propose_status = (-?\d+) \((\w+)\), pos = (-?\d+)') +CKPT_ERASED = re.compile(r'erased invalidated context checkpoint \(pos_min = (-?\d+), pos_max = (-?\d+), n_tokens = (\d+)') +# every line that changes the checkpoint list of the slot, in log order +CKPT_EVENT = re.compile(r'(created context checkpoint \d+ of \d+ \(pos_min = (-?\d+), pos_max = (-?\d+), n_tokens = (\d+)' + r'|superseding context checkpoint at n_tokens = (\d+)' + r'|(?:erased invalidated|erasing old|erasing) context checkpoint[^(]*\(pos_min = (-?\d+), pos_max = (-?\d+), n_tokens = (\d+)' + r'|clearing prompt with)') +# PC2: the RAM cache update of a task, and the slot and the cached prompts after it (dfly_test_log_prompt_cache) +PCACHE = re.compile(r'prompt cache: cache_save_decision = (\w+), n_drop = (-?\d+), cache_save_ms = [\d.]+, cache_load_decision = (\w+), ' + r'r_slot = (-?\d+), r_entry = (-?\d+), cache_restore_ms = [\d.]+, n_entries = (\d+)') +HOOK_PCACHE = re.compile(r'test hook: prompt cache: exact = (\d), by = (\w+), n_tokens = (-?\d+), lcp = (-?\d+), r_after = (-?\d+), ' + r'slot n_tokens = (-?\d+), pos_min = (-?\d+), ckpts \[([^\]]*)\], entries (\d+) \[([^\]]*)\]') +CKPT_TUPLE = re.compile(r'\((-?\d+),(-?\d+),(\d+)\)') + +HTTP = requests.Session() +HTTP.trust_env = False # no proxy for 127.0.0.1 + + +def piece(tok): + # the test vocab detokenizes a token as its id in hex + return format(tok, 'x') + + +def rand_prompt(seed, n): + rng = random.Random(seed) + return [rng.randrange(5, 120) for _ in range(n)] + + +def parse_pcache(seg): + """the prompt cache lines of a request: ([line dicts], [hook dicts])""" + lines = [{'save': m[0], 'n_drop': int(m[1]), 'load': m[2], 'r_slot': int(m[3]), 'r_entry': int(m[4]), 'n_entries': int(m[5])} + for m in PCACHE.findall(seg)] + hooks = [] + for m in HOOK_PCACHE.findall(seg): + ents = [] + for e in m[9].split(';'): + if not e: + continue + E, P, main, drft, ck = e.split(':', 4) + ents.append({'E': int(E), 'P': int(P), 'main': int(main), 'drft': int(drft), + 'ckpts': [tuple(map(int, c)) for c in CKPT_TUPLE.findall(ck)]}) + hooks.append({'exact': int(m[0]), 'by': m[1], 'n_tokens': int(m[2]), 'lcp': int(m[3]), 'r_after': int(m[4]), + 'slot_n_tokens': int(m[5]), 'pos_min': int(m[6]), 'ckpts': [tuple(map(int, c)) for c in CKPT_TUPLE.findall(m[7])], + 'n_entries': int(m[8]), 'entries': ents}) + return lines, hooks + + +def lcp(a, b): + n = 0 + while n < len(a) and n < len(b) and a[n] == b[n]: + n += 1 + return n + + +# off: the existing tests as they are; primed / carry (P11): the DFly servers run with the prompt cache and the slot +# checkpoints, see README.md +CACHE_MODE = 'off' +# carry: the comparisons with a reference sequence are recorded, not judged (the prefill shapes differ) +REF_NOTES = [] + + +def ref_ok(cond, what): + if CACHE_MODE == 'carry': + if not cond: + REF_NOTES.append(what) + return True + return cond + + +class Server: + port_next = 18700 + + def __init__(self, opts, name, draft, spec_type='draft-dfly', extra=(), cache=False, cache_ram=0, env_extra=None, mode='off'): + self.opts = opts + self.name = name + self.mode = mode # off, primed or carry, see CACHE_MODE + ex = list(extra) + k0 = '--spec-draft-n-max' in ex and ex[ex.index('--spec-draft-n-max') + 1] == '0' + self.dfly = draft is not None and spec_type == 'draft-dfly' and not k0 # a DFly slot, with H4 rounds + self.cur_script = {} + self.meta = [] # the slot tokens the client expects, None when unknown + self.meta_partial = False # meta is only a prefix of the slot tokens + self.ckpts = [] # (pos_min, pos_max, n_tokens) of the slot, from the server log + self.g_rows = [] # (request, errors) of the cache checks of every request in primed / carry + self.n_unpredicted = 0 + self.ram_loaded = 0 # carry: requests that took a cached prompt, the client model is unknown after the first + self.port = Server.port_next + Server.port_next += 1 + self.log_path = os.path.join(opts.work, name + '.log') + self.h4_path = os.path.join(opts.work, name + '.h4.jsonl') + self.script_path = os.path.join(opts.work, name + '.script') + for p in (self.h4_path, self.script_path): + if os.path.exists(p): + os.remove(p) + open(self.script_path, 'w').close() + # cache: the target alone with the prompt cache and the slot checkpoints on, the RAM cache off unless --cache-ram-mib (R11) + if cache and cache_ram == 0: + cache_ram = opts.cache_ram_mib + self.cache_ram = cache_ram if cache else 0 + + def opt(flag, dflt): + return int(ex[len(ex) - 1 - ex[::-1].index(flag) + 1]) if flag in ex else dflt + self.t_save = opt('--cache-ram-min-drop', 512) + self.t_gain = opt('--cache-ram-min-gain', 256) + caching = ['--cache-ram', str(cache_ram), '--ctx-checkpoints', '32'] if cache else ['--no-cache-prompt', '--cache-ram', '0', '--ctx-checkpoints', '0'] + cmd = [opts.server, '-m', os.path.join(opts.pair, 'tiny-target.gguf'), '--port', str(self.port), + '-c', '1024', '--parallel', '1', '--fit', 'off'] + caching + ['--no-context-shift', '-t', '8', '-lv', '4'] + if draft: + cmd += ['-md', os.path.join(opts.pair, draft)] + if spec_type: + cmd += ['--spec-type', spec_type] + cmd += list(extra) + self.cmd = cmd + env = dict(os.environ) + env['LLAMA_DFLY_TEST_LOG'] = self.h4_path + env['LLAMA_DFLY_TEST_SCRIPT'] = self.script_path + env['ASAN_OPTIONS'] = 'detect_leaks=0:abort_on_error=0' + env['UBSAN_OPTIONS'] = 'print_stacktrace=1' + env.update(env_extra or {}) + self.logf = open(self.log_path, 'w') + self.proc = subprocess.Popen(cmd, stdout=self.logf, stderr=subprocess.STDOUT, env=env) + deadline = time.time() + 300 + while time.time() < deadline: + if self.proc.poll() is not None: + raise RuntimeError(f'{name}: server exited with {self.proc.returncode}, see {self.log_path}') + try: + if HTTP.get(self.url('/health'), timeout=2).json().get('status') == 'ok': + return + except Exception: + pass + time.sleep(0.5) + raise RuntimeError(f'{name}: server did not start') + + def startup_value(self, pattern): + return int(re.search(pattern, self.log_text()).group(1)) + + def url(self, path): + return f'http://127.0.0.1:{self.port}{path}' + + def alive(self): + try: + return self.proc.poll() is None and HTTP.get(self.url('/health'), timeout=5).json().get('status') == 'ok' + except Exception: + return False + + def script(self, ref=None, r=None, wrong=None, propose_fail=None, verify_fail=None): + self.cur_script = {'propose_fail': set(propose_fail or [])} + lines = [] + if ref is not None: + lines.append('ref ' + ' '.join(map(str, ref))) + if r is not None: + lines.append('r ' + ' '.join(map(str, r))) + for k, v in (wrong or {}).items(): + lines.append(f'wrong {k} {v}') + if propose_fail: + lines.append('propose_fail ' + ' '.join(map(str, propose_fail))) + if verify_fail: + lines.append(f'verify_fail {verify_fail[0]} {verify_fail[1]}') + with open(self.script_path, 'w') as f: + f.write('\n'.join(lines) + '\n') + + def rounds_count(self): + if not os.path.exists(self.h4_path): + return 0 + with open(self.h4_path) as f: + return sum(1 for _ in f) + + def rounds_since(self, n0): + if not os.path.exists(self.h4_path): + return [] + with open(self.h4_path) as f: + lines = f.readlines() + return [json.loads(x) for x in lines[n0:]] + + def log_size(self): + self.logf.flush() + return os.path.getsize(self.log_path) + + def log_from(self, off): + self.logf.flush() + with open(self.log_path, 'rb') as f: + f.seek(off) + return f.read().decode(errors='replace') + + def post(self, body): + """one /completion request: (response, rounds, release lines, server log of the request)""" + n0 = self.rounds_count() + off = self.log_size() + res = HTTP.post(self.url('/completion'), json=body, timeout=600) + js = res.json() + js['_status'] = res.status_code + time.sleep(0.05) + lines = self.rounds_since(n0) + seg = self.log_from(off) + if self.mode != 'off': + self.track(body['prompt'], js, seg) + # the slot state after the request, see dfly_test_log_release + return js, [x for x in lines if x['kind'] != 'release'], [x for x in lines if x['kind'] == 'release'], seg + + def complete(self, prompt, n_predict, **kw): + body = {'prompt': prompt, 'n_predict': n_predict, 'temperature': 0, 'return_tokens': True, + 'cache_prompt': self.mode != 'off', 'seed': 42} + body.update(kw) + if self.mode == 'primed' and body['cache_prompt']: + # the same full prefill before every request, so that the request and its reference share one history + self.post({'prompt': prompt, 'n_predict': 1, 'temperature': 0, 'return_tokens': True, 'cache_prompt': False}) + exp = self.predict(prompt, body['cache_prompt']) if self.mode != 'off' else None + js, rounds, rel, seg = self.post(body) + js['_release'] = rel + if self.mode != 'off': + lines, _ = parse_pcache(seg) + if any(x['load'] == 'loaded' for x in lines): + # R11: the slot took a cached prompt, only G10 is judged; the slot model is unknown from here on + self.ram_loaded += 1 + if exp is not None: + self.n_unpredicted += 1 + t = js.get('timings', {}).get('cache_n', -1) + errs = [f'G10: r_entry {x["r_entry"]} != R {t}' for x in lines if x['r_entry'] != t] + errs += [f'G10: r_after {h["r_after"]} != R {t}' for h in parse_pcache(seg)[1] if h['r_after'] != t] + else: + errs = cache_checks(self, prompt, js, rounds, rel, seg, exp) + self.g_rows.append((f'N={len(prompt)} n_predict={n_predict}', errs)) + return js, rounds + + # ---- the client side model of the slot (P11): what the generic path does with the slot tokens and checkpoints + def track(self, prompt, js, seg): + for m in CKPT_EVENT.finditer(seg): + if m.group(2) is not None: + self.ckpts.append((int(m.group(2)), int(m.group(3)), int(m.group(4)))) + elif m.group(5) is not None: + self.ckpts = [c for c in self.ckpts if c[2] != int(m.group(5))] + elif m.group(6) is not None: + c = (int(m.group(6)), int(m.group(7)), int(m.group(8))) + if c in self.ckpts: + self.ckpts.remove(c) + else: + self.ckpts = [] + if js['_status'] == 200 and js.get('tokens'): + # plan 4.1/4.7: the last sampled token, or the stop token, is not in the slot + self.meta, self.meta_partial = list(prompt) + js['tokens'][:-1], False + elif 'clearing prompt with' in seg: + self.meta, self.meta_partial = [], False + else: + self.meta, self.meta_partial = None, False + + def predict(self, prompt, cache_prompt): + """expected L, R, source, reason and restored checkpoint, by the rules of the generic path; None if unknown""" + N = len(prompt) + if not cache_prompt: + return {'L': 0, 'R': 0, 'src': 'none', 'why': 'cache_off', 'restore': None, 'pos_eval': N - 1} + if self.meta is None or self.ram_loaded: + self.n_unpredicted += 1 + return None + L = lcp(self.meta, prompt) + if self.meta_partial and L == len(self.meta): + self.n_unpredicted += 1 + return None + if L == 0: + return {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match', 'restore': None, 'pos_eval': N - 1} + has_new = L < N + pos_eval = L if has_new else N - 1 + n_swa = self.startup_value(r'n_swa\s+= (\d+)') + thold = max(0, pos_eval - n_swa + 2) + # premise, checked by the decode hook: the SWA cells never wrapped, so the slot's SWA pos_min is 0 + if thold > 0: + R = L if has_new else N - 1 + return {'L': L, 'R': R, 'src': 'slot', 'why': 'none', 'restore': None, 'pos_eval': pos_eval} + for pmin, pmax, nt in reversed(self.ckpts): + if pmax > pos_eval: + continue + # the slot resumes at pmax, whose window starts at pmax - n_swa + 1 + if 0 < pmin and pmin > pmax - n_swa + 1: + continue + if pmin < thold or pmin == 0: + R = min(min(L, max(pmin + 1, pmax)), nt) + if R == N: + R -= 1 + return {'L': L, 'R': R, 'src': 'checkpoint' if R > 0 else 'none', 'why': 'window_check', 'restore': (pmin, pmax), + 'pos_eval': pos_eval} + return {'L': L, 'R': 0, 'src': 'none', 'why': 'no_checkpoint', 'restore': None, 'pos_eval': pos_eval} + + def log_text(self): + self.logf.flush() + with open(self.log_path, errors='replace') as f: + return f.read() + + def stop(self): + if self.proc.poll() is None: + self.proc.terminate() + try: + self.proc.wait(60) + except subprocess.TimeoutExpired: + self.proc.kill() + self.proc.wait() + self.logf.close() + with open(self.log_path, errors='replace') as f: + return [l for l in f if SANITIZER.search(l)] + + +class Result: + def __init__(self): + self.rows = [] + + def add(self, case, ok, info): + self.rows.append((case, ok, info)) + print(('PASS ' if ok else 'FAIL ') + case + ': ' + info, flush=True) + + +def check_rounds(rounds, prompt_len, ref=None, script_r=None, k_eff=None): + """State checks of plan 9.2/9.3 for the rounds of one request; returns (errors, info).""" + errs = [] + info = {'spec': 0, 'ar': 0, 'sumK': 0, 'sumr': 0, 'sumM': 0, 'sumM_spec': 0, 'cmp': 0, 'diverged': None, 'r_hist': {}} + prev = None + next_a = None + idx = 0 # script round: drafts with K_step > 0 + for i, rd in enumerate(rounds): + kind, a, M, toks = rd['kind'], rd['a'], rd['M'], rd['tokens'] + tag = f'round {i} ({kind} a={a})' + info['sumM'] += M + if rd['n_sample'] != M or rd['n_accept'] != M or len(toks) != M: + errs.append(f'{tag}: sample {rd["n_sample"]} accept {rd["n_accept"]} M {M}') + if i == 0: + if kind != 'prefill' or a != prompt_len - 1: + errs.append(f'{tag}: expected the prefill round at {prompt_len - 1}') + else: + if a != next_a: + errs.append(f'{tag}: a {a}, expected {next_a}') + if rd['anchor'] != prev['tokens'][-1]: + errs.append(f'{tag}: anchor {rd["anchor"]}, the last output was {prev["tokens"][-1]}') + if prev is not None and prev['stopped']: + errs.append(f'{tag}: a round after the stop') + script_i = None + if rd['k_step'] > 0: + script_i = idx + idx += 1 + if kind == 'spec': + K, r = rd['K'], rd['r'] + info['spec'] += 1 + info['sumK'] += K + info['sumr'] += r + info['sumM_spec'] += M + info['r_hist'][r] = info['r_hist'].get(r, 0) + 1 + if rd['propose'] != 0 or rd['query_pos'] != a - 1: + errs.append(f'{tag}: propose {rd["propose"]} query_pos {rd["query_pos"]}') + if K != rd['k_step'] or K < 1 or rd['W'] != K + 1 or len(rd['draft']) != K: + errs.append(f'{tag}: K {K} k_step {rd["k_step"]} W {rd["W"]}') + if k_eff is not None and K > k_eff: + errs.append(f'{tag}: K {K} > K_effective {k_eff}') + # r counts the drafts the outputs matched, in order + r_exp = 0 + while r_exp < min(M, K) and toks[r_exp] == rd['draft'][r_exp]: + r_exp += 1 + if r != r_exp: + errs.append(f'{tag}: r {r}, the outputs match {r_exp} drafts') + if not rd['stopped']: + if M != r + 1: + errs.append(f'{tag}: M {M} != r + 1 = {r + 1}') + if rd['seq_pos_max'] != a + r: + errs.append(f'{tag}: seq_pos_max {rd["seq_pos_max"]}, expected a + r = {a + r}') + if rd['n_tokens'] != a + r + 1: + errs.append(f'{tag}: n_tokens {rd["n_tokens"]}, expected {a + r + 1}') + if script_r is not None and script_i is not None and script_i < len(script_r): + if not ref_ok(r == min(script_r[script_i], K) or rd['stopped'], f'{tag}: r {r}, the script gives {script_r[script_i]}'): + errs.append(f'{tag}: r {r}, the script gives {script_r[script_i]}') + next_a = a + r + 1 + if ref is not None and info['diverged'] is None: + for j, t in enumerate(toks): + if a + 1 + j >= len(ref): + break + info['cmp'] += 1 + if ref[a + 1 + j] != t: + if not ref_ok(False, f'{tag}: W={K + 1} token {j} at pos {a + 1 + j} is {t}, ref {ref[a + 1 + j]}'): + errs.append(f'{tag}: W={K + 1} token {j} at pos {a + 1 + j} is {t}, ref {ref[a + 1 + j]}') + break + else: + info['ar'] += 1 + if not rd['stopped'] and (rd['seq_pos_max'] != a or rd['n_tokens'] != a + 1): + errs.append(f'{tag}: seq_pos_max {rd["seq_pos_max"]} n_tokens {rd["n_tokens"]}') + next_a = a + 1 + # W = 1: recorded, not asserted (TG-04b); later rows compare only while the prefix is the reference + if ref is not None and info['diverged'] is None and a + 1 < len(ref) and toks[0] != ref[a + 1]: + info['diverged'] = a + 1 + prev = rd + return errs, info + + +def cache_checks(srv, prompt, js, rounds, rel, seg, exp, erased=None): + """G1-G4, G6 and G7 of a request against the expected exp from Server.predict or a test; returns the errors""" + errs = [] + N = len(prompt) + if exp is None: + return [] + # a request that fails after its prompt (a forced verify failure) has no timings and no release, the rest holds + ok = js['_status'] == 200 + t = js.get('timings', {}) + R = exp['R'] + # G1: the reused length, the replayed length and the metric line + if ok and (t.get('cache_n') != R or t.get('prompt_n') != N - R): + errs.append(f'G1: cache_n {t.get("cache_n")} prompt_n {t.get("prompt_n")}, expected R {R}, N - R {N - R}') + mets = [tuple(m) for m in METRIC.findall(seg)] + want = (str(exp['L']), str(R), str(N - R), exp['src'], exp['why']) + if mets != [want]: + errs.append(f'G1: metric {mets}, expected {[want]}') + # G2: the first evaluated position, the end of the memory and the SWA window it attends to + n_swa = srv.startup_value(r'n_swa\s+= (\d+)') + dec = [tuple(map(int, m)) for m in HOOK_DECODE.findall(seg)] + if not dec: + errs.append('G2: no prompt decode logged') + else: + q, pmin, pmax = dec[0][:3] + if q != R: + errs.append(f'G2: q {q} != R {R}') + if q == 0 and (pmin, pmax) != (-1, -1): + errs.append(f'G2: q 0 with memory [{pmin}, {pmax}]') + if q > 0 and (pmax != q - 1 or not 0 <= pmin <= max(0, q - n_swa + 1)): + errs.append(f'G2: q {q}, memory [{pmin}, {pmax}], the window needs pos_min <= {max(0, q - n_swa + 1)} and pos_max {q - 1}') + # G3: the restored checkpoint, its recorded range against the memory, and not after the first evaluated position + restored = [tuple(map(int, m)) for m in HOOK_RESTORED.findall(seg)] + if exp['restore'] is None: + if restored: + errs.append(f'G3: restored {restored}, expected none') + elif len(restored) != 1 or restored[0][:2] != exp['restore'] or restored[0][:2] != restored[0][2:] or restored[0][1] > exp['pos_eval']: + errs.append(f'G3: restored (recorded, memory) {restored}, expected {exp["restore"]} with pos_max <= {exp["pos_eval"]}') + # G4: the first propose with K_step > 0 runs on the new snapshot of the anchor at N + if srv.dfly: + first = [rd for rd in rounds if rd['k_step'] > 0][:1] + fp = [tuple(m) for m in FIRST_PROPOSE.findall(seg)] + if ok and first and 0 not in srv.cur_script.get('propose_fail', set()): + f = first[0] + if f['kind'] != 'spec' or f['propose'] != 0 or f['a'] != N or f['query_pos'] != N - 1: + errs.append(f'G4: first round kind {f["kind"]} propose {f["propose"]} a {f["a"]} query_pos {f["query_pos"]}, N {N}') + if fp[:1] != [('0', 'ok', str(N))]: + errs.append(f'G4: first_propose_status {fp}, expected 0 (ok) at {N}') + # G6: after the release the memory ends at the slot tokens + if ok and (len(rel) != 1 or not rel[0]['seq_pos_max'] + 1 == rel[0]['n_tokens'] == rel[0]['pos_next']): + errs.append(f'G6: release {rel}') + # G7: the erased checkpoints + if erased is not None: + got = sorted(tuple(map(int, m)) for m in CKPT_ERASED.findall(seg)) + if got != sorted(erased): + errs.append(f'G7: erased {got}, expected {sorted(erased)}') + lines, hooks = parse_pcache(seg) + return errs + pcache_checks(srv, R, exp, lines, hooks) + + +def pcache_checks(srv, R, exp, lines, hooks): + """G9-G12 (PC2) of a request from its prompt cache line and hook; returns the errors""" + if len(hooks) != 1 or len(lines) != (1 if srv.cache_ram > 0 else 0): + return [f'G10: {len(lines)} prompt cache lines, {len(hooks)} hook lines'] + errs = [] + h = hooks[0] + ln = lines[0] if lines else None + # G10: the n_past that server_prompt_restorable() gives for the slot after the update, and for the slot or the + # loaded entry before it, is R; a failed checkpoint restore (injected) is not predicted + if exp['why'] == 'cache_off' or not h['exact']: + if h['r_after'] != -1: + errs.append(f'G10: r_after {h["r_after"]}, expected -1 (not computed)') + elif exp['why'] != 'restore_failed': + if h['r_after'] != R: + errs.append(f'G10: r_after {h["r_after"]} != R {R}') + if ln is not None: + r_line = ln['r_entry'] if ln['load'] == 'loaded' else 0 if ln['load'] == 'failed' else ln['r_slot'] + if r_line != R: + errs.append(f'G10: prompt cache line {ln["load"]} r_slot {ln["r_slot"]} r_entry {ln["r_entry"]}, R {R}') + if ln is not None: + # G11: the decisions follow the thresholds and the values of the line + if ln['n_drop'] != h['n_tokens'] - h['lcp'] or ln['n_entries'] != h['n_entries']: + errs.append(f'G11: n_drop {ln["n_drop"]} n_entries {ln["n_entries"]}, hook {h}') + if h['n_tokens'] == 0: + want_save = None if ln['save'] == 'empty' else 'empty' + else: + f_keep = h['lcp'] / h['n_tokens'] + save = h['by'] == 'lru' or f_keep < 0.5 or (srv.t_save > 0 and ln['n_drop'] >= srv.t_save) + want_save = None if abs(f_keep - 0.5) < 1e-4 or (ln['save'] != 'skipped') == save else ('a save' if save else 'skipped') + if want_save is not None: + errs.append(f'G11: save decision {ln["save"]}, expected {want_save} (by {h["by"]}, lcp {h["lcp"]}/{h["n_tokens"]}, T_save {srv.t_save})') + if h['exact'] and exp['why'] != 'cache_off': + gain = ln['r_entry'] - ln['r_slot'] + want = ('no_entry',) if ln['r_entry'] < 0 else ('loaded', 'failed') if gain >= max(1, srv.t_gain) else ('low_gain',) + if ln['load'] not in want: + errs.append(f'G11: load decision {ln["load"]}, expected {want} (r_slot {ln["r_slot"]}, r_entry {ln["r_entry"]}, T_load {srv.t_gain})') + elif h['exact'] and ln['load'] != 'not_tried': + errs.append(f'G11: load decision {ln["load"]} with cache_prompt false') + # the expected decisions of an R case + for k, v in exp.get('pc', {}).items(): + if ln[k] != v: + errs.append(f'G11: {k} {ln[k]}, expected {v}') + # G9: the cached prompts after the update, (E, P, checkpoint n_tokens), none empty + got = [(e['E'], e['P'], [c[2] for c in e['ckpts']]) for e in h['entries']] + if 'entries' in exp and got != [(E, P, list(ck)) for E, P, ck in exp['entries']]: + errs.append(f'G9: entries {got}, expected {exp["entries"]}') + if any(e['main'] <= 0 for e in h['entries']): + errs.append(f'G9: an empty entry {h["entries"]}') + # G12: the slot checkpoints after a load are those of the entry + if 'slot_ck' in exp and [c[2] for c in h['ckpts']] != list(exp['slot_ck']): + errs.append(f'G12: slot checkpoints {h["ckpts"]}, expected n_tokens {exp["slot_ck"]}') + if 'pos_min' in exp and h['pos_min'] != exp['pos_min']: + errs.append(f'G12: slot pos_min {h["pos_min"]} after the update, expected {exp["pos_min"]}') + return errs + + +def plan_steps(n, a_target, K): + """r of the rounds that move the anchor from position n to a_target.""" + D = a_target - n + assert D >= 0 + rs = [] + while D > 0: + s = min(K + 1, D) + rs.append(s - 1) + D -= s + return rs + + +def gen_of(js): + return js.get('tokens', []) + + +class Tests: + def __init__(self, opts): + self.opts = opts + self.res = Result() + self.servers = [] + self.sanitizer = [] + self.ar_obs = {} # P groups on K = 0: case -> observation, recorded and compared, not judged + + def retire(self, srv): + hits = srv.stop() + if hits: + self.sanitizer.append((srv.name, hits[:5])) + self.servers.remove(srv) + + def server(self, *args, **kw): + s = Server(self.opts, *args, **kw) + self.servers.append(s) + return s + + def stop_all(self): + for s in self.servers: + hits = s.stop() + if hits: + self.sanitizer.append((s.name, hits[:5])) + self.servers = [] + + def want(self, case): + return self.opts.cases is None or case in self.opts.cases + + def record(self, srv, prompt, n_predict, **kw): + srv.script() + js, rounds = srv.complete(prompt, n_predict, **kw) + return prompt + gen_of(js), js, rounds + + # ---- L1: real drafts after prefills of 16, 40 and 300 tokens + def l1(self, srv): + for n in (16, 40, 300): + prompt = rand_prompt(100 + n, n) + ref, js, rounds = self.record(srv, prompt, 260, ignore_eos=True) + errs, info = check_rounds(rounds, n, ref=None, k_eff=4) + js2, rounds2 = srv.complete(prompt, 200, ignore_eos=True) + errs2, info2 = check_rounds(rounds2, n, ref=ref, k_eff=4) + n_ok = sum(1 for rd in rounds2 if rd['kind'] == 'spec') + n_try = sum(1 for rd in rounds2 if rd['k_step'] > 0) + ok = (not errs and not errs2 and n_ok == n_try and len(gen_of(js2)) == 200 + and ref_ok(info2['diverged'] is None, f'L1 prefill {n}: diverged at {info2["diverged"]}')) + self.res.add(f'L1 prefill {n}', ok, + f'{len(rounds2)} rounds, propose OK {n_ok}/{n_try}, r hist {info2["r_hist"]}, {info2["cmp"]} W>=2 tokens == ref' + + ('' if ok else f'; errors {(errs + errs2)[:3]}')) + + # ---- L2: forced r + def l2(self, srv, K, label): + prompt = rand_prompt(240, 40) + ref, _, _ = self.record(srv, prompt, 400, ignore_eos=True) + pats = { + 'all reject x24': [0] * 24, + 'all accept x24': [K] * 24, + 'alternate x24': [K if i % 2 else 0 for i in range(24)], + 'cycle 0..K x4': [i % (K + 1) for i in range(4 * (K + 1))], + } + for name, rs in pats.items(): + # room for the scripted rounds at full K, the rounds after them use the real drafts + n_predict = 1 + sum(r + 1 for r in rs) + 2 * (K + 1) + srv.script(ref=ref, r=rs) + js, rounds = srv.complete(prompt, n_predict, ignore_eos=True) + errs, info = check_rounds(rounds, len(prompt), ref=ref, script_r=rs, k_eff=K) + spec = [rd for rd in rounds if rd['kind'] == 'spec'][:len(rs)] + got = [rd['r'] for rd in spec] + ok = (not errs and all(rd['K'] == K for rd in spec) + and ref_ok(got == rs and info['diverged'] is None and gen_of(js) == ref[len(prompt):len(prompt) + n_predict], + f'L2 {label} {name}: r {got[:12]}, diverged {info["diverged"]}')) + self.res.add(f'L2 {label} {name}', ok, + f'{len(spec)} scripted rounds at K={K}, r = {got[:12]}..., r == script {got == rs}, ' + f'{info["cmp"]} W>=2 tokens, output == ref {gen_of(js) == ref[len(prompt):len(prompt) + n_predict]}' + + ('' if ok else f'; errors {errs[:3]}')) + srv.script() + + # ---- L3: the table of plan 9.3, K = 4 + def l3(self, srv): + prompt = rand_prompt(300, 40) + ref, _, _ = self.record(srv, prompt, 200, ignore_eos=True) + rs = [0, 1, 2, 3, 4, 0] + srv.script(ref=ref, r=rs) + js, rounds = srv.complete(prompt, 40, ignore_eos=True) + errs, _ = check_rounds(rounds, len(prompt), ref=ref, script_r=rs, k_eff=4) + spec = [rd for rd in rounds if rd['kind'] == 'spec'] + table = [] + for i, rd in enumerate(spec[:5]): + a, r = rd['a'], rd['r'] + nxt = spec[i + 1] + row = {'r': r, 'new': rd['M'], 'kept_max': rd['seq_pos_max'], 'next_row': nxt['query_pos'] - a, + 'rm_from': (a + r + 1) if r < 4 else None, 'new_a': nxt['a']} + # carry: the state formulas of the r that ran, the scripted r is a reference comparison + ri = r if CACHE_MODE == 'carry' else i + ref_ok(r == i, f'L3 round {i}: r {r}') + exp = {'r': ri, 'new': ri + 1, 'kept_max': a + ri, 'next_row': ri, 'rm_from': (a + ri + 1) if ri < 4 else None, 'new_a': a + ri + 1} + if row != exp: + errs.append(f'r={i}: {row} != {exp}') + table.append(f'r={r}: new {rd["M"]}, kept max a+{rd["seq_pos_max"] - a}, next row {nxt["query_pos"] - a}, ' + f'rm from {"a+" + str(r + 1) if r < 4 else "none"}, new a a+{nxt["a"] - a}') + self.res.add('L3 plan 9.3 table K=4', not errs, ' | '.join(table) + ('' if not errs else f'; errors {errs[:3]}')) + + # ---- L4: plan 9.5 stops + def find_eos_prompt(self, srv, lo, hi): + for seed in range(1000, 1400): + prompt = rand_prompt(seed, 16) + srv.script() + js, _ = srv.complete(prompt, 120) + g = gen_of(js) + if g and g[-1] == EOS and lo <= len(g) - 1 <= hi: + return prompt, g + raise RuntimeError('no prompt with EOS in range') + + def l4(self, srv, ar): + K = 4 + prompt, gen = self.find_eos_prompt(srv, 12, 80) + n = len(prompt) + ref = prompt + gen + P = n + len(gen) - 1 # the EOS position + cases = [ # name, slot j of the EOS in the final round, script r of the final round, (M, r) + ('d1 matched EOG', 0, 4, (1, 1)), + ('d2 matched EOG', 1, 4, (2, 2)), + ('d4 matched EOG', 3, 4, (4, 4)), + ('d1,d2 matched, correction EOG', 2, 2, (3, 2)), + ('all matched, bonus EOG', 4, 4, (5, 4)), + ] + for name, j, r_last, (M_exp, r_exp) in cases: + rs = plan_steps(n, P - 1 - j, K) + [r_last] + srv.script(ref=ref, r=rs) + js, rounds = srv.complete(prompt, 400) + errs, info = check_rounds(rounds, n, ref=ref, script_r=rs, k_eff=K) + last = rounds[-1] + ok = (not errs and last['stopped'] and last['n_sample'] == last['M'] + and ref_ok(last['kind'] == 'spec' and (last['M'], last['r']) == (M_exp, r_exp) and gen_of(js) == gen + and js.get('stop_type') == 'eos', f'L4 {name}: last (M, r) ({last["M"]}, {last["r"]}), stop {js.get("stop_type")}')) + self.res.add(f'L4 {name}', ok, f'EOS at pos {P}, last round a={last["a"]} (M, r) = ({last["M"]}, {last["r"]}), ' + f'sample {last["n_sample"]}, {len(gen_of(js))} tokens, stop {js.get("stop_type")}' + ('' if ok else f'; errors {errs[:3]}')) + # a rejected EOS draft does not stop + rs = plan_steps(n, P - 3, K) + i_wrong = len(rs) - 1 if rs else 0 + rs_w = rs[:] + rs_w[i_wrong] = 0 + srv.script(ref=ref, r=rs_w + [4, 4], wrong={i_wrong: EOS}) + js, rounds = srv.complete(prompt, 400) + errs, _ = check_rounds(rounds, n, ref=ref, k_eff=K) + sr = [rd for rd in rounds if rd['kind'] == 'spec'] + hit = [rd for rd in sr if EOS in rd['draft'][rd['r']:rd['r'] + 1]] + ok = not errs and ref_ok(bool(hit) and not hit[0]['stopped'] and gen_of(js) == gen, 'L4 rejected EOS draft') + self.res.add('L4 rejected EOS draft', ok, f'round a={hit[0]["a"] if hit else None} draft {hit[0]["draft"] if hit else None} rejected, ' + f'continued to {len(gen_of(js))} tokens' + ('' if ok else f'; errors {errs[:3]}')) + # the first anchor is EOG + p0 = None + for seed in range(2000, 3000): + p = rand_prompt(seed, 16) + srv.script() + js, rounds = srv.complete(p, 50) + if gen_of(js) == [EOS]: + p0 = p + break + ok = p0 is not None and len(rounds) == 1 and rounds[0]['kind'] == 'prefill' and rounds[0]['stopped'] + self.res.add('L4 first anchor EOG', ok, f'prompt seed found {p0 is not None}, rounds {[rd["kind"] for rd in rounds]}, tokens {gen_of(js)}') + # ignore_eos: does not stop on the EOS, W >= 2 rows follow their own reference + ref_ie, _, _ = self.record(srv, prompt, 200, ignore_eos=True) + rs = [4] * 12 + srv.script(ref=ref_ie, r=rs) + js, rounds = srv.complete(prompt, 61, ignore_eos=True) + errs, info = check_rounds(rounds, n, ref=ref_ie, script_r=rs, k_eff=K) + ok = not errs and len(gen_of(js)) == 61 and EOS not in gen_of(js) and js.get('stop_type') == 'limit' + self.res.add('L4 ignore_eos', ok, f'{len(gen_of(js))} tokens past EOS pos {P}, stop {js.get("stop_type")}' + ('' if ok else f'; errors {errs[:3]}')) + # a stop string ending in an accepted draft token + gs = None + pieces = [piece(t) for t in ref_ie[n:]] + text = ''.join(pieces) + ends = [] + acc = 0 + for p in pieces: + acc += len(p) + ends.append(acc) + for g in range(12, 50): + word = pieces[g - 1] + pieces[g] + if text.find(word) + len(word) == ends[g]: + gs = g + break + if gs is not None: + rs = plan_steps(n, n + gs - 2, K) + [4] # token gs at slot j = 1 of a fully matched round + srv.script(ref=ref_ie, r=rs) + js, rounds = srv.complete(prompt, 200, ignore_eos=True, stop=[word]) + errs, _ = check_rounds(rounds, n, ref=ref_ie, k_eff=K) + last = rounds[-1] + ok = (not errs and last['stopped'] + and ref_ok(last['kind'] == 'spec' and (last['M'], last['r']) == (2, 2) and gen_of(js) == ref_ie[n:n + gs + 1] + and js.get('stop_type') == 'word', 'L4 stop string')) + self.res.add('L4 stop string on an accepted token', ok, f'stop "{word}" at token {gs}, last (M, r) = ({last["M"]}, {last["r"]}), ' + f'{len(gen_of(js))} tokens, stop {js.get("stop_type")}' + ('' if ok else f'; errors {errs[:3]}')) + else: + self.res.add('L4 stop string on an accepted token', False, 'no suitable stop string') + # n_predict 1 and 0, the counts of AR + for npred in (1, 0): + srv.script() + js, rounds = srv.complete(prompt, npred) + ja, _ = ar.complete(prompt, npred) + ok = len(gen_of(js)) == len(gen_of(ja)) and all(rd['kind'] != 'spec' for rd in rounds) + self.res.add(f'L4 n_predict={npred}', ok, f'DFly {len(gen_of(js))} tokens, AR {len(gen_of(ja))} tokens, rounds {[rd["kind"] for rd in rounds]}') + + # ---- L5: context and budget limits + def l5(self, srv32, ar32, srv): + prompt = rand_prompt(500, 21) + ref, _, _ = self.record(srv32, prompt, 100, ignore_eos=True) + srv32.script(ref=ref, r=[4, 4, 4]) + js, rounds = srv32.complete(prompt, 100, ignore_eos=True) + ja, _ = ar32.complete(prompt, 100, ignore_eos=True) + errs, _ = check_rounds(rounds, len(prompt), ref=ref, k_eff=4) + last = rounds[-1] + ok = (not errs and last['stopped'] and len(gen_of(js)) == len(gen_of(ja)) + and ref_ok(last['kind'] == 'spec' and last['a'] == 26 and last['K'] == 4 and last['M'] == 5, f'L5 last round a={last["a"]}')) + self.res.add('L5 C=32 K=4 a=26', ok, f'last round a={last["a"]} K={last["K"]} M={last["M"]} stopped {last["stopped"]}; ' + f'DFly {len(gen_of(js))} tokens, AR {len(gen_of(ja))} tokens' + ('' if ok else f'; errors {errs[:3]}')) + # the budget: K_step = min(K_eff, n_ctx - a - 2, R - 1) + prompt = rand_prompt(501, 40) + ref, _, _ = self.record(srv, prompt, 100, ignore_eos=True) + seqs = [] + ok = True + for npred in (8, 7, 3, 2): + srv.script(ref=ref, r=[4] * 10) + js, rounds = srv.complete(prompt, npred, ignore_eos=True) + errs, _ = check_rounds(rounds, len(prompt), ref=ref, k_eff=4) + n_gen = 0 + ks = [] + for rd in rounds: + if rd['kind'] != 'prefill': + R = npred - n_gen + dmax = min(1024 - rd['a'] - 2, R - 1) + k = min(4, dmax) if dmax > 0 else 0 + if rd['k_step'] != k or (dmax > 0 and rd['n_draft_max'] != dmax): + errs.append(f'a={rd["a"]}: k_step {rd["k_step"]} n_draft_max {rd["n_draft_max"]}, expected {k} {dmax}') + ks.append(rd['k_step']) + n_gen += rd['M'] + ok = ok and not errs and len(gen_of(js)) == npred + seqs.append(f'n_predict {npred}: K_step {ks}') + if errs: + seqs.append(f'errors {errs[:2]}') + self.res.add('L5 budget', ok, '; '.join(seqs)) + + # ---- L6: failures + def l6(self, srv): + prompt = rand_prompt(600, 40) + ref, _, _ = self.record(srv, prompt, 200, ignore_eos=True) + rs = [1, 2, 3, 0, 4, 2, 1, 3] + srv.script(ref=ref, r=rs, propose_fail=[2, 5]) + js, rounds = srv.complete(prompt, 40, ignore_eos=True) + errs, info = check_rounds(rounds, len(prompt), ref=None, k_eff=4) + tried = [rd for rd in rounds if rd['k_step'] > 0] + kinds = [(rd['kind'], rd['propose']) for rd in tried] + ok = (not errs and len(tried) > 6 and kinds[2] == ('ar', -2) and kinds[5] == ('ar', -2) + and kinds[3] == ('spec', 0) and kinds[6] == ('spec', 0) and tried[2]['W'] == 1) + self.res.add('L6 H2 propose failure', ok, f'rounds (kind, propose) {kinds[:8]}, W=1 token diverged at {info["diverged"]}' + + ('' if ok else f'; errors {errs[:3]}')) + for ret in (1, 2, -3): + srv.script(ref=ref, r=[1] * 10, verify_fail=(3, ret)) + n_log = len(srv.log_text()) + js, rounds = srv.complete(prompt, 40, ignore_eos=True) + log_new = srv.log_text()[n_log:] + err_resp = js['_status'] != 200 or 'error' in js + retried = 'retrying with smaller batch size' in log_new + srv.script() + js2, rounds2 = srv.complete(prompt, 200, ignore_eos=True) + errs2, info2 = check_rounds(rounds2, len(prompt), ref=ref, k_eff=4) + first = [rd for rd in rounds2 if rd['kind'] == 'spec'][:1] + ok = (err_resp and not retried and srv.alive() and not errs2 and bool(first) and first[0]['query_pos'] == len(prompt) - 1 + and ref_ok(gen_of(js2) == ref[len(prompt):len(prompt) + 200], f'L6 H3 ret={ret}: next request')) + self.res.add(f'L6 H3 verify ret={ret}', ok, f'error response {err_resp} ({js.get("error", {}).get("message", "") if isinstance(js.get("error"), dict) else ""}), ' + f'retry logged {retried}, server alive, next request == ref {gen_of(js2) == ref[len(prompt):len(prompt) + 200]}' + + ('' if ok else f'; errors {errs2[:3]}')) + + # ---- L7: capture order and a clean next request (plan 12.3 items 6 and 9) + def l7(self, srv): + log = srv.log_text() + i_warm = log.find('warming up the model') + i_probe = log.find('initializing, n_slots') + i_cap = log.find('DFly capture enabled') + ok = 0 <= i_warm < i_probe < i_cap + self.res.add('L7 capture_enable after warmup and seq_rm probe', ok, f'log offsets warmup {i_warm}, probe {i_probe}, capture {i_cap}') + + prompt_next = rand_prompt(700, 33) + ref_next, _, _ = self.record(srv, prompt_next, 60, ignore_eos=True) + prompt = rand_prompt(701, 40) + ref, _, _ = self.record(srv, prompt, 200, ignore_eos=True) + + def check_next(what): + srv.script() + js, rounds = srv.complete(prompt_next, 60, ignore_eos=True) + errs, _ = check_rounds(rounds, len(prompt_next), ref=ref_next, k_eff=4) + first = [rd for rd in rounds if rd['k_step'] > 0][:1] + ok = (not errs and bool(first) and first[0]['kind'] == 'spec' and first[0]['query_pos'] == len(prompt_next) - 1 + and ref_ok(gen_of(js) == ref_next[len(prompt_next):], f'L7 next request after {what}')) + self.res.add(f'L7 next request after {what}', ok, f'first propose {first[0]["propose"] if first else None} ' + f'query_pos {first[0]["query_pos"] if first else None}, output == ref {gen_of(js) == ref_next[len(prompt_next):]}' + + ('' if ok else f'; errors {errs[:3]}')) + + # a K_step = 0 round at the end of the budget + srv.script(ref=ref, r=[4, 4]) + js, rounds = srv.complete(prompt, 7, ignore_eos=True) + self.res.add('L7 request ends with K_step=0', ref_ok(rounds[-1]['kind'] == 'ar' and rounds[-1]['k_step'] == 0, 'L7 K_step=0'), + f'last round {rounds[-1]["kind"]} k_step {rounds[-1]["k_step"]}') + check_next('K_step=0') + # a failed propose in the last round + srv.script(ref=ref, r=[4, 4, 4], propose_fail=[1]) + js, rounds = srv.complete(prompt, 7, ignore_eos=True) + check_next('propose failure') + # cancelled while streaming + srv.script() + if srv.mode == 'primed': + srv.post({'prompt': prompt, 'n_predict': 1, 'temperature': 0, 'return_tokens': True, 'cache_prompt': False}) + n0 = srv.rounds_count() + off = srv.log_size() + with HTTP.post(srv.url('/completion'), json={'prompt': prompt, 'n_predict': 400, 'temperature': 0, 'stream': True, + 'cache_prompt': srv.mode != 'off', 'ignore_eos': True}, stream=True, timeout=600) as res: + n_chunks = 0 + for line in res.iter_lines(): + if line: + n_chunks += 1 + if n_chunks >= 5: + break + time.sleep(2.0) + n_cancel = srv.rounds_count() - n0 + if srv.mode != 'off': + # the slot holds the prompt and an unknown part of the output + srv.track(prompt, {'_status': 0}, srv.log_from(off)) + srv.meta, srv.meta_partial = list(prompt), True + self.res.add('L7 cancel', n_cancel < 300, f'{n_chunks} chunks read then closed, {n_cancel} rounds ran') + check_next('cancel') + # a verify error + srv.script(ref=ref, r=[1] * 10, verify_fail=(2, -3)) + srv.complete(prompt, 40, ignore_eos=True) + check_next('verify error') + + # ---- L8: sampling with a grammar + def l8(self, srv): + prompt = rand_prompt(800, 40) + srv.script() + # ignore_eos: the test vocab detokenizes the EOS as "6f", and the grammar would let it end the text early + js, rounds = srv.complete(prompt, 80, temperature=0.8, top_k=20, top_p=0.9, repeat_penalty=1.3, + grammar='root ::= [0-7]+', seed=1234, ignore_eos=True) + errs, info = check_rounds(rounds, len(prompt), ref=None, k_eff=4) + text = js.get('content', '') + ok = not errs and info['spec'] >= 30 and len(gen_of(js)) == 80 and re.fullmatch(r'[0-7]+', text) is not None + self.res.add('L8 sampling + grammar', ok, f'{info["spec"]} spec rounds (sample = accept = M each), r hist {info["r_hist"]}, ' + f'{len(gen_of(js))} tokens, text matches the grammar {re.fullmatch(r"[0-7]+", text) is not None}' + + ('' if ok else f'; errors {errs[:3]}')) + + # ---- L9: statistics + def l9(self, srv): + prompt = rand_prompt(900, 40) + ref, _, _ = self.record(srv, prompt, 200, ignore_eos=True) + runs = [('mixed r', dict(r=[0, 4, 2, 1, 3, 4, 0, 2] * 3, propose_fail=[5])), ('real drafts', None)] + for name, sc in runs: + if sc: + srv.script(ref=ref, **sc) + else: + srv.script() + n_log = len(srv.log_text()) + js, rounds = srv.complete(prompt, 70, ignore_eos=True) + time.sleep(0.2) + log_new = srv.log_text()[n_log:] + _, info = check_rounds(rounds, len(prompt), k_eff=4) + t = js.get('timings', {}) + m = re.findall(r'tokens per round \(sum M / rounds\) = +([0-9.]+)', log_new) + per = info['sumM_spec'] / info['spec'] if info['spec'] else 0.0 + ok = (t.get('draft_n') == info['sumK'] and t.get('draft_n_accepted') == info['sumr'] and t.get('predicted_n') == info['sumM'] + and m and abs(float(m[-1]) - per) < 0.006) + self.res.add(f'L9 statistics, {name}', ok, f'draft_n {t.get("draft_n")} = sum K {info["sumK"]}, accepted {t.get("draft_n_accepted")} = sum r {info["sumr"]}, ' + f'predicted_n {t.get("predicted_n")} = sum M {info["sumM"]} ({info["ar"]} AR/prefill rounds), printed sum M/rounds {m[-1] if m else None} vs {per:.2f}') + # a stopping round is counted once: the bonus EOG case + prompt, gen = self.find_eos_prompt(srv, 12, 80) + n = len(prompt) + P = n + len(gen) - 1 + rs = plan_steps(n, P - 5, 4) + [4] + srv.script(ref=prompt + gen, r=rs) + js, rounds = srv.complete(prompt, 400) + _, info = check_rounds(rounds, n, k_eff=4) + t = js.get('timings', {}) + ok = (t.get('draft_n') == info['sumK'] and t.get('draft_n_accepted') == info['sumr'] and t.get('predicted_n') == info['sumM'] + and rounds[-1]['stopped'] and rounds[-1]['M'] == 5) + self.res.add('L9 statistics with a stopping round', ok, f'draft_n {t.get("draft_n")}/{info["sumK"]}, accepted {t.get("draft_n_accepted")}/{info["sumr"]}, ' + f'predicted_n {t.get("predicted_n")}/{info["sumM"]}, last round M {rounds[-1]["M"]}') + + # ---- C1: SWA checkpoint coverage on the target alone (plan U03, I03) + def c1_case(self, srv, name, seed, M, G, n2, tail=0, want_ckpt=True): + n_swa = int(re.search(r'n_swa\s+= (\d+)', srv.log_text()).group(1)) + prompt = rand_prompt(seed, M) + n_log = len(srv.log_text()) + js1, _ = srv.complete(prompt, G, cache_prompt=True, ignore_eos=True) + seg1 = srv.log_text()[n_log:] + made = [tuple(map(int, m)) for m in CKPT_MADE.findall(seg1)] + new = rand_prompt(seed + 1, tail) + if tail and new[0] == prompt[n2]: + new[0] = 5 if prompt[n2] != 5 else 6 + prompt2 = prompt[:n2] + new + n_log = len(srv.log_text()) + js2, _ = srv.complete(prompt2, 4, cache_prompt=True, ignore_eos=True) + seg2 = srv.log_text()[n_log:] + restored = [tuple(map(int, m)) for m in HOOK_RESTORED.findall(seg2)] + dec = [tuple(map(int, m)) for m in HOOK_DECODE.findall(seg2)] + pos_eval = n2 - (0 if tail else 1) + errs = [] + if js1.get('_status') != 200 or len(gen_of(js1)) != G or js2.get('_status') != 200 or len(gen_of(js2)) != 4: + errs.append(f'requests: status {js1.get("_status")}/{js2.get("_status")}, tokens {len(gen_of(js1))}/{len(gen_of(js2))}') + if want_ckpt and not any(pmax == n2 for _, pmax, _ in made): + errs.append(f'setup: no checkpoint at pos_max {n2}, made {made}') + if not want_ckpt and made: + errs.append(f'checkpoints made {made}') + if not dec: + errs.append('no prompt decode logged') + else: + q, pmin = dec[0][0], dec[0][1] + # the first evaluated position q attends to [q - n_swa + 1, q - 1] + if not ((q == 0 and pmin == -1) or (q > 0 and 0 <= pmin <= max(0, q - n_swa + 1))): + errs.append(f'window: q {q}, memory pos_min {pmin} > {max(0, q - n_swa + 1)}') + # G10: server_prompt_restorable() of the slot gives R, -1 where it does not apply (--swa-full) + hooks = parse_pcache(seg2)[1] + r_want = js2.get('timings', {}).get('cache_n') if want_ckpt else -1 + if [h['r_after'] for h in hooks] != [r_want]: + errs.append(f'G10: r_after {[h["r_after"] for h in hooks]}, expected [{r_want}]') + for rmin, rmax, mmin, mmax in restored: + if (rmin, rmax) != (mmin, mmax): + errs.append(f'record: recorded [{rmin}, {rmax}], restored [{mmin}, {mmax}]') + if rmax > pos_eval: + errs.append(f'select: restored pos_max {rmax} > pos_eval {pos_eval}') + self.res.add(f'C1 {name}', not errs, f'n_swa {n_swa}, M {M}, gen {G}, new prompt {len(prompt2)} (LCP {n2}), checkpoints made (pos_min, pos_max, n_tokens) {made}, ' + f'restored (recorded, memory) {restored}, first decode (q, pos_min, pos_max) {dec[0][:3] if dec else None}' + ('' if not errs else f'; errors {errs}')) + + def c1(self): + srv = self.server('c1-cache', None, spec_type=None, cache=True, extra=['-ub', '32']) + self.c1_case(srv, 'full match, length = a checkpoint pos_max (I03 edge)', 1100, 100, 300, 95) + self.c1_case(srv, 'I03 edge after the SWA ring wrapped', 1200, 600, 300, 595) + self.c1_case(srv, 'full match inside the first window', 1300, 20, 300, 15) + self.c1_case(srv, 'partial match with new tokens', 1400, 100, 300, 95, tail=8) + full = self.server('c1-swa-full', None, spec_type=None, cache=True, extra=['-ub', '32', '--swa-full']) + self.c1_case(full, 'swa_full, no checkpoint', 1500, 100, 300, 95, want_ckpt=False) + + # ---- C2: a checkpoint restore that fails falls back to a full prefill (plan U07, I15) + def c2(self): + for how in ('magic', 'trunc'): + srv = self.server(f'c2-{how}', None, spec_type=None, cache=True, extra=['-ub', '32'], env_extra={'LLAMA_DFLY_TEST_CKPT_CORRUPT': how}) + prompt = rand_prompt(2100, 100) + js1, _ = srv.complete(prompt, 300, cache_prompt=True, ignore_eos=True) + n_made = len(CKPT_MADE.findall(srv.log_text())) + n_log = len(srv.log_text()) + js2, _ = srv.complete(prompt[:95] + rand_prompt(2101, 8), 4, cache_prompt=True, ignore_eos=True) + seg = srv.log_text()[n_log:] + dec = [tuple(map(int, m)) for m in HOOK_DECODE.findall(seg)] + failed = re.findall(r'failed to restore context checkpoint \(.*\), falling back to full prompt re-processing', seg) + n_erased = len(re.findall(r'erased invalidated context checkpoint', seg)) + js3, _ = srv.complete(rand_prompt(2102, 30), 4, cache_prompt=True, ignore_eos=True) + ok = (js1.get('_status') == 200 and len(failed) == 1 and 'test hook: checkpoint restored' not in seg and dec and dec[0][:2] == (0, -1) + and n_erased == n_made and js2.get('_status') == 200 and len(gen_of(js2)) == 4 and srv.alive() + and js3.get('_status') == 200 and len(gen_of(js3)) == 4) + self.res.add(f'C2 checkpoint restore fails ({how})', ok, f'error logged {failed[:1]}, first decode (q, pos_min) {dec[0][:2] if dec else None}, ' + f'checkpoints erased {n_erased}/{n_made}, status {js2.get("_status")} with {len(gen_of(js2))} tokens, alive {srv.alive()}, ' + f'next request {js3.get("_status")} with {len(gen_of(js3))} tokens') + + # ---- C3: no save when the memory does not match the tokens (plan U09, I01) + def c3(self): + for name, env in (('consistent', None), ('metadata 3 tokens short', {'LLAMA_DFLY_TEST_META_DROP': '3'})): + tag = 'c3-' + ('ok' if env is None else 'drop') + srv = self.server(tag, None, spec_type=None, cache=True, cache_ram=64, env_extra=env, + extra=['--slot-save-path', self.opts.work]) + srv.complete(rand_prompt(3100, 40), 8, cache_prompt=True, ignore_eos=True) + n_log = len(srv.log_text()) + res = HTTP.post(srv.url('/slots/0?action=save'), json={'filename': tag + '.bin'}, timeout=60) + srv.complete(rand_prompt(3101, 40), 8, cache_prompt=True, ignore_eos=True) + seg = srv.log_text()[n_log:] + saved_ram = 'saving prompt with length' in seg + refused = re.findall(r'not saving the (prompt|slot), the memory does not match the tokens', seg) + counts = re.findall(r'memory pos_max = (-?\d+), tokens pos_next = (-?\d+)', seg) + if env is None: + ok = res.status_code == 200 and saved_ram and not refused + else: + ok = (res.status_code != 200 and not saved_ram and set(refused) == {'prompt', 'slot'} + and counts and all(int(a) == int(b) + 2 for a, b in counts) and srv.alive()) + self.res.add(f'C3 save, {name}', ok, f'slot save status {res.status_code}, RAM save {saved_ram}, refused {refused}, (pos_max, pos_next) {counts}') + + # ---- L10: a stopping round leaves the memory at the kept tokens (plan U09, I01) + def l10(self, srv): + K = 4 + prompt, gen = self.find_eos_prompt(srv, 12, 80) + n = len(prompt) + ref = prompt + gen + P = n + len(gen) - 1 + cases = [('EOS on draft 1, matched', 0, 4), ('EOS on draft 4, matched', 3, 4), ('EOS on the correction', 2, 2), ('EOS on the bonus', 4, 4)] + for name, j, r_last in cases: + rs = plan_steps(n, P - 1 - j, K) + [r_last] + srv.script(ref=ref, r=rs) + js, rounds = srv.complete(prompt, 400) + last = rounds[-1] + rel = js['_release'] + end = last['a'] + last['M'] # the kept tokens: the anchor of the round and the outputs before the stop + ok = (last['stopped'] and len(rel) == 1 + and rel[0]['seq_pos_max'] + 1 == rel[0]['pos_next'] == rel[0]['n_tokens'] == end and last['seq_pos_max'] + 1 == end + and ref_ok(last['M'] == j + 1 and gen_of(js) == gen, f'L10 {name}: M {last["M"]}')) + self.res.add(f'L10 {name}', ok, f'last round a={last["a"]} K={last["K"]} M={last["M"]} r={last["r"]}, after release {rel[:1]}, expected seq_pos_max {end - 1}') + + + # ---- P1-P12 (PC1, plan 5.2): draft-dfly with the prompt cache and the slot checkpoints, the RAM cache off + # tiny target: n_swa 32; -ub 32 gives 256 SWA cells, and a prompt from R is split at N - 36 and N - 4. A batch that + # starts at s with a non-empty memory and ends within 32 of N makes the checkpoint (max(pos_min, s - 32), s - 1, s): + # a cold prompt of 100 makes C1 = (32, 63, 64) and C2 = (64, 95, 96). q = L, or N - 1 for a full match; the window + # check passes when pos_min < max(0, pos_eval - 30); the lookup goes from the back for pos_max <= pos_eval and + # (pos_min < threshold or pos_min == 0) and resumes at R = pos_max; then the checkpoints with pos_max > pos_next or + # n_tokens > L are erased. A request that stops leaves N + G - 1 tokens (a + M after a stop token). + C1 = (32, 63, 64) + C2 = (64, 95, 96) + + def pserver(self, name, k0, extra=(), cache=True, env_extra=None): + ex = ['-ub', '32'] + list(extra) + (['--spec-draft-n-max', '0'] if k0 else []) + return self.server(name + ('-k0' if k0 else ''), 'tiny-dfly-b5.gguf', cache=cache, extra=ex, env_extra=env_extra) + + def creq(self, srv, case, prompt, n_predict, exp, erased, cache_prompt=True, extra_errs=None, **kw): + """one request with the checks G1-G8 against exp (L, R, src, why, restore); case None reports failures only""" + body = {'prompt': prompt, 'n_predict': n_predict, 'temperature': 0, 'return_tokens': True, 'seed': 42, 'ignore_eos': True} + if cache_prompt is not None: + body['cache_prompt'] = cache_prompt + body.update(kw) + js, rounds, rel, seg = srv.post(body) + N = len(prompt) + e = dict(exp) + e.setdefault('restore', None) + e.setdefault('pos_eval', N - 1 if e['L'] >= N else e['L']) + errs = cache_checks(srv, prompt, js, rounds, rel, seg, e, erased) + if srv.dfly: + ce, _ = check_rounds(rounds, N, k_eff=4) # G5 + errs += ['G5: ' + x for x in ce[:3]] + errs += extra_errs(js, rounds, seg) if extra_errs else [] + if not srv.alive(): + errs.append('G8: the server is not serving') + t = js.get('timings', {}) + lines, hooks = parse_pcache(seg) + obs = (t.get('cache_n'), [tuple(m) for m in METRIC.findall(seg)], [tuple(map(int, m))[:2] for m in HOOK_RESTORED.findall(seg)], + sorted(tuple(map(int, m)) for m in CKPT_ERASED.findall(seg)), + [(x['save'], x['load'], x['r_slot'], x['r_entry']) for x in lines], [(e['E'], e['P']) for h in hooks for e in h['entries']]) + label = case or f'{srv.name} N={N}' + if not srv.dfly: + self.ar_obs[label] = (obs, errs) + elif case is not None or errs: + ar = self.ar_obs.get(label) + note = '' if ar is None else ('; AR (K=0): same' if ar[0] == obs else f'; AR (K=0) differs: {ar[0]}') + self.res.add(label, not errs, f'N {N}, R {obs[0]} (expected {e["R"]}), metric {obs[1]}, restored {obs[2]}, erased {obs[3]}' + + note + ('' if not errs else f'; errors {errs[:4]}')) + return js, seg + + def p_reset(self, srv, p, G=8): + # cache_prompt false: a full prefill, all checkpoints erased, then C1 and C2 again + return self.creq(srv, None, p, G, {'L': 0, 'R': 0, 'src': 'none', 'why': 'cache_off'}, None, cache_prompt=False) + + def p1(self, k0): + nm = {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'} + p = rand_prompt(5001, 100) + srv = self.pserver('p1a', k0) + self.creq(srv, 'P1a first', p, 8, nm, []) + self.creq(srv, 'P1a repeat after 8 tokens', p, 8, {'L': 100, 'R': 99, 'src': 'slot', 'why': 'none'}, []) + self.retire(srv) + # 400 positions in 256 SWA cells: pos_min >= 144 > 69, C2 restores + srv = self.pserver('p1b', k0) + self.creq(srv, 'P1b first, 300 tokens', p, 300, nm, []) + self.creq(srv, 'P1b repeat after 300 tokens', p, 8, {'L': 100, 'R': 95, 'src': 'checkpoint', 'why': 'window_check', 'restore': (64, 95)}, []) + self.retire(srv) + srv = self.pserver('p1c', k0, extra=['--ctx-checkpoints', '0']) + self.creq(srv, 'P1c first, 300 tokens, no checkpoints', p, 300, nm, []) + self.creq(srv, 'P1c repeat, no checkpoints', p, 8, {'L': 100, 'R': 0, 'src': 'none', 'why': 'no_checkpoint'}, []) + self.retire(srv) + # N = 20: pos_eval 19 gives the threshold 0, so pos_min 0 fails the check (plan 4.4, conservative) and (0, 15, 16) restores + srv = self.pserver('p1d', k0) + p20 = rand_prompt(5004, 20) + self.creq(srv, 'P1d first, N=20', p20, 8, nm, []) + self.creq(srv, 'P1d repeat, N=20', p20, 8, {'L': 20, 'R': 15, 'src': 'checkpoint', 'why': 'window_check', 'restore': (0, 15)}, []) + self.retire(srv) + + def p2(self, k0): + srv = self.pserver('p2', k0) + p = rand_prompt(5010, 100) + for L in (30, 31, 32, 33, 63, 64, 65, 79, 80, 81): + self.p_reset(srv, p) + suf = rand_prompt(5100 + L, 12) + if suf[0] == p[L]: + suf[0] = 5 if p[L] != 5 else 6 + if L == 30: + # pos_eval 30, threshold 0: the lookup finds no pos_max <= 30 + self.creq(srv, 'P2 L=30 (threshold 0, no checkpoint)', p[:L] + suf, 8, {'L': 30, 'R': 0, 'src': 'none', 'why': 'no_checkpoint'}, + [self.C1, self.C2]) + continue + self.creq(srv, f'P2 L={L}', p[:L] + suf, 8, {'L': L, 'R': L, 'src': 'slot', 'why': 'none'}, [c for c in (self.C1, self.C2) if c[2] > L]) + if L == 64: + # the request above superseded C1 by (32, 63, 64) and made (40, 71, 72) + self.creq(srv, 'P2 back to the 100 tokens after L=64', p, 8, {'L': 64, 'R': 64, 'src': 'slot', 'why': 'none'}, [(40, 71, 72)]) + self.retire(srv) + + def p3(self, k0): + srv = self.pserver('p3', k0) + p = rand_prompt(5020, 100) + self.p_reset(srv, p) + self.creq(srv, 'P3a shorter prompt p[:60]', p[:60], 8, {'L': 60, 'R': 59, 'src': 'slot', 'why': 'none'}, [self.C1, self.C2]) + self.p_reset(srv, p) + tail = rand_prompt(5021, 5) + if tail[0] == p[95]: + tail[0] = 5 if p[95] != 5 else 6 + # C2 ends at pos_max 95 == pos_next: only n_tokens 96 > L erases it + self.creq(srv, 'P3b L = pos_max of C2', p[:95] + tail, 8, {'L': 95, 'R': 95, 'src': 'slot', 'why': 'none'}, [self.C2]) + self.p_reset(srv, p) + e = list(p) + e[40] = 5 if p[40] != 5 else 6 + self.creq(srv, 'P3c edit at 40', e, 8, {'L': 40, 'R': 40, 'src': 'slot', 'why': 'none'}, [self.C1, self.C2]) + self.p_reset(srv, p, 300) + e = list(p) + e[70] = 5 if p[70] != 5 else 6 + # C2 ends after pos_eval 70; C1 has 32 < 40 + self.creq(srv, 'P3d edit at 70 after 300 tokens', e, 8, {'L': 70, 'R': 63, 'src': 'checkpoint', 'why': 'window_check', 'restore': (32, 63)}, + [self.C2]) + self.p_reset(srv, p) + z = rand_prompt(5022, 61) + if z[0] == p[0]: + z[0] = 5 if p[0] != 5 else 6 + self.creq(srv, 'P4 zero match', z, 8, {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'}, [self.C1, self.C2]) + self.retire(srv) + + def p5(self, k0): + srv = self.pserver('p5', k0) + S = rand_prompt(5030, 120) + x4, a50, b50 = rand_prompt(5031, 4), rand_prompt(5032, 50), rand_prompt(5033, 50) + while a50[0] == x4[0]: + a50[0] += 1 + while b50[0] in (x4[0], a50[0]): + b50[0] += 1 + self.creq(srv, 'P5 S + 4 (checkpoint at the end of S)', S + x4, 4, {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'}, []) + self.creq(srv, 'P5 A = S + a, 300 tokens', S + a50, 300, {'L': 120, 'R': 120, 'src': 'slot', 'why': 'none'}, []) + # (134, 165, 166) and (102, 133, 134) end after 120, (88, 119, 120) has 88 < 90 + A_ck = [(102, 133, 134), (134, 165, 166)] + self.creq(srv, 'P5 B = S + b', S + b50, 8, {'L': 120, 'R': 119, 'src': 'checkpoint', 'why': 'window_check', 'restore': (88, 119)}, A_ck) + # the restored SWA starts at 88 < 90: back to A in the slot + self.creq(srv, 'P5 back to A', S + a50, 8, {'L': 120, 'R': 120, 'src': 'slot', 'why': 'none'}, A_ck) + self.retire(srv) + + def p6(self, k0): + srv = self.pserver('p6', k0) + if not k0: + K = 4 + # P >= 40 keeps the threshold of the continuation above 0 + prompt, gen = self.find_eos_prompt(srv, 24, 80) + n = len(prompt) + ref = prompt + gen + P = n + len(gen) - 1 + for name, j, r_last in (('draft 1', 0, 4), ('draft 4', 3, 4), ('the correction', 2, 2), ('the bonus', 4, 4)): + for n_suf in (0, 6): + rs = plan_steps(n, P - 1 - j, K) + [r_last] + srv.script(ref=ref, r=rs) + # the shape of find_eos_prompt: cache_prompt false + js, rounds, rel, _ = srv.post({'prompt': prompt, 'n_predict': 400, 'temperature': 0, 'return_tokens': True, + 'cache_prompt': False, 'seed': 42}) + srv.script() + last = rounds[-1] + end = last['a'] + last['M'] + okA = (last['stopped'] and last['M'] == j + 1 and gen_of(js) == gen and len(rel) == 1 + and rel[0]['seq_pos_max'] + 1 == rel[0]['n_tokens'] == rel[0]['pos_next'] == end == P) + # G6 of the stopping request; the continuation still runs, it only depends on the slot tokens + self.res.add(f'P6 stop on {name} (+{n_suf}): the stopping request', okA, + f'last round a={last["a"]} M={last["M"]} r={last["r"]}, after release {rel[:1]}, EOS pos {P}') + suf = rand_prompt(5040 + j, n_suf) + self.creq(srv, f'P6 stop on {name}, continuation + {n_suf}', prompt + gen + suf, 8, + {'L': P, 'R': P, 'src': 'slot', 'why': 'none'}, []) + p = rand_prompt(5041, 100) + for n_suf in (0, 6): + js, _ = self.p_reset(srv, p, 20) + cont = p + js.get('tokens', []) + rand_prompt(5042, n_suf) + self.creq(srv, f'P6 limit stop, continuation + {n_suf}', cont, 8, {'L': 119, 'R': 119, 'src': 'slot', 'why': 'none'}, []) + self.retire(srv) + + def p7(self, k0): + off = {'L': 0, 'R': 0, 'src': 'none', 'why': 'cache_off'} + p = rand_prompt(5050, 100) + srv = self.pserver('p7a', k0, cache=False) + self.creq(srv, 'P7a server without the cache, first', p, 8, off, [], cache_prompt=None) + self.creq(srv, 'P7a server without the cache, repeat', p, 8, off, [], cache_prompt=None) + self.retire(srv) + srv = self.pserver('p7b', k0) + self.creq(srv, 'P7b first', p, 8, {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'}, []) + self.creq(srv, 'P7b repeat with cache_prompt false', p, 8, off, [self.C1, self.C2], cache_prompt=False) + self.creq(srv, 'P7b repeat with cache_prompt true', p, 8, {'L': 100, 'R': 99, 'src': 'slot', 'why': 'none'}, []) + self.retire(srv) + + def p8(self, k0): + srv = self.pserver('p8', k0) + p = rand_prompt(5060, 100) + self.creq(srv, 'P8 first', p, 40, {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'}, []) + hit = {'L': 100, 'R': 99, 'src': 'slot', 'why': 'none'} + for name, kw in (('seed', {'seed': 7}), ('temperature', {'temperature': 0.8, 'seed': 1234}), + ('top-k/top-p', {'temperature': 0.8, 'top_k': 20, 'top_p': 0.9, 'seed': 5}), + ('repeat penalty', {'repeat_penalty': 1.3}), ('grammar', {'grammar': 'root ::= [0-7]+'})): + def text_ok(js, rounds, seg, name=name): + ok = name != 'grammar' or re.fullmatch(r'[0-7]+', js.get('content', '')) is not None + return [] if ok else [f'grammar: text {js.get("content", "")[:40]!r}'] + self.creq(srv, f'P8 {name}', p, 40, hit, [], extra_errs=text_ok, **kw) + self.retire(srv) + + def p9(self, k0): + nm = {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'} + srv = self.pserver('p9a', k0) + self.creq(srv, 'P9a N=1 first', [7], 8, nm, []) + # pos_eval 0, threshold 0, and a prompt of 1 made no checkpoint + self.creq(srv, 'P9a N=1 repeat', [7], 8, {'L': 1, 'R': 0, 'src': 'none', 'why': 'no_checkpoint'}, []) + self.retire(srv) + srv = self.pserver('p9b', k0) + p = rand_prompt(5070, 100) + js, _ = self.creq(srv, 'P9b n_predict 0', p, 0, nm, []) + tok = js.get('tokens', [5])[:1] or [5] + # the token of n_predict 0 was sampled, not decoded: it is replayed + self.creq(srv, 'P9b prompt + its token, n_predict 1', p + tok, 1, {'L': 100, 'R': 100, 'src': 'slot', 'why': 'none'}, []) + self.creq(srv, 'P9b the prompt again', p, 8, {'L': 100, 'R': 99, 'src': 'slot', 'why': 'none'}, []) + self.retire(srv) + srv = self.pserver('p9c', k0, extra=['--kv-unified-per-slot', '32']) + p21 = rand_prompt(5071, 21) + js, _ = self.creq(srv, 'P9c C=32 first', p21, 100, nm, []) + g = js.get('tokens', []) + if len(g) < 10: + self.res.add('P9c C=32 (setup)', False, f'{len(g)} tokens, 10 needed') + else: + # N = 30, pos_eval 29: threshold 0, (0, 16, 17) restores + self.creq(srv, 'P9c C=32 N=30', p21 + g[:9], 4, {'L': 30, 'R': 16, 'src': 'checkpoint', 'why': 'window_check', 'restore': (0, 16)}, []) + if not k0: + # N >= n_ctx and the empty prompt return before the lookup: no metric line + for name, pr in (('N=32 >= n_ctx', (p21 + g + rand_prompt(5072, 32))[:32]), ('empty prompt', [])): + js, _, _, seg = srv.post({'prompt': pr, 'n_predict': 4, 'temperature': 0, 'cache_prompt': True}) + ok = not METRIC.findall(seg) and srv.alive() and (name == 'empty prompt' or js['_status'] != 200) + self.res.add(f'P9 {name}', ok, f'status {js["_status"]}, metric lines {METRIC.findall(seg)}, alive {srv.alive()}') + self.retire(srv) + + def p10(self): + for how in ('magic', 'trunc'): + srv = self.pserver(f'p10-{how}', False, env_extra={'LLAMA_DFLY_TEST_CKPT_CORRUPT': how}) + p = rand_prompt(5080, 100) + t8 = rand_prompt(5081, 8) + if t8[0] == p[95]: + t8[0] = 5 if p[95] != 5 else 6 + self.creq(srv, f'P10 {how} first, 300 tokens', p, 300, {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'}, []) + + def failed_once(js, rounds, seg): + n = len(re.findall(r'failed to restore context checkpoint \(.*\), falling back to full prompt re-processing', seg)) + return [] if n == 1 else [f'{n} restore errors logged'] + # C2 is chosen (95 <= 95, 64 < 65) and fails: everything is erased, a full prefill + self.creq(srv, f'P10 {how} restore fails', p[:95] + t8, 8, {'L': 95, 'R': 0, 'src': 'none', 'why': 'restore_failed'}, + [self.C1, self.C2], extra_errs=failed_once) + self.creq(srv, f'P10 {how} next cache request', p[:95] + t8, 8, {'L': 103, 'R': 102, 'src': 'slot', 'why': 'none'}, []) + self.retire(srv) + + def p12(self): + srv = self.pserver('p12', False, extra=['--sleep-idle-seconds', '1']) + p = rand_prompt(5090, 100) + nm = {'L': 0, 'R': 0, 'src': 'none', 'why': 'no_match'} + self.creq(srv, 'P12 before sleep', p, 8, nm, []) + deadline = time.time() + 60 + while 'entering sleeping state' not in srv.log_text() and time.time() < deadline: + time.sleep(0.5) + slept = 'entering sleeping state' in srv.log_text() + if not slept: + self.res.add('P12 sleep (setup)', False, 'the server did not sleep') + # the slots are made again on resume, so nothing is reused and pos_min == -1 does not abort + self.creq(srv, 'P12 after sleep', p, 8, nm, []) + self.retire(srv) + + # ---- R1-R12 (PC2, plan 6): the RAM cache. Thresholds scaled to the tiny target: T_save 32, T_load 16. + # rules: an entry of E tokens keeps the SWA from P = max(0, E - 32), and the slot memory starts there after a load; + # the similarity branch saves when f_keep < 0.5 or n_drop >= T_save, the LRU branch always; then the entry with the + # largest R (server_prompt_restorable) loads if it restores T_load more than the slot, and leaves the cache + def rserver(self, name, k0, extra=(), env_extra=None, ram=256, t_save=32, t_gain=16): + ex = ['-ub', '32', '--cache-ram-min-drop', str(t_save), '--cache-ram-min-gain', str(t_gain)] + list(extra) + ex += ['--spec-draft-n-max', '0'] if k0 else [] + return self.server(name + ('-k0' if k0 else ''), 'tiny-dfly-b5.gguf', cache=True, cache_ram=ram, extra=ex, env_extra=env_extra) + + @staticmethod + def fork(base, n, seed, k): + """base[:n] and k new tokens, the first differs from base[n]""" + t = rand_prompt(seed, k) + if n < len(base) and t and t[0] == base[n]: + t[0] = 5 if base[n] != 5 else 6 + return base[:n] + t + + @staticmethod + def x(L, R, src, why, restore=None, **kw): + e = {'L': L, 'R': R, 'src': src, 'why': why, 'restore': restore} + e.update(kw) + return e + + # the checkpoints of a cold prompt of 170 (A), 60 (Z) and 80 + A_CK = [(102, 133, 134), (134, 165, 166)] + Z_CK = [(0, 23, 24), (24, 55, 56)] + Z80_CK = [(12, 43, 44), (44, 75, 76)] + + def r4(self, k0): + A, Z = rand_prompt(6400, 170), rand_prompt(6401, 60) + nm = self.x(0, 0, 'none', 'no_match') + for how, dec in (('short', 'write_failed'), ('zero', 'refused')): + srv = self.rserver(f'r4-{how}', k0, env_extra={'LLAMA_DFLY_TEST_RAM_SAVE': how}) + self.creq(srv, f'R4 {how}: A', A, 8, dict(nm, pc={'save': 'empty', 'load': 'no_entry'}, entries=[]), []) + # LCP 0 erases all the checkpoints of the slot + self.creq(srv, f'R4 {how}: Z, the save of A fails', Z, 8, dict(nm, pc={'save': dec, 'load': 'no_entry'}, entries=[]), self.A_CK) + self.creq(srv, f'R4 {how}: A, the save of Z fails', A, 8, dict(nm, pc={'save': dec, 'load': 'no_entry'}, entries=[]), self.Z_CK) + self.retire(srv) + + def r5(self, k0): + A, Z, Z2 = rand_prompt(6500, 170), rand_prompt(6501, 60), rand_prompt(6502, 300) + nm = self.x(0, 0, 'none', 'no_match') + for how in ('magic', 'trunc') + (() if k0 else ('drft',)): + srv = self.rserver(f'r5-{how}', k0, env_extra={'LLAMA_DFLY_TEST_RAM_CORRUPT': how}) + self.creq(srv, f'R5 {how}: A', A, 8, dict(nm, pc={'save': 'empty'}, entries=[]), []) + # A (177, 145) keeps (102, 133, 134) and (134, 165, 166) + self.creq(srv, f'R5 {how}: Z saves A', Z, 8, dict(nm, pc={'save': 'saved', 'load': 'low_gain'}, entries=[(177, 145, [134, 166])]), self.A_CK) + # A again: r_entry 165 through (134, 165, 166); the injected restore fails, the entry goes, the slot is empty + self.creq(srv, f'R5 {how}: A, the load fails', A, 8, + self.x(0, 0, 'none', 'entry_corrupt', pc={'save': 'saved', 'load': 'failed', 'r_slot': 0, 'r_entry': 165}, + entries=[(67, 35, [24, 56])], pos_min=-1, slot_ck=[]), []) + # a broken entry no longer blocks the save of the same tokens + self.creq(srv, f'R5 {how}: Z2 saves A again', Z2, 8, + dict(nm, pc={'save': 'saved', 'load': 'low_gain'}, entries=[(67, 35, [24, 56]), (177, 145, [134, 166])]), self.A_CK) + self.creq(srv, f'R5 {how}: A loads the new entry', A, 8, + self.x(170, 165, 'ram_checkpoint', 'window_check', (134, 165), pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': 165}, + entries=[(67, 35, [24, 56]), (307, 275, [264, 296])], slot_ck=[134, 166], pos_min=145), []) + self.retire(srv) + + def r1(self, k0): + S, a, b = rand_prompt(6000, 120), rand_prompt(6001, 50), rand_prompt(6002, 50) + if b[0] == a[0]: + b[0] = 5 if a[0] != 5 else 6 + A, B = S + a, S + b + nm = self.x(0, 0, 'none', 'no_match') + srv = self.rserver('r1', k0) + js, _ = self.creq(srv, 'R1a 1 A', A, 8, dict(nm, pc={'save': 'empty', 'load': 'no_entry'}, entries=[]), []) + A2 = A + gen_of(js) + rand_prompt(6003, 10) + # f_keep 0.678 keeps the ratio rule from saving A, n_drop 57 saves it; A has no checkpoint at or before 120 + js, _ = self.creq(srv, 'R1a 2 B saves A', B, 8, + self.x(120, 120, 'slot', 'none', pc={'save': 'saved', 'n_drop': 57, 'load': 'low_gain', 'r_slot': 120, 'r_entry': 0}, + entries=[(177, 145, [134, 166])]), self.A_CK) + B2 = B + gen_of(js) + rand_prompt(6004, 10) + # L = E = 177: pos_eval 177, threshold 147, P 145; the slot keeps 120 + js, _ = self.creq(srv, 'R1a 3 A2 loads A', A2, 8, + self.x(177, 177, 'ram', 'none', pc={'save': 'saved', 'load': 'loaded', 'r_slot': 120, 'r_entry': 177}, + entries=[(177, 145, [134, 166])], slot_ck=[134, 166], pos_min=145), []) + A2e = A2 + gen_of(js)[:7] + # the slot came from RAM: SWA from 145, no checkpoint at or before 120, r_slot 0 + js, _ = self.creq(srv, 'R1a 4 B2 loads B', B2, 8, + self.x(177, 177, 'ram', 'none', pc={'save': 'saved', 'n_drop': 75, 'load': 'loaded', 'r_slot': 0, 'r_entry': 177}, + entries=[(195, 163, [134, 166, 177, 184])], slot_ck=[134, 166], pos_min=145), []) + B2e = B2 + gen_of(js)[:7] + # pos_eval 186, threshold 156, P 163: (152, 183, 184) restores + self.creq(srv, 'R1b 5 A3 forks A2 at 186', self.fork(A2e, 186, 6005, 8), 8, + self.x(186, 183, 'ram_checkpoint', 'window_check', (152, 183), pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': 183}, + entries=[(195, 163, [134, 166, 177, 184])], slot_ck=[134, 166, 177, 184], pos_min=163), []) + # a full match of 195: pos_eval 194, threshold 164, P 163 passes the window check + self.creq(srv, 'R1 6 the tokens of B2', B2e, 8, + self.x(195, 194, 'ram', 'none', pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': 194}, + entries=[(201, 169, [134, 166, 177, 184, 183, 190])], slot_ck=[134, 166, 177, 184], pos_min=163), []) + self.retire(srv) + # R1c: the default thresholds keep the ratio rule, A2 then keeps only the shared 120 + srv = self.rserver('r1c', k0, t_save=512, t_gain=256) + self.creq(srv, 'R1c 1 A', A, 8, nm, []) + self.creq(srv, 'R1c 2 B, no save', B, 8, self.x(120, 120, 'slot', 'none', pc={'save': 'skipped', 'load': 'no_entry'}, entries=[]), self.A_CK) + self.creq(srv, 'R1c 3 A2, nothing to load', A2, 8, self.x(120, 120, 'slot', 'none', pc={'save': 'skipped', 'load': 'no_entry'}, entries=[]), self.A_CK) + self.retire(srv) + + def r2(self, k0): + nm = self.x(0, 0, 'none', 'no_match') + p = rand_prompt(6100, 100) + # f_keep about 0.7: only n_drop = 107 - L decides; the entry restores 63 through C1 + for L, dec, r_e in ((76, 'skipped', -1), (75, 'saved', 63), (74, 'saved', 63)): + srv = self.rserver(f'r2-{L}', k0) + self.creq(srv, None, p, 8, nm, []) + self.creq(srv, f'R2 n_drop {107 - L}', self.fork(p, L, 6101, 12), 8, + self.x(L, L, 'slot', 'none', pc={'save': dec, 'n_drop': 107 - L, 'load': 'low_gain' if r_e >= 0 else 'no_entry', 'r_slot': L, 'r_entry': r_e}, + entries=[] if r_e < 0 else [(107, 75, [64, 96])]), [self.C2]) + self.retire(srv) + # f_keep 0.426 < 0.5 with n_drop 27 < 32; pos_eval 20 gives the threshold 0, (0, 3, 4) restores + srv = self.rserver('r2-ratio', k0) + q = rand_prompt(6102, 40) + self.creq(srv, None, q, 8, nm, []) + self.creq(srv, 'R2 ratio rule', self.fork(q, 20, 6103, 12), 8, + self.x(20, 3, 'checkpoint', 'window_check', (0, 3), pc={'save': 'saved', 'n_drop': 27, 'load': 'low_gain', 'r_slot': 3, 'r_entry': 3}, + entries=[(47, 15, [4, 36])]), [(4, 35, 36)]) + self.retire(srv) + # f_sim 47/477 <= 0.1: the LRU branch saves although nothing is dropped + srv = self.rserver('r2-lru', k0) + js, _ = self.creq(srv, None, q, 8, nm, []) + self.creq(srv, 'R2 LRU branch', q + gen_of(js)[:7] + rand_prompt(6104, 430), 8, + self.x(47, 47, 'slot', 'none', pc={'save': 'saved', 'n_drop': 0, 'load': 'low_gain', 'r_slot': 47, 'r_entry': 47}, entries=[(47, 15, [4, 36])]), []) + self.retire(srv) + # the default T_save 512 at n_drop 512 / 511; the SWA wrapped and both checkpoints end after 588 + w = rand_prompt(6105, 1093) + for L, dec in ((588, 'saved'), (589, 'skipped')): + srv = self.rserver(f'r2-512-{L}', k0, extra=['-c', '2048'], t_save=512, t_gain=256) + self.creq(srv, None, w, 8, nm, None) + self.creq(srv, f'R2 default T_save, n_drop {1100 - L}', self.fork(w, L, 6106, 12), 8, + self.x(L, 0, 'none', 'no_checkpoint', pc={'save': dec, 'n_drop': 1100 - L, 'r_slot': 0}, + entries=[(1100, 1068, [1057, 1089])] if dec == 'saved' else []), None) + self.retire(srv) + + def r3(self, k0): + nm = self.x(0, 0, 'none', 'no_match') + # the T_load edge (T_save 8): Y forks X at 177 - g, Q continues X; X restores 177, the slot 162 / 161 + X = rand_prompt(6200, 170) + for g in (15, 16): + n = 177 - g + srv = self.rserver(f'r3-gain{g}', k0, t_save=8) + js, _ = self.creq(srv, None, X, 8, nm, []) + Q = self.fork(X + gen_of(js), 177, 6202, 5) + self.creq(srv, f'R3 gain {g}: Y saves X', self.fork(X, n, 6201, 20), 8, + self.x(n, n, 'slot', 'none', pc={'save': 'saved', 'n_drop': g, 'load': 'low_gain', 'r_slot': n, 'r_entry': 133}, + entries=[(177, 145, [134, 166])]), [(134, 165, 166)]) + y_ck = [134, 162, 178] if g == 15 else [134, 161, 177] + if g == 15: + self.creq(srv, 'R3 gain 15 < 16: Q keeps the slot', Q, 8, + self.x(162, 162, 'slot', 'none', pc={'save': 'saved', 'n_drop': 27, 'load': 'low_gain', 'r_slot': 162, 'r_entry': 177}, + entries=[(177, 145, [134, 166]), (189, 157, y_ck)]), [(146, 177, 178)]) + else: + self.creq(srv, 'R3 gain 16: Q loads X', Q, 8, + self.x(177, 177, 'ram', 'none', pc={'save': 'saved', 'n_drop': 27, 'load': 'loaded', 'r_slot': 161, 'r_entry': 177}, + entries=[(188, 156, y_ck)], slot_ck=[134, 166], pos_min=145), []) + self.retire(srv) + # trap 1 (plan 2.9 item 2): X restores only 119 for Y2 although its LCP is larger; the old rule took X out + S, xs, ys = rand_prompt(6210, 120), rand_prompt(6211, 200), rand_prompt(6212, 100) + if ys[0] == xs[0]: + ys[0] = 5 if xs[0] != 5 else 6 + m4 = rand_prompt(6213, 4) + if m4[0] in (xs[0], ys[0]): + m4[0] = next(t for t in range(5, 120) if t not in (xs[0], ys[0])) + X, Y = S + xs, S + ys + srv = self.rserver('r3-trap1', k0) + self.creq(srv, None, S + m4, 4, nm, []) + js, _ = self.creq(srv, 'R3 trap 1: X', X, 8, self.x(120, 120, 'slot', 'none', pc={'save': 'skipped', 'n_drop': 7, 'load': 'no_entry', 'r_slot': 120}), []) + Xt = self.fork(X + gen_of(js), 320, 6215, 5) + x_e = (327, 295, [88, 120, 284, 316]) + self.creq(srv, 'R3 trap 1: Y saves X', Y, 300, + self.x(120, 120, 'slot', 'none', pc={'save': 'saved', 'load': 'low_gain', 'r_slot': 120, 'r_entry': 119}, entries=[x_e]), + [(252, 283, 284), (284, 315, 316)]) + # LCP 122 with X, but X and Y and the slot all restore 119 through (88, 119, 120): gain 0 + self.creq(srv, 'R3 trap 1: Y2 keeps X', self.fork(X, 122, 6214, 100), 8, + self.x(120, 119, 'checkpoint', 'window_check', (88, 119), pc={'save': 'saved', 'load': 'low_gain', 'r_slot': 119, 'r_entry': 119}, + entries=[x_e, (519, 487, [88, 120, 184, 216])]), [(152, 183, 184), (184, 215, 216)]) + self.creq(srv, 'R3 trap 1: X + t5 loads X', Xt, 8, + self.x(320, 315, 'ram_checkpoint', 'window_check', (284, 315), pc={'save': 'saved', 'n_drop': 107, 'load': 'loaded', 'r_slot': 122, 'r_entry': 315}, + entries=[(519, 487, [88, 120, 184, 216]), (229, 197, [88, 120, 186, 218])], slot_ck=[88, 120, 284, 316], pos_min=295), []) + self.retire(srv) + # trap 2: X restores 0 for S + m4 (its checkpoints end after 120), the old rule loaded it there and lost it + S, xs, Z = rand_prompt(6220, 120), rand_prompt(6221, 100), rand_prompt(6222, 80) + if Z[0] == S[0]: + Z[0] = 5 if S[0] != 5 else 6 + m4 = rand_prompt(6223, 4) + if m4[0] == xs[0]: + m4[0] = 5 if xs[0] != 5 else 6 + X = S + xs + srv = self.rserver('r3-trap2', k0) + js, _ = self.creq(srv, None, X, 8, nm, []) + Xt = self.fork(X + gen_of(js), 220, 6224, 5) + self.creq(srv, 'R3 trap 2: Z saves X', Z, 8, dict(nm, pc={'save': 'saved', 'load': 'low_gain', 'r_entry': 0}, entries=[(227, 195, [184, 216])]), + [(152, 183, 184), (184, 215, 216)]) + self.creq(srv, 'R3 trap 2: S + m4 keeps X', S + m4, 4, + dict(nm, pc={'save': 'saved', 'load': 'low_gain', 'r_slot': 0, 'r_entry': 0}, entries=[(227, 195, [184, 216]), (87, 55, [44, 76])]), self.Z80_CK) + # n_drop 7: no save, the load is decided on its own (D2) + self.creq(srv, 'R3 trap 2: X + t5 loads X without a save', Xt, 8, + self.x(220, 215, 'ram_checkpoint', 'window_check', (184, 215), pc={'save': 'skipped', 'n_drop': 7, 'load': 'loaded', 'r_slot': 120, 'r_entry': 215}, + entries=[(87, 55, [44, 76])], slot_ck=[184, 216], pos_min=195), []) + self.retire(srv) + + def r6(self, k0): + # n_predict 1 keeps E = N; T_load 1000 never loads + nm = self.x(0, 0, 'none', 'no_match') + X, Z, Z2 = rand_prompt(6300, 200), rand_prompt(6301, 80), rand_prompt(6302, 80) + x_ck, x_e, z_e = [(132, 163, 164), (164, 195, 196)], (200, 168, [164, 196]), (80, 48, [44, 76]) + for name, n, dec in (('a', 164, 'superseded'), ('b', 170, 'saved')): + srv = self.rserver(f'r6{name}', k0, t_save=8, t_gain=1000) + self.creq(srv, None, X, 1, nm, []) + self.creq(srv, None, Z, 1, dict(nm, entries=[x_e]), x_ck) + # X restores 163 of X[:n] through (132, 163, 164) + q_ck = [(96, 127, 128), (128, 159, 160)] if n == 164 else self.A_CK + self.creq(srv, f'R6{name} X[:{n}]', X[:n], 1, dict(nm, pc={'save': 'saved', 'r_entry': 163}, entries=[x_e, z_e]), self.Z80_CK) + self.creq(srv, f'R6{name} saving X[:{n}]: {dec}', Z2, 1, + dict(nm, pc={'save': dec}, entries=[x_e, z_e] + ([] if n == 164 else [(170, 138, [134, 166])])), q_ck) + self.retire(srv) + Y, Z = rand_prompt(6310, 100), rand_prompt(6303, 80) + Yp = self.fork(Y, 90, 6311, 20) + for name, k, keep in (('c', 4, False), ('d', 3, True)): + srv = self.rserver(f'r6{name}', k0, t_save=8, t_gain=1000) + self.creq(srv, None, Y, 1, nm, []) + self.creq(srv, None, Yp, 1, self.x(90, 90, 'slot', 'none', entries=[(100, 68, [64, 96])]), [self.C2]) + Ys = self.fork(Y, 100, 6312, k) + self.creq(srv, None, Ys, 1, self.x(90, 90, 'slot', 'none', entries=[(100, 68, [64, 96]), (110, 78, [64, 90, 106])]), [(74, 105, 106)]) + # Y + s4 restores 99 = len - 1 of Y through (68, 99, 100); Y + s3 only 98 through (67, 98, 99) + ys_e = (100 + k, 68 + k, [64, 90, 96 + k]) + self.creq(srv, f'R6{name} saving Y + s{k}: Y {"kept" if keep else "removed"}', Z, 1, + dict(nm, pc={'save': 'saved'}, entries=([(100, 68, [64, 96])] if keep else []) + [(110, 78, [64, 90, 106]), ys_e]), + [(32, 63, 64), (58, 89, 90), (64 + k, 95 + k, 96 + k)]) + self.retire(srv) + + def r7(self, k0): + nm = self.x(0, 0, 'none', 'no_match') + # a: every state is larger than 1 MiB + A, Z = rand_prompt(6700, 170), rand_prompt(6701, 60) + srv = self.rserver('r7-1mib', k0, ram=1) + self.creq(srv, None, A, 8, nm, []) + self.creq(srv, 'R7a budget: A', Z, 8, dict(nm, pc={'save': 'budget'}, entries=[]), self.A_CK) + self.creq(srv, 'R7a budget: Z', A, 8, dict(nm, pc={'save': 'budget'}, entries=[]), self.Z_CK) + self.retire(srv) + # b: an entry of 87 tokens is about 1.31 MB, 3 fit in 4 MiB, the oldest goes first + zs = [] + for i in range(5): + z = rand_prompt(6710 + i, 80) + while z[0] in [y[0] for y in zs]: + z[0] = 5 + (z[0] - 4) % 115 + zs.append(z) + e = (87, 55, [44, 76]) + srv = self.rserver('r7-4mib', k0, ram=4) + for i, z in enumerate(zs): + self.creq(srv, None, z, 8, dict(nm, entries=[e] * min(i, 3)), [] if i == 0 else self.Z80_CK) + self.creq(srv, 'R7b Z1 was evicted', zs[0], 8, dict(nm, pc={'save': 'saved', 'load': 'low_gain'}, entries=[e] * 3), self.Z80_CK) + self.creq(srv, 'R7b Z4 loads', zs[3], 8, + self.x(80, 75, 'ram_checkpoint', 'window_check', (44, 75), pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': 75}, + entries=[e] * 2, slot_ck=[44, 76], pos_min=55), []) + self.retire(srv) + # c: two checkpoints per slot, the entry of A2 keeps only (150, 181, 182) and (182, 213, 214) + A = rand_prompt(6720, 170) + srv = self.rserver('r7-ck2', k0, extra=['--ctx-checkpoints', '2']) + js, _ = self.creq(srv, None, A, 8, nm, []) + self.creq(srv, None, A + gen_of(js) + rand_prompt(6721, 40), 8, self.x(177, 177, 'slot', 'none', entries=[]), []) + self.creq(srv, None, Z, 8, dict(nm, entries=[(225, 193, [182, 214])]), [(150, 181, 182), (182, 213, 214)]) + self.creq(srv, 'R7c evicted checkpoints: A restores 0 from A2', A, 8, + dict(nm, pc={'save': 'saved', 'load': 'low_gain', 'r_slot': 0, 'r_entry': 0}, entries=[(225, 193, [182, 214]), (67, 35, [24, 56])]), self.Z_CK) + self.retire(srv) + + def r8(self, k0): + nm = self.x(0, 0, 'none', 'no_match') + Z, s6 = rand_prompt(6801, 80), rand_prompt(6802, 6) + if not k0: + K = 4 + finder = self.server('r8-find', 'tiny-dfly-b5.gguf') + prompt, gen = self.find_eos_prompt(finder, 24, 80) + self.retire(finder) + n = len(prompt) + ref = prompt + gen + P = n + len(gen) - 1 + for name, j, r_last in (('draft 1', 0, 4), ('draft 4', 3, 4), ('the correction', 2, 2), ('the bonus', 4, 4)): + srv = self.rserver(f'r8-{j}{r_last}', k0) + srv.script(ref=ref, r=plan_steps(n, P - 1 - j, K) + [r_last]) + js, rounds, rel, _ = srv.post({'prompt': prompt, 'n_predict': 400, 'temperature': 0, 'return_tokens': True, 'cache_prompt': False, 'seed': 42}) + srv.script() + last = rounds[-1] if rounds else {} + ok = (bool(rounds) and last['stopped'] and last['a'] + last['M'] == P and gen_of(js) == gen and len(rel) == 1 + and rel[0]['seq_pos_max'] + 1 == rel[0]['n_tokens'] == P) + self.res.add(f'R8 stop on {name}: the stopping request', ok, f'last round {({k: last.get(k) for k in ("a", "M", "r")})}, release {rel[:1]}, EOS pos {P}') + # the stopped state saves with E = P and the SWA from P - 32 + self.creq(srv, f'R8 stop on {name}: Z saves it', Z, 8, dict(nm, pc={'save': 'saved'}, entries=[(P, P - 32, [12])]), [(0, 11, 12)]) + self.creq(srv, f'R8 stop on {name}: the continuation loads it', prompt + gen + s6, 8, + self.x(P, P, 'ram', 'none', pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': P}, + entries=[(87, 55, [44, 76])], slot_ck=[12], pos_min=P - 32), []) + self.retire(srv) + p = rand_prompt(6803, 100) + srv = self.rserver('r8-limit', k0) + js, _ = self.creq(srv, None, p, 20, nm, []) + self.creq(srv, 'R8 limit stop: Z saves it', Z, 8, dict(nm, pc={'save': 'saved'}, entries=[(119, 87, [64, 96])]), [self.C1, self.C2]) + self.creq(srv, 'R8 limit stop: the continuation loads it', p + gen_of(js) + s6, 8, + self.x(119, 119, 'ram', 'none', pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': 119}, + entries=[(87, 55, [44, 76])], slot_ck=[64, 96], pos_min=87), []) + self.retire(srv) + + def r9(self, k0): + # an agent: a main session and 3 sub-sessions of 3 turns on one slot, dispatched in turn or round robin + S, m4 = rand_prompt(6900, 120), rand_prompt(6901, 4) + tasks = [] + for i in range(3): + t = rand_prompt(6910 + i, 40) + while t[0] in [m4[0]] + [u[0] for u in tasks]: + t[0] = 5 + (t[0] - 4) % 115 + tasks.append(t) + e1, e2, e3 = (167, 135, [88, 120, 124, 156]), (205, 173, [88, 120, 124, 156, 167, 194]), (243, 211, [88, 120, 124, 156, 167, 194, 205, 232]) + R = {1: 120, 2: 167, 3: 205} + orders = { + 'in turn': [(i, t) for i in range(3) for t in (1, 2, 3)], + 'round robin': [(i, t) for t in (1, 2, 3) for i in range(3)], + } + # per request after M: (save, load, r_slot, entries after); the in turn slot keeps the SWA from 0 + want = { + 'in turn': [('skipped', 'no_entry', 120, []), ('skipped', 'no_entry', 167, []), ('skipped', 'no_entry', 205, []), + ('saved', 'low_gain', 120, [e3]), ('skipped', 'low_gain', 167, [e3]), ('skipped', 'low_gain', 205, [e3]), + ('saved', 'low_gain', 120, [e3, e3]), ('skipped', 'low_gain', 167, [e3, e3]), ('skipped', 'low_gain', 205, [e3, e3])], + 'round robin': [('skipped', 'no_entry', 120, []), ('saved', 'low_gain', 120, [e1]), ('saved', 'low_gain', 120, [e1, e1]), + ('saved', 'loaded', 120, [e1, e1]), ('saved', 'loaded', 119, [e1, e2]), ('saved', 'loaded', 119, [e2, e2]), + ('saved', 'loaded', 119, [e2, e2]), ('saved', 'loaded', 119, [e2, e3]), ('saved', 'loaded', 119, [e3, e3])], + } + for oname, order in orders.items(): + srv = self.rserver('r9-' + oname.replace(' ', ''), k0) + hist = {} + prefill = 124 + self.creq(srv, None, S + m4, 8, self.x(0, 0, 'none', 'no_match'), []) + for step, ((i, t), (sv, ld, r_slot, ents)) in enumerate(zip(order, want[oname])): + prompt = S + tasks[i] if t == 1 else hist[i] + rand_prompt(6920 + 10 * i + t, 30) + ram = ld == 'loaded' + e = self.x(R[t], R[t], 'ram' if ram else 'slot', 'none', pc={'save': sv, 'load': ld, 'r_slot': r_slot}, entries=ents) + if ram: + e.update(slot_ck=[e1, e2, e3][t - 2][2], pos_min=[e1, e2, e3][t - 2][1]) + js, _ = self.creq(srv, f'R9 {oname} {step + 1}: session {i} turn {t}', prompt, 8, e, None) + hist[i] = prompt + gen_of(js) + prefill += js.get('timings', {}).get('prompt_n', 0) + self.res.add(f'R9 {oname}: prefill' + (' (K=0)' if k0 else ''), prefill == 430, f'{prefill} tokens, expected 124 + 3 x 40 + 6 x 31 = 430') + self.retire(srv) + + def r10(self): + srv = self.rserver('r10', False, extra=['--sleep-idle-seconds', '1']) + nm = self.x(0, 0, 'none', 'no_match') + A, Z = rand_prompt(6950, 170), rand_prompt(6951, 60) + self.creq(srv, None, A, 8, nm, []) + self.creq(srv, None, Z, 8, dict(nm, entries=[(177, 145, [134, 166])]), self.A_CK) + deadline = time.time() + 60 + while 'entering sleeping state' not in srv.log_text() and time.time() < deadline: + time.sleep(0.5) + if 'entering sleeping state' not in srv.log_text(): + self.res.add('R10 sleep (setup)', False, 'the server did not sleep') + # the resume makes the cache and the slots again: nothing to load, nothing to save + self.creq(srv, 'R10 after sleep', A, 8, dict(nm, pc={'save': 'empty', 'load': 'no_entry'}, entries=[]), []) + self.retire(srv) + + def r12(self, k0, seed, n_req): + """U11: random sequences; R is not predicted, the checks are G10 (the function), G2-G4, G6, G9 and G11""" + rng = random.Random(seed) + srv = self.rserver(f'r12-{seed}', k0) + hist, errs_all, n_load = [], [], 0 + prev_entries = 0 + for k in range(n_req): + op = rng.choice(['fork', 'cont', 'short', 'repeat', 'new', 'shared'] if hist else ['new']) + if op == 'fork': + h = rng.choice(hist) + prompt = self.fork(h, rng.randrange(1, len(h)) if len(h) > 1 else 1, rng.randrange(1 << 30), rng.randrange(1, 40)) + elif op == 'cont': + prompt = hist[-1] + rand_prompt(rng.randrange(1 << 30), rng.randrange(1, 40)) + elif op == 'short': + prompt = rand_prompt(rng.randrange(1 << 30), rng.randrange(1, 30)) + elif op == 'repeat': + prompt = list(rng.choice(hist)) + elif op == 'new': + prompt = rand_prompt(rng.randrange(1 << 30), rng.randrange(40, 200)) + else: + prompt = rng.choice(hist)[:rng.randrange(40, 160)] + rand_prompt(rng.randrange(1 << 30), rng.randrange(1, 60)) + prompt = prompt[:800] + n_predict = rng.randrange(1, 40) + js, rounds, rel, seg = srv.post({'prompt': prompt, 'n_predict': n_predict, 'temperature': 0, 'return_tokens': True, + 'seed': 42, 'ignore_eos': True, 'cache_prompt': True}) + N = len(prompt) + mets = METRIC.findall(seg) + restored = [tuple(map(int, m)) for m in HOOK_RESTORED.findall(seg)] + lines, hooks = parse_pcache(seg) + errs = [] + if js['_status'] != 200 or len(mets) != 1: + errs.append(f'status {js["_status"]}, metric {mets}') + else: + L, R, why = int(mets[0][0]), int(mets[0][1]), mets[0][4] + e = {'L': L, 'R': R, 'src': mets[0][3], 'why': why, 'restore': restored[0][:2] if restored else None, + 'pos_eval': N - 1 if L >= N else L} + errs += cache_checks(srv, prompt, js, rounds, rel, seg, e) + if lines and lines[0]['load'] == 'loaded': + n_load += 1 + # the loaded entry left the cache + if lines[0]['n_entries'] > prev_entries + (lines[0]['save'] == 'saved') - 1: + errs.append(f'G9: {lines[0]["n_entries"]} entries after a load, {prev_entries} before') + prev_entries = lines[0]['n_entries'] if lines else prev_entries + if errs: + errs_all.append((k, op, N, n_predict, errs[:3])) + hist.append(prompt + gen_of(js)[:max(0, len(gen_of(js)) - 1)]) + hist = hist[-12:] + self.res.add(f'R12 random seed {seed}' + (' (K=0)' if k0 else ''), not errs_all and srv.alive(), + f'{n_req} requests, {n_load} loads' + ('' if not errs_all else f'; errors {errs_all[:3]}')) + self.retire(srv) + + def r13(self, k0): + # a checkpoint made right after a resume at s keeps (s - 31, s - 1, s): its own window misses s - 32, so it is skipped + nm = self.x(0, 0, 'none', 'no_match') + p = rand_prompt(7001, 100) + srv = self.pserver('r13-slot', k0) + self.creq(srv, None, p, 300, nm, []) + # resumes at 95 and makes the short (64, 94, 95) + self.creq(srv, None, p, 300, self.x(100, 95, 'checkpoint', 'window_check', self.C2[:2]), []) + self.creq(srv, None, self.fork(p, 95, 7002, 8), 300, self.x(95, 95, 'checkpoint', 'window_check', self.C2[:2]), [self.C2]) + self.creq(srv, 'R13 slot: the short (64, 94, 95) is skipped, C1 restores', self.fork(p, 95, 7003, 8), 8, + self.x(95, 63, 'checkpoint', 'window_check', self.C1[:2]), [(64, 94, 95), (67, 98, 99)]) + self.retire(srv) + # a full match of an entry resumes at E - 1 = 176 with the SWA from 145 and makes the short (145, 175, 176) + X, Z, Z2 = rand_prompt(7010, 170), rand_prompt(7011, 60), rand_prompt(7012, 60) + srv = self.rserver('r13-ram', k0) + js, _ = self.creq(srv, None, X, 8, nm, []) + Xe = X + gen_of(js)[:7] + self.creq(srv, None, Z, 8, dict(nm, entries=[(177, 145, [134, 166])]), self.A_CK) + js, _ = self.creq(srv, None, Xe, 8, self.x(177, 176, 'ram', 'none', pc={'load': 'loaded', 'r_entry': 176}, entries=[(67, 35, [24, 56])]), []) + X2e = Xe + gen_of(js)[:7] + self.creq(srv, None, Z2, 8, dict(nm, entries=[(67, 35, [24, 56]), (184, 152, [134, 166, 176])]), self.A_CK + [(145, 175, 176)]) + self.creq(srv, 'R13 RAM: the short (145, 175, 176) of the entry is skipped', self.fork(X2e, 177, 7013, 8), 8, + self.x(177, 165, 'ram_checkpoint', 'window_check', (134, 165), pc={'save': 'saved', 'load': 'loaded', 'r_slot': 0, 'r_entry': 165}, + entries=[(67, 35, [24, 56]), (67, 35, [24, 56])], slot_ck=[134, 166, 176], pos_min=152), [(145, 175, 176)]) + self.retire(srv) + + def r_groups(self): + keys0 = set(self.ar_obs) + groups = [('R1', self.r1), ('R2', self.r2), ('R3', self.r3), ('R4', self.r4), ('R5', self.r5), ('R6', self.r6), ('R7', self.r7), + ('R8', self.r8), ('R9', self.r9), ('R13', self.r13)] + for name, f in groups: + if self.want(name): + f(True) + f(False) + if self.want('R10'): + self.r10() + if self.want('R12'): + for seed in (1, 2): + self.r12(True, seed, self.opts.r12_n) + self.r12(False, seed, self.opts.r12_n) + # the K = 0 runs of the R groups: the same checks, judged (AR changes A1-A8) + rk = {k: v for k, v in self.ar_obs.items() if k not in keys0} + if rk: + bad = [(k, v[1][:2]) for k, v in rk.items() if v[1]] + with open(os.path.join(self.opts.work, 'r-ar-control.json'), 'w') as f: + json.dump({k: {'obs': v[0], 'errors': v[1]} for k, v in rk.items()}, f, indent=1) + self.res.add('R AR control (K=0)', not bad, f'{len(rk)} K=0 requests, checks failing on {len(bad)}: {bad[:3]}') + + def p_groups(self): + groups = [('P1', self.p1), ('P2', self.p2), ('P3', self.p3), ('P5', self.p5), ('P6', self.p6), ('P7', self.p7), + ('P8', self.p8), ('P9', self.p9)] + for name, f in groups: + if self.want(name) or (name == 'P3' and self.want('P4')): + f(True) # the AR control on K = 0 first, so that the DFly rows can compare + f(False) + if self.want('P10'): + self.p10() + if self.want('P12'): + self.p12() + if self.ar_obs: + bad = [(k, v[1][:2]) for k, v in self.ar_obs.items() if v[1]] + with open(os.path.join(self.opts.work, 'ar-control.json'), 'w') as f: + json.dump({k: {'obs': v[0], 'errors': v[1]} for k, v in self.ar_obs.items()}, f, indent=1) + self.res.add('P AR control (recorded, not judged)', True, f'{len(self.ar_obs)} K=0 requests, checks failing on {len(bad)}: {bad[:3]}') + + def p11_rows(self): + # P11: the cache checks of every request of the L groups in primed / carry + for srv in self.servers: + if srv.mode == 'off': + continue + bad = [(r, e) for r, e in srv.g_rows if e] + self.res.add(f'P11 {srv.mode} {srv.name} cache checks', not bad, + f'{len(srv.g_rows)} requests, {srv.n_unpredicted} without an expected R' + ('' if not bad else f'; errors {bad[:3]}')) + if CACHE_MODE == 'carry': + with open(os.path.join(self.opts.work, 'carry-ref-notes.txt'), 'w') as f: + f.write('\n'.join(REF_NOTES) + '\n') + self.res.add('P11 carry: comparisons with a reference (recorded, not judged)', True, f'{len(REF_NOTES)} differ: {REF_NOTES[:3]}') + + # ---- M: several DFly slots (multi-seq design doc, 7.3) + def mserver(self, name, n, extra=(), cache=False, cache_ram=0, env_extra=None): + # -b == -ub, n * (1 + K) <= 64, the slots within the pool of 1024 cells + ex = ['--parallel', str(n), '-kvu', '-b', '64', '-ub', '64', '--kv-unified-per-slot', str(1024 // n)] + list(extra) + return self.server(name, 'tiny-dfly-b5.gguf', extra=ex, cache=cache, cache_ram=cache_ram, env_extra=env_extra) + + def m_post_all(self, srv, bodies, delays=None): + """post the bodies at once (or after their delays), each from its own thread; returns (responses, rounds per response)""" + n0 = srv.rounds_count() + res = [None] * len(bodies) + + def one(i): + if delays: + time.sleep(delays[i]) + r = HTTP.post(srv.url('/completion'), json=bodies[i], timeout=600) + js = r.json() + js['_status'] = r.status_code + res[i] = js + + th = [threading.Thread(target=one, args=(i,)) for i in range(len(bodies))] + for t in th: + t.start() + for t in th: + t.join() + time.sleep(0.1) + rounds = srv.rounds_since(n0) + return res, self.m_split(rounds, res) + + @staticmethod + def m_split(rounds, res): + """the H4 rounds of each response: grouped by request, matched by the slot and the generated tokens""" + by_req = {} + for rd in rounds: + if rd['kind'] != 'release': + by_req.setdefault(rd['req'], []).append(rd) + out = [] + used = set() + for js in res: + gen = gen_of(js) if js else [] + slot = js.get('id_slot') if js else None + cands = [k for k, v in by_req.items() if k not in used and v[0].get('slot') == slot and sum((rd['tokens'] for rd in v), []) == gen] + if cands: + used.add(cands[0]) + out.append(by_req[cands[0]]) + else: + out.append(None) + return out + + def m_body(self, prompt, n_predict, **kw): + body = {'prompt': prompt, 'n_predict': n_predict, 'temperature': 0, 'return_tokens': True, 'cache_prompt': False, + 'seed': 42, 'ignore_eos': True} + body.update(kw) + return body + + def m_check(self, case, srv, prompts, res, rr, refs, extra_info=''): + errs = [] + n_spec = n_try = n_eq = 0 + for i, (p, js, rounds) in enumerate(zip(prompts, res, rr)): + if js is None or js['_status'] != 200: + errs.append(f'request {i}: status {js and js["_status"]}') + continue + if rounds is None: + errs.append(f'request {i}: rounds not found') + continue + e, info = check_rounds(rounds, len(p), k_eff=4) + errs += [f'request {i}: {x}' for x in e[:2]] + n_spec += sum(1 for rd in rounds if rd['kind'] == 'spec') + n_try += sum(1 for rd in rounds if rd['k_step'] > 0) + if refs is not None: + n_eq += gen_of(js) == refs[i] + text = srv.log_text() + bad = 'bad snapshot' in text or 'not one ubatch' in text + firsts = FIRST_PROPOSE.findall(text) + # outputs == single runs is recorded only: the tiny target's logits are near ties, a batch of another shape flips + # them (AR with the same slots does so too, logs/MP); the state is judged by the round checks and by MU-01 + ok = not errs and n_spec == n_try and not bad + self.res.add(case, ok, f'{len(prompts)} requests, propose OK {n_spec}/{n_try}, outputs == single runs {n_eq}/{len(prompts) if refs else "-"} (recorded), ' + f'bad snapshot or not one ubatch logged: {bad}, first proposes {[f[1] for f in firsts][-len(prompts):]}{extra_info}' + + ('' if ok else f'; errors {errs[:4]}')) + return ok + + def m2(self, n): + srv = self.mserver(f'm2-p{n}', n) + # within the 1024 / n cells of a slot + prompts = [rand_prompt(500 + i, L) for i, L in enumerate([40, 300] if n == 2 else [16, 40, 150, 100])] + n_predict = 120 if n == 2 else 80 + refs = [] + for p in prompts: + js, _ = srv.complete(p, n_predict, ignore_eos=True) + refs.append(gen_of(js)) + res, rr = self.m_post_all(srv, [self.m_body(p, n_predict) for p in prompts]) + self.m_check(f'M2 {n} slots: concurrent == single', srv, prompts, res, rr, refs) + self.retire(srv) + + def m3(self, n): + srv = self.mserver(f'm3-p{n}', n) + p = rand_prompt(600, 40) + res, rr = self.m_post_all(srv, [self.m_body(p, 120) for _ in range(n)]) + same = all(gen_of(js) == gen_of(res[0]) for js in res) + self.m_check(f'M3 {n} slots: one prompt {n} times', srv, [p] * n, res, rr, None, f', all outputs equal {same} (recorded)') + self.retire(srv) + + def m4(self): + # A generates, B, C, D start while it does: A's proposes stay OK (per-sequence invalidate) + srv = self.mserver('m4-p4', 4) + prompts = [rand_prompt(700 + i, 30 + 10*i) for i in range(4)] + bodies = [self.m_body(prompts[0], 200)] + [self.m_body(p, 60) for p in prompts[1:]] + res, rr = self.m_post_all(srv, bodies, delays=[0, 0.5, 1.0, 1.5]) + a_rounds = rr[0] or [] + a_bad = [rd for rd in a_rounds[1:] if rd['k_step'] > 0 and rd['propose'] != 0] + self.m_check('M4 staggered starts', srv, prompts, res, rr, None, f', A rounds {len(a_rounds)}, A proposes not OK {len(a_bad)}') + self.retire(srv) + + def m5(self): + # a RAM load into one slot while another generates: the generating slot is not invalidated (per-sequence decode ids) + srv = self.mserver('m5-p2', 2, extra=['--no-cache-idle-slots'], cache=True, cache_ram=64) + P1, Q, R = rand_prompt(800, 420), rand_prompt(801, 30), rand_prompt(802, 30) + srv.complete(P1, 4, cache_prompt=True) + srv.complete(Q, 4, cache_prompt=True) + off = srv.log_size() + # R takes the slot of P1 (LRU), which saves P1; B = P1 + more takes the other slot and loads P1 back + bodies = [self.m_body(R, 300, cache_prompt=True), self.m_body(P1 + rand_prompt(803, 20), 60, cache_prompt=True)] + res, rr = self.m_post_all(srv, bodies, delays=[0, 1.5]) + seg = srv.log_from(off) + loaded = 'cache_load_decision = loaded' in seg + a_rounds = rr[0] or [] + a_bad = [rd for rd in a_rounds[1:] if rd['k_step'] > 0 and rd['propose'] != 0] + ok_extra = f', RAM load seen {loaded}, A proposes not OK {len(a_bad)}' + good = self.m_check('M5 RAM load next to a generating slot', srv, [R, bodies[1]['prompt']], res, rr, None, ok_extra) + if good and not loaded: + self.res.add('M5 RAM load happened', False, 'no RAM load in the log, the case did not test what it should') + self.retire(srv) + + def m8(self): + # design 4.11: a failed decode with A's verify and B's first prompt chunk; then both retry at once + for name, env in (('fail -3 before the compute', {'LLAMA_DFLY_TEST_MIXED_FAIL': '-3'}), + ('abort in the compute', {'LLAMA_DFLY_TEST_MIXED_ABORT': '1'})): + srv = self.mserver('m8-' + name.split()[0], 2, cache=True, env_extra=env) + A, B = rand_prompt(900, 40), rand_prompt(901, 200) + res, _ = self.m_post_all(srv, [self.m_body(A, 400, cache_prompt=True), self.m_body(B, 30, cache_prompt=True)], delays=[0, 1.0]) + failed = [js['_status'] != 200 for js in res] + text = srv.log_text() + # the retries: B's slot was cleared, so B prefills from 0 + res2, rr2 = self.m_post_all(srv, [self.m_body(A, 40, cache_prompt=True), self.m_body(B, 30, cache_prompt=True)]) + alive = srv.alive() + n_prompt_b = res2[1].get('timings', {}).get('prompt_n') if res2[1] else None + rel = [x for x in srv.rounds_since(0) if x['kind'] == 'release'] + g6 = all(x['seq_pos_max'] + 1 == x['n_tokens'] for x in rel) + ok = (failed == [True, True] and 'DFly verify failed' in text and alive and all(js['_status'] == 200 for js in res2) + and n_prompt_b == len(B) and g6 and 'pos_min == -1' not in srv.log_text()) + self.res.add(f'M8 {name}', ok, f'first requests failed {failed}, retries {[js["_status"] for js in res2]}, B retry prompt_n {n_prompt_b} ' + f'(prompt {len(B)}), server alive {alive}, releases with seq_pos_max + 1 == n_tokens {g6} ({len(rel)})') + self.retire(srv) + # exits 2 and 3: a verify that throws after a row, a prompt chunk that throws after adding its rows + for name, env in (('verify throws after row 0', {'LLAMA_DFLY_TEST_VERIFY_THROW': '6:0'}), + ('prompt chunk throws', {'LLAMA_DFLY_TEST_PROMPT_THROW': '3'})): + srv = self.mserver('m8-' + name.split()[0], 2, cache=True, env_extra=env) + A, B = rand_prompt(910, 40), rand_prompt(911, 200) + res, _ = self.m_post_all(srv, [self.m_body(A, 100, cache_prompt=True), self.m_body(B, 30, cache_prompt=True)], delays=[0, 1.5]) + st = [js['_status'] for js in res] + res2, _ = self.m_post_all(srv, [self.m_body(A, 40, cache_prompt=True), self.m_body(B, 30, cache_prompt=True)]) + rel = [x for x in srv.rounds_since(0) if x['kind'] == 'release'] + g6 = all(x['seq_pos_max'] + 1 == x['n_tokens'] for x in rel) + alive = srv.alive() + ok = st.count(200) == 1 and alive and all(js['_status'] == 200 for js in res2) and g6 and 'test hook' in srv.log_text() + self.res.add(f'M8 {name}', ok, f'first requests {st} (one fails), retries {[js["_status"] for js in res2]}, server alive {alive}, ' + f'releases with seq_pos_max + 1 == n_tokens {g6} ({len(rel)})') + self.retire(srv) + + def m12(self): + # design 4.12: with --no-cache-idle-slots an idle slot keeps its KV when another task starts + for idle, extra in (('--no-cache-idle-slots', ['--no-cache-idle-slots']), ('default', [])): + srv = self.mserver('m12-' + ('noidle' if extra else 'idle'), 2, extra=extra, cache=True, cache_ram=64) + A, B = rand_prompt(920, 300), rand_prompt(921, 300) + jsA, _ = srv.complete(A, 8, cache_prompt=True) + srv.complete(B, 8, cache_prompt=True) + off = srv.log_size() + js, _ = srv.complete(A + gen_of(jsA)[:-1] + rand_prompt(922, 10), 8, cache_prompt=True) + seg = srv.log_from(off) + m = METRIC.findall(seg) + src = m[-1][3] if m else None + loaded = 'cache_load_decision = loaded' in seg + want = 'slot' if extra else None + ok = js['_status'] == 200 and ((src == 'slot' and not loaded) if extra else (loaded or src != 'slot')) + self.res.add(f'M12 {idle}', ok, f'A again after B: restore_source {src}, RAM load {loaded} (expected {"slot, no load" if want else "a RAM load"})') + self.retire(srv) + + def m13(self): + # design 4.16: with --prompt-quota 16 a prompt next to a generating slot comes in chunks of at most 16 rows, + # the generating slot keeps a round per decode; without the quota the chunk takes what the batch has left + for quota in (16, 0): + srv = self.mserver(f'm13-q{quota}', 2, extra=['--prompt-quota', str(quota)]) + A, B = rand_prompt(930, 40), rand_prompt(931, 300) + res, rr = self.m_post_all(srv, [self.m_body(A, 400), self.m_body(B, 20)], delays=[0, 1.0]) + sb = res[1].get('id_slot') if res[1] else -1 + qs = [int(q) for q in re.findall(rf'id +{sb} \| task -?\d+ \| test hook: before prompt decode: q = (\d+)', srv.log_text())] + chunks = [b - a for a, b in zip(qs, qs[1:])] + a_errs, _ = check_rounds(rr[0] or [], len(A), k_eff=4) + if quota > 0: + ok = bool(chunks) and max(chunks) <= quota and not a_errs and all(js['_status'] == 200 for js in res) + else: + ok = bool(chunks) and max(chunks) > 16 and not a_errs + self.res.add(f'M13 --prompt-quota {quota}', ok, f'prompt chunks of B next to A: {chunks[:12]}, A round errors {a_errs[:2]}') + self.retire(srv) + + def m14(self): + # MP24: a task takes the prompt of another slot (seq_cp of the full KV, a copy of the SWA window, the checkpoints) + for name, extra in (('copy', []), ('--no-cache-slot-copy', ['--no-cache-slot-copy'])): + srv = self.mserver('m14-' + ('copy' if not extra else 'nocopy'), 2, extra=['--no-cache-idle-slots'] + extra, cache=True, cache_ram=64) + A = rand_prompt(940, 300) + jsA, _ = srv.complete(A, 8, cache_prompt=True) + sa = jsA.get('id_slot', 0) + # a: the idle slot of A holds the prompt of B but for the last 20 tokens, B is pinned to the other slot + B = A + gen_of(jsA)[:-1] + rand_prompt(941, 20) + off = srv.log_size() + res, rr = self.m_post_all(srv, [self.m_body(B, 60, cache_prompt=True, id_slot=1 - sa)]) + m = METRIC.findall(srv.log_from(off)) + src_a, reused_a = (m[-1][3], int(m[-1][1])) if m else (None, -1) + ok_a = self.m_check(f'M14 {name}: pinned slot, idle source', srv, [B], res, rr, None, f', restore_source {src_a}, reused {reused_a}') + # b: A' generates while B' = A' + 20 tokens arrives, B' takes the free slot (LRU) + A2 = rand_prompt(942, 300) + B2 = A2 + rand_prompt(943, 20) + off = srv.log_size() + res2, rr2 = self.m_post_all(srv, [self.m_body(A2, 300, cache_prompt=True), self.m_body(B2, 60, cache_prompt=True)], delays=[0, 1.0]) + seg = srv.log_from(off) + sb = res2[1].get('id_slot') if res2[1] else -1 + mb = [x for x in re.findall(rf'id +{sb} \| task -?\d+ \| prefix cache: prefix_match_tokens = (\d+), prefix_reused_tokens = (\d+), ' + rf'prefix_replayed_tokens = (-?\d+), restore_source = (\w+)', seg)] + src_b, reused_b = (mb[-1][3], int(mb[-1][1])) if mb else (None, -1) + a_bad = [rd for rd in (rr2[0] or [])[1:] if rd['k_step'] > 0 and rd['propose'] != 0] + ok_b = self.m_check(f'M14 {name}: busy source', srv, [A2, B2], res2, rr2, None, + f', B restore_source {src_b}, reused {reused_b}, A proposes not OK {len(a_bad)}') + rel = [x for x in srv.rounds_since(0) if x['kind'] == 'release'] + g6 = all(x['seq_pos_max'] + 1 == x['n_tokens'] for x in rel) + if extra: + want = src_a != 'copy' and src_b not in ('copy', 'copy_checkpoint') and reused_b == 0 + else: + want = src_a == 'copy' and reused_a >= len(A) and src_b in ('copy', 'copy_checkpoint') and reused_b >= len(A2) - 40 + self.res.add(f'M14 {name}: restore sources', ok_a and ok_b and want and g6 and not a_bad, + f'pinned: {src_a} {reused_a} (A {len(A)}), busy: {src_b} {reused_b} (A\' {len(A2)}), releases with seq_pos_max + 1 == n_tokens {g6}') + self.retire(srv) + + def m_groups(self): + for n in (2, 4): + if self.want('M2'): + self.m2(n) + if self.want('M3'): + self.m3(n) + if self.want('M4'): + self.m4() + if self.want('M5'): + self.m5() + if self.want('M8'): + self.m8() + if self.want('M12'): + self.m12() + if self.want('M13'): + self.m13() + if self.want('M14'): + self.m14() + + def run(self): + mode = CACHE_MODE + # P11: the L groups with the cache on; the AR servers are then K = 0 with the same cache + lk = {} if mode == 'off' else {'cache': True, 'mode': mode} + + def ar_server(name, extra=()): + if mode == 'off': + return self.server(name, 'tiny-dfly-b5.gguf', spec_type='none', extra=list(extra)) + return self.server(name, 'tiny-dfly-b5.gguf', extra=list(extra) + ['--spec-draft-n-max', '0'], **lk) + try: + if mode == 'off': + self.m_groups() + if self.want('C1'): + self.c1() + if self.want('C2'): + self.c2() + if self.want('C3'): + self.c3() + self.p_groups() + if self.opts.cache_ram_mib == 0: + self.r_groups() + if self.want('L10'): + self.l10(self.server('b5k4-l10', 'tiny-dfly-b5.gguf', **lk)) + need_b5 = any(self.want(c) for c in ('L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8', 'L9')) + if need_b5: + b5 = self.server('b5k4', 'tiny-dfly-b5.gguf', **lk) + if self.want('L7'): + self.l7(b5) + if self.want('L1'): + self.l1(b5) + if self.want('L2'): + self.l2(b5, 4, 'B=5 K=4') + if self.want('L3'): + self.l3(b5) + if self.want('L4') or self.want('L5'): + ar = ar_server('ar') + if self.want('L4'): + self.l4(b5, ar) + if self.want('L5'): + b5c = self.server('b5k4-c32', 'tiny-dfly-b5.gguf', extra=['--kv-unified-per-slot', '32'], **lk) + arc = ar_server('ar-c32', ['--kv-unified-per-slot', '32']) + self.l5(b5c, arc, b5) + if self.want('L6'): + self.l6(b5) + if self.want('L8'): + self.l8(b5) + if self.want('L9'): + self.l9(b5) + if self.want('L2'): + b8 = self.server('b8k7', 'tiny-dfly-b8.gguf', extra=['--spec-draft-n-max', '7'], **lk) + self.l2(b8, 7, 'B=8 K=7') + except Exception as e: + import traceback + traceback.print_exc() + self.res.add('driver', False, f'exception: {e!r}') + finally: + if mode != 'off': + self.p11_rows() + self.stop_all() + self.res.add('sanitizer', not self.sanitizer, f'reports {self.sanitizer}' if self.sanitizer else 'no ASan/UBSan report in any server log') + lines = [('PASS ' if ok else 'FAIL ') + case + ': ' + info for case, ok, info in self.res.rows] + n_fail = sum(1 for _, ok, _ in self.res.rows if not ok) + lines.append(f'== {len(self.res.rows) - n_fail}/{len(self.res.rows)} passed') + with open(self.opts.summary, 'w') as f: + f.write('\n'.join(lines) + '\n') + print(lines[-1]) + return n_fail == 0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--server', required=True) + ap.add_argument('--pair', required=True, help='directory of tiny-target.gguf and tiny-dfly-b{3,5,8}.gguf') + ap.add_argument('--work', required=True) + ap.add_argument('--summary', required=True) + ap.add_argument('--cases', default=None, help='comma separated groups, e.g. L1,L4') + ap.add_argument('--cache-mode', default='off', choices=['off', 'primed', 'carry'], + help='off: as the groups are; primed / carry: P11, the L groups with the prompt cache and the slot checkpoints') + ap.add_argument('--port', type=int, default=18700, help='the first server port, a run uses about 100') + ap.add_argument('--r12-n', type=int, default=50, help='R12: requests per random sequence') + ap.add_argument('--cache-ram-mib', type=int, default=0, + help='R11: the servers with the prompt cache use --cache-ram N instead of 0 (default thresholds); the R groups do not run') + opts = ap.parse_args() + global CACHE_MODE + CACHE_MODE = opts.cache_mode + opts.cases = set(opts.cases.split(',')) if opts.cases else None + Server.port_next = opts.port + os.makedirs(opts.work, exist_ok=True) + sys.exit(0 if Tests(opts).run() else 1) + + +if __name__ == '__main__': + main() diff --git a/tests/gguf-fixture.h b/tests/gguf-fixture.h new file mode 100644 index 0000000000000000000000000000000000000000..ce39308b47ab6b1914286020f1996fe3659e0003 --- /dev/null +++ b/tests/gguf-fixture.h @@ -0,0 +1,810 @@ +#pragma once + +#include "ggml.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" +#include "gguf.h" +#include "llama.h" +#include "llama-cpp.h" + +#include "../src/llama-ext.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// writes arch-resolved GGUF keys into the fixture context, the test-side equivalent of llama_model_saver +struct kv_writer { + struct gguf_context * gguf_ctx; + const llm_arch arch; + + kv_writer(enum llm_arch arch, struct gguf_context * gguf_ctx) : gguf_ctx(gguf_ctx), arch(arch) {} + + void add_kv(enum llm_kv key, uint32_t value) { gguf_set_val_u32 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } + void add_kv(enum llm_kv key, int32_t value) { gguf_set_val_i32 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } + void add_kv(enum llm_kv key, uint64_t value) { gguf_set_val_u64 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } + void add_kv(enum llm_kv key, float value) { gguf_set_val_f32 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } + void add_kv(enum llm_kv key, bool value) { gguf_set_val_bool(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } + void add_kv(enum llm_kv key, const char * value) { gguf_set_val_str (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } + + template + void add_kv(enum llm_kv key, const std::vector & value) { + if (value.empty()) { + return; + } + if (std::is_same::value) { + gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_UINT32, value.data(), value.size()); + } else if (std::is_same::value) { + gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_INT32, value.data(), value.size()); + } else if (std::is_same::value) { + gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_UINT64, value.data(), value.size()); + } else if (std::is_same::value) { + gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_FLOAT32, value.data(), value.size()); + } else { + GGML_ABORT("fatal error"); + } + } + + void add_kv(enum llm_kv key, const std::vector & value) { + std::vector tmp(value.size()); + for (size_t i = 0; i < value.size(); ++i) { + tmp[i] = value[i].c_str(); + } + gguf_set_arr_str(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), tmp.data(), tmp.size()); + } +}; + +struct tensor_data_params { + size_t seed; + float stdev; +}; + +// fills the values of one tensor, the name carries whatever the property needs +typedef void (*tensor_filler)(std::vector & dst, const char * name, const tensor_data_params & params); + +// a pool of normal draws, generated once and reused for every model +static std::vector g_normal_pool; +static const size_t NORMAL_POOL_SIZE = 16 * 1024 * 1024; + +// fill the pool once; each tensor copies a slice of it +static void init_normal_pool(const size_t seed, const float stdev) { + g_normal_pool.resize(NORMAL_POOL_SIZE); + std::mt19937 gen(seed); + std::normal_distribution dist(0.0f, stdev); + for (float & v : g_normal_pool) { + v = dist(gen); + } +} + +// a normal draw keyed on a name, so that tensors which share a draw ask for the same key +static void fill_normal(std::vector & dst, const char * key, const tensor_data_params &) { + const size_t n = dst.size(); + const size_t pool_size = g_normal_pool.size(); + const size_t start = std::hash{}(key) % pool_size; + + // copy a cyclic slice of the pool, so a tensor larger than the pool still fills + size_t i = 0; + size_t pos = start; + while (i < n) { + const size_t chunk = std::min(pool_size - pos, n - i); + std::memcpy(dst.data() + i, g_normal_pool.data() + pos, chunk * sizeof(float)); + i += chunk; + pos = 0; + } +} + +// Mamba A must be negative (state decay) +static void fill_ssm_a(std::vector & dst, const char * name, const tensor_data_params & params) { + fill_normal(dst, name, params); + for (float & v : dst) { + v = -fabsf(v); + } +} + +// a norm preserving residual gate holds alpha^2 + beta^2 == 1, and the conversion resolves both from one raw weight +// the alpha and the beta of a block share that weight, so the key drops the suffix and keeps the block +static void fill_resid_gate(std::vector & dst, const char * name, const tensor_data_params & params) { + const char * suffix = strstr(name, "_resid_"); + const bool is_beta = strstr(suffix, "_resid_beta") != nullptr; + fill_normal(dst, std::string(name, suffix - name).c_str(), params); + for (float & v : dst) { + const float beta = 1.0f / (1.0f + expf(-v)); + v = is_beta ? beta : sqrtf(1.0f - beta*beta); + } +} + +// a random router bias can tie within the noise between the backends, a ramp keeps the top-k selection the same +static void fill_exp_probs_b(std::vector & dst, const char *, const tensor_data_params &) { + for (size_t i = 0; i < dst.size(); i++) { + dst[i] = 2.0f*i; + } +} + +// a tensor whose values hold a property of their own, matched on a substring of its name, first match wins +static const struct { const char * match; tensor_filler fill; } TENSOR_FILLERS[] = { + { "ssm_a", fill_ssm_a }, + { "_resid_", fill_resid_gate }, + { "exp_probs_b", fill_exp_probs_b }, +}; + +static void set_tensor_data(struct ggml_tensor * tensor, void * userdata) { + const tensor_data_params & params = *(const tensor_data_params *) userdata; + + tensor_filler fill = fill_normal; + for (const auto & filler : TENSOR_FILLERS) { + if (strstr(tensor->name, filler.match) != nullptr) { + fill = filler.fill; + break; + } + } + + std::vector tmp(ggml_nelements(tensor)); + fill(tmp, tensor->name, params); + + if (tensor->type == GGML_TYPE_F32) { + ggml_backend_tensor_set(tensor, tmp.data(), 0, ggml_nbytes(tensor)); + } else if (tensor->type == GGML_TYPE_F16) { + std::vector tmp16(tmp.size()); + for (size_t i = 0; i < tmp.size(); i++) { + tmp16[i] = ggml_fp32_to_fp16(tmp[i]); + } + ggml_backend_tensor_set(tensor, tmp16.data(), 0, ggml_nbytes(tensor)); + } else { + GGML_ABORT("fatal error"); + } +} + +static std::vector get_tokens(const uint32_t n_tokens, const uint32_t n_vocab, const size_t seed){ + std::mt19937 gen(seed); + std::uniform_int_distribution<> dis(0, n_vocab - 1); + std::vector ret; + ret.reserve(n_tokens); + for (uint32_t i = 0; i < n_tokens; i++) { + ret.push_back(dis(gen)); + } + return ret; +} + +// MoE archs that are also tested with the experts in host memory +static bool host_experts_test(const llm_arch arch) { + switch (arch) { + case LLM_ARCH_DEEPSEEK2: + return true; + default: + return false; + } +} + +static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const uint32_t n_layer_override = 0) { + gguf_context_ptr ret(gguf_init_empty()); + kv_writer ms(arch, ret.get()); + const uint32_t n_ctx = 256; + + uint32_t n_vocab = 128; + uint32_t n_embd = 256; + uint32_t n_head = 2; + uint32_t n_ff = 384; + uint32_t n_layer = 2; + if (arch == LLM_ARCH_LLAMA4) { + n_layer = 4; // hparams.n_no_rope_layer_step is hard-coded to 4 + } else if (arch == LLM_ARCH_MAION_CODER) { + n_head = 4; + n_layer = 4; // dense and MoE layers, each with local and full attention + } else if (arch == LLM_ARCH_GEMMA4) { + // TODO: expand coverage to both GQA and MQA (see https://github.com/ggml-org/llama.cpp/pull/31401#pullrequestreview-5710165130) + n_head = 4; + n_layer = 10; // last 5 layers reuse KV, both SWA and full attention + } else if (arch == LLM_ARCH_GEMMA3N) { + n_embd = 64; + n_head = 1; + n_ff = 96; + n_layer = 22; // hparams.n_layer_kv_from_start = 20 is hardcoded + } else if (arch == LLM_ARCH_LFM3) { + n_layer = 3; + } else if (arch == LLM_ARCH_DEEPSEEK4) { + // head size 64 so that GPU flash attention kernels support the model + n_embd = 512; + n_head = 8; + n_ff = 1024; + n_layer = 4; + } else if (arch == LLM_ARCH_DEEPSEEK41) { + // window-only, Engram, ratio-2 and ratio-1 sources, top-k reuse and a candidate-masked index layer + n_embd = 512; + n_head = 8; + n_ff = 1024; + n_layer = 6; + } else if (arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_LAGUNA) { + n_embd = 160; // exercise per-head tensor split granularity with head size 80 + } else if (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_AFMOE) { + n_head = 4; + } else if (arch == LLM_ARCH_LIMITE) { + n_head = 4; + n_layer = 4; // dense connections on the last two layers + } else if (arch == LLM_ARCH_DEEPSEEK2 + || arch == LLM_ARCH_DEEPSEEK32 + || arch == LLM_ARCH_GLM_DSA + || arch == LLM_ARCH_DOTS3NOTE + || arch == LLM_ARCH_KIMI_LINEAR + || arch == LLM_ARCH_BAILINGMOE3 + || arch == LLM_ARCH_KIMI_K3 + || arch == LLM_ARCH_GLM5_NEXT + || arch == LLM_ARCH_MISTRAL4 + || arch == LLM_ARCH_MISTRAL_LARGE4 + || arch == LLM_ARCH_HY_V4 + || arch == LLM_ARCH_HY_V4_FLASH) { + n_embd = 128; + n_head = 1; + n_ff = 192; + if (arch == LLM_ARCH_MISTRAL_LARGE4) { + n_layer = 4; // cover NoPE, shared indexer and KV sharing layers + } + if (arch == LLM_ARCH_HY_V4_FLASH) { + n_layer = 4; // dense + MoE across both sparse and sliding attention layers + } + } else if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { + n_layer = 3; + } else if (arch == LLM_ARCH_CHAMELEON) { + n_vocab = 10240; + } else if (arch == LLM_ARCH_QWEN3TTS) { + //n_vocab = 4096; // must be >= the hard-coded codec head size (3072) + n_vocab = 3072; // TODO: should be 4096, but user code cannot get `n_vocab_out` yet [TAG_LLAMA_N_VOCAB_OUT] + } else if (arch == LLM_ARCH_HRM_TEXT) { + n_layer = 6; // 1 layer per stack x 2 h-cycles x (2 l-cycles + 1) cache slots + } + + uint32_t n_head_kv = n_head; + if (arch == LLM_ARCH_QWEN3) { + n_head_kv = 1; // MQA coverage + } else if (arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_AFMOE || arch == LLM_ARCH_MAION_CODER || + arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_LIMITE || arch == LLM_ARCH_GEMMA4) { + n_head_kv = 2; // GQA coverage + } + if (arch == LLM_ARCH_BEAM) { + n_head = 4; + n_head_kv = 2; + n_layer = 4; + } + // n_layer_override is only verified for hy_v4_flash, whose per-layer arrays all follow n_layer + n_layer = n_layer_override != 0 ? n_layer_override : n_layer; + const uint32_t n_embd_head = n_embd / n_head; + + ms.add_kv(LLM_KV_GENERAL_ARCHITECTURE, llama_arch_name(arch)); + ms.add_kv(LLM_KV_VOCAB_SIZE, n_vocab); + ms.add_kv(LLM_KV_CONTEXT_LENGTH, n_ctx); + ms.add_kv(LLM_KV_EMBEDDING_LENGTH, n_embd); + ms.add_kv(LLM_KV_FEATURES_LENGTH, n_embd); + ms.add_kv(LLM_KV_BLOCK_COUNT, n_layer); + ms.add_kv(LLM_KV_LEADING_DENSE_BLOCK_COUNT, uint32_t(1)); + + if (arch == LLM_ARCH_K2_HORIZON) { + ms.add_kv(LLM_KV_ROPE_SCALING_YARN_BETA_FAST, 128.0f); + ms.add_kv(LLM_KV_ROPE_SCALING_YARN_BETA_SLOW, 4.0f); + } + + if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { + std::vector n_ff_per_layer; + n_ff_per_layer.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + n_ff_per_layer.push_back(il <= 1 ? 0 : n_ff); + } + ms.add_kv(LLM_KV_FEED_FORWARD_LENGTH, n_ff_per_layer); + } else { + ms.add_kv(LLM_KV_FEED_FORWARD_LENGTH, n_ff); + } + + ms.add_kv(LLM_KV_USE_PARALLEL_RESIDUAL, false); + ms.add_kv(LLM_KV_LOGIT_SCALE, 1.0f); + ms.add_kv(LLM_KV_TIME_MIX_EXTRA_DIM, uint32_t(64)); + ms.add_kv(LLM_KV_TIME_DECAY_EXTRA_DIM, uint32_t(128)); + ms.add_kv(LLM_KV_FULL_ATTENTION_INTERVAL, uint32_t(2)); + + if (arch == LLM_ARCH_PLAMO2 || arch == LLM_ARCH_JAMBA || arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE || + arch == LLM_ARCH_GRANITE_HYBRID || arch == LLM_ARCH_LFM2 || arch == LLM_ARCH_LFM2MOE || arch == LLM_ARCH_LFM3 || + arch == LLM_ARCH_KIMI_LINEAR || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_GLM5_NEXT || + arch == LLM_ARCH_HY_V4_FLASH + ) { + GGML_ASSERT(n_layer >= 2); + std::vector n_head_per_layer; + n_head_per_layer.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + // hy_v4_flash has no recurrent layer: the odd layers are sliding-window and + // carry twice the heads over the same latent geometry + n_head_per_layer.push_back(arch == LLM_ARCH_HY_V4_FLASH + ? (il % 2 ? 2*n_head : n_head) + : (il == 1 ? 0 : n_head)); + } + // GLM5 next KDA heads come from the uniform head count, only head_count_kv is per layer. + if (arch == LLM_ARCH_GLM5_NEXT) { + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head); + } else { + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head_per_layer); + } + if (arch == LLM_ARCH_HY_V4_FLASH) { + // MLA-as-MQA: one latent KV head on every layer, whatever the query head count + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, uint32_t(1)); + } else { + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer); + } + } else { + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head); + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(1) : n_head_kv); + } + + ms.add_kv(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, 8.0f); + if (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) { + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH, n_embd_head); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH, n_embd_head); + ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, n_embd_head/2); + } else if (arch == LLM_ARCH_DEEPSEEK2 + || arch == LLM_ARCH_DEEPSEEK32 + || arch == LLM_ARCH_GLM_DSA + || arch == LLM_ARCH_DOTS3NOTE + || arch == LLM_ARCH_KIMI_LINEAR + || arch == LLM_ARCH_BAILINGMOE3 + || arch == LLM_ARCH_KIMI_K3 + || arch == LLM_ARCH_GLM5_NEXT + || arch == LLM_ARCH_HY_V4 + || arch == LLM_ARCH_HY_V4_FLASH + || arch == LLM_ARCH_MISTRAL4 + || arch == LLM_ARCH_MISTRAL_LARGE4) { + // GLM5 next MLA is nope only, the cache row is the compressed latent alone. + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH, arch == LLM_ARCH_GLM5_NEXT ? uint32_t(512) : uint32_t(576)); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH, uint32_t(512)); + ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, arch == LLM_ARCH_GLM5_NEXT ? uint32_t(0) : uint32_t(64)); + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA, uint32_t(192)); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, uint32_t(128)); + if (arch == LLM_ARCH_DOTS3NOTE) { + // SWA layers reuse the same MLA geometry as the full layers in this fixture + ms.add_kv(LLM_KV_ATTENTION_KV_LORA_RANK_SWA, uint32_t(512)); + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, uint32_t(576)); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, uint32_t(512)); + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA_SWA, uint32_t(192)); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_MLA_SWA, uint32_t(128)); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + // indexer on the full-attention layers (inverse of the swa pattern) + std::vector indexer_types; + indexer_types.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + indexer_types.push_back(il % 2 ? 0 : 1); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); + } + } else if (arch == LLM_ARCH_MINIMAX_M3) { + // partial rotary: n_rot must not exceed the indexer key length (64) + ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, uint32_t(64)); + } + if (arch == LLM_ARCH_SENSENOVA_U1) { + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SPATIAL, 10000.0f); + } + ms.add_kv(LLM_KV_ATTENTION_CLAMP_KQV, 1.0f); + ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, 1e-5f); + ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f); + ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, 1e-5f); + ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, uint32_t(8)); + ms.add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(64) : uint32_t(512)); + ms.add_kv(LLM_KV_ATTENTION_KV_LORA_RANK, uint32_t(512)); + ms.add_kv(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, uint32_t(8)); + ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW, n_ctx/8); + + if (arch == LLM_ARCH_MAION_CODER) { + ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector{1, 1, 0, 0}); + } else if (arch == LLM_ARCH_GEMMA4) { + ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, n_embd/2); + ms.add_kv(LLM_KV_ATTENTION_SHARED_KV_LAYERS, uint32_t(5)); + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, n_embd_head); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, n_embd_head); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + // SWA pattern: every 5th layer is full attention (matches E2B layer_types) + std::vector pattern; + pattern.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + pattern.push_back((il + 1) % 5 != 0); + } + ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); + } else if (arch == LLM_ARCH_COHERE2MOE || arch == LLM_ARCH_MIMO2 || arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_SPARK2_5 || + arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_GRANITE_SWA || arch == LLM_ARCH_DOTS3NOTE || + arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || + arch == LLM_ARCH_HY_V4_FLASH) { + std::vector pattern; + pattern.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + pattern.push_back(il % 2); + } + ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); + if (arch == LLM_ARCH_FLINT) { + ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, pattern); + } + } else if (arch == LLM_ARCH_LFM3) { + ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector({0, 0, 1})); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + } else { + ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, uint32_t(2)); + } + + if (arch == LLM_ARCH_MUSE_SPARK) { + ms.add_kv(LLM_KV_POST_NORM_EPS, 1e-5f); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + ms.add_kv(LLM_KV_FINAL_LOGIT_SOFTCAPPING, 30.0f); + ms.add_kv(LLM_KV_MOE_LATENT_SIZE, n_embd/2); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + } + + if (arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_LIMITE) { + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, false); + } + + // MSA requires one indexer head per GQA (KV) head, unlike the DSA archs where the + // indexer head count is independent of the main attention head count. + if (arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_GLM5_NEXT) { + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS, uint32_t(2)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_LOW_RANK, uint32_t(8)); + // without this the QSA layers fall back to dense and go uncovered + ms.add_kv(LLM_KV_ATTENTION_COMPRESS_RATIOS, std::vector(n_layer, 4)); + + // has_cell_ext() needs ple_n_heads here: the indexer cache serializes no ext without it + const uint32_t ple_ngram_size = 3; + const uint32_t ple_heads_per_ngram = 2; + const uint32_t ple_n_heads = (ple_ngram_size - 1)*ple_heads_per_ngram; + GGML_ASSERT(n_embd % ple_n_heads == 0); + const uint32_t ple_head_dim = n_embd/ple_n_heads; + + std::vector ple_head_offsets(ple_n_heads); + std::vector ple_head_vocab_sizes(ple_n_heads, n_vocab); + for (uint32_t h = 0; h < ple_n_heads; h++) { + ple_head_offsets[h] = uint64_t(h)*n_vocab; + } + + // the PLE history lives in the recurrent cache, so it must sit on a linear attention layer + ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({ 0 })); + ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, ple_ngram_size); + ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, ple_heads_per_ngram); + ms.add_kv(LLM_KV_PLE_CONV_KERNEL, uint32_t(4)); + ms.add_kv(LLM_KV_PLE_EOS_TOKEN_ID, uint32_t(0)); + ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, ple_head_dim); + ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({ 1, 3, 5 })); + ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, ple_head_offsets); + ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, ple_head_vocab_sizes); + } + + // minimax-m3 keeps one indexer head per GQA head; the rest use a fixed 64 to match the fused + ms.add_kv(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, arch == LLM_ARCH_MINIMAX_M3 ? n_head : uint32_t(64)); + // qwen4exp ropes indexer keys with the main rotary width, so its head can't be < n_rot + ms.add_kv(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, + arch == LLM_ARCH_QWEN4EXP ? n_embd_head : uint32_t(128)); + + // note: using a realistic top-k here makes the results unstable and hard to match between CPU and GPU + // a large value makes things deterministic since all data is selected by the indexer + //ms.add_kv(LLM_KV_ATTENTION_INDEXER_TOP_K, uint32_t(8)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TOP_K, uint32_t(131072)); + + ms.add_kv(LLM_KV_ATTENTION_INDEXER_BLOCK_SIZE, uint32_t(4)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_KPOOL, uint32_t(4)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_KPOOL_SELECT_TAIL, true); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, uint32_t(1)); + // mrope sections count rope pairs; Ling 3.0 VL files carry [t, h, w] sections + // summing to n_rot / 2 (n_rot is 64 in this fixture) + if (arch == LLM_ARCH_BAILINGMOE3) { + ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({8, 12, 12, 0})); + } else { + ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({n_embd_head/4, n_embd_head/4, n_embd_head/4, n_embd_head/4})); + } + + if (arch == LLM_ARCH_HY_V4) { + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + // layer 0 must own an indexer, the odd layers share it + std::vector indexer_types; + indexer_types.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + indexer_types.push_back(il % 2 ? 0 : 1); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); + } + + if (arch == LLM_ARCH_HY_V4_FLASH) { + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + // the sliding window and its il%2 pattern come from the shared blocks above, + // which is what the per-layer head count is matched to + // the indexer lives on the non-SWA layers, which here are the even ones. The shared + // INDEXER_TOP_K above is deliberately huge, so every pool is selected and the result stays + // comparable with the full-attention path. + { + std::vector indexer_types; + indexer_types.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + indexer_types.push_back(il % 2 ? 0 : 1); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, uint32_t(96)); + + // one Engram module, on layer 1. The bucket counts are tiny but must stay distinct and + // above 1, and their running sum is what the head offsets rebase into. + { + // the loader reads the bucket ranges as u64 arrays + const std::vector primes = {7, 11, 13, 17}; + std::vector offsets; + uint64_t base = 0; + for (uint64_t p : primes) { + offsets.push_back(base); + base += p; + } + ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({1})); + ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, uint32_t(3)); + ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, uint32_t(2)); + ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, uint32_t(32)); + // n_modules * ngram_size multipliers, odd as the reference derives them + ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({3, 5, 7})); + ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, offsets); + ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, primes); + ms.add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, uint32_t(1)); + std::vector token_map(n_vocab); + for (uint32_t t = 0; t < n_vocab; t++) { + token_map[t] = (int32_t) t; + } + ms.add_kv(LLM_KV_ENGRAM_TOKEN_MAP, token_map); + } + } + + if (arch == LLM_ARCH_MISTRAL_LARGE4) { + // layer 3 reads the KV cache of layer 2, both are NoPE + ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, std::vector({1, 1, 0, 0})); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, std::vector({1, 0, 1, 1})); + ms.add_kv(LLM_KV_ATTENTION_KV_SOURCE_MAP, std::vector({0, 1, 2, 2})); + ms.add_kv(LLM_KV_FINAL_LOGIT_SOFTCAPPING, 30.0f); + } + + if (arch == LLM_ARCH_DEEPSEEK4) { + ms.add_kv(LLM_KV_ATTENTION_OUTPUT_GROUP_COUNT, uint32_t(8)); + ms.add_kv(LLM_KV_ATTENTION_OUTPUT_LORA_RANK, uint32_t(32)); + ms.add_kv(LLM_KV_ATTENTION_COMPRESS_RATIOS, std::vector({0, 0, 4, 128})); + ms.add_kv(LLM_KV_ATTENTION_COMPRESS_ROPE_FREQ_BASE, 160000.0f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS, uint32_t(2)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HASH_LAYER_COUNT, uint32_t(0)); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + } + + if (arch == LLM_ARCH_DEEPSEEK41) { + ms.add_kv(LLM_KV_ATTENTION_OUTPUT_GROUP_COUNT, uint32_t(8)); + ms.add_kv(LLM_KV_ATTENTION_OUTPUT_LORA_RANK, uint32_t(32)); + ms.add_kv(LLM_KV_ATTENTION_COMPRESS_RATIOS, std::vector({0, 0, 2, 2, 1, 1})); + ms.add_kv(LLM_KV_ATTENTION_COMPRESS_ROPE_FREQ_BASE, 160000.0f); + ms.add_kv(LLM_KV_ATTENTION_KV_SOURCE_LAYERS, std::vector({2, 4})); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_SOURCE_LAYERS, std::vector({2, 4, 5})); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_SOURCE_LAYER, int32_t(4)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_TOP_K_BLOCKS, uint32_t(4096)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_BLOCK_SIZE, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS, uint32_t(2)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HASH_LAYER_COUNT, uint32_t(0)); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + std::vector token_map(n_vocab); + for (uint32_t i = 0; i < n_vocab; ++i) { + token_map[i] = (int32_t) (i % 61); + } + ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({1, 3})); + ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, uint32_t(3)); + ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, uint32_t(2)); + ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, uint32_t(64)); + ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({ 76632096046245ull, 4839876093313ull, 35959672319349ull, + 67716810739261ull, 51510806800915ull, 30921347202721ull })); + ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, std::vector({0, 101, 204, 311, 420, 533, 660, 791})); + ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, std::vector({101, 103, 107, 109, 113, 127, 131, 137})); + ms.add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, uint32_t(2)); + ms.add_kv(LLM_KV_ENGRAM_TOKEN_MAP, token_map); + } + + if (arch == LLM_ARCH_HRM_TEXT) { + // 6 cache slots alias 2 physical blocks: 1 low-stack layer + 1 high-stack layer + ms.add_kv(LLM_KV_HRM_LAYERS_PER_STACK, uint32_t(1)); + ms.add_kv(LLM_KV_HRM_H_CYCLES, uint32_t(2)); + ms.add_kv(LLM_KV_HRM_L_CYCLES, uint32_t(2)); + } + + if (arch == LLM_ARCH_MAPLE) { + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 7.0f); + } + + if (arch == LLM_ARCH_LIMITE) { + ms.add_kv(LLM_KV_ATTENTION_SCALE, 0.1f); + ms.add_kv(LLM_KV_ATTENTION_XSA_EPS, 1e-4f); + ms.add_kv(LLM_KV_FINAL_LOGIT_SIGMOID_CAPPING, std::vector({23.0f, 5.0f, 7.5f})); + ms.add_kv(LLM_KV_MUDD_FEED_FORWARD_LENGTH, uint32_t(8)); + ms.add_kv(LLM_KV_MUDD_TAP_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_MUDD_TAP_INDICES, std::vector({-1, -1, -1, -1, 0, 2, 1, 3})); + } + + // dummy tokenizer: token ids are derived from fixed-size chunks and detokenized as hex ids + { + std::vector tokenizer_list(n_vocab); + std::vector tokenizer_scores(n_vocab, 0.0f); + + ms.add_kv(LLM_KV_TOKENIZER_MODEL, "test"); + for (uint32_t i = 0; i < n_vocab; i++) { + tokenizer_list[i] = "tok_" + std::to_string(i); + } + ms.add_kv(LLM_KV_TOKENIZER_LIST, tokenizer_list); + ms.add_kv(LLM_KV_TOKENIZER_SCORES, tokenizer_scores); + } + + // ms.add_kv(LLM_KV_DENSE_2_FEAT_OUT, n_embd); + // ms.add_kv(LLM_KV_DENSE_3_FEAT_IN, n_embd); + + if (moe) { + ms.add_kv(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, n_ff); + ms.add_kv(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, n_ff / 2); // distinct from n_ff so a saver key-clobber surfaces on reload + // keep the latent width distinct from n_ff_exp, or a transposed routed_down / routed_up + // would still load and the orientation would go untested + ms.add_kv(LLM_KV_EXPERT_LATENT_LENGTH, arch == LLM_ARCH_HY_V4_FLASH ? uint32_t(64) : n_ff); + ms.add_kv(LLM_KV_INTERLEAVE_MOE_LAYER_STEP, uint32_t(2)); + // with more experts than a ubatch uses, the copy of the used experts in host memory skips some of them + ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(host_experts_test(arch) ? 64 : arch == LLM_ARCH_CLOVER_MOE ? 4 : 2)); + ms.add_kv(LLM_KV_EXPERT_USED_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_EXPERT_SHARED_COUNT, uint32_t(1)); + + uint32_t gating_func = 2; + switch (arch) { + case LLM_ARCH_MELLUM: + gating_func = 1; + break; + case LLM_ARCH_DEEPSEEK4: + case LLM_ARCH_DEEPSEEK41: + gating_func = 4; + break; + default: + break; + } + + ms.add_kv(LLM_KV_EXPERT_GATING_FUNC, gating_func); // sigmoid : softmax : sqrtsoftplus + ms.add_kv(LLM_KV_EXPERT_GROUP_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERTS_PER_GROUP, uint32_t(1)); + if (arch == LLM_ARCH_FLINT) { + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + } + if (arch == LLM_ARCH_K2_HORIZON) { + ms.add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_USED_COUNT, uint32_t(2)); + } + } + + if (arch == LLM_ARCH_BEAM) { + ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(8)); + ms.add_kv(LLM_KV_EXPERT_GROUP_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_EXPERT_GROUP_USED_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 2.5f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + } + + if (arch == LLM_ARCH_MAION_CODER) { + ms.add_kv(LLM_KV_MOE_LATENT_SIZE, n_embd / 2); + ms.add_kv(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, std::vector{n_ff, n_ff / 2, n_ff, n_ff}); + } + + ms.add_kv(LLM_KV_POSNET_EMBEDDING_LENGTH, n_embd); + ms.add_kv(LLM_KV_POSNET_BLOCK_COUNT, n_layer); + ms.add_kv(LLM_KV_CONVNEXT_EMBEDDING_LENGTH, n_embd); + ms.add_kv(LLM_KV_CONVNEXT_BLOCK_COUNT, n_layer); + ms.add_kv(LLM_KV_XIELU_ALPHA_N, 1.0f); + ms.add_kv(LLM_KV_XIELU_ALPHA_P, 1.0f); + ms.add_kv(LLM_KV_XIELU_BETA, 1.0f); + ms.add_kv(LLM_KV_XIELU_EPS, 1.0e-7f); + ms.add_kv(LLM_KV_SSM_INNER_SIZE, arch == LLM_ARCH_QWEN3NEXT || arch == LLM_ARCH_QWEN35 || arch == LLM_ARCH_QWEN35MOE || arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_CLOVER_MOE ? 256 : 2*n_embd); + ms.add_kv(LLM_KV_SSM_CONV_KERNEL, uint32_t(4)); + ms.add_kv(LLM_KV_SSM_STATE_SIZE, uint32_t(128)); + ms.add_kv(LLM_KV_SSM_TIME_STEP_RANK, n_head); + ms.add_kv(LLM_KV_SSM_GROUP_COUNT, arch == LLM_ARCH_PLAMO2 ? 0 : uint32_t(2)); + ms.add_kv(LLM_KV_KDA_HEAD_DIM, uint32_t(128)); + ms.add_kv(LLM_KV_KDA_SAFE_GATE, true); + ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f); + if (arch == LLM_ARCH_BAILINGMOE3) { + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, std::vector({0.0f, 4.0f})); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_SHEXP, std::vector({0.0f, 5.0f})); + } + ms.add_kv(LLM_KV_WKV_HEAD_SIZE, n_embd/n_head); + ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(3)); + ms.add_kv(LLM_KV_RESIDUAL_SCALE, 3.5565588200778455f); + ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(12)); + ms.add_kv(LLM_KV_ACTIVATION_SITU_BETA, 4.0f); + ms.add_kv(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, 25.0f); + ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f); + + for (uint32_t il = 0; il < n_layer; il++) { + ggml_tensor t; + memset(&t, 0, sizeof(ggml_tensor)); + t.type = GGML_TYPE_F16; + ggml_format_name(&t, "conv%" PRIu32 "d.weight", il); + gguf_add_tensor(ms.gguf_ctx, &t); + ggml_format_name(&t, "posnet.%" PRIu32 ".conv1.weight", il); + gguf_add_tensor(ms.gguf_ctx, &t); + ggml_format_name(&t, "posnet.%" PRIu32 ".conv2.weight", il); + gguf_add_tensor(ms.gguf_ctx, &t); + ggml_format_name(&t, "convnext.%" PRIu32 ".dw.weight", il); + gguf_add_tensor(ms.gguf_ctx, &t); + } + return ret; +} + +static bool silent_model_load_progress(float /*progress*/, void * /*user_data*/) { + return true; +} + +// the 10-layer hy_v4_flash tiny target: even layers are sparse with an indexer, odd ones sliding window +struct hy_v4_flash_tiny { + uint32_t n_layer = 10; + uint32_t top_k = 8; // indexer.top_k, the S a paired DFly draft uses + uint32_t n_swa = 32; + uint32_t n_ctx_train = 1u << 20; + float rope_base = 1e7f; // the sparse layers; the window layers keep the fixture's 1e4 + size_t seed = 42; + float stdev = 0.1f; + ggml_backend_dev_t dev = nullptr; // nullptr: the CPU device alone; else this device alone, all layers on it + const llama_model_tensor_buft_override * overrides = nullptr; // tensor_buft_overrides, nullptr-terminated + int64_t eos_id = -1; // tokenizer.ggml.eos_token_id if >= 0, the test vocab has none +}; + +static llama_model_ptr hy_v4_flash_tiny_target(const hy_v4_flash_tiny & p) { + const llm_arch arch = LLM_ARCH_HY_V4_FLASH; + + gguf_context_ptr gguf_ctx = get_gguf_ctx(arch, true, p.n_layer); + gguf_set_val_u32(gguf_ctx.get(), llama_arch_kv_name(arch, LLM_KV_CONTEXT_LENGTH).c_str(), p.n_ctx_train); + gguf_set_val_u32(gguf_ctx.get(), llama_arch_kv_name(arch, LLM_KV_ATTENTION_INDEXER_TOP_K).c_str(), p.top_k); + gguf_set_val_u32(gguf_ctx.get(), llama_arch_kv_name(arch, LLM_KV_ATTENTION_SLIDING_WINDOW).c_str(), p.n_swa); + gguf_set_val_f32(gguf_ctx.get(), llama_arch_kv_name(arch, LLM_KV_ROPE_FREQ_BASE).c_str(), p.rope_base); + if (p.eos_id >= 0) { + gguf_set_val_u32(gguf_ctx.get(), llama_arch_kv_name(arch, LLM_KV_TOKENIZER_EOS_ID).c_str(), (uint32_t) p.eos_id); + } + + // the pool is global and anyone may have refilled it: rebuild unless its head matches a fresh draw + { + std::mt19937 gen(p.seed); + std::normal_distribution dist(0.0f, p.stdev); + float head[16]; + for (float & v : head) { + v = dist(gen); + } + if (g_normal_pool.size() != NORMAL_POOL_SIZE || memcmp(g_normal_pool.data(), head, sizeof(head)) != 0) { + init_normal_pool(p.seed, p.stdev); + } + } + + ggml_backend_dev_t devs[] = { p.dev ? p.dev : ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr }; + + llama_model_params mp = llama_model_default_params(); + mp.devices = devs; + mp.progress_callback = silent_model_load_progress; + if (p.dev) { + mp.n_gpu_layers = 999; + } + mp.tensor_buft_overrides = p.overrides; + + tensor_data_params tp = { p.seed, p.stdev }; + return llama_model_ptr(llama_model_init_from_user(gguf_ctx.get(), set_tensor_data, &tp, mp)); +} diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index eec0423cbef583b689a916a00fe49d3d67bb868a..367ab540be35e13191d3b2c949f93cd69f020d7b 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -4535,6 +4535,62 @@ struct test_snake_fuse : public test_case { }; +struct test_dsv4_hc_gate : public test_case { + const int64_t n_tokens; + const bool post; + const bool live_mul; + const bool view_bias; + + test_dsv4_hc_gate(int64_t n_tokens, bool post, bool live_mul = false, bool view_bias = false) + : n_tokens(n_tokens), post(post), live_mul(live_mul), view_bias(view_bias) {} + + std::string vars() override { return VARS_TO_STR4(n_tokens, post, live_mul, view_bias); } + std::string op_desc(ggml_tensor *) override { return "DSV4_HC_GATE"; } + bool run_whole_graph() override { return true; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * mixes = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 8, n_tokens); + ggml_tensor * factor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1); + ggml_tensor * bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, view_bias ? 8 : 4); + if (view_bias) { + bias = ggml_view_1d(ctx, bias, 4, post ? 4*sizeof(float) : 0); + } + ggml_tensor * x = ggml_view_2d(ctx, mixes, 4, n_tokens, mixes->nb[1], post ? 4*sizeof(float) : 0); + ggml_tensor * mul = ggml_mul(ctx, x, factor); + ggml_tensor * out = ggml_add(ctx, mul, bias); + out = ggml_sigmoid(ctx, out); + if (post) { + out = ggml_scale(ctx, out, 2.0f); + } + out = ggml_scale_bias(ctx, out, 1.0f, 1e-6f); + return live_mul ? ggml_concat(ctx, out, mul, 0) : out; + } +}; + +struct test_dsv4_hc_gate_consumer : public test_dsv4_hc_gate { + const int64_t width; + const bool live_gate; + + test_dsv4_hc_gate_consumer(int64_t width, int64_t nt, bool post, bool live_gate) + : test_dsv4_hc_gate(nt, post, false, true), width(width), live_gate(live_gate) {} + + std::string vars() override { return VARS_TO_STR5(width, n_tokens, post, live_gate, view_bias); } + std::string op_desc(ggml_tensor *) override { return "DSV4_HC_GATE_CONSUMER"; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * gate = test_dsv4_hc_gate::build_graph(ctx); + ggml_tensor * residual = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, width, 4, n_tokens); + ggml_tensor * out; + if (post) { + ggml_tensor * x = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, width, n_tokens); + out = ggml_dsv4_hc_post(ctx, x, residual, gate, nullptr); + } else { + out = ggml_dsv4_hc_pre(ctx, residual, gate); + } + return live_gate ? ggml_add(ctx, out, ggml_sum(ctx, gate)) : out; + } +}; + struct test_dsv4_hc : public test_case { static constexpr int64_t hc = 4; @@ -7808,6 +7864,48 @@ struct test_mul_mat_add : public test_case { } }; +struct test_mmvq_q8_reuse : public test_case { + const ggml_type type; + const int64_t k; + const int64_t n; + const int mode; + + test_mmvq_q8_reuse(ggml_type type, int64_t k, int mode, int64_t n = 1) + : type(type), k(k), n(n), mode(mode) {} + + std::string vars() override { return VARS_TO_STR4(type, k, n, mode); } + std::string op_desc(ggml_tensor *) override { return "MMVQ_Q8_REUSE"; } + bool run_whole_graph() override { return true; } + bool use_weight_context() override { return true; } + double max_nmse_err() override { return 5e-4; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + return build_graph(ctx, ctx); + } + + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * weights) override { + ggml_tensor * w0 = ggml_new_tensor_2d(weights, type, k, 128); + ggml_tensor * w1 = ggml_new_tensor_2d(weights, GGML_TYPE_Q8_0, k, 128); + ggml_tensor * w2 = ggml_new_tensor_2d(weights, type, k, 128); + ggml_tensor * base = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k + 32, n); + ggml_tensor * x = ggml_view_2d(ctx, base, k, n, base->nb[1], 32*sizeof(float)); + ggml_tensor * a = ggml_mul_mat(ctx, w0, x); + ggml_tensor * middle; + if (mode == 1) { + // A write through another view must prevent reuse of the old quantization. + ggml_tensor * alias = ggml_view_tensor(ctx, x); + middle = ggml_mul_mat(ctx, w1, ggml_scale_inplace(ctx, alias, 0.5f)); + } else if (mode == 2) { + ggml_tensor * other = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k, n); + middle = ggml_mul_mat(ctx, w1, other); + } else { + middle = ggml_mul_mat(ctx, w1, x); + } + ggml_tensor * b = ggml_mul_mat(ctx, w2, mode == 3 ? ggml_view_tensor(ctx, x) : x); + return ggml_concat(ctx, ggml_concat(ctx, a, middle, 0), b, 0); + } +}; + struct test_mul_mat_vec_fusion : public test_case { const ggml_type type; const ggml_glu_op glu_op; @@ -7995,6 +8093,63 @@ struct test_mul_mat_vec_fusion : public test_case { } }; + +struct test_spark_decode_layout : public test_mul_mat_vec_fusion { + test_spark_decode_layout(int64_t rows, int64_t tokens, bool broadcast, bool scales, bool gate) + : test_mul_mat_vec_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU_CLAMP, tokens, rows, 1536, + true, 32, 16, broadcast, false, gate, scales) {} + + std::string op_desc(ggml_tensor *) override { return "SPARK_DECODE_LAYOUT"; } + bool use_weight_context() override { return true; } + + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * weights) override { + ggml_tensor * up_w = ggml_new_tensor_3d(weights, type, k, n, n_mats); + ggml_tensor * gate_w = ggml_new_tensor_3d(weights, type, k, n, n_mats); + ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_mats, m); + ids = ggml_view_2d(ctx, ids, n_used, m, ids->nb[1], 0); + ggml_tensor * input = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, k, b ? 1 : n_used, m); + ggml_tensor * up = ggml_mul_mat_id(ctx, up_w, input, ids); + ggml_tensor * gate = with_gate ? ggml_mul_mat_id(ctx, gate_w, input, ids) : nullptr; + if (with_lane_scale) { + up = build_lane_scale_id(ctx, weights, up, ids); + if (gate) { + gate = build_lane_scale_id(ctx, weights, gate, ids); + } + } + return gate ? build_gate(ctx, gate, up) : up; + } +}; + +struct test_spark_mmq_fusion : public test_mul_mat_vec_fusion { + bool skewed = false; + test_spark_mmq_fusion(int64_t tokens, int64_t rows, int64_t k, bool broadcast, ggml_glu_op op, bool bias = false, bool scale = true) + : test_mul_mat_vec_fusion(GGML_TYPE_NVFP4, op, tokens, rows, k, true, 32, 4, broadcast, bias, true, scale) {} + + std::string op_desc(ggml_tensor *) override { return "SPARK_MMQ_FUSION"; } + + void initialize_tensors(ggml_context * ctx) override { + test_mul_mat_vec_fusion::initialize_tensors(ctx); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t; t = ggml_get_next_tensor(ctx, t)) { + if (skewed && t->type == GGML_TYPE_I32 && !t->view_src) { + std::vector ids(ggml_nelements(t)); + for (size_t i = 0; i < ids.size(); ++i) { + ids[i] = i % n_mats; + } + ggml_backend_tensor_set(t, ids.data(), 0, ids.size()*sizeof(int32_t)); + } + if (strcmp(t->name, "cur") != 0) { + continue; + } + const float values[] = {-6, -4, -3, -2, -1.5f, -1, -0.5f, 0, 0.5f, 1, 1.5f, 2, 3, 4, 6, 0}; + std::vector data(ggml_nelements(t)); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = values[i % 16] * (1 << ((i / t->ne[0]) % 3)); + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float)); + } + } +}; + // GGML_OP_SUM struct test_sum : public test_case { const ggml_type type; @@ -10204,6 +10359,43 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_snake_fuse(type, { 64, 32, 2, 3})); // ne[2] > 1 and ne[3] > 1 } + for (ggml_type type : { GGML_TYPE_Q8_0, GGML_TYPE_NVFP4 }) { + for (int mode : { 0, 1, 2, 3 }) { + test_cases.emplace_back(new test_mmvq_q8_reuse(type, 1536, mode)); + test_cases.emplace_back(new test_mmvq_q8_reuse(type, 3072, mode)); + } + } + test_cases.emplace_back(new test_mmvq_q8_reuse(GGML_TYPE_Q8_0, 512, 0, 3)); + + for (int64_t rows : { 512, 1536 }) { + for (int64_t tokens : { 1, 3 }) { + for (bool broadcast : { false, true }) { + for (bool scales : { false, true }) { + for (bool gate : { false, true }) { + test_cases.emplace_back(new test_spark_decode_layout(rows, tokens, broadcast, scales, gate)); + } + } + } + } + } + + for (int64_t nt : { 1, 17, 512 }) { + for (bool post : { false, true }) { + test_cases.emplace_back(new test_dsv4_hc_gate(nt, post)); + test_cases.emplace_back(new test_dsv4_hc_gate(nt, post, false, true)); + } + } + test_cases.emplace_back(new test_dsv4_hc_gate(17, false, true, true)); + test_cases.emplace_back(new test_dsv4_hc_gate(17, true, true, true)); + + for (int64_t width : { 1, 257, 3072 }) { + for (bool post : { false, true }) { + test_cases.emplace_back(new test_dsv4_hc_gate_consumer(width, 1, post, false)); + test_cases.emplace_back(new test_dsv4_hc_gate_consumer(width, 1, post, true)); + test_cases.emplace_back(new test_dsv4_hc_gate_consumer(width, 17, post, false)); + } + } + test_cases.emplace_back(new test_dsv4_hc_comb(1, 1)); test_cases.emplace_back(new test_dsv4_hc_comb(17, 4)); test_cases.emplace_back(new test_dsv4_hc_comb(257, 8)); @@ -10850,6 +11042,10 @@ static std::vector> make_test_cases_eval() { // quant block count not a multiple of the kernel block size test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_Q4_0, {96, 1, 1, 1})); test_cases.emplace_back(new test_cpy(GGML_TYPE_Q4_0, GGML_TYPE_F32, {96, 1, 1, 1})); + for (int64_t width : {128, 132, 129}) { + test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {width, 67, 5, 3}, + {width*67, 15, 1, 1}, {0, 2, 3, 1})); + } test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_I32, {256, 2, 3, 4})); test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_I32, {256, 2, 3, 4}, {-1,-1,-1,-1}, {1, 0, 2, 3})); test_cases.emplace_back(new test_cpy(GGML_TYPE_I32, GGML_TYPE_F32, {256, 2, 3, 4})); @@ -12584,6 +12780,21 @@ static std::vector> make_test_cases_eval() { } // Fused gate/up + GLU on the MMQ path, only used if its tiling is efficient: ~1280 tiles per case, one case per type and GLU op. + for (const bool broadcast : {false, true}) { + for (const ggml_glu_op op : {GGML_GLU_OP_SWIGLU, GGML_GLU_OP_SWIGLU_CLAMP}) { + test_cases.emplace_back(new test_spark_mmq_fusion(33, 128, 512, broadcast, op)); + test_cases.emplace_back(new test_spark_mmq_fusion(129, 256, 1536, broadcast, op)); + test_cases.emplace_back(new test_spark_mmq_fusion(129, 256, 1536, broadcast, op, false, false)); + } + } + for (bool broadcast : {false, true}) { + auto * skewed = new test_spark_mmq_fusion(385, 128, 512, broadcast, GGML_GLU_OP_SWIGLU_CLAMP); + skewed->skewed = true; + test_cases.emplace_back(skewed); + } + test_cases.emplace_back(new test_spark_mmq_fusion(33, 192, 512, true, GGML_GLU_OP_SWIGLU_CLAMP)); + test_cases.emplace_back(new test_spark_mmq_fusion(33, 128, 512, true, GGML_GLU_OP_SWIGLU_CLAMP, true)); + test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 81920, 256, false, 1, 1, false, false, true, false, { 1, 1 })); test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q5_K, GGML_GLU_OP_GEGLU, 150, 40960, 256, false, 1, 1, false, false, true, false, { 1, 1 })); test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q6_K, GGML_GLU_OP_SWIGLU_OAI, 150, 40960, 256, false, 1, 1, false, false, true, false, { 1, 1 })); @@ -12706,7 +12917,7 @@ static std::vector> make_test_cases_eval() { // lightning_indexer for (int kv : { 256 }) { for (int bs : { 1, 512 }) { - for (int nh : { 4, 32, 64 }) { + for (int nh : { 4, 16, 32, 64 }) { for (auto [ns, nm] : { std::pair{1, 1}, std::pair{4, 4}, std::pair{4, 1} }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { test_cases.emplace_back(new test_lightning_indexer(128, nh, kv, bs, ns, nm, type_K)); @@ -12716,6 +12927,12 @@ static std::vector> make_test_cases_eval() { } } + for (int kv : { 1, 7, 31, 32, 33, 63, 64, 65 }) { + for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0}) { + test_cases.emplace_back(new test_lightning_indexer(128, 16, kv, 3, 4, 1, type_K)); + } + } + for (int kv : { 1, 7, 8, 63, 64, 65 }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0}) { test_cases.emplace_back(new test_lightning_indexer(128, 64, kv, 32, 4, 1, type_K)); @@ -13243,7 +13460,7 @@ static std::vector> make_test_cases_perf() { // lightning_indexer for (int kv : { 256, 4096, 65536 }) { for (int bs : { 1, 512, 2048 }) { - for (int nh : { 4, 32, 64 }) { + for (int nh : { 4, 16, 32, 64 }) { for (int ns : { 1, 4 }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { test_cases.emplace_back(new test_lightning_indexer(128, nh, kv, bs, ns, ns, type_K)); diff --git a/tests/test-dfly-real.cpp b/tests/test-dfly-real.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25a09e213d44e4eb932a09cd79323497e0b3ad24 --- /dev/null +++ b/tests/test-dfly-real.cpp @@ -0,0 +1,680 @@ +// test-dfly-real: one DFly propose on the real target and draft, written as a dfly-io-1 case for the S5a oracle, +// plus the no-write check of plan 12.3 item 4 at the real dimensions. Not part of ctest (446 GB target). +// +// usage: test-dfly-real --target --dfly --out --device cpu|cuda0 --prompt-file F [--n-prompt N] +// [--k 4|7 ...] [--hf-target DIR] [--threads N] +// --n-prompt and --k may repeat: every N with every K, one model load. DFLY_REAL_SCHED_DEBUG= sets GGML_SCHED_DEBUG +// for the draft's scheduler only. + +#include "ggml.h" +#include "ggml-backend.h" +#include "llama.h" +#include "llama-cpp.h" + +#include "../src/llama-context.h" +#include "../src/llama-dfly.h" +#include "../src/llama-ext.h" +#include "../src/llama-kv-cache.h" +#include "../src/llama-kv-cache-iswa.h" +#include "../src/llama-memory-idx-iswa.h" +#include "../src/llama-model.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +struct args { + std::string target; + std::string dfly; + std::string out; + std::string device = "cpu"; + std::string prompt_file; // the plan document in the S5c runs + std::string hf_target = "/taijifs_nj32/models/dawesli/A12B_new_Dfly_target_model"; + int n_threads = 64; + std::vector ns; + std::vector ks; +}; + +static void usage() { + fprintf(stderr, "usage: test-dfly-real --target --dfly --out --device cpu|cuda0 --prompt-file F [--n-prompt N]\n" + " [--k 4|7 ...] [--hf-target DIR] [--threads N]\n"); + exit(2); +} + +static args parse(int argc, char ** argv) { + args a; + for (int i = 1; i < argc; ++i) { + const std::string k = argv[i]; + auto v = [&]() -> std::string { + if (i + 1 >= argc) { + usage(); + } + return argv[++i]; + }; + if (k == "--target") a.target = v(); + else if (k == "--dfly") a.dfly = v(); + else if (k == "--out") a.out = v(); + else if (k == "--device") a.device = v(); + else if (k == "--prompt-file") a.prompt_file = v(); + else if (k == "--hf-target") a.hf_target = v(); + else if (k == "--n-prompt") a.ns.push_back(std::stoi(v())); + else if (k == "--threads") a.n_threads = std::stoi(v()); + else if (k == "--k") a.ks.push_back(std::stoi(v())); + else usage(); + } + if (a.target.empty() || a.dfly.empty() || a.out.empty() || a.prompt_file.empty() || (a.device != "cpu" && a.device != "cuda0")) { + usage(); + } + if (a.ks.empty()) { + a.ks = { 4 }; + } + if (a.ns.empty()) { + a.ns = { 128 }; + } + return a; +} + +static double ms_since(std::chrono::steady_clock::time_point t0) { + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +// named dfly_* graph tensors of the draft, whole names only +struct cap_tensor { + std::array ne = {}; + std::vector f; + std::vector i; +}; + +struct cap_eval { + std::map t; +}; + +static bool cap_cb(struct ggml_tensor * t, bool ask, void * user_data) { + const bool want = strncmp(t->name, "dfly_", 5) == 0 && strchr(t->name, ' ') == nullptr && + (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_I32); + if (ask) { + return want; + } + if (!want) { + return true; + } + auto * ev = (cap_eval *) user_data; + cap_tensor & o = ev->t[t->name]; + std::copy(t->ne, t->ne + 4, o.ne.begin()); + std::vector raw(ggml_nbytes(t)); + ggml_backend_tensor_get(t, raw.data(), 0, raw.size()); + o.f.clear(); + o.i.clear(); + for (int64_t i3 = 0; i3 < t->ne[3]; ++i3) { + for (int64_t i2 = 0; i2 < t->ne[2]; ++i2) { + for (int64_t i1 = 0; i1 < t->ne[1]; ++i1) { + for (int64_t i0 = 0; i0 < t->ne[0]; ++i0) { + const uint8_t * p = raw.data() + i0*t->nb[0] + i1*t->nb[1] + i2*t->nb[2] + i3*t->nb[3]; + if (t->type == GGML_TYPE_F32) { + o.f.push_back(*(const float *) p); + } else { + o.i.push_back(*(const int32_t *) p); + } + } + } + } + } + return true; +} + +static std::string dev_name(const ggml_tensor * t) { + if (t == nullptr || t->buffer == nullptr) { + return "none"; + } + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(t->buffer); + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + return std::string(ggml_backend_buft_name(buft)) + (dev ? std::string(" @ ") + ggml_backend_dev_name(dev) : ""); +} + +static llama_kv_cache * base_of(llama_context * tgt) { + auto * mem = dynamic_cast(llama_get_memory(tgt)); + if (mem == nullptr) { + throw std::runtime_error("the target has no indexer memory"); + } + return mem->get_mem_attn()->get_base(); +} + +static std::vector to_f32(ggml_type type, const uint8_t * p, int64_t n) { + std::vector out(n); + switch (type) { + case GGML_TYPE_F32: memcpy(out.data(), p, n*sizeof(float)); break; + case GGML_TYPE_F16: ggml_fp16_to_fp32_row((const ggml_fp16_t *) p, out.data(), n); break; + case GGML_TYPE_BF16: ggml_bf16_to_fp32_row((const ggml_bf16_t *) p, out.data(), n); break; + default: throw std::runtime_error(std::string("unsupported K type ") + ggml_type_name(type)); + } + return out; +} + +// one row of the target K storage, read on the host +static std::vector k_row(llama_context * tgt, int32_t il, uint32_t strm, uint32_t cell) { + ggml_tensor * k = base_of(tgt)->get_k_storage(il); + std::vector buf(k->nb[1]); + ggml_backend_tensor_get(k, buf.data(), strm*k->nb[2] + cell*k->nb[1], k->nb[1]); + return to_f32(k->type, buf.data(), k->ne[0]); +} + +static std::vector bytes_of(const ggml_tensor * t) { + std::vector b(ggml_nbytes(t)); + ggml_backend_tensor_get(t, b.data(), 0, b.size()); + return b; +} + +template +static std::string list_str(const std::vector & v) { + std::string s = "["; + for (size_t i = 0; i < v.size(); ++i) { + s += (i ? ", " : "") + std::to_string(v[i]); + } + return s + "]"; +} + +static void write_bin(const std::string & path, const void * data, size_t n) { + std::ofstream f(path, std::ios::binary); + f.write((const char *) data, (std::streamsize) n); + if (!f.good()) { + throw std::runtime_error("failed to write " + path); + } +} + +struct json_tensors { + std::string dir; + std::vector entries; + + void add_f32(const std::string & name, const std::vector & v, const std::vector & shape) { + int64_t n = 1; + for (int64_t x : shape) { + n *= x; + } + if ((int64_t) v.size() != n) { + throw std::runtime_error(name + ": " + std::to_string(v.size()) + " values for shape " + list_str(shape)); + } + write_bin(dir + "/" + name + ".f32", v.data(), v.size()*sizeof(float)); + entries.push_back("\"" + name + "\": {\"file\": \"" + name + ".f32\", \"dtype\": \"f32\", \"shape\": " + list_str(shape) + "}"); + } + void add_i32(const std::string & name, const std::vector & v, const std::vector & shape) { + write_bin(dir + "/" + name + ".i32", v.data(), v.size()*sizeof(int32_t)); + entries.push_back("\"" + name + "\": {\"file\": \"" + name + ".i32\", \"dtype\": \"i32\", \"shape\": " + list_str(shape) + "}"); + } + std::string json() const { + std::string s = "{\n"; + for (size_t i = 0; i < entries.size(); ++i) { + s += " " + entries[i] + (i + 1 < entries.size() ? ",\n" : "\n"); + } + return s + " }"; + } +}; + +static int decode_rows(llama_context * ctx, const std::vector & toks, llama_pos p0, bool all_out) { + llama_batch b = llama_batch_init((int32_t) toks.size(), 0, 1); + for (size_t i = 0; i < toks.size(); ++i) { + b.token[i] = toks[i]; + b.pos[i] = p0 + (llama_pos) i; + b.n_seq_id[i] = 1; + b.seq_id[i][0] = 0; + b.logits[i] = all_out || i + 1 == toks.size(); + } + b.n_tokens = (int32_t) toks.size(); + const int ret = llama_decode(ctx, b); + llama_batch_free(b); + return ret; +} + +// warmup and the seq_rm probe, as common does before capture_enable +static void warmup_and_probe(llama_context * ctx) { + decode_rows(ctx, { 1 }, 0, true); + llama_memory_clear(llama_get_memory(ctx), true); + decode_rows(ctx, { 0, 0 }, 0, true); + llama_memory_seq_rm(llama_get_memory(ctx), 0, 1, -1); + llama_memory_clear(llama_get_memory(ctx), true); +} + +int main(int argc, char ** argv) { + const args a = parse(argc, argv); + const bool cuda = a.device == "cuda0"; + + llama_backend_init(); + ggml_backend_load_all(); + + ggml_backend_dev_t gpu = nullptr; + if (cuda) { + gpu = ggml_backend_dev_by_name("CUDA0"); + if (gpu == nullptr) { + fprintf(stderr, "no CUDA0\n"); + return 1; + } + } + + // CUDA0: all target layers on the GPU except the routed experts and the Engram table (per_layer_token_embd), + // and the one token_embd on the GPU so the draft reads it there + std::vector ov; + if (cuda) { + ov.push_back({ "^per_layer_token_embd\\.weight$", ggml_backend_cpu_buffer_type() }); + ov.push_back({ "\\.ffn_(up|gate|down)_exps\\.weight$", ggml_backend_cpu_buffer_type() }); + ov.push_back({ "^token_embd\\.weight$", ggml_backend_dev_buffer_type(gpu) }); + } + ov.push_back({ nullptr, nullptr }); + + ggml_backend_dev_t devs[] = { gpu, nullptr }; + + llama_model_params mp = llama_model_default_params(); + mp.devices = devs; + mp.n_gpu_layers = cuda ? 999 : 0; + mp.split_mode = LLAMA_SPLIT_MODE_NONE; + mp.main_gpu = 0; + mp.tensor_buft_overrides = ov.data(); + + auto t0 = std::chrono::steady_clock::now(); + llama_model_ptr target(llama_model_load_from_file(a.target.c_str(), mp)); + if (!target) { + fprintf(stderr, "failed to load the target\n"); + return 1; + } + printf("target loaded in %.1f s\n", ms_since(t0)/1000.0); + + llama_model_params dp = llama_model_default_params(); + dp.devices = devs; + dp.n_gpu_layers = cuda ? 999 : 0; + dp.split_mode = LLAMA_SPLIT_MODE_NONE; + llama_model_ptr dfly(llama_model_load_from_file(a.dfly.c_str(), dp)); + if (!dfly) { + fprintf(stderr, "failed to load the draft\n"); + return 1; + } + + const auto & hp = dfly->hparams; + const int64_t D = hp.n_embd, H = hp.n_head(), Rq = hp.n_lora_q, Rkv = hp.n_lora_kv, Dr = hp.n_rot(), Dv = hp.n_embd_head_v_mla(); + const int64_t R = Rkv + Dr, S = hp.dfly_target_index_top_k, V = llama_vocab_n_tokens(llama_model_get_vocab(dfly.get())); + std::vector layers(hp.dfly_target_kv_layers.begin(), hp.dfly_target_kv_layers.end()); + const int k_max = *std::max_element(a.ks.begin(), a.ks.end()); + + auto tgt_params = [&]() { + llama_context_params p = llama_context_default_params(); + p.n_ctx = 4096; + p.n_batch = 4096; + p.n_ubatch = 512; + p.n_seq_max = 1; + p.type_k = GGML_TYPE_F16; + p.type_v = GGML_TYPE_F16; + p.n_threads = a.n_threads; + p.n_threads_batch = a.n_threads; + return p; + }; + + llama_context_ptr tgt(llama_init_from_model(target.get(), tgt_params())); + llama_context_ptr tgt2(llama_init_from_model(target.get(), tgt_params())); + if (!tgt || !tgt2) { + fprintf(stderr, "failed to create the target contexts\n"); + return 1; + } + warmup_and_probe(tgt.get()); + warmup_and_probe(tgt2.get()); + + // the trace of the draft only: the target schedulers exist already, capture_enable re-reserves the target below + const char * sched_debug = getenv("DFLY_REAL_SCHED_DEBUG"); + if (sched_debug) { + setenv("GGML_SCHED_DEBUG", sched_debug, 1); + } + + cap_eval ev; + llama_context_params dcp = llama_context_default_params(); + dcp.n_ctx = 0; + dcp.n_batch = k_max + 1; + dcp.n_ubatch = k_max + 1; + dcp.n_seq_max = 1; + dcp.ctx_other = tgt.get(); + dcp.n_threads = a.n_threads; + dcp.n_threads_batch = a.n_threads; + dcp.cb_eval = cap_cb; + dcp.cb_eval_user_data = &ev; + llama_context_ptr dft(llama_init_from_model(dfly.get(), dcp)); + unsetenv("GGML_SCHED_DEBUG"); + if (!dft) { + fprintf(stderr, "failed to create the draft context (binding check)\n"); + return 1; + } + + // a second draft without the eval callback, for the timing only + dcp.cb_eval = nullptr; + dcp.cb_eval_user_data = nullptr; + llama_context_ptr dft_t(llama_init_from_model(dfly.get(), dcp)); + if (!dft_t) { + fprintf(stderr, "failed to create the timing draft context\n"); + return 1; + } + + // the placement as the buffers have it + printf("placement:\n"); + printf(" token_embd.weight %s (%s)\n", dev_name(target->tok_embd).c_str(), ggml_type_name(target->tok_embd->type)); + printf(" output.weight %s (%s)\n", dev_name(target->output).c_str(), ggml_type_name(target->output->type)); + for (int32_t il : layers) { + ggml_tensor * k = base_of(tgt.get())->get_k_storage(il); + printf(" K storage layer %2d %s (%s, ne %lld x %lld x %lld)\n", il, dev_name(k).c_str(), ggml_type_name(k->type), + (long long) k->ne[0], (long long) k->ne[1], (long long) k->ne[2]); + } + std::map dfly_devs; + for (const auto & [name, t] : dfly->tensors_by_name) { + dfly_devs[dev_name(t)]++; + } + for (const auto & [d, n] : dfly_devs) { + printf(" DFly weights %s: %d tensors\n", d.c_str(), n); + } + + if (llama_dfly_capture_enable(dft.get()) != LLAMA_DFLY_OK) { + fprintf(stderr, "capture_enable failed\n"); + return 1; + } + // the second target exports the same selection so that both run the same graph + { + std::string err; + if (!tgt2->dfly_capture_configure(layers.data(), (uint32_t) layers.size(), (uint32_t) S, err)) { + fprintf(stderr, "configure tgt2: %s\n", err.c_str()); + return 1; + } + } + + int rc = 0; + + // the prompt: the first N tokens of a fixed text file + std::string text; + { + std::ifstream f(a.prompt_file, std::ios::binary); + std::stringstream ss; + ss << f.rdbuf(); + text = ss.str(); + } + const llama_vocab * vocab = llama_model_get_vocab(target.get()); + std::vector all(text.size() + 16); + const int n_tok = llama_tokenize(vocab, text.c_str(), (int32_t) text.size(), all.data(), (int32_t) all.size(), false, false); + all.resize(std::max(n_tok, 0)); + + for (const int n_prompt : a.ns) { + if (n_tok < n_prompt) { + fprintf(stderr, "the prompt file has %d tokens, need %d\n", n_tok, n_prompt); + return 1; + } + const std::vector toks(all.begin(), all.begin() + n_prompt); + printf("\n== N=%d\nprompt: %s, %d tokens in the file, first %d used\n", n_prompt, a.prompt_file.c_str(), n_tok, n_prompt); + + llama_memory_clear(llama_get_memory(tgt.get()), true); + llama_memory_clear(llama_get_memory(tgt2.get()), true); + llama_dfly_invalidate(dft.get(), 0); + + t0 = std::chrono::steady_clock::now(); + if (decode_rows(tgt.get(), toks, 0, false) != 0 || decode_rows(tgt2.get(), toks, 0, false) != 0) { + fprintf(stderr, "prefill failed\n"); + return 1; + } + printf("prefill of both targets: %.1f s\n", ms_since(t0)/1000.0); + + const float * lg = llama_get_logits_ith(tgt.get(), -1); + const llama_token anchor = (llama_token) (std::max_element(lg, lg + V) - lg); + const llama_pos a_pos = n_prompt; + printf("anchor %d at %d\n", anchor, a_pos); + + if (llama_dfly_capture_pull(dft.get()) != LLAMA_DFLY_OK) { + fprintf(stderr, "pull failed\n"); + return 1; + } + const auto & snaps = dft->dfly_snapshots_for_test(); + if (snaps.size() != 1 || snaps[0].query_pos != a_pos - 1) { + fprintf(stderr, "expected one snapshot at %d\n", a_pos - 1); + return 1; + } + const llama_dfly_snapshot snap = snaps[0]; + size_t count_max = 0; + for (int i = 0; i < (int) layers.size(); ++i) { + printf(" layer %d (target %d): count %zu\n", i, layers[i], snap.layer[i].pos.size()); + count_max = std::max(count_max, snap.layer[i].pos.size()); + } + + // K storage of both targets before any propose + auto k_bytes = [&](llama_context * c) { + std::vector> v; + for (int32_t il : layers) { + v.push_back(bytes_of(base_of(c)->get_k_storage(il))); + } + return v; + }; + const auto k_before = k_bytes(tgt.get()); + + printf(" max count %zu\n", count_max); + std::vector last_draft; + std::map> last_tokens; + for (int K : a.ks) { + std::vector out(K); + llama_dfly_request rq = { 0, anchor, a_pos, K }; + llama_dfly_result rs = { out.data(), K, 0 }; + ev.t.clear(); + // the first propose of an anchor consumes its snapshot + dft->dfly_rearm_for_test(); + fprintf(stderr, "=== propose N=%d K=%d begin\n", n_prompt, K); + t0 = std::chrono::steady_clock::now(); + const llama_dfly_status st = llama_dfly_propose(dft.get(), &rq, &rs); + const double t_ms = ms_since(t0); + fprintf(stderr, "=== propose N=%d K=%d end\n", n_prompt, K); + // a second, timed only; the graph is reused + const cap_eval keep = ev; + dft->dfly_rearm_for_test(); + std::vector out2(K); + llama_dfly_result rs2 = { out2.data(), K, 0 }; + t0 = std::chrono::steady_clock::now(); + llama_dfly_propose(dft.get(), &rq, &rs2); + const double t2_ms = ms_since(t0); + ev = keep; + printf("propose K=%d: status %d, n_tokens %d, %.2f ms (again, graph reused: %.2f ms), tokens %s\n", K, (int) st, rs.n_tokens, t_ms, t2_ms, + list_str(std::vector(out.begin(), out.end())).c_str()); + if (st != LLAMA_DFLY_OK || out2 != out) { + rc = 1; + continue; + } + last_draft = out; + last_tokens[K] = out; + + // the case + const int64_t W = K + 1; + const std::string dir = a.out + "/n" + std::to_string(n_prompt) + "_w" + std::to_string(W) + "_" + a.device; + fs::remove_all(dir); + fs::create_directories(dir + "/cpp"); + + json_tensors in; + in.dir = dir; + in.add_f32("h_t", snap.h_final, { D }); + std::string ctx_json; + for (int i = 0; i < (int) layers.size(); ++i) { + const auto & l = snap.layer[i]; + std::vector rows; + for (uint32_t c : l.cell) { + const auto r = k_row(tgt.get(), layers[i], l.strm, c); + rows.insert(rows.end(), r.begin(), r.end()); + } + in.add_f32("l" + std::to_string(i) + ".kctx", rows, { (int64_t) l.cell.size(), R }); + ctx_json += std::string(i ? ",\n " : " ") + "{\"target_layer\": " + std::to_string(layers[i]) + ", \"count\": " + + std::to_string(l.pos.size()) + ", \"pos\": " + list_str(l.pos) + "}"; + } + std::vector block(W, llama_vocab_mask(llama_model_get_vocab(dfly.get()))); + block[0] = anchor; + std::vector prev = { anchor }; + for (int j = 1; j < K; ++j) { + prev.push_back(std::min(std::max(out[j - 1], 0), (int32_t) V - 1)); + } + const char * commit = getenv("LLAMA_DFLY_TEST_COMMIT"); + std::ofstream(dir + "/inputs.json") << "{\n \"format\": \"dfly-io-1\",\n \"note\": \"real; target " + a.target + "; prompt " + + a.prompt_file + " first " + std::to_string(n_prompt) + " tokens; backend " + (cuda ? "CUDA0" : "CPU") + "; commit " + + (commit ? commit : "unknown") + "; test-dfly-real\",\n" + + " \"dfly\": {\"kind\": \"gguf\", \"path\": \"" + fs::absolute(a.dfly).string() + "\"},\n" + + " \"eo\": {\"kind\": \"hf_target\", \"dir\": \"" + a.hf_target + "\"},\n" + + " \"anchor_token\": " + std::to_string(anchor) + ",\n \"anchor_pos\": " + std::to_string(a_pos) + ",\n \"W\": " + + std::to_string(W) + ",\n \"mask_token\": " + std::to_string(block.size() > 1 ? block[1] : 0) + ",\n \"block_tokens\": " + + list_str(block) + ",\n \"prev_tokens\": " + list_str(prev) + ",\n \"ctx\": [\n" + ctx_json + "\n ],\n \"tensors\": " + + in.json() + "\n}\n"; + + const auto & inp = dft->dfly_input_for_test(); + json_tensors cp; + cp.dir = dir + "/cpp"; + bool ok = true; + auto get = [&](const std::string & name) -> const cap_tensor * { + const auto it = ev.t.find(name); + if (it == ev.t.end()) { + fprintf(stderr, "missing %s\n", name.c_str()); + ok = false; + return nullptr; + } + return &it->second; + }; + auto lname = [](const char * n, int i) { return std::string("dfly_") + n + "-" + std::to_string(i); }; + auto sname = [](int j, const char * n) { return "dfly_s" + std::to_string(j) + "." + n; }; + auto direct = [&](const std::string & io, const std::string & name, const std::vector & shape) { + if (const cap_tensor * x = get(name)) { + cp.add_f32(io, x->f, shape); + } + }; + direct("x_embd", "dfly_x_embd", { W, D }); + direct("fusion_in", "dfly_fusion_in", { 2*D }); + direct("fusion_delta", "dfly_fusion_delta", { D }); + direct("x0", "dfly_x0", { W, D }); + for (int i = 0; i < (int) layers.size(); ++i) { + const std::string p = "l" + std::to_string(i) + "."; + const int64_t n = (int64_t) snap.layer[i].cell.size(); + const int64_t N = S + W; + direct(p + "u", lname("u", i), { W, D }); + direct(p + "qr", lname("qr", i), { W, Rq }); + direct(p + "qp", lname("qp", i), { W, H, Dr }); + direct(p + "q", lname("q", i), { W, H, R }); + direct(p + "c_block", lname("c_block", i), { W, Rkv }); + direct(p + "kp_block", lname("kp_block", i), { W, Dr }); + direct(p + "gate", lname("gate", i), { W, H, Dv }); + direct(p + "attn_out", lname("attn_out", i), { W, D }); + direct(p + "post_proj", lname("post_proj", i), { W, D }); + direct(p + "x_mid", lname("x_mid", i), { W, D }); + direct(p + "ffn_out", lname("ffn_out", i), { W, D }); + direct(p + "x_out", lname("x_out", i), { W, D }); + if (const cap_tensor * x = get(lname("kctx", i))) { + cp.add_f32(p + "kctx", std::vector(x->f.begin(), x->f.begin() + n*R), { n, R }); + } + auto col = [&](int64_t c) { return c < n ? c : S + (c - n); }; + std::vector mask; + for (int64_t j = 0; j < W; ++j) { + for (int64_t c = 0; c < n + W; ++c) { + mask.push_back(inp.mask[i][j*N + col(c)]); + } + } + cp.add_f32(p + "mask", mask, { W, n + W }); + if (const cap_tensor * x = get(lname("probs", i))) { + std::vector v; + for (int64_t j = 0; j < W; ++j) { + for (int64_t h = 0; h < H; ++h) { + for (int64_t c = 0; c < n + W; ++c) { + v.push_back(x->f[col(c) + N*(j + W*h)]); + } + } + } + cp.add_f32(p + "probs", v, { W, H, n + W }); + } + auto wh = [&](const std::string & io, const std::string & name, int64_t C) { + const cap_tensor * x = get(name); + if (!x) { + return; + } + std::vector v; + for (int64_t j = 0; j < W; ++j) { + for (int64_t h = 0; h < H; ++h) { + v.insert(v.end(), x->f.begin() + C*(j + W*h), x->f.begin() + C*(j + W*h + 1)); + } + } + cp.add_f32(io, v, { W, H, C }); + }; + wh(p + "o_latent", lname("o_latent", i), Rkv); + wh(p + "o", lname("o", i), Dv); + } + direct("h_d", "dfly_h_d", { W, D }); + for (int j = 1; j <= K; ++j) { + const std::string p = "s" + std::to_string(j) + "."; + direct(p + "corr_in", sname(j, "corr_in"), { 2*D }); + direct(p + "corr_delta", sname(j, "corr_delta"), { D }); + direct(p + "h_corr", sname(j, "h_corr"), { D }); + direct(p + "logits", sname(j, "logits"), { V }); + direct(p + "finite_probe", sname(j, "finite_probe"), { 1 }); + if (const cap_tensor * x = get(sname(j, "raw_id"))) { + cp.add_i32(p + "raw_id", x->i, { 1 }); + cp.add_i32(p + "safe_id", { std::min(std::max(x->i[0], 0), (int32_t) V - 1) }, { 1 }); + } + } + std::ofstream(dir + "/cpp/tensors.json") << "{\n \"meta\": {\"producer\": \"cpp\", \"mode\": \"ggml\", \"backend\": \"" + + std::string(cuda ? "CUDA0" : "CPU") + "\", \"commit\": \"" + (commit ? commit : "unknown") + "\"},\n \"tensors\": " + cp.json() + "\n}\n"; + printf("case written: %s%s\n", dir.c_str(), ok ? "" : " (INCOMPLETE)"); + if (!ok) { + rc = 1; + } + } + + // the timing: graph reused after the first round, no intermediates copied out + for (int K : a.ks) { + std::vector ms; + std::vector out(K); + llama_dfly_request rq = { 0, anchor, a_pos, K }; + for (int it = 0; it < 6; ++it) { + dft_t->dfly_set_snapshots_for_test({ snap }, snap.prefix_epoch); + llama_dfly_result rs = { out.data(), K, 0 }; + t0 = std::chrono::steady_clock::now(); + const llama_dfly_status st = llama_dfly_propose(dft_t.get(), &rq, &rs); + ms.push_back(ms_since(t0)); + if (st != LLAMA_DFLY_OK || out != last_tokens[K]) { + printf("timing propose K=%d: status %d, tokens differ from the traced run\n", K, (int) st); + rc = 1; + } + } + const double first = ms[0]; + std::sort(ms.begin() + 1, ms.end()); + printf("timing propose K=%d (no callback): first %.2f ms, median of 5 more %.2f ms\n", K, first, ms[3]); + } + + // plan 12.3 item 4 at the real dimensions: propose wrote nothing, the same verify gives the same logits + { + const bool k_same = k_bytes(tgt.get()) == k_before && k_before == k_bytes(tgt2.get()); + const auto & c1 = base_of(tgt.get())->get_cells(0).seq_pos_get(0); + const auto & c2 = base_of(tgt2.get())->get_cells(0).seq_pos_get(0); + const bool cells_same = c1 == c2; + std::vector verify = { anchor }; + verify.insert(verify.end(), last_draft.begin(), last_draft.end()); + const bool d1 = decode_rows(tgt.get(), verify, a_pos, true) == 0; + const bool d2 = decode_rows(tgt2.get(), verify, a_pos, true) == 0; + bool logits_same = d1 && d2; + for (int i = 0; logits_same && i < (int) verify.size(); ++i) { + logits_same = memcmp(llama_get_logits_ith(tgt.get(), i), llama_get_logits_ith(tgt2.get(), i), V*sizeof(float)) == 0; + } + printf("12.3 item 4: K storage of the 5 layers unchanged and equal to the untouched target: %s; cells equal: %s; " + "verify of %zu rows bitwise equal logits: %s\n", k_same ? "yes" : "NO", cells_same ? "yes" : "NO", verify.size(), + logits_same ? "yes" : "NO"); + if (!k_same || !cells_same || !logits_same) { + rc = 1; + } + } + } + + dft_t.reset(); + dft.reset(); + tgt2.reset(); + tgt.reset(); + dfly.reset(); + target.reset(); + llama_backend_free(); + printf("EXIT_STATUS=%d\n", rc); + return rc; +} diff --git a/tests/test-dfly-target.cpp b/tests/test-dfly-target.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3775f0d3da9a470673b80ca7133d506e52dd142 --- /dev/null +++ b/tests/test-dfly-target.cpp @@ -0,0 +1,3142 @@ +#include "testing.h" +#include "gguf-fixture.h" + +#include "ggml.h" +#include "ggml-backend.h" +#include "gguf.h" +#include "llama.h" +#include "llama-cpp.h" + +#include "../src/llama-context.h" +#include "../src/llama-dfly.h" +#include "../src/llama-ext.h" +#include "../src/llama-kv-cache.h" +#include "../src/llama-kv-cache-iswa.h" +#include "../src/llama-kv-cells.h" +#include "../src/llama-memory-idx-iswa.h" +#include "../src/llama-model.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// target-only tests on the 10-layer hy_v4_flash tiny target of gguf-fixture.h, CPU only, no DFly model: +// batch width (TG-04), and verify rollback against a same-shape replay (TG-05..07) + +static const uint32_t TG_VOCAB = 128; +static const size_t TG_SEED = 1234; +static const uint32_t TG_P = 40; + +static const char * const TG_CACHE[3] = { "base", "idx", "swa" }; + +static double tg_ms_since(std::chrono::steady_clock::time_point t0) { + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +// one model per (top_k, n_swa), everything else at the hy_v4_flash_tiny defaults +static std::map, llama_model_ptr> g_models; + +static llama_model * tg_model(uint32_t top_k, uint32_t n_swa) { + llama_model_ptr & m = g_models[{ top_k, n_swa }]; + if (!m) { + hy_v4_flash_tiny p; + p.top_k = top_k; + p.n_swa = n_swa; + m = hy_v4_flash_tiny_target(p); + } + return m.get(); +} + +// copies the named tensors as they are computed; names match whole, a view's name is " (reshaped)" +struct tg_eval { + std::vector names; + std::map> data; + std::map> ne; + int n_hits = 0; + bool bad = false; + + void reset() { + data.clear(); + ne.clear(); + n_hits = 0; + bad = false; + } +}; + +static bool tg_eval_cb(struct ggml_tensor * t, bool ask, void * user_data) { + auto * ev = (tg_eval *) user_data; + const bool want = std::any_of(ev->names.begin(), ev->names.end(), [&](const std::string & n) { return strcmp(t->name, n.c_str()) == 0; }); + if (ask || !want) { + return want || !ask; + } + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t)) { + ev->bad = true; + return true; + } + std::vector & d = ev->data[t->name]; + d.resize(ggml_nelements(t)); + ggml_backend_tensor_get(t, d.data(), 0, ggml_nbytes(t)); + ev->ne[t->name] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; + ev->n_hits++; + return true; +} + +static llama_context_ptr tg_context(llama_model * model, uint32_t n_ctx, uint32_t U, bool swa_full, tg_eval * ev) { + llama_context_params params = llama_context_default_params(); + params.n_ctx = n_ctx; + params.n_batch = U; + params.n_ubatch = U; + params.n_seq_max = 1; + params.kv_unified = false; + params.swa_full = swa_full; + params.type_k = GGML_TYPE_F16; + params.type_v = GGML_TYPE_F16; + params.n_threads = 4; + params.n_threads_batch = 4; + if (ev != nullptr) { + params.cb_eval = tg_eval_cb; + params.cb_eval_user_data = ev; + } + return llama_context_ptr(llama_init_from_model(model, params)); +} + +struct tg_batch { + llama_batch b; + + explicit tg_batch(int n) : b(llama_batch_init(n, 0, 1)) {} + ~tg_batch() { llama_batch_free(b); } + + void clear() { b.n_tokens = 0; } + + void add(llama_token tok, llama_pos pos, bool out) { + const int i = b.n_tokens++; + b.token [i] = tok; + b.pos [i] = pos; + b.n_seq_id[i] = 1; + b.seq_id [i][0] = 0; + b.logits [i] = out; + } +}; + +// T[0, P) in chunks of U, only the last row has an output +static int tg_prefill(llama_context * ctx, const std::vector & T, uint32_t P, uint32_t U) { + tg_batch bt(U); + for (uint32_t i0 = 0; i0 < P; i0 += U) { + bt.clear(); + for (uint32_t i = i0; i < std::min(P, i0 + U); ++i) { + bt.add(T[i], i, i == P - 1); + } + const int ret = llama_decode(ctx, bt.b); + if (ret != 0) { + return ret; + } + } + return 0; +} + +// a token different from tok +static llama_token tg_junk(llama_token tok, std::mt19937 & g) { + return (llama_token) ((tok + 1 + g() % (TG_VOCAB - 1)) % TG_VOCAB); +} + +static void tg_caches(llama_context * ctx, llama_kv_cache * kv[3]) { + auto * mem = dynamic_cast(llama_get_memory(ctx)); + GGML_ASSERT(mem != nullptr); + kv[0] = mem->get_mem_attn()->get_base(); + kv[1] = mem->get_mem_idx(); + kv[2] = mem->get_mem_attn()->get_swa(); +} + +// the (pos, cell) pairs of seq 0 from a scan of every cell, not from the cells' own position index +static std::vector> tg_scan(const llama_kv_cache * kv) { + const llama_kv_cells & cells = kv->get_cells(0); + std::vector> res; + for (uint32_t i = 0; i < cells.size(); ++i) { + if (!cells.is_empty(i) && cells.seq_has(i, 0)) { + res.push_back({ cells.pos_get(i), i }); + } + } + std::sort(res.begin(), res.end()); + return res; +} + +static std::set tg_positions(const llama_kv_cache * kv) { + std::set res; + for (const auto & pc : tg_scan(kv)) { + res.insert(pc.first); + } + return res; +} + +static std::map tg_cells(const llama_kv_cache * kv) { + std::map res; + for (const auto & pc : tg_scan(kv)) { + res[pc.first] = pc.second; + } + return res; +} + +// one K storage row as F16 bytes +static std::vector tg_row(const llama_kv_cache * kv, int il, uint32_t cell) { + const ggml_tensor * k = kv->get_k_storage(il); + GGML_ASSERT(k->type == GGML_TYPE_F16); + std::vector out(k->ne[0]*sizeof(ggml_fp16_t)); + ggml_backend_tensor_get(k, out.data(), (size_t) cell*k->nb[1], out.size()); + return out; +} + +// an indexer row is value | gate | pooled, the pooled third only holds a key in the rep row of a complete group +static size_t tg_idx_split(const llama_kv_cache * idx, int il) { + const ggml_tensor * k = idx->get_k_storage(il); + GGML_ASSERT(k->ne[0] % 3 == 0); + return (size_t) k->ne[0]/3*2*sizeof(ggml_fp16_t); +} + +static uint64_t tg_hash(const uint8_t * p, size_t n) { + uint64_t h = 1469598103934665603ull; + for (size_t i = 0; i < n; ++i) { + h = (h ^ p[i])*1099511628211ull; + } + return h; +} + +// (cache, layer, pos, part): part 0 is the whole row, or value | gate for the indexer; part 1 the pooled key +using tg_key = std::tuple; + +static std::string tg_where(const tg_key & k) { + return std::string(TG_CACHE[std::get<0>(k)]) + " layer " + std::to_string(std::get<1>(k)) + " pos " + + std::to_string(std::get<2>(k)) + (std::get<3>(k) ? " pooled" : ""); +} + +// the rows of positions [p0, p1) in every layer of every cache, pooled keys only for rep rows of complete groups +static std::map> tg_rows(llama_kv_cache * const kv[3], llama_pos p0, llama_pos p1, llama_pos n_valid) { + std::map> res; + for (int c = 0; c < 3; ++c) { + const auto cells = tg_cells(kv[c]); + for (const uint32_t il : kv[c]->get_layer_ids()) { + const size_t split = c == 1 ? tg_idx_split(kv[c], il) : 0; + for (llama_pos p = std::max(0, p0); p < p1; ++p) { + auto it = cells.find(p); + if (it == cells.end()) { + continue; + } + std::vector row = tg_row(kv[c], il, it->second); + if (c != 1) { + res[{ c, (int) il, p, 0 }] = std::move(row); + continue; + } + res[{ c, (int) il, p, 0 }] = std::vector(row.begin(), row.begin() + split); + if (p % 4 == 3 && p < n_valid) { + res[{ c, (int) il, p, 1 }] = std::vector(row.begin() + split, row.end()); + } + } + } + } + return res; +} + +// the r schedule of the seed harness, copied as data: every r once, long runs of r=0 and r=K, alternation, a seeded tail +static std::vector make_schedule(uint32_t K, size_t n, uint32_t seed) { + std::vector s; + for (uint32_t r = 0; r <= K; ++r) s.push_back(r); + for (int i = 0; i < 25; ++i) s.push_back(0); + for (int i = 0; i < 25; ++i) s.push_back(K); + for (int i = 0; i < 20; ++i) s.push_back(i % 2 ? K : 0); + for (uint32_t m = 0; m < 4; ++m) for (uint32_t r = 0; r <= K; ++r) s.push_back(r); + std::mt19937 g(seed); + while (s.size() < n) { + const uint32_t u = g() % 10; + s.push_back(u < 4 ? 0 : (u < 6 ? K : g() % (K + 1))); + } + return s; +} + +// +// the rollback engine: verify rounds [a, a+K] with a forced acceptance r, then seq_rm(a+r+1, -1) when r < K +// + +struct tg_cfg { + std::string name; + uint32_t n_swa; + uint32_t U; + uint32_t K; + uint32_t top_k; + uint32_t L; + uint32_t n_ctx; + bool swa_full; + bool tight; // the SWA cache is n_swa + U cells, so a verify may evict exactly a - n_swa +}; + +static const tg_cfg TG07A = { "TG-07a", 32, 8, 4, 16, 600, 1024, false, false }; +static const tg_cfg TG07B = { "TG-07b", 251, 5, 4, 16, 900, 1024, false, true }; +static const tg_cfg TG07C = { "TG-07c", 248, 8, 7, 8, 900, 1024, false, true }; +static const tg_cfg TG07D = { "TG-07d", 251, 5, 4, 16, 600, 1024, true, false }; + +// test: rejected slots hold unrelated tokens; replay: the true tokens; other: a second set of unrelated tokens +enum class tg_branch { test, replay, other }; + +// negative cases, injected into the test branch only +enum class tg_neg { none, keep_one_more, drop_swa_row, stale_pooled }; + +struct tg_fail { + std::string check; + int round; // -1: after the prefill, rounds.size(): the end of the run + llama_pos a; + uint32_t r; + llama_pos pos; // the first position involved, -1 if none + std::string where; +}; + +struct tg_round { + llama_pos a; + uint32_t r; + std::vector logits; // rows 0..r + std::vector engram; // rows 0..r of engram_rows-1 + std::map rows; // the rows kept from this round, [a, a+r] + std::map, std::vector> pooled; // (layer, rep pos) of those rows +}; + +// C8: the pooled key of group h, left by unrelated tokens, and the one after the group was refilled +struct tg_judge { + int round; + llama_pos h; + int x; // the rejection point inside the group, (a+r+1) % 4 + std::vector layers; // the indexer layers of old_v and new_v + std::vector> old_v; + std::vector> new_v; +}; + +struct tg_run { + tg_cfg cfg; + tg_branch branch; + tg_neg neg; + bool engram; + + std::vector rounds; + std::vector fails; + + std::map r_hist; + std::set rej_res; // (a+r+1) % 4 of the rounds with r < K + size_t c2_rounds = 0; // rounds that evicted SWA rows + size_t c2_at_bound = 0; // rounds whose largest evicted position is exactly a - n_swa + long c2_max = LONG_MIN; // largest (evicted - (a - n_swa)) + uint32_t swa_cells = 0; + llama_pos a_end = 0; + bool truncated = false; + + std::map> final_rows; + std::vector judged; + + int inject_round = -1; // the round of the injection (n3: R2) + int record_round = -1; // n3: R1 + llama_pos inject_pos = -1; // n1: a', n2: v, n3: 4h+3 + double ms = 0; +}; + +static void tg_add(tg_run & run, const std::string & check, int round, llama_pos a, uint32_t r, llama_pos pos, const std::string & where) { + run.fails.push_back({ check, round, a, r, pos, where }); +} + +// C1, the SWA part: the window the next query reads is there, or everything with a full size SWA cache +static void tg_check_swa(tg_run & run, llama_kv_cache * const kv[3], int round, llama_pos a, uint32_t r, llama_pos a_next) { + const tg_cfg & c = run.cfg; + const std::set sp = tg_positions(kv[2]); + const llama_pos lo = c.swa_full ? 0 : std::max(0, a_next - (llama_pos) c.n_swa + 1); + for (llama_pos p = lo; p < a_next; ++p) { + if (!sp.count(p)) { + tg_add(run, "C1.swa", round, a, r, p, "swa misses pos " + std::to_string(p)); + } + } +} + +// C1, the rest: base and indexer hold exactly [0, a'), no cache holds a' or later, tokens and pos_max agree +// returns true when the caches are past use: the next round would collide with the extra rows +static bool tg_check_entry(tg_run & run, llama_context * ctx, llama_kv_cache * const kv[3], const std::vector & T, + int round, llama_pos a, uint32_t r, llama_pos a_next) { + bool stop = false; + std::vector> scan[3]; + for (int c = 0; c < 3; ++c) { + scan[c] = tg_scan(kv[c]); + const auto & sp = kv[c]->get_cells(0).seq_pos_get(0); + if (std::vector>(sp.begin(), sp.end()) != scan[c]) { + tg_add(run, "C1.index", round, a, r, -1, std::string(TG_CACHE[c]) + " seq_pos index differs from the cells"); + stop = true; + } + } + std::vector pos[3]; + for (int c = 0; c < 3; ++c) { + for (const auto & pc : scan[c]) { + pos[c].push_back(pc.first); + } + } + + // base holds exactly [0, a'), each position once + bool base_ok = pos[0].size() == (size_t) a_next; + for (size_t i = 0; base_ok && i < pos[0].size(); ++i) { + base_ok = pos[0][i] == (llama_pos) i; + } + if (!base_ok) { + tg_add(run, "C1.base", round, a, r, -1, "base holds " + std::to_string(pos[0].size()) + " cells, not [0, " + std::to_string(a_next) + ")"); + stop = true; + } + + if (pos[1] != pos[0]) { + tg_add(run, "C1.idx", round, a, r, -1, "the indexer positions differ from base"); + stop = true; + } + + // no cache holds a' or later + for (int c = 0; c < 3; ++c) { + for (const llama_pos p : pos[c]) { + if (p >= a_next) { + tg_add(run, "C1.future", round, a, r, p, std::string(TG_CACHE[c]) + " holds pos " + std::to_string(p)); + stop = true; + } + } + } + + // every live cell carries the token of its position + for (int c = 0; c < 3; ++c) { + const llama_kv_cells & cells = kv[c]->get_cells(0); + for (const auto & pc : scan[c]) { + const llama_pos p = pc.first; + if (p < 0 || (size_t) p >= T.size() || cells.ext_get(pc.second).tok != T[p]) { + tg_add(run, "C1.tok", round, a, r, p, std::string(TG_CACHE[c]) + " pos " + std::to_string(p) + " holds token " + + std::to_string(cells.ext_get(pc.second).tok)); + } + } + } + + const llama_pos pos_max = llama_memory_seq_pos_max(llama_get_memory(ctx), 0); + if (pos_max != a_next - 1) { + tg_add(run, "C1.pos_max", round, a, r, pos_max, "pos_max " + std::to_string(pos_max)); + stop = true; + } + + return stop; +} + +// the pooled keys of rep row pos in every indexer layer +static std::vector> tg_pooled(llama_kv_cache * idx, llama_pos pos) { + std::vector> res; + const auto cells = tg_cells(idx); + auto it = cells.find(pos); + for (const uint32_t il : idx->get_layer_ids()) { + if (it == cells.end()) { + res.emplace_back(); + continue; + } + const std::vector row = tg_row(idx, il, it->second); + res.emplace_back(row.begin() + tg_idx_split(idx, il), row.end()); + } + return res; +} + +static tg_run tg_rollback(const tg_cfg & c, tg_branch branch, tg_neg neg, bool engram) { + const auto t0 = std::chrono::steady_clock::now(); + + tg_run run; + run.cfg = c; + run.branch = branch; + run.neg = neg; + run.engram = engram; + + tg_eval ev; + ev.names = { "engram_rows-1" }; + + llama_model * model = tg_model(c.top_k, c.n_swa); + if (model == nullptr) { + tg_add(run, "setup", -1, 0, 0, -1, "the tiny target does not build"); + return run; + } + llama_context_ptr ctx_ptr = tg_context(model, c.n_ctx, c.U, c.swa_full, engram ? &ev : nullptr); + if (!ctx_ptr) { + tg_add(run, "setup", -1, 0, 0, -1, "no context"); + return run; + } + llama_context * ctx = ctx_ptr.get(); + llama_kv_cache * kv[3]; + tg_caches(ctx, kv); + run.swa_cells = kv[2]->get_size(); + + const std::vector T = get_tokens(c.L + 8, TG_VOCAB, TG_SEED); + const std::vector sched = make_schedule(c.K, 4096, TG_SEED); + std::mt19937 g(TG_SEED + 7 + (branch == tg_branch::other ? 1000 : 0)); + + if (tg_prefill(ctx, T, TG_P, c.U) != 0) { + tg_add(run, "decode", -1, 0, 0, -1, "prefill"); + run.truncated = true; + return run; + } + tg_check_swa(run, kv, -1, TG_P, 0, TG_P); + if (tg_check_entry(run, ctx, kv, T, -1, TG_P, 0, TG_P)) { + run.truncated = true; + return run; + } + + const uint32_t K = c.K; + const llama_pos neg_from = (llama_pos) (TG_P + 3*c.n_swa); + std::map pending; // C8, by group + std::vector> n3_old; + tg_batch bt(K + 1); + llama_pos a = TG_P; + size_t ri = 0; + while ((uint32_t) a + K + 1 < c.L) { + const int round = (int) run.rounds.size(); + const uint32_t r = std::min(K, sched[ri++ % sched.size()]); + + bt.clear(); + for (uint32_t j = 0; j <= K; ++j) { + llama_token tok = T[a + j]; + if (j > r && branch != tg_branch::replay) { + tok = tg_junk(tok, g); + } + bt.add(tok, a + j, true); + } + + const std::set swa_before = tg_positions(kv[2]); + ev.reset(); + if (llama_decode(ctx, bt.b) != 0) { + tg_add(run, "decode", round, a, r, a, "verify decode failed"); + run.truncated = true; + break; + } + llama_synchronize(ctx); + + // C2: a verify only evicts SWA rows the window has left, at most a - n_swa + { + const std::set swa_after = tg_positions(kv[2]); + bool evicted = false; + llama_pos mx = 0; + for (const llama_pos p : swa_before) { + if (!swa_after.count(p)) { + mx = evicted ? std::max(mx, p) : p; + evicted = true; + } + } + if (evicted) { + run.c2_rounds++; + run.c2_max = std::max(run.c2_max, (long) mx - (long) (a - (llama_pos) c.n_swa)); + run.c2_at_bound += mx == a - (llama_pos) c.n_swa; + } + if (evicted && mx > a - (llama_pos) c.n_swa) { + tg_add(run, "C2", round, a, r, mx, "the verify evicted swa pos " + std::to_string(mx)); + } + } + + tg_round rd; + rd.a = a; + rd.r = r; + for (uint32_t j = 0; j <= r; ++j) { + const float * lg = llama_get_logits_ith(ctx, j); + rd.logits.insert(rd.logits.end(), lg, lg + TG_VOCAB); + } + if (engram) { + auto it = ev.data.find("engram_rows-1"); + if (ev.bad || ev.n_hits != 1 || it == ev.data.end() || ev.ne["engram_rows-1"][2] != (int64_t) K + 1) { + tg_add(run, "C9.capture", round, a, r, -1, "engram_rows-1 was not captured"); + } else { + const size_t row = it->second.size()/(K + 1)*sizeof(float); + const uint8_t * src = (const uint8_t *) it->second.data(); + rd.engram.assign(src, src + row*(r + 1)); + } + } + + // C8, record: the rejection point is inside group h and the batch wrote the whole group + const llama_pos h = (a + r + 1)/4; + const int x = (a + r + 1) % 4; + if (branch == tg_branch::test && r < K && x != 0 && 4*h + 3 <= a + (llama_pos) K) { + tg_judge & jd = pending[h]; + if (jd.old_v.empty()) { + jd.h = h; + jd.x = x; + } + jd.old_v = tg_pooled(kv[1], 4*h + 3); + jd.layers = kv[1]->get_layer_ids(); + if (neg == tg_neg::stale_pooled && run.record_round < 0 && a > neg_from) { + run.record_round = round; + run.inject_pos = 4*h + 3; + } + // n3 writes back what the test branch last left in the rep row, the old key C8 compares with + if (neg == tg_neg::stale_pooled && run.inject_round < 0 && run.inject_pos == 4*h + 3) { + n3_old = jd.old_v; + } + } + + // roll back the rejected suffix + const llama_pos a_next = a + r + 1; + llama_pos p_rm = a_next; + if (neg == tg_neg::keep_one_more && run.inject_round < 0 && a_next > neg_from && r < K) { + p_rm = a_next + 1; + run.inject_round = round; + run.inject_pos = a_next; + } + if (r < K && !llama_memory_seq_rm(llama_get_memory(ctx), 0, p_rm, -1)) { + tg_add(run, "seq_rm", round, a, r, p_rm, "seq_rm returned false"); + run.truncated = true; + break; + } + + // the negative cases inject their fault here, after the rollback + if (neg == tg_neg::drop_swa_row && run.inject_round < 0 && a_next > neg_from && r < K) { + const llama_pos v = a_next - (llama_pos) c.n_swa + 1; + kv[2]->seq_rm(0, v, v + 1); + run.inject_round = round; + run.inject_pos = v; + } + if (neg == tg_neg::stale_pooled && run.record_round >= 0 && run.inject_round < 0 && round > run.record_round && + a + (llama_pos) r >= run.inject_pos) { + const auto cells = tg_cells(kv[1]); + const auto ids = kv[1]->get_layer_ids(); + for (size_t li = 0; li < ids.size(); ++li) { + ggml_tensor * k = kv[1]->get_k_storage(ids[li]); + ggml_backend_tensor_set(k, n3_old[li].data(), (size_t) cells.at(run.inject_pos)*k->nb[1] + tg_idx_split(kv[1], ids[li]), n3_old[li].size()); + } + run.inject_round = round; + } + + // C1, after the injection and before the next decode + tg_check_swa(run, kv, round, a, r, a_next); + const bool stop = tg_check_entry(run, ctx, kv, T, round, a, r, a_next); + + // C6, record: the rows this round keeps + for (const auto & kr : tg_rows(kv, a, a_next, a_next)) { + rd.rows[kr.first] = tg_hash(kr.second.data(), kr.second.size()); + if (std::get<3>(kr.first) == 1) { + rd.pooled[{ std::get<1>(kr.first), std::get<2>(kr.first) }] = kr.second; + } + } + + // C8, judge: the first round that keeps the rep row of a pending group + for (auto it = pending.begin(); it != pending.end(); ) { + if (4*it->first + 3 <= a + (llama_pos) r) { + it->second.round = round; + it->second.new_v = tg_pooled(kv[1], 4*it->first + 3); + run.judged.push_back(it->second); + it = pending.erase(it); + } else { + ++it; + } + } + + run.r_hist[r]++; + if (r < K) { + run.rej_res.insert((int) (a_next % 4)); + } + run.rounds.push_back(std::move(rd)); + a = a_next; + if (stop) { + run.truncated = true; + break; + } + } + run.a_end = a; + + // C6, the end: every live row the next round could read + { + auto all = tg_rows(kv, 0, a, a); + for (auto & kr : all) { + const int cc = std::get<0>(kr.first); + const llama_pos p = std::get<2>(kr.first); + if (cc == 2 && !c.swa_full && p < a - (llama_pos) c.n_swa + 1) { + continue; + } + run.final_rows[kr.first] = std::move(kr.second); + } + } + + run.ms = tg_ms_since(t0); + return run; +} + +// runs by (config, branch, negative case, callback, instance): instance 1 is an independent second run +static std::map, std::unique_ptr> g_runs; + +static const tg_run & tg_get(const tg_cfg & c, tg_branch branch, tg_neg neg = tg_neg::none, bool engram = false, int inst = 0) { + auto & slot = g_runs[{ c.name, (int) branch, (int) neg, engram, inst }]; + if (!slot) { + slot = std::make_unique(tg_rollback(c, branch, neg, engram)); + } + return *slot; +} + +static std::string tg_describe(const tg_cfg & c, const tg_fail & f) { + return f.check + " " + c.name + " round " + std::to_string(f.round) + " a=" + std::to_string(f.a) + " r=" + std::to_string(f.r) + + " K=" + std::to_string(c.K) + ": " + f.where; +} + +static bool tg_none(testing & t, const tg_cfg & c, const std::string & what, const std::vector & fails) { + for (size_t i = 0; i < fails.size() && i < 10; ++i) { + t.out << t.indent() << " " << tg_describe(c, fails[i]) << "\n"; + } + return t.assert_true(what + " (" + std::to_string(fails.size()) + " failures)", fails.empty()); +} + +// C3/C4/C5: rows 0..r of every round, bit for bit, over the rounds both runs have +static void tg_cmp_logits(std::vector & out, const char * check, const tg_run & A, const tg_run & B) { + const size_t n = std::min(A.rounds.size(), B.rounds.size()); + for (size_t i = 0; i < n; ++i) { + const tg_round & ra = A.rounds[i]; + const tg_round & rb = B.rounds[i]; + if (ra.a != rb.a || ra.r != rb.r) { + out.push_back({ check, (int) i, ra.a, ra.r, ra.a, "the rounds differ in shape" }); + return; + } + for (uint32_t j = 0; j <= ra.r; ++j) { + if (memcmp(ra.logits.data() + j*TG_VOCAB, rb.logits.data() + j*TG_VOCAB, TG_VOCAB*sizeof(float)) != 0) { + out.push_back({ check, (int) i, ra.a, ra.r, ra.a + (llama_pos) j, "logits of pos " + std::to_string(ra.a + j) }); + break; + } + } + } +} + +// C6 (and C5): the rows kept each round by hash, then every live row at the end byte for byte +static void tg_cmp_rows(std::vector & out, const char * check, const tg_run & A, const tg_run & B) { + const size_t n = std::min(A.rounds.size(), B.rounds.size()); + for (size_t i = 0; i < n; ++i) { + const tg_round & ra = A.rounds[i]; + const tg_round & rb = B.rounds[i]; + for (const auto & kv : ra.rows) { + auto it = rb.rows.find(kv.first); + if (it == rb.rows.end() || it->second != kv.second) { + out.push_back({ check, (int) i, ra.a, ra.r, std::get<2>(kv.first), tg_where(kv.first) }); + } + } + for (const auto & kv : rb.rows) { + if (!ra.rows.count(kv.first)) { + out.push_back({ check, (int) i, ra.a, ra.r, std::get<2>(kv.first), tg_where(kv.first) + " only in the reference" }); + } + } + } + if (A.truncated || B.truncated || A.a_end != B.a_end) { + return; + } + const int end = (int) A.rounds.size(); + for (const auto & kv : A.final_rows) { + auto it = B.final_rows.find(kv.first); + if (it == B.final_rows.end() || it->second != kv.second) { + out.push_back({ check, end, A.a_end, 0, std::get<2>(kv.first), "end: " + tg_where(kv.first) }); + } + } + for (const auto & kv : B.final_rows) { + if (!A.final_rows.count(kv.first)) { + out.push_back({ check, end, A.a_end, 0, std::get<2>(kv.first), "end: " + tg_where(kv.first) + " only in the reference" }); + } + } +} + +// C8: a pooled key rewritten by unrelated tokens is pooled again after the refill, and equals the replay's +static void tg_cmp_judged(std::vector & out, const tg_run & S, const tg_run & R) { + for (const tg_judge & jd : S.judged) { + const llama_pos rep = 4*jd.h + 3; + const tg_round & rs = S.rounds[jd.round]; + if ((size_t) jd.round >= R.rounds.size()) { + out.push_back({ "C8", jd.round, rs.a, rs.r, rep, "no replay round" }); + continue; + } + const tg_round & rr = R.rounds[jd.round]; + for (size_t li = 0; li < jd.new_v.size(); ++li) { + const int il = (int) jd.layers[li]; + if (jd.new_v[li] == jd.old_v[li]) { + out.push_back({ "C8", jd.round, rs.a, rs.r, rep, "group " + std::to_string(jd.h) + " layer " + std::to_string(il) + " was not pooled again" }); + } + auto it = rr.pooled.find({ il, rep }); + if (it == rr.pooled.end() || it->second != jd.new_v[li]) { + out.push_back({ "C8", jd.round, rs.a, rs.r, rep, "group " + std::to_string(jd.h) + " layer " + std::to_string(il) + " differs from the replay" }); + } + } + } +} + +// C9: rows 0..r of engram_rows-1 +static void tg_cmp_engram(std::vector & out, const tg_run & A, const tg_run & B) { + const size_t n = std::min(A.rounds.size(), B.rounds.size()); + for (size_t i = 0; i < n; ++i) { + if (A.rounds[i].engram.empty() || A.rounds[i].engram != B.rounds[i].engram) { + out.push_back({ "C9", (int) i, A.rounds[i].a, A.rounds[i].r, A.rounds[i].a, "engram_rows-1 differs or is missing" }); + } + } +} + +static void tg_print_stats(testing & t, const tg_run & run) { + std::string hist; + for (const auto & rh : run.r_hist) { + hist += " r" + std::to_string(rh.first) + "=" + std::to_string(rh.second); + } + t.out << t.indent() << " " << run.cfg.name << " (n_swa " << run.cfg.n_swa << ", U " << run.cfg.U << ", K " << run.cfg.K << ", top_k " + << run.cfg.top_k << ", L " << run.cfg.L << ", n_ctx " << run.cfg.n_ctx << ", swa_full " << run.cfg.swa_full << "): rounds " + << run.rounds.size() << ", a_end " << run.a_end << ", swa cells " << run.swa_cells << ", r_hist" << hist + << "; C2 evicting rounds " << run.c2_rounds << ", max - (a - n_swa) " + << (run.c2_rounds ? std::to_string(run.c2_max) : std::string("-")) << ", rounds at a - n_swa " << run.c2_at_bound + << "; " << (long) run.ms << " ms\n"; +} + +// C7: what the run covered +static void tg_check_cover(testing & t, const tg_run & S) { + const tg_cfg & c = S.cfg; + bool all_r = true; + for (uint32_t r = 0; r <= c.K; ++r) { + all_r = all_r && S.r_hist.count(r) && S.r_hist.at(r) > 0; + } + t.assert_true(c.name + " C7: every r in 0..K", all_r); + t.assert_true(c.name + " C7: rejection points cover every (a+r+1) % 4", S.rej_res.size() == 4); + if (!c.swa_full) { + t.assert_true(c.name + " C7: the SWA cache wraps twice", S.a_end >= (llama_pos) (2*S.swa_cells)); + } else { + t.assert_equal(c.name + " C7: a full size SWA cache evicts nothing", (size_t) 0, S.c2_rounds); + } + if (c.tight) { + t.assert_true(c.name + " C7: some verify evicts exactly a - n_swa", S.c2_at_bound >= 1); + } +} + +// TG-07: test, replay, other unrelated tokens and a second replay, C1..C7 +static void tg07_check(testing & t, const tg_cfg & c) { + const tg_run & R = tg_get(c, tg_branch::replay); + const tg_run & R2 = tg_get(c, tg_branch::replay, tg_neg::none, false, 1); + { + std::vector c5; + tg_cmp_logits(c5, "C5", R, R2); + tg_cmp_rows (c5, "C5", R, R2); + if (!tg_none(t, c, c.name + " C5: the replay is deterministic", c5)) { + return; + } + } + const tg_run & S = tg_get(c, tg_branch::test); + const tg_run & O = tg_get(c, tg_branch::other); + tg_print_stats(t, S); + + for (const tg_run * run : { &S, &R, &O, &R2 }) { + tg_none(t, c, c.name + " C1/C2 hold in every round of a branch", run->fails); + t.assert_true(c.name + " the branch ran to the end", !run->truncated); + } + t.assert_true(c.name + " the branches have the same rounds", + S.rounds.size() == R.rounds.size() && O.rounds.size() == R.rounds.size() && S.a_end == R.a_end && O.a_end == R.a_end); + + std::vector c3, c4, c6; + tg_cmp_logits(c3, "C3", S, R); + tg_cmp_logits(c4, "C4", S, O); + tg_cmp_rows (c6, "C6", S, R); + tg_none(t, c, c.name + " C3: test and replay logits are bitwise equal", c3); + tg_none(t, c, c.name + " C4: another set of unrelated tokens gives the same logits", c4); + tg_none(t, c, c.name + " C6: test and replay cache rows are bitwise equal", c6); + tg_check_cover(t, S); +} + +static void test_fixture(testing & t) { + t.test("TF-01_tiny_target_shape", [](testing & t) { + llama_model_ptr model = hy_v4_flash_tiny_target(hy_v4_flash_tiny{}); + if (!t.assert_true("the tiny target builds", model != nullptr)) { + return; + } + const llama_hparams & hp = model->hparams; + t.assert_equal("n_layer", 10u, hp.n_layer()); + t.assert_equal("n_layer_nextn", 0u, hp.n_layer_nextn); + for (uint32_t il = 0; il < hp.n_layer(); ++il) { + const std::string l = "layer " + std::to_string(il); + if (il % 2 == 0) { + t.assert_true(l + " is sparse with an indexer", !hp.is_swa(il) && hp.is_indexer_full(il)); + } else { + t.assert_true(l + " is sliding window", hp.is_swa(il)); + } + t.assert_equal(l + " Engram", il == 1, hp.is_ple(il)); + } + t.assert_equal("indexer_top_k", 8u, hp.indexer_top_k); + t.assert_equal("indexer_kpool", 4u, hp.indexer_kpool); + t.assert_true ("indexer_kpool_select_tail", hp.indexer_kpool_select_tail); + t.assert_equal("n_swa", 32u, hp.n_swa); + t.assert_equal("rope base of the sparse layers", 1e7f, hp.rope_freq_base_train); + t.assert_equal("rope base of the window layers", 1e4f, hp.rope_freq_base_train_swa); + t.assert_equal("n_embd", 128u, hp.n_embd); + t.assert_equal("vocab", 128, llama_vocab_n_tokens(llama_model_get_vocab(model.get()))); + t.assert_equal("n_lora_q", 512u, hp.n_lora_q); + t.assert_equal("n_lora_kv", 512u, hp.n_lora_kv); + t.assert_equal("k_mla", 192u, hp.n_embd_head_k_mla()); + t.assert_equal("v_mla", 128u, hp.n_embd_head_v_mla()); + t.assert_equal("n_rot", 64u, hp.n_rot()); + + llama_context_ptr ctx = tg_context(model.get(), 1024, 8, false, nullptr); + if (!t.assert_true("context", ctx != nullptr)) { + return; + } + auto * mem = dynamic_cast(llama_get_memory(ctx.get())); + if (!t.assert_true("the memory is a llama_memory_idx_iswa", mem != nullptr)) { + return; + } + const std::vector full = { 0, 2, 4, 6, 8 }; + const std::vector swa = { 1, 3, 5, 7, 9 }; + t.assert_true("base layers", mem->get_mem_attn()->get_base()->get_layer_ids() == full); + t.assert_true("indexer layers", mem->get_mem_idx()->get_layer_ids() == full); + t.assert_true("swa layers", mem->get_mem_attn()->get_swa()->get_layer_ids() == swa); + t.assert_equal("kpool", 4u, mem->get_kpool()); + t.assert_true ("pools by position", !mem->get_kpool_by_order()); + }); + + t.test("TF-02_generator_override", [](testing & t) { + const llm_arch arch = LLM_ARCH_HY_V4_FLASH; + for (const uint32_t n : { 0u, 10u }) { + gguf_context_ptr g = get_gguf_ctx(arch, true, n); + const uint32_t want = n == 0 ? 4 : 10; + const std::string w = n == 0 ? "default: " : "override 10: "; + const int64_t bc = gguf_find_key(g.get(), llama_arch_kv_name(arch, LLM_KV_BLOCK_COUNT).c_str()); + if (t.assert_true(w + "block_count is set", bc >= 0)) { + t.assert_equal(w + "block_count", want, gguf_get_val_u32(g.get(), bc)); + } + for (const llm_kv key : { LLM_KV_ATTENTION_HEAD_COUNT, LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, LLM_KV_ATTENTION_INDEXER_TYPES }) { + const std::string name = llama_arch_kv_name(arch, key); + const int64_t id = gguf_find_key(g.get(), name.c_str()); + if (t.assert_true(w + name + " is an array", id >= 0 && gguf_get_kv_type(g.get(), id) == GGUF_TYPE_ARRAY)) { + t.assert_equal(w + name + " length", (size_t) want, gguf_get_arr_n(g.get(), id)); + } + } + } + }); +} + +// +// TG-04: batch width, target only +// + +static const uint32_t TG04_TOP_K = 16; +static const uint32_t TG04_SWA = 32; +static const uint32_t TG04_U = 8; +static const uint32_t TG04_CTX = 1024; + +struct tg04_out { + std::vector logits; + std::map> rows; +}; + +// prefill T[0, P), then one batch of W rows at [P, P+W); rows j >= first_junk hold unrelated tokens +static bool tg04_decode(const std::vector & T, uint32_t P, uint32_t W, uint32_t first_junk, tg04_out & out) { + llama_context_ptr ctx = tg_context(tg_model(TG04_TOP_K, TG04_SWA), TG04_CTX, TG04_U, false, nullptr); + if (!ctx || tg_prefill(ctx.get(), T, P, TG04_U) != 0) { + return false; + } + std::mt19937 g(TG_SEED + 7); + tg_batch bt(W); + for (uint32_t j = 0; j < W; ++j) { + bt.add(j >= first_junk ? tg_junk(T[P + j], g) : T[P + j], P + j, true); + } + if (llama_decode(ctx.get(), bt.b) != 0) { + return false; + } + llama_synchronize(ctx.get()); + for (uint32_t j = 0; j < W; ++j) { + const float * lg = llama_get_logits_ith(ctx.get(), j); + out.logits.insert(out.logits.end(), lg, lg + TG_VOCAB); + } + llama_kv_cache * kv[3]; + tg_caches(ctx.get(), kv); + out.rows = tg_rows(kv, 0, P + W, P + W); + return true; +} + +// the pools a row's indexer keeps: the first min(n_pool, top_k/4) by score, tie when the cut splits equal scores +struct tg_pools { + std::vector set; + bool tie = false; + int n_finite = 0; +}; + +static tg_pools tg_pick(const float * s, int64_t n_pool, uint32_t top_k) { + tg_pools res; + std::vector> v; + for (int64_t i = 0; i < n_pool; ++i) { + if (std::isfinite(s[i])) { + v.push_back({ s[i], (int) i }); + } + } + res.n_finite = (int) v.size(); + std::sort(v.begin(), v.end(), [](const auto & a, const auto & b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }); + const size_t n = std::min((size_t) n_pool, top_k/4); + for (size_t i = 0; i < n && i < v.size(); ++i) { + res.set.push_back(v[i].second); + } + res.tie = n > 0 && n < v.size() && v[n - 1].first == v[n].first; + std::sort(res.set.begin(), res.set.end()); + return res; +} + +static const int TG04_IDX[5] = { 0, 2, 4, 6, 8 }; + +struct tg04_width { + std::map> logits; + std::map> pools; // per indexer layer + bool ok = true; + std::string err; +}; + +// W true tokens per round from P = 64, every row out, no rollback, until [64, 160) is covered +static tg04_width tg04_run(uint32_t W) { + const uint32_t P = 64, N = 96; + tg04_width res; + tg_eval ev; + for (const int il : TG04_IDX) { + ev.names.push_back("indexer_score-" + std::to_string(il)); + } + llama_context_ptr ctx = tg_context(tg_model(TG04_TOP_K, TG04_SWA), TG04_CTX, TG04_U, false, &ev); + const std::vector T = get_tokens(P + N + 8, TG_VOCAB, TG_SEED); + if (!ctx || tg_prefill(ctx.get(), T, P, TG04_U) != 0) { + res.ok = false; + res.err = "prefill"; + return res; + } + tg_batch bt(W); + for (llama_pos a = P; a < (llama_pos) (P + N); a += W) { + bt.clear(); + for (uint32_t j = 0; j < W; ++j) { + bt.add(T[a + j], a + j, true); + } + ev.reset(); + if (llama_decode(ctx.get(), bt.b) != 0) { + res.ok = false; + res.err = "decode at " + std::to_string(a); + return res; + } + llama_synchronize(ctx.get()); + if (ev.bad || ev.n_hits != 5) { + res.ok = false; + res.err = "indexer_score was not captured at " + std::to_string(a); + return res; + } + for (uint32_t j = 0; j < W; ++j) { + const llama_pos p = a + j; + const float * lg = llama_get_logits_ith(ctx.get(), j); + res.logits[p].assign(lg, lg + TG_VOCAB); + for (const int il : TG04_IDX) { + const std::string name = "indexer_score-" + std::to_string(il); + const auto & ne = ev.ne[name]; + if (ne[1] != (int64_t) W) { + res.ok = false; + res.err = name + " has " + std::to_string(ne[1]) + " rows"; + return res; + } + tg_pools pk = tg_pick(ev.data[name].data() + (size_t) j*ne[0], ne[0], TG04_TOP_K); + // single sequence from pos 0: pool i is group i, so the visible pools are the groups ending at or before p + if (pk.n_finite != p/4) { + res.ok = false; + res.err = name + " pos " + std::to_string(p) + " has " + std::to_string(pk.n_finite) + " finite scores"; + return res; + } + res.pools[p].push_back(pk); + } + } + } + return res; +} + +static void test_width(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + + t.test("TG-04a_future_suffix", [](testing & t) { + const std::vector T = get_tokens(256, TG_VOCAB, TG_SEED); + size_t n_pairs = 0; + for (uint32_t P = 64; P <= 67; ++P) { + for (uint32_t W = 2; W <= 8; ++W) { + tg04_out real; + if (!t.assert_true("P " + std::to_string(P) + " W " + std::to_string(W) + " decodes", tg04_decode(T, P, W, W, real))) { + continue; + } + const std::set js = { 1, (W + 1)/2, W - 1 }; + for (const uint32_t j : js) { + const std::string w = "P " + std::to_string(P) + " W " + std::to_string(W) + " j " + std::to_string(j); + tg04_out alt; + if (!t.assert_true(w + " decodes", tg04_decode(T, P, W, j, alt))) { + continue; + } + n_pairs++; + t.assert_true(w + ": rows before j have bitwise equal logits", + memcmp(real.logits.data(), alt.logits.data(), (size_t) j*TG_VOCAB*sizeof(float)) == 0); + // the cache rows of positions before P + j; pooled keys of groups that end before it + auto keep = [&](const std::map> & rows) { + std::map> res; + for (const auto & kr : rows) { + if (std::get<2>(kr.first) < (llama_pos) (P + j)) { + res.insert(kr); + } + } + return res; + }; + const auto ra = keep(real.rows); + const auto rb = keep(alt.rows); + std::string first; + if (ra != rb) { + for (const auto & kr : ra) { + auto it = rb.find(kr.first); + if (it == rb.end() || it->second != kr.second) { + first = tg_where(kr.first); + break; + } + } + } + t.assert_true(w + ": cache rows before P + j are bitwise equal " + first, ra == rb && !ra.empty()); + } + } + } + t.out << t.indent() << " " << n_pairs << " (P, W, j) pairs\n"; + }); + + t.test("TG-04b_width_record", [](testing & t) { + std::map runs; + for (uint32_t W = 1; W <= 8; ++W) { + runs[W] = tg04_run(W); + if (!t.assert_true("W " + std::to_string(W) + " runs: " + runs[W].err, runs[W].ok)) { + return; + } + } + const tg04_width & w1 = runs[1]; + { + const tg04_width again = tg04_run(1); + bool same = again.ok && again.logits == w1.logits; + for (const auto & pp : w1.pools) { + for (size_t li = 0; same && li < pp.second.size(); ++li) { + same = again.pools.at(pp.first)[li].set == pp.second[li].set && again.pools.at(pp.first)[li].tie == pp.second[li].tie; + } + } + if (!t.assert_true("W=1 twice gives bitwise equal logits and pool sets", same)) { + return; + } + } + // eq_w2: positions whose logits are also bitwise equal to those of W=2 + t.out << t.indent() << " W positions bitwise_equal max_rel_l2 argmax_diff min_w1_margin pool_set_diff(il 0/2/4/6/8, ties) eq_w2\n"; + for (uint32_t W = 2; W <= 8; ++W) { + const tg04_width & wr = runs[W]; + size_t n = 0, n_eq = 0, n_amax = 0, n_eq2 = 0; + double max_rel = 0, min_margin = INFINITY; + size_t pool_diff[5] = {}, pool_tie[5] = {}; + for (llama_pos p = 64; p < 160; ++p) { + const std::vector & a = wr.logits.at(p); + const std::vector & b = w1.logits.at(p); + n++; + n_eq += memcmp(a.data(), b.data(), TG_VOCAB*sizeof(float)) == 0; + n_eq2 += memcmp(a.data(), runs[2].logits.at(p).data(), TG_VOCAB*sizeof(float)) == 0; + double num = 0, den = 0; + for (uint32_t i = 0; i < TG_VOCAB; ++i) { + num += ((double) a[i] - b[i])*((double) a[i] - b[i]); + den += (double) b[i]*b[i]; + } + max_rel = std::max(max_rel, std::sqrt(num/den)); + const int ia = (int) (std::max_element(a.begin(), a.end()) - a.begin()); + const int ib = (int) (std::max_element(b.begin(), b.end()) - b.begin()); + if (ia != ib) { + n_amax++; + std::vector s = b; + std::partial_sort(s.begin(), s.begin() + 2, s.end(), std::greater()); + min_margin = std::min(min_margin, (double) s[0] - s[1]); + } + for (int li = 0; li < 5; ++li) { + const tg_pools & pa = wr.pools.at(p)[li]; + const tg_pools & pb = w1.pools.at(p)[li]; + if (pa.tie || pb.tie) { + pool_tie[li]++; + } else if (pa.set != pb.set) { + pool_diff[li]++; + } + } + } + char line[256]; + snprintf(line, sizeof(line), " %u %9zu %13zu %10.3e %11zu %13s %zu/%zu/%zu/%zu/%zu, ties %zu/%zu/%zu/%zu/%zu %zu\n", + W, n, n_eq, max_rel, n_amax, n_amax ? std::to_string(min_margin).c_str() : "-", + pool_diff[0], pool_diff[1], pool_diff[2], pool_diff[3], pool_diff[4], + pool_tie[0], pool_tie[1], pool_tie[2], pool_tie[3], pool_tie[4], n_eq2); + t.out << t.indent() << line; + } + }); + + t.out << t.indent() << " width group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +// +// TG-05..07: rollback against a same-shape replay +// + +static void test_rollback(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + + t.test("TG-05_refill_inside_group", [](testing & t) { + std::set res; + for (const tg_cfg * c : { &TG07A, &TG07B }) { + const tg_run & S = tg_get(*c, tg_branch::test); + const tg_run & R = tg_get(*c, tg_branch::replay); + tg_none(t, *c, c->name + " the branches hold C1/C2", S.fails); + tg_none(t, *c, c->name + " the replay holds C1/C2", R.fails); + std::vector c8; + tg_cmp_judged(c8, S, R); + tg_none(t, *c, c->name + " C8: a group refilled after a rejection inside it is pooled again, as in the replay", c8); + size_t n_x[4] = {}; + for (const tg_judge & jd : S.judged) { + n_x[jd.x]++; + res.insert(jd.x); + } + t.out << t.indent() << " " << c->name << ": " << S.judged.size() << " groups judged, rejection inside at 1/2/3: " + << n_x[1] << "/" << n_x[2] << "/" << n_x[3] << "\n"; + } + t.assert_true("C8 covers rejection points 1, 2 and 3 inside a group", res == std::set({ 1, 2, 3 })); + }); + + t.test("TG-06_engram_history", [](testing & t) { + const tg_run & S = tg_get(TG07A, tg_branch::test, tg_neg::none, true); + const tg_run & R = tg_get(TG07A, tg_branch::replay, tg_neg::none, true); + tg_none(t, TG07A, "the test branch holds C1/C2 and captures engram_rows-1", S.fails); + tg_none(t, TG07A, "the replay holds C1/C2 and captures engram_rows-1", R.fails); + t.assert_true("the branches have the same rounds", !S.rounds.empty() && S.rounds.size() == R.rounds.size() && !S.truncated && !R.truncated); + std::vector c9, c3; + tg_cmp_engram(c9, S, R); + tg_cmp_logits(c3, "C3", S, R); + tg_none(t, TG07A, "C9: engram_rows-1 is bitwise equal to the replay's in every kept row", c9); + tg_none(t, TG07A, "C3 with the callback set", c3); + }); + + t.test("TG-07a_compact_wrap", [](testing & t) { tg07_check(t, TG07A); }); + t.test("TG-07b_tight_window", [](testing & t) { tg07_check(t, TG07B); }); + t.test("TG-07c_tight_k7", [](testing & t) { tg07_check(t, TG07C); }); + t.test("TG-07d_full_smoke", [](testing & t) { tg07_check(t, TG07D); }); + + t.out << t.indent() << " rollback group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +// every failure of a negative run: its own C1/C2 and the comparisons with the clean replay +static std::vector tg_neg_fails(const tg_run & S, const tg_run & R) { + std::vector all = S.fails; + tg_cmp_logits(all, "C3", S, R); + tg_cmp_rows (all, "C6", S, R); + tg_cmp_judged(all, S, R); + return all; +} + +static int tg_first_round(const std::vector & fails) { + int res = INT_MAX; + for (const tg_fail & f : fails) { + res = std::min(res, f.round); + } + return res; +} + +static bool tg_has(const std::vector & fails, const std::string & check, int round, llama_pos pos, const std::string & where = "") { + return std::any_of(fails.begin(), fails.end(), [&](const tg_fail & f) { + return f.check == check && (round < 0 || f.round == round) && (pos < 0 || f.pos == pos) && f.where.find(where) != std::string::npos; + }); +} + +static void tg_neg_report(testing & t, const tg_run & S, const std::vector & all) { + std::map n; + for (const tg_fail & f : all) { + n[f.check]++; + } + std::string s; + for (const auto & kv : n) { + s += " " + kv.first + "=" + std::to_string(kv.second); + } + t.out << t.indent() << " injected in round " << S.inject_round << " (pos " << S.inject_pos << "), first failing round " + << tg_first_round(all) << ", failures:" << s << "\n"; + for (size_t i = 0; i < all.size() && i < 6; ++i) { + t.out << t.indent() << " " << tg_describe(S.cfg, all[i]) << "\n"; + } +} + +static void test_rollback_neg(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + + t.test("TG-07n1_keep_one_more", [](testing & t) { + const tg_run & R = tg_get(TG07A, tg_branch::replay); + tg_none(t, TG07A, "the replay holds C1/C2", R.fails); + const tg_run & S = tg_get(TG07A, tg_branch::test, tg_neg::keep_one_more); + const std::vector all = tg_neg_fails(S, R); + tg_neg_report(t, S, all); + if (!t.assert_true("the fault was injected", S.inject_round >= 0)) { + return; + } + const int ir = S.inject_round; + for (const char * c : { "base", "idx", "swa" }) { + t.assert_true(std::string("C1 reports that ") + c + " holds a'", tg_has(all, "C1.future", ir, S.inject_pos, std::string(c) + " holds")); + t.assert_true(std::string("C1 reports the unrelated token of a' in ") + c, tg_has(all, "C1.tok", ir, S.inject_pos, std::string(c) + " pos")); + } + const int first = tg_first_round(all); + t.assert_true("the first failure is in the injection round or the next", first == ir || first == ir + 1); + t.assert_true("the branch stops after the extra row", S.truncated); + }); + + t.test("TG-07n2_drop_swa_row", [](testing & t) { + const tg_run & R = tg_get(TG07A, tg_branch::replay); + tg_none(t, TG07A, "the replay holds C1/C2", R.fails); + const tg_run & S = tg_get(TG07A, tg_branch::test, tg_neg::drop_swa_row); + const std::vector all = tg_neg_fails(S, R); + tg_neg_report(t, S, all); + if (!t.assert_true("the fault was injected", S.inject_round >= 0)) { + return; + } + const int ir = S.inject_round; + const llama_pos a_next = S.rounds[ir].a + (llama_pos) S.rounds[ir].r + 1; + t.assert_true("C1 reports the missing SWA row v", tg_has(all, "C1.swa", ir, S.inject_pos)); + int c3_first = INT_MAX; + llama_pos c3_pos = -1; + for (const tg_fail & f : all) { + if (f.check == "C3" && f.round < c3_first) { + c3_first = f.round; + c3_pos = f.pos; + } + } + t.assert_true("C3 reports different logits from a' on", c3_first != INT_MAX && c3_first > ir && c3_pos >= a_next); + const int first = tg_first_round(all); + t.assert_true("the first failure is in the injection round or the next", first == ir || first == ir + 1); + }); + + t.test("TG-07n3_stale_pooled_key", [](testing & t) { + const tg_run & R = tg_get(TG07A, tg_branch::replay); + tg_none(t, TG07A, "the replay holds C1/C2", R.fails); + const tg_run & S = tg_get(TG07A, tg_branch::test, tg_neg::stale_pooled); + const std::vector all = tg_neg_fails(S, R); + tg_neg_report(t, S, all); + if (!t.assert_true("R1 found", S.record_round >= 0) || !t.assert_true("R2 found: the test can inject", S.inject_round >= 0)) { + return; + } + const int r2 = S.inject_round; + t.assert_true("C8 at R2: the key equals the recorded old one", tg_has(all, "C8", r2, S.inject_pos, "was not pooled again")); + t.assert_true("C8 at R2: the key differs from the replay", tg_has(all, "C8", r2, S.inject_pos, "differs from the replay")); + t.assert_true("C6 at R2 covers the injected rep row", tg_has(all, "C6", r2, S.inject_pos, "pooled")); + t.assert_true("C3 reports different logits later", tg_has(all, "C3", -1, -1) && + std::all_of(all.begin(), all.end(), [&](const tg_fail & f) { return f.check != "C3" || f.round > r2; })); + t.assert_true("C1 reports nothing: the fault changes no metadata", + std::none_of(all.begin(), all.end(), [](const tg_fail & f) { return f.check.rfind("C1", 0) == 0; })); + t.assert_equal("the first failure is in R2", r2, tg_first_round(all)); + }); + + t.out << t.indent() << " rollback_neg group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +static void test_rollback_long(testing & t) { + const char * e = getenv("LLAMA_DFLY_TEST_LONG"); + if (e == nullptr || std::string(e) != "1") { + t.skip("set LLAMA_DFLY_TEST_LONG=1 to run"); + return; + } + const auto t0 = std::chrono::steady_clock::now(); + t.test("TG-07L_seed_scale", [](testing & t) { + const tg_cfg cfgs[] = { + { "TG-07L-swa32", 32, 8, 4, 131072, 1500, 2048, false, false }, + { "TG-07L-tight251", 251, 5, 4, 16, 2500, 4096, false, true }, + { "TG-07L-tight248k7", 248, 8, 7, 131072, 2500, 4096, false, true }, + { "TG-07L-full251", 251, 5, 4, 131072, 2500, 4096, true, false }, + }; + for (const tg_cfg & c : cfgs) { + tg07_check(t, c); + } + }); + t.out << t.indent() << " rollback_long group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +// +// capture: the target exports the selection and hidden state of its output rows (S4b-2) +// + +static const int32_t CP_LAYERS[LLAMA_DFLY_N_LAYER] = { 0, 2, 4, 6, 8 }; +static const int32_t CP_LAYERS_SHUFFLED[LLAMA_DFLY_N_LAYER] = { 8, 0, 4, 2, 6 }; +static const uint32_t CP_W = 5; + +// r of verify round rd, covers 0..W-1 +static uint32_t cp_r(int rd) { + return (uint32_t) (rd*7 + 3) % CP_W; +} + +// models per (top_k, device); the CPU ones are tg_model's +static std::map, llama_model_ptr> g_cp_models; + +static llama_model * cp_model(uint32_t top_k, ggml_backend_dev_t dev) { + if (dev == nullptr) { + return tg_model(top_k, 32); + } + llama_model_ptr & m = g_cp_models[{ top_k, dev }]; + if (!m) { + hy_v4_flash_tiny p; + p.top_k = top_k; + p.dev = dev; + m = hy_v4_flash_tiny_target(p); + } + return m.get(); +} + +// true when name is exactly ""; a view is named " (reshaped)" and does not match +static bool cp_name_is(const char * name, const char * prefix, int & il) { + const size_t n = strlen(prefix); + if (strncmp(name, prefix, n) != 0 || name[n] == '\0') { + return false; + } + char * end = nullptr; + const long v = strtol(name + n, &end, 10); + if (*end != '\0') { + return false; + } + il = (int) v; + return true; +} + +// per ubatch, cut where indexer_score-0 is computed +struct cp_ub { + std::map> score, sel; + std::map> score_ne, sel_ne; + std::map> mask_src; // src[1..4] of a fused mask node + std::set seen; // dfly_sel_* and indexer_top_k-* nodes +}; + +struct cp_eval { + bool data = true; // copy indexer_score/indexer_sel + int abort_at = -1; // raise abort_now at this indexer_score-0 + int n_score0 = 0; + bool abort_now = false; + std::vector ubs; + + void reset() { + ubs.clear(); + } +}; + +static void cp_copy_f32(const ggml_tensor * t, std::vector & d) { + d.resize(ggml_nelements(t)); + if (t->type == GGML_TYPE_F32) { + ggml_backend_tensor_get(t, d.data(), 0, ggml_nbytes(t)); + } else { + std::vector h(d.size()); + ggml_backend_tensor_get(t, h.data(), 0, ggml_nbytes(t)); + for (size_t i = 0; i < d.size(); ++i) { + d[i] = ggml_fp16_to_fp32(h[i]); + } + } +} + +static bool cp_eval_cb(struct ggml_tensor * t, bool ask, void * user_data) { + auto * ev = (cp_eval *) user_data; + int il = -1; + const bool is_score = cp_name_is(t->name, "indexer_score-", il); + const bool is_sel = !is_score && cp_name_is(t->name, "indexer_sel-", il); + const bool is_seen = !is_score && !is_sel && (cp_name_is(t->name, "dfly_sel_ids-", il) || + cp_name_is(t->name, "dfly_sel_scores-", il) || cp_name_is(t->name, "indexer_top_k-", il)); + if (ask) { + return is_seen || (is_score && il == 0) || ((is_score || is_sel) && ev->data); + } + if (!is_score && !is_sel && !is_seen) { + return true; + } + if (is_score && il == 0) { + ev->ubs.emplace_back(); + if (++ev->n_score0 == ev->abort_at) { + ev->abort_now = true; + } + } + if (ev->ubs.empty()) { + ev->ubs.emplace_back(); + } + cp_ub & u = ev->ubs.back(); + if (is_seen) { + u.seen.insert(t->name); + return true; + } + if (!ev->data) { + return true; + } + if (is_score) { + cp_copy_f32(t, u.score[il]); + u.score_ne[il] = { t->ne[0], t->ne[1] }; + } else { + cp_copy_f32(t, u.sel[il]); + u.sel_ne[il] = { t->ne[0], t->ne[1] }; + if (t->op == GGML_OP_TOP_K_MASK) { + u.mask_src[il] = { t->src[1], t->src[2], t->src[3], t->src[4] }; + } + } + return true; +} + +static llama_context_ptr cp_context(llama_model * model, uint32_t n_ctx, uint32_t n_batch, uint32_t n_ubatch, cp_eval * ev, + uint32_t n_seq = 1, bool unified = false) { + llama_context_params params = llama_context_default_params(); + params.n_ctx = n_ctx; + params.n_batch = n_batch; + params.n_ubatch = n_ubatch; + params.n_seq_max = n_seq; + params.kv_unified = unified; + params.swa_full = false; + params.type_k = GGML_TYPE_F16; + params.type_v = GGML_TYPE_F16; + params.n_threads = 4; + params.n_threads_batch = 4; + if (ev != nullptr) { + params.cb_eval = cp_eval_cb; + params.cb_eval_user_data = ev; + } + return llama_context_ptr(llama_init_from_model(model, params)); +} + +static bool cp_configure(llama_context * ctx, uint32_t S, const int32_t * layers = CP_LAYERS) { + std::string err; + const bool ok = ctx->dfly_capture_configure(layers, LLAMA_DFLY_N_LAYER, S, err); + if (!ok) { + fprintf(stderr, "configure: %s\n", err.c_str()); + } + return ok; +} + +// T[p0, p1) of seq 0; out: 0 none, 1 last row, 2 all rows +static int cp_decode(llama_context * ctx, const std::vector & T, llama_pos p0, llama_pos p1, int out) { + tg_batch bt(p1 - p0); + for (llama_pos p = p0; p < p1; ++p) { + bt.add(T[p], p, out == 2 || (out == 1 && p == p1 - 1)); + } + return llama_decode(ctx, bt.b); +} + +static llama_dfly_capture_status cp_take(llama_context * ctx, std::vector & out, std::string & err) { + // garbage in, so that a failing take is seen to clear it + out.assign(1, llama_dfly_snapshot()); + out[0].batch_row = 12345; + err.clear(); + return ctx->dfly_capture_take(7, out, err); +} + +// prefill P0 rows in one decode with the last one output, then verify rounds of W rows with rollback; +// f runs after every decode, before the rollback, with the decode's first position and size +using cp_after = std::function; + +static bool cp_script(llama_context * ctx, const std::vector & T, uint32_t P0, int n_rounds, const cp_after & f) { + if (cp_decode(ctx, T, 0, P0, 1) != 0) { + return false; + } + f(ctx, 0, P0); + llama_pos a = P0; + for (int rd = 0; rd < n_rounds; ++rd) { + if (cp_decode(ctx, T, a, a + CP_W, 2) != 0) { + return false; + } + f(ctx, a, CP_W); + const uint32_t r = cp_r(rd); + if (r + 1 < CP_W) { + llama_memory_seq_rm(llama_get_memory(ctx), 0, a + r + 1, -1); + } + a += r + 1; + } + return true; +} + +static std::map cp_base_cells(llama_context * ctx) { + auto * mem = dynamic_cast(llama_get_memory(ctx)); + const auto & sp = mem->get_mem_attn()->get_base()->get_cells(0).seq_pos_get(0); + return std::map(sp.begin(), sp.end()); +} + +static bool cp_same_snap(const llama_dfly_snapshot & a, const llama_dfly_snapshot & b) { + bool eq = a.target_ctx_id == b.target_ctx_id && a.decode_id == b.decode_id && a.prefix_epoch == b.prefix_epoch && + a.seq_id == b.seq_id && a.batch_row == b.batch_row && a.query_pos == b.query_pos && + a.h_final.size() == b.h_final.size() && memcmp(a.h_final.data(), b.h_final.data(), a.h_final.size()*sizeof(float)) == 0; + for (size_t k = 0; eq && k < a.layer.size(); ++k) { + eq = a.layer[k].target_layer == b.layer[k].target_layer && a.layer[k].strm == b.layer[k].strm && + a.layer[k].pos == b.layer[k].pos && a.layer[k].cell == b.layer[k].cell; + } + return eq; +} + +// same content, ignoring the per-context ids +static bool cp_same_content(const llama_dfly_snapshot & a, const llama_dfly_snapshot & b) { + llama_dfly_snapshot c = b; + c.target_ctx_id = a.target_ctx_id; + c.decode_id = a.decode_id; + return cp_same_snap(a, c); +} + +// counts of one check over many items, with the first few failures spelled out +struct cp_count { + size_t n = 0; + size_t bad = 0; + std::vector first; + + void add(bool ok, const std::string & what) { + ++n; + if (!ok) { + if (bad < 5) { + first.push_back(what); + } + ++bad; + } + } +}; + +static void cp_assert(testing & t, const std::string & what, const cp_count & c) { + for (const auto & f : c.first) { + t.out << t.indent() << " fail: " << f << "\n"; + } + t.assert_true(what + " (" + std::to_string(c.n - c.bad) + "/" + std::to_string(c.n) + ")", c.n > 0 && c.bad == 0); +} + +static std::string cp_where(llama_pos p, int il) { + return "p " + std::to_string(p) + " layer " + std::to_string(il); +} + +// +// CP-02..04: one script, checked against the graph's own scores and masks and against the base cache +// + +struct cp_sel_run { + bool ok = false; + bool unfused_seen = false; // indexer_top_k- was computed + cp_count cb_rows; // the callback holds every staged row + cp_count score_same; // CP-02: exported score == the graph's score of that id + cp_count is_top; // CP-02: no unexported finite score above the lowest exported one + cp_count raw_is_mask; // CP-03 + cp_count take_ok; + cp_count norm; // CP-04 + size_t n_fin = 0, n_inf = 0; +}; + +// checks the staged rows of one decode of the context with callback ev +static void cp_check_selection(cp_sel_run & R, llama_context * ctx, const cp_eval & ev, uint32_t n_ubatch, uint32_t S, + llama_pos a, uint32_t n_tok) { + llama_synchronize(ctx); + auto * mem = dynamic_cast(llama_get_memory(ctx)); + const size_t n_ub = (n_tok + n_ubatch - 1)/n_ubatch; + R.cb_rows.add(ev.ubs.size() == n_ub, "decode at " + std::to_string(a) + ": " + std::to_string(ev.ubs.size()) + " ubatches seen"); + if (ev.ubs.size() != n_ub) { + return; + } + for (size_t b = 0; b < ctx->dfly_stage_n_blocks_for_test(); ++b) { + const auto & bl = ctx->dfly_stage_block_for_test(b); + for (int64_t r = 0; r < bl.n_rows; ++r) { + const int32_t br = bl.batch_row[r]; + const llama_pos p = bl.pos[r]; + const cp_ub & u = ev.ubs[br / n_ubatch]; + const int64_t tok = br % n_ubatch; + for (int k = 0; k < LLAMA_DFLY_N_LAYER; ++k) { + const int il = CP_LAYERS[k]; + const std::string w = cp_where(p, il); + const bool have = u.score.count(il) && u.sel.count(il); + R.cb_rows.add(have, w + ": no callback data"); + if (!have) { + continue; + } + const auto & sc = u.score.at(il); + const auto sne = u.score_ne.at(il); + const int32_t * ids = bl.ids[k].data() + r*bl.n_top; + const float * scs = bl.scores[k].data() + r*bl.n_top; + + std::set exported; + float min_fin = INFINITY; + bool same = true; + for (int64_t i = 0; i < bl.n_top; ++i) { + if (ids[i] < 0 || ids[i] >= sne[0] || tok >= sne[1]) { + same = false; + continue; + } + const float ref = sc[(size_t) tok*sne[0] + ids[i]]; + same = same && memcmp(&ref, &scs[i], sizeof(float)) == 0; + exported.insert(ids[i]); + if (std::isfinite(scs[i])) { + R.n_fin++; + min_fin = std::min(min_fin, scs[i]); + } else { + R.n_inf++; + } + } + R.score_same.add(same, w); + bool top = true; + for (int64_t q = 0; q < sne[0] && tok < sne[1]; ++q) { + const float v = sc[(size_t) tok*sne[0] + q]; + if (!exported.count((int32_t) q) && std::isfinite(v) && v > min_fin) { + top = false; + } + } + R.is_top.add(top, w); + + llama_memory_idx_iswa::kpool_refs refs; + std::string err; + if (!mem->kpool_copy_refs(0, p, ids, bl.n_top, refs, err)) { + R.raw_is_mask.add(false, w + ": " + err); + continue; + } + std::set raw; + for (int64_t i = 0; i < bl.n_top; ++i) { + if (std::isfinite(scs[i]) && refs.found[i]) { + for (uint32_t m = 0; m < refs.kpool; ++m) { + raw.insert(refs.cell[i*refs.kpool + m]); + } + } + } + raw.insert(refs.cur_cell.begin(), refs.cur_cell.end()); + const auto & sel = u.sel.at(il); + const auto mne = u.sel_ne.at(il); + std::set kept; + for (int64_t c = 0; c < mne[0]; ++c) { + if (sel[(size_t) tok*mne[0] + c] == 0.0f) { + kept.insert((uint32_t) c); + } + } + R.raw_is_mask.add(raw == kept, w + ": raw " + std::to_string(raw.size()) + " kept " + std::to_string(kept.size())); + } + } + } + (void) S; +} + +// CP-04 on one take +static void cp_check_norm(cp_count & c, const std::vector & snaps, const std::map & cells, + uint32_t S, const int32_t * layers) { + for (const auto & s : snaps) { + const llama_pos p = s.query_pos; + const int64_t g = p/4; + const size_t cnt = 4*std::min(S/4 - 1, g) + p%4 + 1; + for (int k = 0; k < LLAMA_DFLY_N_LAYER; ++k) { + const auto & lc = s.layer[k]; + bool ok = lc.target_layer == layers[k] && lc.strm == 0 && lc.pos.size() == cnt && lc.cell.size() == cnt && + !lc.pos.empty() && lc.pos.back() == p; + for (size_t i = 1; ok && i < lc.pos.size(); ++i) { + ok = lc.pos[i - 1] < lc.pos[i]; + } + if (ok && p < (llama_pos) S) { + for (size_t i = 0; ok && i < lc.pos.size(); ++i) { + ok = lc.pos[i] == (llama_pos) i; + } + } + for (size_t i = 0; ok && i < lc.pos.size(); ++i) { + const auto it = cells.find(lc.pos[i]); + ok = it != cells.end() && it->second == lc.cell[i]; + } + c.add(ok, cp_where(p, layers[k]) + " count " + std::to_string(lc.pos.size()) + " want " + std::to_string(cnt)); + } + } +} + +static cp_sel_run cp_selection_run(bool fused, ggml_backend_dev_t dev) { + cp_sel_run R; + const uint32_t S = 8; + const uint32_t U = 64; + cp_eval ev; + llama_context_ptr ctx = cp_context(cp_model(S, dev), 1024, 512, U, &ev); + if (!ctx) { + return R; + } + if (!fused) { + const_cast(ctx->get_cparams()).fused_top_k_mask = false; + } + if (!cp_configure(ctx.get(), S)) { + return R; + } + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + R.ok = cp_script(ctx.get(), T, 300, 60, [&](llama_context * c, llama_pos a, uint32_t n_tok) { + for (const auto & u : ev.ubs) { + for (const auto & n : u.seen) { + R.unfused_seen = R.unfused_seen || n.rfind("indexer_top_k-", 0) == 0; + } + } + cp_check_selection(R, c, ev, U, S, a, n_tok); + std::vector snaps; + std::string err; + const auto st = cp_take(c, snaps, err); + R.take_ok.add(st == LLAMA_DFLY_CAPTURE_STATUS_OK && snaps.size() == (n_tok == CP_W ? CP_W : 1), "take at " + std::to_string(a) + ": " + err); + cp_check_norm(R.norm, snaps, cp_base_cells(c), S, CP_LAYERS); + ev.reset(); + }); + return R; +} + +static std::map, cp_sel_run> g_cp_sel; + +static const cp_sel_run & cp_sel_get(bool fused, ggml_backend_dev_t dev) { + auto it = g_cp_sel.find({ fused, dev }); + if (it == g_cp_sel.end()) { + it = g_cp_sel.emplace(std::make_pair(fused, dev), cp_selection_run(fused, dev)).first; + } + return it->second; +} + +static void cp02_check(testing & t, ggml_backend_dev_t dev, bool unfused_too) { + for (const bool fused : { true, false }) { + if (!fused && !unfused_too) { + continue; + } + const std::string w = fused ? "fused: " : "unfused: "; + const cp_sel_run & R = cp_sel_get(fused, dev); + t.assert_true(w + "the script runs", R.ok); + t.assert_equal(w + "indexer_top_k- is computed only on the unfused path", !fused, R.unfused_seen); + cp_assert(t, w + "the callback holds every staged row and layer", R.cb_rows); + cp_assert(t, w + "every exported score is bitwise the graph's score of that id", R.score_same); + cp_assert(t, w + "no unexported finite score is above the lowest exported finite one", R.is_top); + t.out << t.indent() << " " << w << R.score_same.n << " row-layers, " << R.n_fin << " finite and " << R.n_inf << " -inf exported items\n"; + t.assert_true(w + "finite items are exported, so the top-k check is not vacuous", R.n_fin > 0); + } +} + +static void cp03_check(testing & t, ggml_backend_dev_t dev, bool unfused_too) { + for (const bool fused : { true, false }) { + if (!fused && !unfused_too) { + continue; + } + const std::string w = fused ? "fused: " : "unfused: "; + const cp_sel_run & R = cp_sel_get(fused, dev); + t.assert_true(w + "the script runs", R.ok); + cp_assert(t, w + "the exported visible groups plus the tail are exactly the cells the mask keeps", R.raw_is_mask); + } +} + +// +// CP-07: capture does not change the target +// + +struct cp_logits_run { + bool ok = false; + std::vector> rows; + std::vector reused; // n_reused after each decode + size_t staged_blocks = 0; // summed over decodes +}; + +static cp_logits_run cp_logits(llama_model * model, bool capture) { + cp_logits_run L; + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!ctx || (capture && !cp_configure(ctx.get(), 8))) { + return L; + } + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + L.ok = cp_script(ctx.get(), T, 300, 60, [&](llama_context * c, llama_pos, uint32_t n_tok) { + const uint32_t n_out = n_tok == CP_W ? CP_W : 1; + for (uint32_t j = 0; j < n_out; ++j) { + const float * lg = llama_get_logits_ith(c, n_tok == CP_W ? (int32_t) j : -1); + L.rows.emplace_back(lg, lg + TG_VOCAB); + } + L.reused.push_back(llama_perf_context(c).n_reused); + L.staged_blocks += c->dfly_stage_n_blocks_for_test(); + }); + return L; +} + +static std::vector> cp_logits_all(llama_model * model, bool capture, size_t & blocks) { + std::vector> rows; + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!ctx || (capture && !cp_configure(ctx.get(), 8))) { + return rows; + } + const std::vector T = get_tokens(300, TG_VOCAB, TG_SEED); + if (cp_decode(ctx.get(), T, 0, 300, 2) != 0) { + return rows; + } + for (int i = 0; i < 300; ++i) { + const float * lg = llama_get_logits_ith(ctx.get(), i); + rows.emplace_back(lg, lg + TG_VOCAB); + } + blocks = ctx->dfly_stage_n_blocks_for_test(); + return rows; +} + +static size_t cp_bitwise_diff(const std::vector> & A, const std::vector> & B) { + if (A.size() != B.size()) { + return SIZE_MAX; + } + size_t n = 0; + for (size_t i = 0; i < A.size(); ++i) { + n += A[i].size() != B[i].size() || memcmp(A[i].data(), B[i].data(), A[i].size()*sizeof(float)) != 0; + } + return n; +} + +static void cp07_check(testing & t, ggml_backend_dev_t dev) { + llama_model * model = cp_model(8, dev); + const cp_logits_run A = cp_logits(model, false); + const cp_logits_run B = cp_logits(model, true); + t.assert_true("both scripts run", A.ok && B.ok); + t.assert_equal("prefill + 60 verify rounds: 301 output rows", (size_t) 301, B.rows.size()); + t.assert_equal("logits of capture off vs on: bitwise different rows", (size_t) 0, cp_bitwise_diff(A.rows, B.rows)); + // a prefill reuses within its own ubatches, so compare with A rather than with 0 + t.assert_true("B: the first decode after configure reuses no more than A", !B.reused.empty() && B.reused[0] == A.reused[0]); + t.assert_true("B reuses the graph exactly where A does", B.reused == A.reused); + t.assert_true("B: later decodes reuse the graph", !B.reused.empty() && B.reused.back() > 0); + t.assert_equal("A: nothing is staged", (size_t) 0, A.staged_blocks); + t.out << t.indent() << " reused A " << (A.reused.empty() ? -1 : A.reused.back()) << ", B " << (B.reused.empty() ? -1 : B.reused.back()) << "\n"; + + size_t blocks_a = 0, blocks_b = 0; + const auto PA = cp_logits_all(model, false, blocks_a); + const auto PB = cp_logits_all(model, true, blocks_b); + t.assert_equal("all-output prefill of 300: rows", (size_t) 300, PB.size()); + t.assert_equal("all-output prefill of 300: bitwise different rows", (size_t) 0, cp_bitwise_diff(PA, PB)); + t.assert_equal("all-output prefill of 300: 5 staged blocks with capture", (size_t) 5, blocks_b); + t.assert_equal("all-output prefill of 300: none without", (size_t) 0, blocks_a); + + // without capture there is nothing to take and no export in the graph + cp_eval eva, evb; + llama_context_ptr ca = cp_context(model, 1024, 512, 64, &eva); + llama_context_ptr cb = cp_context(model, 1024, 512, 64, &evb); + eva.data = evb.data = false; + if (!t.assert_true("contexts with the callback", ca && cb && cp_configure(cb.get(), 8))) { + return; + } + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + size_t n_dfly_a = 0, n_dfly_b = 0, n_ub_a = 0, n_take_a = 0, n_take_bad_a = 0; + auto count = [](const cp_eval & ev, size_t & n_dfly, size_t * n_ub) { + for (const auto & u : ev.ubs) { + for (const auto & n : u.seen) { + n_dfly += n.rfind("dfly_sel_", 0) == 0; + } + } + if (n_ub) { + *n_ub += ev.ubs.size(); + } + }; + const bool ok_a = cp_script(ca.get(), T, 300, 3, [&](llama_context * c, llama_pos, uint32_t) { + count(eva, n_dfly_a, &n_ub_a); + eva.reset(); + std::vector s; + std::string err; + ++n_take_a; + n_take_bad_a += cp_take(c, s, err) != LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED || !s.empty() || + c->dfly_stage_n_blocks_for_test() != 0; + }); + const bool ok_b = cp_script(cb.get(), T, 300, 3, [&](llama_context *, llama_pos, uint32_t) { + count(evb, n_dfly_b, nullptr); + evb.reset(); + }); + t.assert_true("callback scripts run", ok_a && ok_b); + t.assert_true("A: the callback saw the ubatches", n_ub_a >= 8); + t.assert_equal("A: no dfly_sel_* node in any graph", (size_t) 0, n_dfly_a); + t.assert_true("B: dfly_sel_* nodes are seen (the check above is not vacuous)", n_dfly_b > 0); + t.assert_true("A: take is NOT_CONFIGURED and nothing is staged after every decode", n_take_a == 4 && n_take_bad_a == 0); +} + +// +// CP-12: S = 2048 on the real target +// + +static void cp12_check(testing & t, ggml_backend_dev_t dev) { + const uint32_t S = 2048; + cp_eval ev; + llama_context_ptr ctx = cp_context(cp_model(S, dev), 4096, 4096, 512, &ev); + if (!t.assert_true("context and configure", ctx && cp_configure(ctx.get(), S))) { + return; + } + const std::vector T = get_tokens(2056, TG_VOCAB, TG_SEED); + ev.data = false; + if (!t.assert_equal("prefill 0..2042 without outputs", 0, cp_decode(ctx.get(), T, 0, 2043, 0))) { + return; + } + t.assert_equal("the prefill stages nothing", (size_t) 0, ctx->dfly_stage_n_blocks_for_test()); + ev.reset(); + ev.data = true; + if (!t.assert_equal("decode 2043..2055, all output", 0, cp_decode(ctx.get(), T, 2043, 2056, 2))) { + return; + } + cp_sel_run R; + cp_check_selection(R, ctx.get(), ev, 512, S, 2043, 13); + cp_assert(t, "the callback holds every row and layer", R.cb_rows); + cp_assert(t, "exported scores are the graph's", R.score_same); + cp_assert(t, "the raw set is the mask", R.raw_is_mask); + + // card sec 0 and S4a SN-02 (selection-original.log), p = 2043..2055 + static const size_t mask_want[13] = { 2044, 2045, 2046, 2047, 2048, 2045, 2046, 2047, 2048, 2045, 2046, 2047, 2048 }; + static const size_t norm_want[13] = { 2044, 2045, 2046, 2047, 2048, 2045, 2046, 2047, 2048, 2045, 2046, 2047, 2048 }; + + std::vector snaps; + std::string err; + const auto st = cp_take(ctx.get(), snaps, err); + if (!t.assert_true("take is OK with 13 rows: " + err, st == LLAMA_DFLY_CAPTURE_STATUS_OK && snaps.size() == 13)) { + return; + } + const cp_ub & u = ev.ubs.at(0); + cp_count mask_n, norm_n, cur_group; + for (int r = 0; r < 13; ++r) { + const llama_pos p = 2043 + r; + for (int k = 0; k < LLAMA_DFLY_N_LAYER; ++k) { + const int il = CP_LAYERS[k]; + const auto & sel = u.sel.at(il); + const int64_t n_kv = u.sel_ne.at(il)[0]; + size_t kept = 0; + for (int64_t c = 0; c < n_kv; ++c) { + kept += sel[(size_t) r*n_kv + c] == 0.0f; + } + mask_n.add(kept == mask_want[r], cp_where(p, il) + " mask " + std::to_string(kept)); + const auto & lc = snaps[r].layer[k]; + norm_n.add(snaps[r].query_pos == p && lc.pos.size() == norm_want[r], cp_where(p, il) + " count " + std::to_string(lc.pos.size())); + if (p == 2051 || p == 2055) { + bool all = true; + for (llama_pos q = p - 3; q <= p; ++q) { + all = all && std::find(lc.pos.begin(), lc.pos.end(), q) != lc.pos.end(); + } + cur_group.add(all, cp_where(p, il)); + } + } + } + cp_assert(t, "target mask reserves the full current group within S", mask_n); + cp_assert(t, "normalized counts are 2044..2048, 2045..2048, 2045..2048", norm_n); + cp_assert(t, "p = 2051 and 2055 keep their whole current group", cur_group); + t.assert_equal("p = 2051 and 2055 in 5 layers", (size_t) 10, cur_group.n); +} + +static void test_capture(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + + t.test("CP-01_configure", [](testing & t) { + const uint32_t S = 8; + llama_model * model = cp_model(S, nullptr); + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + auto n_reused = [](llama_context * c) { return llama_perf_context(c).n_reused; }; + + // warmup and the seq_rm probe come before the capture is enabled; then same-shape AR steps + auto warm = [&](llama_context * c) { + return cp_decode(c, T, 0, 40, 1) == 0 && cp_decode(c, T, 40, 41, 1) == 0 && + llama_memory_seq_rm(llama_get_memory(c), 0, 40, -1); + }; + for (const bool nextn_first : { false, true }) { + const std::string w = nextn_first ? "masked nextn first: " : ""; + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!t.assert_true(w + "context and warmup", ctx && warm(ctx.get()))) { + return; + } + if (nextn_first) { + llama_set_embeddings_nextn(ctx.get(), true, true); + } + llama_pos p = 40; + t.assert_equal(w + "AR step", 0, cp_decode(ctx.get(), T, p, p + 1, 1)); ++p; + int32_t r0 = n_reused(ctx.get()); + t.assert_equal(w + "AR step", 0, cp_decode(ctx.get(), T, p, p + 1, 1)); ++p; + if (!t.assert_equal(w + "control: the same shape reuses the graph before configure", r0 + 1, n_reused(ctx.get()))) { + return; + } + std::vector snaps; + std::string err; + t.assert_equal(w + "take before configure", (int) LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED, (int) cp_take(ctx.get(), snaps, err)); + t.assert_true(w + "configure", cp_configure(ctx.get(), S)); + r0 = n_reused(ctx.get()); + t.assert_equal(w + "AR step after configure", 0, cp_decode(ctx.get(), T, p, p + 1, 1)); ++p; + t.assert_equal(w + "the decode after configure does not reuse the old graph", r0, n_reused(ctx.get())); + t.assert_equal(w + "take after it: " + err, (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) cp_take(ctx.get(), snaps, err)); + t.assert_equal(w + "one row", (size_t) 1, snaps.size()); + t.assert_true(w + "configure again with the same arguments", cp_configure(ctx.get(), S)); + r0 = n_reused(ctx.get()); + t.assert_equal(w + "AR step", 0, cp_decode(ctx.get(), T, p, p + 1, 1)); ++p; + t.assert_equal(w + "the same configure again keeps the graph", r0 + 1, n_reused(ctx.get())); + t.assert_equal(w + "take: " + err, (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) cp_take(ctx.get(), snaps, err)); + + if (nextn_first) { + continue; + } + // other layers once configured: refused, the first configuration stays + const int32_t moved[LLAMA_DFLY_N_LAYER] = { 2, 0, 4, 6, 8 }; + std::string e2; + t.assert_true("other layers after configure are refused", !ctx->dfly_capture_configure(moved, LLAMA_DFLY_N_LAYER, S, e2) && !e2.empty()); + t.assert_equal(w + "AR step", 0, cp_decode(ctx.get(), T, p, p + 1, 1)); ++p; + const bool ok = cp_take(ctx.get(), snaps, err) == LLAMA_DFLY_CAPTURE_STATUS_OK && snaps.size() == 1; + bool same_layers = ok; + for (int k = 0; ok && k < LLAMA_DFLY_N_LAYER; ++k) { + same_layers = same_layers && snaps[0].layer[k].target_layer == CP_LAYERS[k]; + } + t.assert_true("the first configuration still works", same_layers); + } + + // refused arguments: false with a reason, nothing configured + struct neg { const char * what; std::vector layers; uint32_t S; }; + const std::vector negs = { + { "4 layers", { 0, 2, 4, 6 }, 8 }, + { "6 layers", { 0, 2, 4, 6, 8, 0 }, 8 }, + { "a repeated layer", { 0, 2, 4, 4, 8 }, 8 }, + { "a window layer (1)", { 0, 1, 4, 6, 8 }, 8 }, + { "layer 10", { 0, 2, 4, 6, 10 }, 8 }, + { "layer -1", { -1, 2, 4, 6, 8 }, 8 }, + { "S 0", { 0, 2, 4, 6, 8 }, 0 }, + { "S 6", { 0, 2, 4, 6, 8 }, 6 }, + { "S 16 (target top_k 8)", { 0, 2, 4, 6, 8 }, 16 }, + { "S 2052", { 0, 2, 4, 6, 8 }, 2052 }, + }; + for (const auto & n : negs) { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + std::string err; + const bool ok = ctx->dfly_capture_configure(n.layers.data(), (uint32_t) n.layers.size(), n.S, err); + std::vector snaps; + std::string e2; + const auto st = cp_take(ctx.get(), snaps, e2); + t.assert_true(std::string("refused: ") + n.what + " (" + err + ")", !ok && !err.empty() && st == LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED && snaps.empty()); + } + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + llama_set_embeddings_nextn(ctx.get(), true, false); + std::string err; + const bool ok = ctx->dfly_capture_configure(CP_LAYERS, LLAMA_DFLY_N_LAYER, S, err); + std::vector snaps; + std::string e2; + const auto st = cp_take(ctx.get(), snaps, e2); + t.assert_true("refused: unmasked nextn (" + err + ")", !ok && !err.empty() && st == LLAMA_DFLY_CAPTURE_STATUS_NOT_CONFIGURED); + } + }); + + t.test("CP-02_export_is_the_selection", [](testing & t) { cp02_check(t, nullptr, true); }); + t.test("CP-03_raw_set_is_the_mask", [](testing & t) { cp03_check(t, nullptr, true); }); + + t.test("CP-04_normalized_set", [](testing & t) { + for (const bool fused : { true, false }) { + const std::string w = fused ? "fused: " : "unfused: "; + const cp_sel_run & R = cp_sel_get(fused, nullptr); + cp_assert(t, w + "take is OK after every decode with every output row", R.take_ok); + cp_assert(t, w + "count, order, [0, p] below S, cells of the base cache, strm 0, target_layer", R.norm); + } + }); + + t.test("CP-05_row_mapping", [](testing & t) { + const uint32_t S = 8; + llama_model * model = cp_model(S, nullptr); + const std::vector T = get_tokens(4096, TG_VOCAB, TG_SEED); + for (const uint32_t P : { 1u, 3u, 16u, 32u, 2047u }) { + const std::string w = "P " + std::to_string(P) + ": "; + llama_context_ptr ctx = cp_context(model, 4096, 4096, 512, nullptr); + llama_context_ptr ref = cp_context(model, 4096, 4096, 512, nullptr); + if (!t.assert_true(w + "contexts", ctx && ref && cp_configure(ctx.get(), S))) { + return; + } + llama_set_embeddings_nextn(ref.get(), true, true); + if (!t.assert_true(w + "prefill", cp_decode(ctx.get(), T, 0, P, 1) == 0 && cp_decode(ref.get(), T, 0, P, 1) == 0)) { + continue; + } + std::vector snaps; + std::string err; + const auto st = cp_take(ctx.get(), snaps, err); + if (!t.assert_true(w + "take one row: " + err, st == LLAMA_DFLY_CAPTURE_STATUS_OK && snaps.size() == 1)) { + continue; + } + t.assert_true(w + "batch_row = query_pos = P - 1", snaps[0].batch_row == (int32_t) P - 1 && snaps[0].query_pos == (llama_pos) P - 1); + t.assert_equal(w + "one staged block", (size_t) 1, ctx->dfly_stage_n_blocks_for_test()); + if (P <= 3) { + const auto & bl = ctx->dfly_stage_block_for_test(0); + bool all_inf = true, prefix = true; + for (int k = 0; k < LLAMA_DFLY_N_LAYER; ++k) { + for (float v : bl.scores[k]) { + all_inf = all_inf && std::isinf(v) && v < 0; + } + const auto & lc = snaps[0].layer[k]; + prefix = prefix && lc.pos.size() == P; + for (size_t i = 0; prefix && i < lc.pos.size(); ++i) { + prefix = lc.pos[i] == (llama_pos) i; + } + } + t.assert_true(w + "every exported score is -inf", all_inf); + t.assert_true(w + "the normalized set is [0, P - 1]", prefix); + } + uint64_t last_id = snaps[0].decode_id; + llama_pos a = P; + size_t same_pairs = 0; + for (uint32_t r = 0; r < CP_W; ++r) { + const std::string wr = w + "r " + std::to_string(r) + ": "; + if (!t.assert_true(wr + "verify", cp_decode(ctx.get(), T, a, a + CP_W, 2) == 0 && cp_decode(ref.get(), T, a, a + CP_W, 2) == 0)) { + break; + } + const auto st2 = cp_take(ctx.get(), snaps, err); + if (!t.assert_true(wr + "take 5 rows: " + err, st2 == LLAMA_DFLY_CAPTURE_STATUS_OK && snaps.size() == CP_W)) { + break; + } + bool rows = true, hidden = true, distinct = true; + for (uint32_t j = 0; j < CP_W; ++j) { + rows = rows && snaps[j].batch_row == (int32_t) j && snaps[j].query_pos == a + (llama_pos) j && snaps[j].seq_id == 0; + const float * h = llama_get_embeddings_nextn_ith(ref.get(), j); + hidden = hidden && h && snaps[j].h_final.size() == 128 && memcmp(h, snaps[j].h_final.data(), 128*sizeof(float)) == 0; + for (uint32_t i = 0; i < j; ++i) { + distinct = distinct && snaps[i].h_final != snaps[j].h_final; + } + for (int k1 = 0; k1 < LLAMA_DFLY_N_LAYER; ++k1) { + for (int k2 = 0; k2 < k1; ++k2) { + same_pairs += snaps[j].layer[k1].pos == snaps[j].layer[k2].pos; + } + } + } + t.assert_true(wr + "batch_row 0..4, query_pos a..a+4", rows); + t.assert_true(wr + "decode_id grows", snaps[0].decode_id > last_id); + t.assert_true(wr + "h_final is bitwise the reference context's nextn row", hidden); + t.assert_true(wr + "the 5 hidden rows differ", distinct); + last_id = snaps[0].decode_id; + if (r + 1 < CP_W) { + llama_memory_seq_rm(llama_get_memory(ctx.get()), 0, a + r + 1, -1); + llama_memory_seq_rm(llama_get_memory(ref.get()), 0, a + r + 1, -1); + } + a += r + 1; + } + t.out << t.indent() << " " << w << "layer pairs with the same selection, over the verify rows: " << same_pairs << "\n"; + } + + // all-output prefill across ubatches: every row maps to its own batch row + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!t.assert_true("all-output prefill: context", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_equal("all-output prefill of 300", 0, cp_decode(ctx.get(), T, 0, 300, 2)); + t.assert_equal("5 staged blocks", (size_t) 5, ctx->dfly_stage_n_blocks_for_test()); + std::vector snaps; + std::string err; + const auto st = cp_take(ctx.get(), snaps, err); + t.assert_true("take 300 rows: " + err, st == LLAMA_DFLY_CAPTURE_STATUS_OK && snaps.size() == 300); + std::vector seen(300, 0); + bool rows = true; + for (const auto & s : snaps) { + rows = rows && s.batch_row >= 0 && s.batch_row < 300 && s.query_pos == s.batch_row; + if (s.batch_row >= 0 && s.batch_row < 300) { + seen[s.batch_row]++; + } + } + t.assert_true("batch_row 0..299 once each, query_pos = batch_row", rows && std::all_of(seen.begin(), seen.end(), [](int n) { return n == 1; })); + cp_count c; + cp_check_norm(c, snaps, cp_base_cells(ctx.get()), S, CP_LAYERS); + cp_assert(t, "every row normalizes to cells of the base cache", c); + } + + // slots follow the configured order, not the layer numbers + { + llama_context_ptr ca = cp_context(model, 1024, 512, 64, nullptr); + llama_context_ptr cb = cp_context(model, 1024, 512, 64, nullptr); + if (!t.assert_true("shuffled layers: contexts", ca && cb && cp_configure(ca.get(), S) && cp_configure(cb.get(), S, CP_LAYERS_SHUFFLED))) { + return; + } + std::vector> SA, SB; + auto keep = [](std::vector> & dst) { + return [&dst](llama_context * c, llama_pos, uint32_t) { + std::vector s; + std::string err; + cp_take(c, s, err); + dst.push_back(std::move(s)); + }; + }; + const bool ok = cp_script(ca.get(), T, 300, 12, keep(SA)) && cp_script(cb.get(), T, 300, 12, keep(SB)); + cp_count c; + for (size_t d = 0; ok && d < SA.size() && d < SB.size(); ++d) { + c.add(!SA[d].empty() && SA[d].size() == SB[d].size(), "decode " + std::to_string(d)); + for (size_t i = 0; i < SA[d].size() && i < SB[d].size(); ++i) { + for (int k = 0; k < LLAMA_DFLY_N_LAYER; ++k) { + const int il = CP_LAYERS_SHUFFLED[k]; + const int ka = (int) (std::find(CP_LAYERS, CP_LAYERS + LLAMA_DFLY_N_LAYER, il) - CP_LAYERS); + const auto & lb = SB[d][i].layer[k]; + const auto & la = SA[d][i].layer[ka]; + c.add(lb.target_layer == il && la.target_layer == il && lb.strm == la.strm && lb.pos == la.pos && lb.cell == la.cell, + "decode " + std::to_string(d) + " " + cp_where(SB[d][i].query_pos, il)); + } + c.add(SA[d][i].h_final == SB[d][i].h_final, "hidden"); + } + } + t.assert_true("shuffled layers: scripts run", ok && SA.size() == 13 && SB.size() == 13); + cp_assert(t, "slot k of {8,0,4,2,6} is layer L[k], bitwise the ascending configuration's", c); + } + }); + + t.test("CP-06_reuse_and_ownership", [](testing & t) { + const uint32_t S = 8; + llama_model * model = cp_model(S, nullptr); + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + + // reuse, and owned snapshots + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!t.assert_true("context", ctx && cp_configure(ctx.get(), S))) { + return; + } + cp_count after_reuse; + int n_dec = 0; + int32_t reused_prev = 0; + std::vector kept, kept_ref; + bool owned_ok = false, new_id = false; + const bool ok = cp_script(ctx.get(), T, 300, 60, [&](llama_context * c, llama_pos a, uint32_t n_tok) { + const int32_t reused = llama_perf_context(c).n_reused; + std::vector s; + std::string err; + const auto st = cp_take(c, s, err); + if (reused > reused_prev) { + bool full = st == LLAMA_DFLY_CAPTURE_STATUS_OK && s.size() == (n_tok == CP_W ? CP_W : 1); + for (const auto & x : s) { + for (const auto & lc : x.layer) { + full = full && !lc.pos.empty(); + } + } + after_reuse.add(full, "decode at " + std::to_string(a) + ": " + err); + } + reused_prev = reused; + if (n_dec == 10) { + kept_ref = s; + kept = std::move(s); + } else if (n_dec == 11) { + new_id = !s.empty() && !kept_ref.empty() && s[0].decode_id != kept_ref[0].decode_id; + } else if (n_dec == 12) { + owned_ok = kept.size() == kept_ref.size() && !kept.empty(); + for (size_t i = 0; owned_ok && i < kept.size(); ++i) { + owned_ok = cp_same_snap(kept[i], kept_ref[i]); + } + } + ++n_dec; + }); + t.assert_true("script", ok); + t.assert_true("the script reuses the graph", llama_perf_context(ctx.get()).n_reused > 0); + cp_assert(t, "take after a reused graph returns every row with 5 layers", after_reuse); + t.assert_true("a later take has another decode_id", new_id); + t.assert_true("a taken vector is unchanged by later decodes and takes", owned_ok); + } + + // polluting the fused mask inputs after the decode does not change the snapshots + { + cp_eval e1, e2; + llama_context_ptr c1 = cp_context(model, 1024, 512, 64, &e1); + llama_context_ptr c2 = cp_context(model, 1024, 512, 64, &e2); + if (!t.assert_true("pollution: contexts", c1 && c2 && cp_configure(c1.get(), S) && cp_configure(c2.get(), S))) { + return; + } + t.assert_true("pollution: prefill", cp_decode(c1.get(), T, 0, 120, 1) == 0 && cp_decode(c2.get(), T, 0, 120, 1) == 0); + size_t same = 0, polluted = 0; + for (int rd = 0; rd < 10; ++rd) { + const llama_pos a = 120 + rd*CP_W; + e1.reset(); + e2.reset(); + if (cp_decode(c1.get(), T, a, a + CP_W, 2) != 0 || cp_decode(c2.get(), T, a, a + CP_W, 2) != 0) { + break; + } + llama_synchronize(c1.get()); + for (const auto & u : e1.ubs) { + for (const auto & [il, src] : u.mask_src) { + for (ggml_tensor * x : src) { + if (x != nullptr && x->buffer != nullptr) { + std::vector junk(ggml_nbytes(x), 0xff); + ggml_backend_tensor_set(x, junk.data(), 0, junk.size()); + ++polluted; + } + } + } + } + std::vector s1, s2; + std::string err1, err2; + const bool ok = cp_take(c1.get(), s1, err1) == LLAMA_DFLY_CAPTURE_STATUS_OK && cp_take(c2.get(), s2, err2) == LLAMA_DFLY_CAPTURE_STATUS_OK; + bool eq = ok && s1.size() == CP_W && s1.size() == s2.size(); + for (size_t i = 0; eq && i < s1.size(); ++i) { + eq = cp_same_content(s1[i], s2[i]); + } + same += eq; + } + t.assert_equal("10 rounds of 4 inputs in 5 layers are polluted", (size_t) 200, polluted); + t.assert_equal("rounds with snapshots equal to the clean context", (size_t) 10, same); + } + + // staging does not grow with n_ctx + { + std::vector bytes[2]; + int i = 0; + for (const uint32_t n_ctx : { 1024u, 4096u }) { + llama_context_ptr ctx = cp_context(model, n_ctx, 512, 64, nullptr); + if (!ctx || !cp_configure(ctx.get(), S)) { + break; + } + cp_script(ctx.get(), T, 300, 10, [&](llama_context * c, llama_pos, uint32_t) { bytes[i].push_back(c->dfly_stage_bytes_for_test()); }); + ++i; + } + t.assert_true("staged bytes per decode are the same at n_ctx 1024 and 4096", bytes[0].size() == 11 && bytes[0] == bytes[1]); + if (!bytes[0].empty()) { + t.out << t.indent() << " staged bytes: prefill " << bytes[0][0] << ", verify " << bytes[0].back() << "\n"; + } + } + }); + + t.test("CP-07_target_unchanged", [](testing & t) { cp07_check(t, nullptr); }); + + t.test("CP-08_rows_without_outputs", [](testing & t) { + const uint32_t S = 8; + cp_eval ev; + ev.data = false; + llama_context_ptr ctx = cp_context(cp_model(S, nullptr), 1024, 512, 64, &ev); + if (!t.assert_true("context", ctx && cp_configure(ctx.get(), S))) { + return; + } + const std::vector T = get_tokens(200, TG_VOCAB, TG_SEED); + t.assert_equal("120 tokens, the last one output", 0, cp_decode(ctx.get(), T, 0, 120, 1)); + t.assert_equal("one staged block", (size_t) 1, ctx->dfly_stage_n_blocks_for_test()); + if (t.assert_equal("two ubatches", (size_t) 2, ev.ubs.size())) { + size_t n0 = 0; + for (const auto & n : ev.ubs[0].seen) { + n0 += n.rfind("dfly_sel_", 0) == 0; + } + t.assert_equal("the first ubatch has no dfly_sel_* node", (size_t) 0, n0); + t.assert_true("the second has them", ev.ubs[1].seen.count("dfly_sel_ids-0") && ev.ubs[1].seen.count("dfly_sel_scores-8")); + } + t.assert_equal("10 tokens without outputs", 0, cp_decode(ctx.get(), T, 120, 130, 0)); + std::vector snaps; + std::string err; + t.assert_equal("take: NO_ROWS", (int) LLAMA_DFLY_CAPTURE_STATUS_NO_ROWS, (int) cp_take(ctx.get(), snaps, err)); + t.assert_true("nothing staged, out cleared", ctx->dfly_stage_n_blocks_for_test() == 0 && snaps.empty()); + }); + + t.test("CP-12_s2048_boundary", [](testing & t) { cp12_check(t, nullptr); }); + + t.out << t.indent() << " capture group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +static void test_capture_neg(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + + t.test("CP-09_lifecycle", [](testing & t) { + const uint32_t S = 8; + cp_eval ev; + ev.data = false; + llama_context_ptr ctx = cp_context(cp_model(S, nullptr), 1024, 512, 64, &ev); + if (!t.assert_true("context", ctx && cp_configure(ctx.get(), S))) { + return; + } + llama_set_abort_callback(ctx.get(), [](void * d) { return ((cp_eval *) d)->abort_now; }, &ev); + llama_memory_t mem = llama_get_memory(ctx.get()); + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + std::vector snaps; + std::string err; + auto take = [&]() { return (int) cp_take(ctx.get(), snaps, err); }; + const int OK = LLAMA_DFLY_CAPTURE_STATUS_OK, NO_ROWS = LLAMA_DFLY_CAPTURE_STATUS_NO_ROWS, ERR = LLAMA_DFLY_CAPTURE_STATUS_ERROR; + auto next_ok = [&](const std::string & w) { + const llama_pos a = llama_memory_seq_pos_max(mem, 0) + 1; + t.assert_equal(w + ": a good verify after it", 0, cp_decode(ctx.get(), T, a, a + CP_W, 2)); + t.assert_equal(w + ": take recovers: " + err, OK, take()); + t.assert_equal(w + ": 5 rows", (size_t) CP_W, snaps.size()); + }; + + t.assert_equal("prefill", 0, cp_decode(ctx.get(), T, 0, 100, 1)); + t.assert_equal("verify", 0, cp_decode(ctx.get(), T, 100, 105, 2)); + t.assert_equal("take after the verify", OK, take()); + + t.assert_equal("a decode with a position gap fails", -1, cp_decode(ctx.get(), T, 200, 205, 2)); + t.assert_equal("take after it: NO_ROWS, not the previous rows", NO_ROWS, take()); + t.assert_true("out is cleared", snaps.empty()); + next_ok("position gap"); + + { + const llama_pos a = llama_memory_seq_pos_max(mem, 0) + 1; + ev.n_score0 = 0; + ev.abort_at = 2; + const int rc = cp_decode(ctx.get(), T, a, a + 120, 2); + ev.abort_at = -1; + ev.abort_now = false; + t.assert_equal("abort in the second ubatch returns 2", 2, rc); + t.assert_equal("take after the abort: NO_ROWS", NO_ROWS, take()); + t.assert_true("out is cleared", snaps.empty()); + next_ok("abort"); + } + + { + const llama_pos pmax = llama_memory_seq_pos_max(mem, 0); + llama_memory_seq_rm(mem, 0, pmax - 1, -1); + t.assert_equal("take after seq_rm: ERROR", ERR, take()); + t.assert_true("the helper refuses the stale sequence: " + err, err.find("was edited since the last batch") != std::string::npos && snaps.empty()); + next_ok("seq_rm"); + } + + { + llama_memory_clear(mem, true); + t.assert_equal("take after memory_clear: ERROR", ERR, take()); + t.assert_true("out is cleared: " + err, snaps.empty() && !err.empty()); + t.assert_equal("prefill again", 0, cp_decode(ctx.get(), T, 0, 20, 1)); + t.assert_equal("take: OK", OK, take()); + next_ok("memory_clear"); + } + }); + + t.test("CP-10_bad_scores", [](testing & t) { + const uint32_t S = 8; + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + std::vector snaps; + std::string err; + { + llama_context_ptr ctx = cp_context(cp_model(S, nullptr), 1024, 512, 64, nullptr); + if (!t.assert_true("context", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_true("prefill and verify", cp_decode(ctx.get(), T, 0, 100, 1) == 0 && cp_decode(ctx.get(), T, 100, 105, 2) == 0); + llama_synchronize(ctx.get()); + const auto & bl = ctx->dfly_stage_block_for_test(0); + const int64_t row = 2; + float * sc = ctx->dfly_stage_scores_for_test(0, 1) + row*bl.n_top; + int64_t i_fin = -1; + for (int64_t i = 0; i < bl.n_top; ++i) { + if (std::isfinite(sc[i])) { + i_fin = i; + break; + } + } + if (!t.assert_true("row 2 of layer 2 has a finite item", i_fin >= 0)) { + return; + } + const float orig = sc[i_fin]; + for (const float bad : { std::numeric_limits::quiet_NaN(), INFINITY }) { + const std::string w = std::isnan(bad) ? "NaN: " : "+inf: "; + sc[i_fin] = bad; + const auto st = cp_take(ctx.get(), snaps, err); + t.assert_equal(w + "ERROR", (int) LLAMA_DFLY_CAPTURE_STATUS_ERROR, (int) st); + t.assert_true(w + "err names the row, the layer and non_finite: " + err, + err.find("row 2 ") != std::string::npos && err.find("layer 2:") != std::string::npos && err.find("non_finite") != std::string::npos); + t.assert_true(w + "out is cleared", snaps.empty()); + sc[i_fin] = orig; + t.assert_equal(w + "restored: OK", (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) cp_take(ctx.get(), snaps, err)); + } + } + { + llama_context_ptr ctx = cp_context(cp_model(S, nullptr), 1024, 512, 64, nullptr); + if (!t.assert_true("P = 3: context", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_equal("P = 3: prefill", 0, cp_decode(ctx.get(), T, 0, 3, 1)); + llama_synchronize(ctx.get()); + float * sc = ctx->dfly_stage_scores_for_test(0, 0); + t.assert_true("P = 3: the first item is -inf", std::isinf(sc[0]) && sc[0] < 0); + sc[0] = 0.5f; + const auto st = cp_take(ctx.get(), snaps, err); + t.assert_equal("P = 3, a finite padding or future item: ERROR", (int) LLAMA_DFLY_CAPTURE_STATUS_ERROR, (int) st); + t.assert_true("err is bad_pool or future_group: " + err, + (err.find("bad_pool") != std::string::npos || err.find("future_group") != std::string::npos) && snaps.empty()); + } + }); + + t.test("CP-11_row_order", [](testing & t) { + const uint32_t S = 8; + llama_model * model = cp_model(S, nullptr); + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + std::vector snaps; + std::string err; + // 20 rows of each of two sequences, interleaved; one stream per sequence splits the batch by sequence + auto interleaved = [&](llama_context * ctx) { + llama_batch b = llama_batch_init(64, 0, 1); + b.n_tokens = 0; + for (int i = 0; i < 20; ++i) { + for (int s = 0; s < 2; ++s) { + const int k = b.n_tokens++; + b.token[k] = T[i + 7*s]; + b.pos[k] = i; + b.n_seq_id[k] = 1; + b.seq_id[k][0] = s; + b.logits[k] = 1; + } + } + const int ret = llama_decode(ctx, b); + llama_batch_free(b); + return ret; + }; + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr, 2, false); + if (!t.assert_true("two streams: context and configure", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_equal("interleaved decode", 0, interleaved(ctx.get())); + llama_get_logits_ith(ctx.get(), 0); + const auto st = cp_take(ctx.get(), snaps, err); + t.assert_equal("take after a getter: ERROR", (int) LLAMA_DFLY_CAPTURE_STATUS_ERROR, (int) st); + t.assert_equal("the error is the row order", std::string("output rows are reordered"), err); + t.assert_true("out is cleared", snaps.empty()); + } + { + // design 4.3: one shared stream takes the batch in order, one ubatch, no reorder (MU02) + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr, 2, true); + if (!t.assert_true("one stream: context and configure", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_equal("interleaved decode", 0, interleaved(ctx.get())); + const auto st = cp_take(ctx.get(), snaps, err); + t.assert_equal("one stream: take OK " + err, (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) st); + bool in_order = snaps.size() == 40; + for (size_t k = 0; in_order && k < snaps.size(); ++k) { + in_order = snaps[k].batch_row == (int32_t) k && snaps[k].seq_id == (llama_seq_id) (k % 2) && snaps[k].query_pos == (llama_pos) (k / 2); + } + t.assert_true("one stream: 40 rows in batch order", in_order); + t.assert_equal("one stream: one staging block", (size_t) 1, ctx->dfly_stage_n_blocks_for_test()); + } + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr, 2, true); + if (!t.assert_true("one sequence in a 2-sequence context", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_equal("40 rows of seq 0", 0, cp_decode(ctx.get(), T, 0, 40, 2)); + t.assert_equal("take: OK " + err, (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) cp_take(ctx.get(), snaps, err)); + t.assert_true("40 rows of seq 0 taken", snaps.size() == 40 && snaps.back().seq_id == 0 && snaps.back().query_pos == 39); + } + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!t.assert_true("rows 9, 19, 29: context", ctx && cp_configure(ctx.get(), S))) { + return; + } + tg_batch bt(30); + for (int i = 0; i < 30; ++i) { + bt.add(T[i], i, i % 10 == 9); + } + t.assert_equal("decode", 0, llama_decode(ctx.get(), bt.b)); + const auto st = cp_take(ctx.get(), snaps, err); + t.assert_equal("take: OK " + err, (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) st); + t.assert_true("rows 9, 19, 29", snaps.size() == 3 && snaps[0].batch_row == 9 && snaps[1].batch_row == 19 && snaps[2].batch_row == 29 && + snaps[0].query_pos == 9 && snaps[2].query_pos == 29); + } + }); + + t.out << t.indent() << " capture_neg group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +static void test_capture_gpu(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); + if (dev == nullptr) { + t.skip("no GPU device"); + return; + } + t.out << t.indent() << " device: " << ggml_backend_dev_name(dev) << "\n"; + t.test("CP-02_export_is_the_selection", [dev](testing & t) { cp02_check(t, dev, false); }); + t.test("CP-03_raw_set_is_the_mask", [dev](testing & t) { cp03_check(t, dev, false); }); + t.test("CP-07_target_unchanged", [dev](testing & t) { cp07_check(t, dev); }); + t.test("CP-12_s2048_boundary", [dev](testing & t) { cp12_check(t, dev); }); + t.out << t.indent() << " capture_gpu group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +// plan U03: a sequence state keeps only the SWA cells that the window of its last position sees, with and without +// swa_full, so a restore starts the SWA cache at max(resident pos_min, pos_max - n_swa + 1) +static void test_swa_coverage(testing & t) { + t.test("U03_swa_saved_range", [](testing & t) { + const uint32_t n_swa = 32; + const std::vector T = get_tokens(600, TG_VOCAB, TG_SEED); + for (const bool swa_full : { false, true }) { + for (const uint32_t P : { 20u, 31u, 32u, 33u, 300u, 600u }) { + for (const llama_state_seq_flags flags : { (llama_state_seq_flags) 0, (llama_state_seq_flags) LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY }) { + const std::string w = std::string(swa_full ? "swa_full" : "compact") + " P " + std::to_string(P) + (flags ? " partial" : " full"); + llama_context_ptr ctx = tg_context(tg_model(8, n_swa), 1024, 32, swa_full, nullptr); + llama_kv_cache * kv[3]; + tg_caches(ctx.get(), kv); + if (!t.assert_equal(w + ": prefill", 0, tg_prefill(ctx.get(), T, P, 32))) { + continue; + } + const llama_pos resident = kv[2]->seq_pos_min(0); + std::vector buf(llama_state_seq_get_size_ext(ctx.get(), 0, flags)); + t.assert_equal(w + ": saved", buf.size(), llama_state_seq_get_data_ext(ctx.get(), buf.data(), buf.size(), 0, flags)); + llama_memory_seq_rm(llama_get_memory(ctx.get()), 0, -1, -1); + t.assert_equal(w + ": read", buf.size(), llama_state_seq_set_data_ext(ctx.get(), buf.data(), buf.size(), 0, flags)); + const llama_pos want = std::max(resident, (llama_pos) P - 1 - (llama_pos) n_swa + 1); + t.assert_equal(w + ": restored SWA pos_min (resident " + std::to_string(resident) + ")", want, kv[2]->seq_pos_min(0)); + t.assert_equal(w + ": restored SWA pos_max", (llama_pos) P - 1, kv[2]->seq_pos_max(0)); + t.assert_equal(w + ": the API reads the SWA cache", kv[2]->seq_pos_min(0), llama_memory_seq_pos_min(llama_get_memory(ctx.get()), 0)); + } + } + } + }); +} + +// +// MU: several sequences in one unified target, multi-seq design doc section 7.2 +// + +// the positions of seq s in a cache, from a scan of every cell +static std::set mu_positions(const llama_kv_cache * kv, llama_seq_id s) { + const llama_kv_cells & cells = kv->get_cells(s); + std::set res; + for (uint32_t i = 0; i < cells.size(); ++i) { + if (!cells.is_empty(i) && cells.seq_has(i, s)) { + res.insert(cells.pos_get(i)); + } + } + return res; +} + +// (cell, seq, pos) of every used cell of the three caches +static std::vector> mu_meta(llama_kv_cache * const kv[3], uint32_t n_seq) { + std::vector> res; + for (int c = 0; c < 3; ++c) { + const llama_kv_cells & cells = kv[c]->get_cells(0); + for (uint32_t i = 0; i < cells.size(); ++i) { + for (uint32_t s = 0; s < n_seq && !cells.is_empty(i); ++s) { + if (cells.seq_has(i, s)) { + res.push_back({ c, i, s, cells.pos_get(i) }); + } + } + } + } + return res; +} + +// the ERROR lines logged while it lives +struct mu_errors { + ggml_log_callback prev_cb = nullptr; + void * prev_ud = nullptr; + std::vector lines; + + mu_errors() { + llama_log_get(&prev_cb, &prev_ud); + llama_log_set([](ggml_log_level level, const char * text, void * ud) { + if (level == GGML_LOG_LEVEL_ERROR) { + ((mu_errors *) ud)->lines.push_back(text); + } + }, this); + } + ~mu_errors() { llama_log_set(prev_cb, prev_ud); } + + bool has(const std::string & needle) const { + return std::any_of(lines.begin(), lines.end(), [&](const std::string & l) { return l.find(needle) != std::string::npos; }); + } +}; + +static llama_context_ptr mu_context(llama_model * model, uint32_t n_ctx, uint32_t n_batch, uint32_t n_ubatch, uint32_t n_seq) { + llama_context_params params = llama_context_default_params(); + params.n_ctx = n_ctx; + params.n_batch = n_batch; + params.n_ubatch = n_ubatch; + params.n_seq_max = n_seq; + params.kv_unified = true; + params.swa_full = false; + params.type_k = GGML_TYPE_F16; + params.type_v = GGML_TYPE_F16; + params.n_threads = 4; + params.n_threads_batch = 4; + return llama_context_ptr(llama_init_from_model(model, params)); +} + +static void mu_add(llama_batch & b, llama_token tok, llama_pos pos, llama_seq_id s, bool out) { + const int i = b.n_tokens++; + b.token [i] = tok; + b.pos [i] = pos; + b.n_seq_id[i] = 1; + b.seq_id [i][0] = s; + b.logits [i] = out; +} + +struct mu01_result { + int rounds = 0; + int swa_miss = 0; // positions of a next query's window missing from the SWA cache + int base_bad = 0; // rounds after which base or indexer do not hold exactly [0, a') + int fail = 0; // decodes that failed + std::string first; +}; + +// MU01: in every decode, a verify of 5 rows of seq 0, a verify of 3 rows of seq 1 and a prompt chunk of seq 2 +// (3 or 40 tokens, so at most 48 rows), then seq 0 and seq 1 roll back to a forced acceptance r; +// a compact SWA cache of n_swa*3 + U = 256 cells with n_swa = 64 makes the reuse of masked cells the rule +static mu01_result mu01_run(uint32_t n_batch, uint32_t n_ubatch, int n_rounds, uint32_t seed) { + const llama_pos N_SWA = 64; + const llama_pos W[2] = { 5, 3 }; + mu01_result res; + + llama_model * model = tg_model(16, (uint32_t) N_SWA); + llama_context_ptr ctx = model ? mu_context(model, 2048, n_batch, n_ubatch, 3) : nullptr; + if (!ctx) { + res.first = "setup"; + res.fail = 1; + return res; + } + llama_kv_cache * kv[3]; + tg_caches(ctx.get(), kv); + llama_memory_t mem = llama_get_memory(ctx.get()); + + const std::vector T = get_tokens(3*2048, TG_VOCAB, TG_SEED + seed); + auto tok = [&](llama_seq_id s, llama_pos p) { return T[(size_t) s*2048 + p]; }; + std::mt19937 g(seed); + + llama_batch b = llama_batch_init((int32_t) n_batch, 0, 1); + llama_pos a[3] = { 0, 0, 0 }; + + // prefill: seq 0 and seq 1 past the window, seq 2 a little + const llama_pos P[3] = { 100, 100, 10 }; + for (llama_seq_id s = 0; s < 3 && res.fail == 0; ++s) { + while (a[s] < P[s]) { + b.n_tokens = 0; + for (llama_pos p = a[s]; p < std::min(P[s], a[s] + (llama_pos) n_ubatch); ++p) { + mu_add(b, tok(s, p), p, s, false); + } + if (llama_decode(ctx.get(), b) != 0) { + res.fail++; + res.first = "prefill"; + break; + } + a[s] += b.n_tokens; + } + } + + for (int rd = 0; rd < n_rounds && res.fail == 0; ++rd) { + const llama_pos L = rd % 2 ? 40 : 3; + b.n_tokens = 0; + for (llama_seq_id s = 0; s < 2; ++s) { + for (llama_pos j = 0; j < W[s]; ++j) { + mu_add(b, tok(s, a[s] + j), a[s] + j, s, true); + } + } + for (llama_pos j = 0; j < L; ++j) { + mu_add(b, tok(2, a[2] + j), a[2] + j, 2, j == L - 1); + } + if (llama_decode(ctx.get(), b) != 0) { + res.fail++; + res.first = "decode in round " + std::to_string(rd); + break; + } + for (llama_seq_id s = 0; s < 2; ++s) { + const llama_pos r = (llama_pos) (g() % (uint32_t) W[s]); + if (r < W[s] - 1) { + llama_memory_seq_rm(mem, s, a[s] + r + 1, -1); + } + a[s] += r + 1; + } + a[2] += L; + res.rounds++; + + for (llama_seq_id s = 0; s < 3; ++s) { + const std::set sw = mu_positions(kv[2], s); + for (llama_pos p = std::max(0, a[s] - N_SWA + 1); p < a[s]; ++p) { + if (!sw.count(p)) { + if (res.swa_miss++ == 0) { + res.first = "round " + std::to_string(rd) + ": seq " + std::to_string(s) + " swa misses pos " + std::to_string(p) + + " (next query " + std::to_string(a[s]) + ")"; + } + } + } + for (int c = 0; c < 2; ++c) { + const std::set ps = mu_positions(kv[c], s); + const bool exact = (llama_pos) ps.size() == a[s] && (ps.empty() || (*ps.begin() == 0 && *ps.rbegin() == a[s] - 1)); + if (!exact) { + if (res.base_bad++ == 0 && res.first.empty()) { + res.first = "round " + std::to_string(rd) + ": seq " + std::to_string(s) + " " + TG_CACHE[c] + " does not hold [0, " + + std::to_string(a[s]) + ")"; + } + } + } + } + } + llama_batch_free(b); + return res; +} + +static void test_multiseq(testing & t) { + const auto t0 = std::chrono::steady_clock::now(); + + // design 4.4: with -b == -ub every decode is one ubatch, the window of every sequence survives every rollback + t.test("MU-01_mixed_rounds", [](testing & t) { + for (uint32_t seed : { 1u, 2u }) { + const mu01_result r = mu01_run(64, 64, 50, seed); + const std::string w = "seed " + std::to_string(seed); + t.assert_equal(w + ": no failed decode (" + r.first + ")", 0, r.fail); + t.assert_equal(w + ": 50 rounds", 50, r.rounds); + t.assert_equal(w + ": no SWA row missing (" + r.first + ")", 0, r.swa_miss); + t.assert_equal(w + ": base and indexer exact (" + r.first + ")", 0, r.base_bad); + } + }); + + // the control: -b > -ub splits a decode, a later ubatch reuses the cells another sequence still needs (MP02) + t.test("MU-01_control_split", [](testing & t) { + int miss = 0; + std::string first; + for (uint32_t seed : { 1u, 2u }) { + const mu01_result r = mu01_run(64, 16, 50, seed); + miss += r.swa_miss; + first = first.empty() ? r.first : first; + t.assert_equal("seed " + std::to_string(seed) + ": no failed decode (" + r.first + ")", 0, r.fail); + } + t.assert_true("the split decodes lose SWA rows (" + first + ")", miss > 0); + }); + + // design 4.7: with the capture on and several sequences a decode that is not one ubatch is refused before it runs + t.test("MU-08_one_ubatch", [](testing & t) { + const uint32_t S = 8; + llama_model * model = cp_model(S, nullptr); + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr, 2, true); + if (!t.assert_true("context and configure", ctx && cp_configure(ctx.get(), S))) { + return; + } + llama_kv_cache * kv[3]; + tg_caches(ctx.get(), kv); + llama_batch b = llama_batch_init(512, 0, 1); + b.n_tokens = 0; + for (llama_pos p = 0; p < 20; ++p) { + mu_add(b, T[p], p, 0, p == 19); + mu_add(b, T[p + 100], p, 1, p == 19); + } + t.assert_equal("40 rows of two sequences", 0, llama_decode(ctx.get(), b)); + const auto before = mu_meta(kv, 2); + + b.n_tokens = 0; + for (llama_pos p = 20; p < 70; ++p) { + mu_add(b, T[p], p, 0, p == 69); + mu_add(b, T[p + 100], p, 1, p == 69); + } + { + mu_errors logs; + t.assert_equal("100 rows: refused", -1, llama_decode(ctx.get(), b)); + t.assert_true("the log names the ubatch", logs.has("not one ubatch")); + } + t.assert_true("the memory is unchanged", mu_meta(kv, 2) == before); + + b.n_tokens = 0; + for (llama_pos p = 20; p < 52; ++p) { + mu_add(b, T[p], p, 0, p == 51); + mu_add(b, T[p + 100], p, 1, p == 51); + } + t.assert_equal("64 rows: decoded", 0, llama_decode(ctx.get(), b)); + std::vector snaps; + std::string err; + t.assert_equal("take OK " + err, (int) LLAMA_DFLY_CAPTURE_STATUS_OK, (int) cp_take(ctx.get(), snaps, err)); + t.assert_true("two rows", snaps.size() == 2 && snaps[0].seq_id == 0 && snaps[1].seq_id == 1); + llama_batch_free(b); + } + { + llama_context_ptr ctx = cp_context(model, 1024, 512, 64, nullptr); + if (!t.assert_true("one sequence: context and configure", ctx && cp_configure(ctx.get(), S))) { + return; + } + t.assert_equal("one sequence: 300 rows in 5 ubatches", 0, cp_decode(ctx.get(), T, 0, 300, 1)); + } + }); + + // a sequence that does not write keeps its last n_swa rows, as a single sequence does: a checkpoint or a state save + // at its pos_max and the replay of pos_max need the oldest of them (MR7: 16K re-prefill after 511-row checkpoints) + t.test("MU-14_idle_window", [](testing & t) { + const llama_pos N_SWA = 64; + llama_model * model = tg_model(16, (uint32_t) N_SWA); + llama_context_ptr ctx = model ? mu_context(model, 1024, 64, 64, 2) : nullptr; + if (!t.assert_true("context", ctx != nullptr)) { + return; + } + llama_kv_cache * kv[3]; + tg_caches(ctx.get(), kv); + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + llama_batch b = llama_batch_init(64, 0, 1); + auto run = [&](llama_seq_id s, llama_pos p0, llama_pos p1) { + for (llama_pos a = p0; a < p1; a += 64) { + b.n_tokens = 0; + for (llama_pos p = a; p < std::min(p1, a + 64); ++p) { + mu_add(b, T[p + 300*s], p, s, p == p1 - 1); + } + if (llama_decode(ctx.get(), b) != 0) { + return false; + } + } + return true; + }; + t.assert_true("seq 0 to 200", run(0, 0, 200)); + t.assert_true("seq 1 to 600 while seq 0 waits", run(1, 0, 600)); + const std::set sw = mu_positions(kv[2], 0); + int miss = 0; + for (llama_pos p = 200 - N_SWA; p < 200; ++p) { + miss += !sw.count(p); + } + t.assert_equal("seq 0 keeps [136, 199] in the SWA cache", 0, miss); + // a SWA-only state of seq 0, as a checkpoint takes it, holds the whole window + llama_memory_t mem = llama_get_memory(ctx.get()); + t.assert_equal("seq 0 SWA pos_min", (int) (200 - N_SWA), (int) llama_memory_seq_pos_min(mem, 0)); + // seq 0 writes again: its own oldest row may go now, seq 1 keeps its window + t.assert_true("seq 0 on to 264", run(0, 200, 264)); + const std::set sw1 = mu_positions(kv[2], 1); + miss = 0; + for (llama_pos p = 600 - N_SWA; p < 600; ++p) { + miss += !sw1.count(p); + } + t.assert_equal("seq 1 keeps [536, 599]", 0, miss); + llama_batch_free(b); + }); + + // MP24: a slot takes the prompt of another one as the server does: seq_cp shares the full KV cells, the SWA window + // of pos_max is copied, and a checkpoint of the source can roll the copy back; the copy must go on like a sequence + // computed from scratch, the SWA cells must not be shared (shared cells are never reused by the window) + // the indexer keeps every key (top_k 1024): a top-k pick turns float noise of another cell layout into whole + // logit jumps (0.017 at top_k 16, 0.0001 here, scratch vs scratch 0.0001) + t.test("MU-15_slot_copy", [](testing & t) { + const llama_pos N_SWA = 64; + llama_model * model = tg_model(1024, (uint32_t) N_SWA); + llama_context_ptr ctx = model ? mu_context(model, 2048, 64, 64, 3) : nullptr; + if (!t.assert_true("context", ctx != nullptr)) { + return; + } + llama_kv_cache * kv[3]; + tg_caches(ctx.get(), kv); + llama_memory_t mem = llama_get_memory(ctx.get()); + const auto PARTIAL = (llama_state_seq_flags) LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY; + const std::vector T = get_tokens(1024, TG_VOCAB, TG_SEED); + llama_batch b = llama_batch_init(64, 0, 1); + std::vector last; + // positions [p0, p1) of seq s with the tokens T[p + off], the logits of p1 - 1 in last + auto run = [&](llama_seq_id s, llama_pos p0, llama_pos p1, size_t off) { + for (llama_pos a = p0; a < p1; a += 64) { + b.n_tokens = 0; + for (llama_pos p = a; p < std::min(p1, a + 64); ++p) { + mu_add(b, T[p + off], p, s, p == p1 - 1); + } + if (llama_decode(ctx.get(), b) != 0) { + return false; + } + } + const float * l = llama_get_logits_ith(ctx.get(), -1); + last.assign(l, l + TG_VOCAB); + return true; + }; + auto state = [&](llama_seq_id s) { + std::vector buf(llama_state_seq_get_size_ext(ctx.get(), s, PARTIAL)); + buf.resize(llama_state_seq_get_data_ext(ctx.get(), buf.data(), buf.size(), s, PARTIAL)); + return buf; + }; + auto load = [&](const std::vector & buf, llama_seq_id s) { + return llama_state_seq_set_data_ext(ctx.get(), buf.data(), buf.size(), s, PARTIAL) == buf.size(); + }; + auto copy = [&](llama_seq_id src, llama_seq_id dst) { + const std::vector swa = state(src); + llama_memory_seq_rm(mem, dst, -1, -1); + llama_memory_seq_cp(mem, src, dst, -1, -1); + return load(swa, dst); + }; + auto shared = [&](int c, llama_seq_id s0, llama_seq_id s1) { + const llama_kv_cells & cells = kv[c]->get_cells(0); + int n = 0; + for (uint32_t i = 0; i < cells.size(); ++i) { + n += !cells.is_empty(i) && cells.seq_has(i, s0) && cells.seq_has(i, s1); + } + return n; + }; + auto range = [](llama_pos p0, llama_pos p1) { + std::set res; + for (llama_pos p = p0; p < p1; ++p) { + res.insert(p); + } + return res; + }; + auto has_all = [&](int c, llama_seq_id s, llama_pos p0, llama_pos p1) { + const std::set got = mu_positions(kv[c], s); + for (llama_pos p = p0; p < p1; ++p) { + if (!got.count(p)) { + return false; + } + } + return true; + }; + auto window_ok = [&](llama_seq_id s) { + const llama_pos pm = kv[0]->seq_pos_max(s); + return has_all(2, s, std::max(0, pm - N_SWA + 1), pm + 1); + }; + auto max_diff = [](const std::vector & a, const std::vector & b2) { + float d = 0.0f; + for (size_t i = 0; i < a.size() && i < b2.size(); ++i) { + d = std::max(d, std::fabs(a[i] - b2[i])); + } + return d; + }; + auto argmax = [](const std::vector & a) { + return (int) (std::max_element(a.begin(), a.end()) - a.begin()); + }; + + // the indexer rows (key | gate | pooled) of the cells of seq 0 below 300, in every indexer layer + auto idx_rows = [&]() { + std::vector res; + const llama_kv_cells & cells = kv[1]->get_cells(0); + for (const uint32_t il : kv[1]->get_layer_ids()) { + ggml_tensor * k = kv[1]->get_k_storage((int32_t) il); + std::vector row(k->nb[1]); + for (uint32_t i = 0; i < cells.size(); ++i) { + if (!cells.is_empty(i) && cells.seq_has(i, 0) && cells.pos_get(i) < 300) { + ggml_backend_tensor_get(k, row.data(), (size_t) i*k->nb[1], row.size()); + res.insert(res.end(), row.begin(), row.end()); + } + } + } + return res; + }; + + // A: the copy goes on from the end of the source (replay of pos_max, no checkpoint) + t.assert_true("A: seq 0 to 300", run(0, 0, 300, 0)); + const std::vector rows0 = idx_rows(); + t.assert_true("A: copy 0 -> 1", copy(0, 1)); + t.assert_true("A: base of seq 1 is [0, 300)", mu_positions(kv[0], 1) == range(0, 300)); + t.assert_true("A: indexer of seq 1 is [0, 300)", mu_positions(kv[1], 1) == range(0, 300)); + t.assert_equal("A: base cells shared", 300, shared(0, 0, 1)); + t.assert_true("A: SWA of seq 1 is the window [236, 300)", mu_positions(kv[2], 1) == range(300 - N_SWA, 300)); + t.assert_equal("A: no shared SWA cell", 0, shared(2, 0, 1)); + t.assert_true("A: seq 0 keeps its window", window_ok(0)); + llama_memory_seq_rm(mem, 1, 299, -1); + bool ok = run(0, 300, 340, 0); + ok = ok && run(1, 299, 300, 0) && run(1, 300, 360, 400); + const std::vector l1 = last; + ok = ok && run(0, 340, 380, 0); + // the same shapes from scratch: seq 0's prefill, the replay of 299, the new text + ok = ok && run(2, 0, 300, 0); + llama_memory_seq_rm(mem, 2, 299, -1); + ok = ok && run(2, 299, 300, 0) && run(2, 300, 360, 400); + t.assert_true("A: decodes", ok); + // seq 1 re-pools its whole copy into the shared rep rows (stale from 0), which must not change seq 0's rows + t.assert_true("A: the indexer rows of seq 0 below 300 are unchanged, bitwise", !rows0.empty() && idx_rows() == rows0); + const float dA = max_diff(l1, last); + t.log("A: max logit diff copy vs scratch = " + std::to_string(dA) + ", argmax " + std::to_string(argmax(l1)) + " / " + std::to_string(argmax(last))); + t.assert_true("A: the copy goes on like a sequence from scratch", ok && dA < 2e-3f); + for (llama_seq_id s = 0; s < 3; ++s) { + t.assert_true("A: window of seq " + std::to_string(s), window_ok(s)); + } + + // B: a checkpoint of the source rolls the copy back past the window of the source + const std::vector ck = state(0); // seq 0 at [0, 380), pos_max 379 + llama_memory_seq_rm(mem, 2, -1, -1); + t.assert_true("B: seq 0 on to 500", run(0, 380, 500, 0)); + t.assert_true("B: copy 0 -> 1", copy(0, 1)); + t.assert_true("B: checkpoint into seq 1", load(ck, 1)); + t.assert_true("B: SWA of seq 1 is the checkpoint window [316, 380)", mu_positions(kv[2], 1) == range(380 - N_SWA, 380)); + t.assert_equal("B: no shared SWA cell", 0, shared(2, 0, 1)); + llama_memory_seq_rm(mem, 1, 379, -1); + t.assert_true("B: base of seq 1 is [0, 379)", mu_positions(kv[0], 1) == range(0, 379)); + ok = run(1, 379, 380, 0) && run(1, 380, 440, 400); + const std::vector l2 = last; + ok = ok && run(0, 500, 540, 0); + // from scratch with seq 0's shapes up to 380 ([0, 300) and two chunks of 40), the replay of 379, the new text + ok = ok && run(2, 0, 300, 0) && run(2, 300, 340, 0) && run(2, 340, 380, 0); + llama_memory_seq_rm(mem, 2, 379, -1); + ok = ok && run(2, 379, 380, 0) && run(2, 380, 440, 400); + t.assert_true("B: decodes", ok); + const float dB = max_diff(l2, last); + t.log("B: max logit diff copy vs scratch = " + std::to_string(dB) + ", argmax " + std::to_string(argmax(l2)) + " / " + std::to_string(argmax(last))); + t.assert_true("B: the copy goes on like a sequence from scratch", ok && dB < 2e-3f); + for (llama_seq_id s = 0; s < 3; ++s) { + t.assert_true("B: window of seq " + std::to_string(s), window_ok(s)); + } + t.assert_true("B: seq 0 base is [0, 540)", mu_positions(kv[0], 0) == range(0, 540)); + // C (noise floor): the same scratch steps in seq 1, at other cells than seq 2's + { + const std::vector l2s = last; + llama_memory_seq_rm(mem, 1, -1, -1); + bool okc = run(1, 0, 300, 0) && run(1, 300, 340, 0) && run(1, 340, 380, 0); + llama_memory_seq_rm(mem, 1, 379, -1); + okc = okc && run(1, 379, 380, 0) && run(1, 380, 440, 400); + t.log("C: max logit diff scratch vs scratch = " + std::to_string(max_diff(l2s, last)) + (okc ? "" : " (decode failed)")); + } + llama_batch_free(b); + }); + + t.out << t.indent() << " multiseq group: " << (long) tg_ms_since(t0) << " ms\n"; +} + +int main(int argc, char ** argv) { + testing t; + + const char * verbose = getenv("LLAMA_TEST_VERBOSE"); + if (verbose) { + t.verbose = std::string(verbose) == "1"; + } + if (!t.verbose) { + llama_log_set([](ggml_log_level, const char *, void *) {}, nullptr); + } + + llama_backend_init(); + + if (argc > 1) { + t.set_filter(argv[1]); + } + + t.test("swa_coverage", test_swa_coverage); + t.test("fixture", test_fixture); + t.test("width", test_width); + t.test("rollback", test_rollback); + t.test("rollback_neg", test_rollback_neg); + t.test("rollback_long", test_rollback_long); + t.test("capture", test_capture); + t.test("capture_neg", test_capture_neg); + t.test("capture_gpu", test_capture_gpu); + t.test("multiseq", test_multiseq); + + g_runs.clear(); + g_cp_sel.clear(); + g_cp_models.clear(); + g_models.clear(); + llama_backend_free(); + + return t.summary(); +} diff --git a/tests/test-dfly.cpp b/tests/test-dfly.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f3d5d4356ce46aef1438306afc0f79086e66a10 --- /dev/null +++ b/tests/test-dfly.cpp @@ -0,0 +1,6063 @@ +#include "testing.h" +#include "gguf-fixture.h" + +#include "ggml.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" +#include "gguf.h" +#include "llama.h" +#include "llama-cpp.h" + +#include "../src/llama-arch.h" +#include "../src/llama-context.h" +#include "../src/llama-cparams.h" +#include "../src/llama-dfly.h" +#include "../src/llama-ext.h" +#include "../src/llama-kv-cache.h" +#include "../src/llama-kv-cache-iswa.h" +#include "../src/llama-kv-cells.h" +#include "../src/llama-memory.h" +#include "../src/llama-memory-idx-iswa.h" +#include "../src/llama-model.h" +#include "../src/models/hy-v4-next-dfly.h" + +#include "arg.h" +#include "common.h" +#include "speculative.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +static const llm_arch arch = LLM_ARCH_HY_V4_NEXT_DFLY; +static const int n_layer = 5; + +// written out on purpose: the expected names must not be derived from llama-arch.cpp +static const std::vector expected_tensor_names = { + "blk.0.attn_norm.weight", + "blk.0.attn_q_a.weight", + "blk.0.attn_q_a_norm.weight", + "blk.0.attn_q_b.weight", + "blk.0.attn_kv_a_mqa.weight", + "blk.0.attn_kv_a_norm.weight", + "blk.0.attn_k_b.weight", + "blk.0.attn_v_b.weight", + "blk.0.attn_sinks.weight", + "blk.0.attn_gate.weight", + "blk.0.attn_output.weight", + "blk.0.post_attention_norm.weight", + "blk.0.ffn_norm.weight", + "blk.0.ffn_gate.weight", + "blk.0.ffn_up.weight", + "blk.0.ffn_down.weight", + "blk.1.attn_norm.weight", + "blk.1.attn_q_a.weight", + "blk.1.attn_q_a_norm.weight", + "blk.1.attn_q_b.weight", + "blk.1.attn_kv_a_mqa.weight", + "blk.1.attn_kv_a_norm.weight", + "blk.1.attn_k_b.weight", + "blk.1.attn_v_b.weight", + "blk.1.attn_sinks.weight", + "blk.1.attn_gate.weight", + "blk.1.attn_output.weight", + "blk.1.post_attention_norm.weight", + "blk.1.ffn_norm.weight", + "blk.1.ffn_gate.weight", + "blk.1.ffn_up.weight", + "blk.1.ffn_down.weight", + "blk.2.attn_norm.weight", + "blk.2.attn_q_a.weight", + "blk.2.attn_q_a_norm.weight", + "blk.2.attn_q_b.weight", + "blk.2.attn_kv_a_mqa.weight", + "blk.2.attn_kv_a_norm.weight", + "blk.2.attn_k_b.weight", + "blk.2.attn_v_b.weight", + "blk.2.attn_sinks.weight", + "blk.2.attn_gate.weight", + "blk.2.attn_output.weight", + "blk.2.post_attention_norm.weight", + "blk.2.ffn_norm.weight", + "blk.2.ffn_gate.weight", + "blk.2.ffn_up.weight", + "blk.2.ffn_down.weight", + "blk.3.attn_norm.weight", + "blk.3.attn_q_a.weight", + "blk.3.attn_q_a_norm.weight", + "blk.3.attn_q_b.weight", + "blk.3.attn_kv_a_mqa.weight", + "blk.3.attn_kv_a_norm.weight", + "blk.3.attn_k_b.weight", + "blk.3.attn_v_b.weight", + "blk.3.attn_sinks.weight", + "blk.3.attn_gate.weight", + "blk.3.attn_output.weight", + "blk.3.post_attention_norm.weight", + "blk.3.ffn_norm.weight", + "blk.3.ffn_gate.weight", + "blk.3.ffn_up.weight", + "blk.3.ffn_down.weight", + "blk.4.attn_norm.weight", + "blk.4.attn_q_a.weight", + "blk.4.attn_q_a_norm.weight", + "blk.4.attn_q_b.weight", + "blk.4.attn_kv_a_mqa.weight", + "blk.4.attn_kv_a_norm.weight", + "blk.4.attn_k_b.weight", + "blk.4.attn_v_b.weight", + "blk.4.attn_sinks.weight", + "blk.4.attn_gate.weight", + "blk.4.attn_output.weight", + "blk.4.post_attention_norm.weight", + "blk.4.ffn_norm.weight", + "blk.4.ffn_gate.weight", + "blk.4.ffn_up.weight", + "blk.4.ffn_down.weight", + "output_norm.weight", + "dfly_fusion_enorm.weight", + "dfly_fusion_hnorm.weight", + "dfly_fusion_eh.weight", + "dfly_fusion_gate.weight", + "dfly_correction_hnorm.weight", + "dfly_correction_enorm.weight", + "dfly_correction_gate.weight", + "dfly_correction_up.weight", + "dfly_correction_down.weight", + "dfly_confidence.weight", + "dfly_confidence.bias", +}; + +static const std::pair expected_keys[] = { + { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" }, + { LLM_KV_DFLY_SCHEMA_VERSION, "hy_v4_next_dfly.schema_version" }, + { LLM_KV_DFLASH_BLOCK_SIZE, "hy_v4_next_dfly.block_size" }, + { LLM_KV_ATTENTION_CAUSAL, "hy_v4_next_dfly.attention.causal" }, + { LLM_KV_BLOCK_COUNT, "hy_v4_next_dfly.block_count" }, + { LLM_KV_CONTEXT_LENGTH, "hy_v4_next_dfly.context_length" }, + { LLM_KV_EMBEDDING_LENGTH, "hy_v4_next_dfly.embedding_length" }, + { LLM_KV_FEED_FORWARD_LENGTH, "hy_v4_next_dfly.feed_forward_length" }, + { LLM_KV_ATTENTION_HEAD_COUNT, "hy_v4_next_dfly.attention.head_count" }, + { LLM_KV_ATTENTION_HEAD_COUNT_KV, "hy_v4_next_dfly.attention.head_count_kv" }, + { LLM_KV_ATTENTION_Q_LORA_RANK, "hy_v4_next_dfly.attention.q_lora_rank" }, + { LLM_KV_ATTENTION_KV_LORA_RANK, "hy_v4_next_dfly.attention.kv_lora_rank" }, + { LLM_KV_ATTENTION_KEY_LENGTH, "hy_v4_next_dfly.attention.key_length" }, + { LLM_KV_ATTENTION_VALUE_LENGTH, "hy_v4_next_dfly.attention.value_length" }, + { LLM_KV_ATTENTION_KEY_LENGTH_MLA, "hy_v4_next_dfly.attention.key_length_mla" }, + { LLM_KV_ATTENTION_VALUE_LENGTH_MLA, "hy_v4_next_dfly.attention.value_length_mla" }, + { LLM_KV_ROPE_DIMENSION_COUNT, "hy_v4_next_dfly.rope.dimension_count" }, + { LLM_KV_ROPE_FREQ_BASE, "hy_v4_next_dfly.rope.freq_base" }, + { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "hy_v4_next_dfly.attention.layer_norm_rms_epsilon" }, + { LLM_KV_DFLY_TARGET_KV_LAYERS, "hy_v4_next_dfly.target_kv_layers" }, + { LLM_KV_DFLY_TARGET_INDEX_LAYERS, "hy_v4_next_dfly.target_index_layers" }, + { LLM_KV_DFLY_TARGET_INDEX_TOP_K, "hy_v4_next_dfly.target_index_top_k" }, + { LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, "hy_v4_next_dfly.hidden_correction_length" }, + { LLM_KV_HAS_CONFIDENCE_HEAD, "hy_v4_next_dfly.has_confidence_head" }, + { LLM_KV_DFLY_MTP_FUSION, "hy_v4_next_dfly.mtp_fusion" }, + { LLM_KV_DFLY_ROPE_LAYOUT, "hy_v4_next_dfly.rope_layout" }, + { LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, "hy_v4_next_dfly.source_mrope_sections" }, + { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" }, +}; + +// per-layer types, in the order of expected_tensor_names +static const llm_tensor layer_tensors[] = { + LLM_TENSOR_ATTN_NORM, + LLM_TENSOR_ATTN_Q_A, + LLM_TENSOR_ATTN_Q_A_NORM, + LLM_TENSOR_ATTN_Q_B, + LLM_TENSOR_ATTN_KV_A_MQA, + LLM_TENSOR_ATTN_KV_A_NORM, + LLM_TENSOR_ATTN_K_B, + LLM_TENSOR_ATTN_V_B, + LLM_TENSOR_ATTN_SINKS, + LLM_TENSOR_ATTN_GATE, + LLM_TENSOR_ATTN_OUT, + LLM_TENSOR_ATTN_POST_NORM, + LLM_TENSOR_FFN_NORM, + LLM_TENSOR_FFN_GATE, + LLM_TENSOR_FFN_UP, + LLM_TENSOR_FFN_DOWN, +}; + +// global types, all LLM_TENSOR_LAYER_OUTPUT, in the order of expected_tensor_names +static const std::pair global_tensors[] = { + { LLM_TENSOR_OUTPUT_NORM, GGML_OP_MUL }, + { LLM_TENSOR_DFLY_FUSION_ENORM, GGML_OP_MUL }, + { LLM_TENSOR_DFLY_FUSION_HNORM, GGML_OP_MUL }, + { LLM_TENSOR_DFLY_FUSION_EH, GGML_OP_MUL_MAT }, + { LLM_TENSOR_DFLY_FUSION_GATE, GGML_OP_MUL }, + { LLM_TENSOR_DFLY_CORRECTION_HNORM, GGML_OP_MUL }, + { LLM_TENSOR_DFLY_CORRECTION_ENORM, GGML_OP_MUL }, + { LLM_TENSOR_DFLY_CORRECTION_GATE, GGML_OP_MUL_MAT }, + { LLM_TENSOR_DFLY_CORRECTION_UP, GGML_OP_MUL_MAT }, + { LLM_TENSOR_DFLY_CORRECTION_DOWN, GGML_OP_MUL_MAT }, + { LLM_TENSOR_DFLY_CONFIDENCE, GGML_OP_MUL_MAT }, +}; + +static_assert(std::is_same::type, int32_t>::value, "llama_dfly_status is not int32_t"); +static_assert(LLAMA_DFLY_OK == 0, "LLAMA_DFLY_OK"); +static_assert(LLAMA_DFLY_NO_SNAPSHOT == 1, "LLAMA_DFLY_NO_SNAPSHOT"); +static_assert(LLAMA_DFLY_BAD_SNAPSHOT == 2, "LLAMA_DFLY_BAD_SNAPSHOT"); +static_assert(LLAMA_DFLY_BAD_TOKEN == 3, "LLAMA_DFLY_BAD_TOKEN"); +static_assert(LLAMA_DFLY_COMPUTE_FAILED == 4, "LLAMA_DFLY_COMPUTE_FAILED"); +static_assert(LLAMA_DFLY_BAD_REQUEST == 5, "LLAMA_DFLY_BAD_REQUEST"); + +static_assert(std::is_same::value, "llama_dfly_request::seq_id"); +static_assert(std::is_same::value, "llama_dfly_request::anchor_token"); +static_assert(std::is_same::value, "llama_dfly_request::anchor_pos"); +static_assert(std::is_same::value, "llama_dfly_request::k_step"); +static_assert(std::is_same::value, "llama_dfly_result::tokens"); +static_assert(std::is_same::value, "llama_dfly_result::capacity"); +static_assert(std::is_same::value, "llama_dfly_result::n_tokens"); + +// field order is part of the frozen ABI, the field types alone do not pin it +static_assert(offsetof(llama_dfly_request, seq_id) == 0*sizeof(int32_t), "llama_dfly_request layout"); +static_assert(offsetof(llama_dfly_request, anchor_token) == 1*sizeof(int32_t), "llama_dfly_request layout"); +static_assert(offsetof(llama_dfly_request, anchor_pos) == 2*sizeof(int32_t), "llama_dfly_request layout"); +static_assert(offsetof(llama_dfly_request, k_step) == 3*sizeof(int32_t), "llama_dfly_request layout"); +static_assert(sizeof(llama_dfly_request) == 4*sizeof(int32_t), "llama_dfly_request layout"); +static_assert(offsetof(llama_dfly_result, tokens) == 0, "llama_dfly_result layout"); +static_assert(offsetof(llama_dfly_result, capacity) == sizeof(llama_token *), "llama_dfly_result layout"); +static_assert(offsetof(llama_dfly_result, n_tokens) == sizeof(llama_token *) + sizeof(int32_t), "llama_dfly_result layout"); +static_assert(sizeof(llama_dfly_result) == sizeof(llama_token *) + 2*sizeof(int32_t), "llama_dfly_result layout"); + +using dfly_capture_fn = llama_dfly_status (*)(llama_context *); +using dfly_propose_fn = llama_dfly_status (*)(llama_context *, const llama_dfly_request *, llama_dfly_result *); +using dfly_invalidate_fn = void (*)(llama_context *, llama_seq_id); + +static_assert(std::is_same::value, "llama_dfly_capture_enable"); +static_assert(std::is_same::value, "llama_dfly_capture_pull"); +static_assert(std::is_same::value, "llama_dfly_propose"); +static_assert(std::is_same::value, "llama_dfly_invalidate"); + +static std::string layer_name(llm_tensor_layer layer) { + switch (layer) { + case LLM_TENSOR_LAYER_INPUT: return "input"; + case LLM_TENSOR_LAYER_REPEATING: return "repeating"; + case LLM_TENSOR_LAYER_OUTPUT: return "output"; + } + return "unknown"; +} + +static void test_arch(testing & t) { + t.assert_equal("name", std::string("hy_v4_next_dfly"), std::string(llama_arch_name(arch))); + t.assert_equal("from_string", arch, llama_arch_from_string("hy_v4_next_dfly")); + + const std::vector all = llama_arch_all(); + t.assert_true("listed by llama_arch_all", std::find(all.begin(), all.end(), arch) != all.end()); + + t.assert_true("no tensor split", !llama_arch_supports_sm_tensor(arch)); + t.assert_true("no save", !llama_arch_supports_save(arch)); +} + +static void test_tensor_names(testing & t) { + const LLM_TN tn(arch); + + std::vector names; + for (int il = 0; il < n_layer; ++il) { + for (llm_tensor type : layer_tensors) { + names.push_back(tn(type, "weight", il).str()); + } + } + for (const auto & type : global_tensors) { + names.push_back(tn(type.first, "weight").str()); + } + names.push_back(tn(LLM_TENSOR_DFLY_CONFIDENCE, "bias").str()); + + t.assert_equal("expected count", (size_t) 92, expected_tensor_names.size()); + t.assert_equal("count", expected_tensor_names.size(), names.size()); + for (size_t i = 0; i < std::min(names.size(), expected_tensor_names.size()); ++i) { + t.assert_equal("name " + std::to_string(i), expected_tensor_names[i], names[i]); + } + t.assert_equal("unique", names.size(), std::set(names.begin(), names.end()).size()); +} + +// test labels come from expected_tensor_names, LLM_TN aborts on a missing name entry +static void test_tensor_info(testing & t) { + const size_t n_layer_types = std::size(layer_tensors); + + for (size_t i = 0; i < n_layer_types; ++i) { + const llm_tensor type = layer_tensors[i]; + t.test(expected_tensor_names.at(i), [&](testing & t) { + const llm_tensor_info & info = llm_tensor_info_for(type); + t.assert_equal("layer", std::string("repeating"), layer_name(info.layer)); + t.assert_true("op is not NONE", info.op != GGML_OP_NONE); + }); + } + for (size_t i = 0; i < std::size(global_tensors); ++i) { + const auto & type = global_tensors[i]; + t.test(expected_tensor_names.at(n_layer*n_layer_types + i), [&](testing & t) { + const llm_tensor_info & info = llm_tensor_info_for(type.first); + t.assert_equal("layer", std::string("output"), layer_name(info.layer)); + t.assert_equal("op", std::string(ggml_op_name(type.second)), std::string(ggml_op_name(info.op))); + }); + } +} + +static void test_kv_names(testing & t) { + for (const auto & key : expected_keys) { + t.test(key.second, [&](testing & t) { + t.assert_equal(std::string(key.second), llama_arch_kv_name(arch, key.first)); + }); + } +} + +// a nullptr ctx is never a DFly ctx, so every call must fail without writing tokens +static void test_api(testing & t) { + const llama_dfly_request request = { 0, 1, 1, 4 }; + + t.test("propose_rejects_null_ctx", [&](testing & t) { + llama_token tokens[8]; + std::fill(std::begin(tokens), std::end(tokens), LLAMA_TOKEN_NULL); + llama_dfly_result result = { tokens, 8, 123 }; + + t.assert_equal(LLAMA_DFLY_BAD_REQUEST, llama_dfly_propose(nullptr, &request, &result)); + t.assert_equal("n_tokens", 0, result.n_tokens); + t.assert_true("tokens not written", std::all_of(std::begin(tokens), std::end(tokens), [](llama_token id) { return id == LLAMA_TOKEN_NULL; })); + }); + + t.test("propose_rejects_null_request", [&](testing & t) { + llama_token tokens[8]; + llama_dfly_result result = { tokens, 8, 123 }; + + t.assert_equal(LLAMA_DFLY_BAD_REQUEST, llama_dfly_propose(nullptr, nullptr, &result)); + t.assert_equal("n_tokens", 0, result.n_tokens); + }); + + t.test("propose_rejects_null_result", [&](testing & t) { + t.assert_equal(LLAMA_DFLY_BAD_REQUEST, llama_dfly_propose(nullptr, &request, nullptr)); + }); + + t.test("capture_rejects_null_ctx", [&](testing & t) { + t.assert_equal("enable", LLAMA_DFLY_BAD_REQUEST, llama_dfly_capture_enable(nullptr)); + t.assert_equal("pull", LLAMA_DFLY_BAD_REQUEST, llama_dfly_capture_pull(nullptr)); + }); + + t.test("invalidate_accepts_null_ctx", [](testing &) { + llama_dfly_invalidate(nullptr, 0); + }); +} + +// +// loader tests: a tiny DFly GGUF is written to a file and loaded through llama_model_load_from_file, +// llama_model_init_from_user does not check shapes, missing or extra tensors +// + +// production ne from the plan, appendix A.2 (in every layer) and A.4 (global), written out on purpose +static const std::vector>> prod_layer_ne = { + { "attn_norm.weight", { 3072 } }, + { "attn_q_a.weight", { 3072, 1024 } }, + { "attn_q_a_norm.weight", { 1024 } }, + { "attn_q_b.weight", { 1024, 8192 } }, + { "attn_kv_a_mqa.weight", { 3072, 576 } }, + { "attn_kv_a_norm.weight", { 512 } }, + { "attn_k_b.weight", { 192, 512, 32 } }, + { "attn_v_b.weight", { 512, 256, 32 } }, + { "attn_sinks.weight", { 32 } }, + { "attn_gate.weight", { 3072, 8192 } }, + { "attn_output.weight", { 8192, 3072 } }, + { "post_attention_norm.weight", { 3072 } }, + { "ffn_norm.weight", { 3072 } }, + { "ffn_gate.weight", { 3072, 9216 } }, + { "ffn_up.weight", { 3072, 9216 } }, + { "ffn_down.weight", { 9216, 3072 } }, +}; + +static const std::vector>> prod_global_ne = { + { "output_norm.weight", { 3072 } }, + { "dfly_fusion_enorm.weight", { 3072 } }, + { "dfly_fusion_hnorm.weight", { 3072 } }, + { "dfly_fusion_eh.weight", { 6144, 3072 } }, + { "dfly_fusion_gate.weight", { 3072 } }, + { "dfly_correction_hnorm.weight", { 3072 } }, + { "dfly_correction_enorm.weight", { 3072 } }, + { "dfly_correction_gate.weight", { 6144, 3072 } }, + { "dfly_correction_up.weight", { 6144, 3072 } }, + { "dfly_correction_down.weight", { 3072, 3072 } }, + { "dfly_confidence.weight", { 3072, 1 } }, + { "dfly_confidence.bias", { 1 } }, +}; + +// appendix A.1: 5 x 155,920,928 + 66,081,793 +static const uint64_t prod_n_params = 845686433; + +// the llama_layer field of each per-layer tensor, the table of the S3 card section 2.3 +static const std::pair layer_fields[] = { + { &llama_layer::attn_norm, "attn_norm.weight" }, + { &llama_layer::wq_a, "attn_q_a.weight" }, + { &llama_layer::attn_q_a_norm, "attn_q_a_norm.weight" }, + { &llama_layer::wq_b, "attn_q_b.weight" }, + { &llama_layer::wkv_a_mqa, "attn_kv_a_mqa.weight" }, + { &llama_layer::attn_kv_a_norm, "attn_kv_a_norm.weight" }, + { &llama_layer::wk_b, "attn_k_b.weight" }, + { &llama_layer::wv_b, "attn_v_b.weight" }, + { &llama_layer::attn_sinks, "attn_sinks.weight" }, + { &llama_layer::wqkv_gate, "attn_gate.weight" }, + { &llama_layer::wo, "attn_output.weight" }, + { &llama_layer::attn_post_norm, "post_attention_norm.weight" }, + { &llama_layer::ffn_norm, "ffn_norm.weight" }, + { &llama_layer::ffn_gate, "ffn_gate.weight" }, + { &llama_layer::ffn_up, "ffn_up.weight" }, + { &llama_layer::ffn_down, "ffn_down.weight" }, +}; + +static const std::pair global_fields[] = { + { &llama_model::output_norm, "output_norm.weight" }, + { &llama_model::dfly_fusion_enorm, "dfly_fusion_enorm.weight" }, + { &llama_model::dfly_fusion_hnorm, "dfly_fusion_hnorm.weight" }, + { &llama_model::dfly_fusion_eh, "dfly_fusion_eh.weight" }, + { &llama_model::dfly_fusion_gate, "dfly_fusion_gate.weight" }, + { &llama_model::dfly_correction_hnorm, "dfly_correction_hnorm.weight" }, + { &llama_model::dfly_correction_enorm, "dfly_correction_enorm.weight" }, + { &llama_model::dfly_correction_gate, "dfly_correction_gate.weight" }, + { &llama_model::dfly_correction_up, "dfly_correction_up.weight" }, + { &llama_model::dfly_correction_down, "dfly_correction_down.weight" }, + { &llama_model::dfly_confidence, "dfly_confidence.weight" }, + { &llama_model::dfly_confidence_b, "dfly_confidence.bias" }, +}; + +// a DFly geometry; the defaults are the tiny one, where all 14 shape numbers differ, H != 2 and C != D +struct dfly_dims { + uint32_t n_embd = 24; // D + uint32_t n_ff = 38; // F + uint32_t n_head = 3; // H + uint32_t n_lora_q = 20; // Rq + uint32_t n_lora_kv = 22; // Rkv + uint32_t n_nope = 6; // Dn + uint32_t n_rot = 4; // Dr + uint32_t n_v = 9; // Dv + uint32_t n_corr = 32; // C + uint32_t n_vocab = 40; // V + uint32_t top_k = 16; // S + uint32_t mask = 37; + uint32_t block_size = 8; // B + uint32_t n_ctx = 4096; + float theta = 1e7f; + float eps = 1e-5f; + + std::vector target_layers = { 3, 5, 7, 9, 11 }; + std::vector mrope_sections = { 1, 1, 0 }; +}; + +// the production profile, plan section 4.1 (B from the training team) +static dfly_dims dfly_dims_production() { + dfly_dims d; + d.n_embd = 3072; + d.n_ff = 9216; + d.n_head = 32; + d.n_lora_q = 1024; + d.n_lora_kv = 512; + d.n_nope = 192; + d.n_rot = 64; + d.n_v = 256; + d.n_corr = 3072; + d.n_vocab = 120832; + d.top_k = 2048; + d.mask = 120009; + d.block_size = 8; + d.n_ctx = 1048576; + d.target_layers = { 25, 29, 33, 37, 41 }; + d.mrope_sections = { 12, 10, 10 }; + return d; +} + +// D, V, Rkv and Dr of the hy_v4_flash fixture in test-llama-archs, target layers of plan section 12.7 +static dfly_dims dfly_dims_second() { + dfly_dims d; + d.n_embd = 128; + d.n_ff = 192; + d.n_head = 2; + d.n_lora_q = 512; + d.n_lora_kv = 512; + d.n_nope = 128; + d.n_rot = 64; + d.n_v = 128; + d.n_corr = 128; + d.n_vocab = 128; + d.top_k = 8; + d.mask = 120; + d.block_size = 5; + d.target_layers = { 0, 2, 4, 6, 8 }; + d.mrope_sections = { 12, 10, 10 }; // sums to Dr/2 + return d; +} + +struct dfly_tensor { + std::string name; + std::vector ne; + ggml_type type; + std::vector data; +}; + +// appendix A, ggml order, with q_b rows H*(Dn+Dr) and gate/o_proj H*Dv (plan 8.3), correction 2D -> C -> D (plan 8.5) +static std::vector dfly_shapes(const dfly_dims & d, ggml_type mat = GGML_TYPE_BF16) { + const int64_t D = d.n_embd; + const int64_t F = d.n_ff; + const int64_t H = d.n_head; + const int64_t Rq = d.n_lora_q; + const int64_t Rkv = d.n_lora_kv; + const int64_t Dn = d.n_nope; + const int64_t Dr = d.n_rot; + const int64_t Dv = d.n_v; + const int64_t C = d.n_corr; + + // all 1D tensors and the confidence head are F32 (plan A.5) + const ggml_type f32 = GGML_TYPE_F32; + + std::vector out; + for (int il = 0; il < n_layer; ++il) { + const std::string p = "blk." + std::to_string(il) + "."; + out.push_back({ p + "attn_norm.weight", { D }, f32, {} }); + out.push_back({ p + "attn_q_a.weight", { D, Rq }, mat, {} }); + out.push_back({ p + "attn_q_a_norm.weight", { Rq }, f32, {} }); + out.push_back({ p + "attn_q_b.weight", { Rq, H*(Dn + Dr) }, mat, {} }); + out.push_back({ p + "attn_kv_a_mqa.weight", { D, Rkv + Dr }, mat, {} }); + out.push_back({ p + "attn_kv_a_norm.weight", { Rkv }, f32, {} }); + out.push_back({ p + "attn_k_b.weight", { Dn, Rkv, H }, mat, {} }); + out.push_back({ p + "attn_v_b.weight", { Rkv, Dv, H }, mat, {} }); + out.push_back({ p + "attn_sinks.weight", { H }, f32, {} }); + out.push_back({ p + "attn_gate.weight", { D, H*Dv }, mat, {} }); + out.push_back({ p + "attn_output.weight", { H*Dv, D }, mat, {} }); + out.push_back({ p + "post_attention_norm.weight", { D }, f32, {} }); + out.push_back({ p + "ffn_norm.weight", { D }, f32, {} }); + out.push_back({ p + "ffn_gate.weight", { D, F }, mat, {} }); + out.push_back({ p + "ffn_up.weight", { D, F }, mat, {} }); + out.push_back({ p + "ffn_down.weight", { F, D }, mat, {} }); + } + out.push_back({ "output_norm.weight", { D }, f32, {} }); + out.push_back({ "dfly_fusion_enorm.weight", { D }, f32, {} }); + out.push_back({ "dfly_fusion_hnorm.weight", { D }, f32, {} }); + out.push_back({ "dfly_fusion_eh.weight", { 2*D, D }, mat, {} }); + out.push_back({ "dfly_fusion_gate.weight", { D }, f32, {} }); + out.push_back({ "dfly_correction_hnorm.weight", { D }, f32, {} }); + out.push_back({ "dfly_correction_enorm.weight", { D }, f32, {} }); + out.push_back({ "dfly_correction_gate.weight", { 2*D, C }, mat, {} }); + out.push_back({ "dfly_correction_up.weight", { 2*D, C }, mat, {} }); + out.push_back({ "dfly_correction_down.weight", { C, D }, mat, {} }); + out.push_back({ "dfly_confidence.weight", { D, 1 }, f32, {} }); + out.push_back({ "dfly_confidence.bias", { 1 }, f32, {} }); + return out; +} + +static int64_t n_elements(const std::vector & ne) { + int64_t n = 1; + for (int64_t x : ne) { + n *= x; + } + return n; +} + +static uint64_t dfly_n_params(const dfly_dims & d) { + uint64_t n = 0; + for (const auto & t : dfly_shapes(d)) { + n += n_elements(t.ne); + } + return n; +} + +template +static std::string list_str(const T & v) { + std::string s = "["; + for (auto it = std::begin(v); it != std::end(v); ++it) { + s += (it == std::begin(v) ? "" : ", ") + std::to_string(*it); + } + return s + "]"; +} + +// the full key names come from the hand-written expected_keys +static std::string key_name(llm_kv kv) { + for (const auto & key : expected_keys) { + if (key.first == kv) { + return key.second; + } + } + GGML_ABORT("key %d is not in expected_keys", (int) kv); +} + +using kv_edit_fn = std::function; +using tensor_edit_fn = std::function &)>; +using patch_fn = std::function &)>; + +// a written DFly GGUF, removed again when this goes out of scope (free the model first) +struct dfly_file { + std::string path; + std::vector tensors; + + dfly_file() = default; + dfly_file(const dfly_file &) = delete; + dfly_file & operator=(const dfly_file &) = delete; + + ~dfly_file() { + if (!path.empty()) { + std::remove(path.c_str()); + } + } +}; + +static std::string dfly_tmp_path() { +#ifdef _WIN32 + const int pid = _getpid(); +#else + const int pid = (int) getpid(); +#endif + static int id = 0; + // the build and build-asan test-dfly may run at the same time + const std::string name = "test-dfly-" + std::to_string(pid) + "-" + std::to_string(++id) + ".gguf"; + return (std::filesystem::temp_directory_path() / name).string(); +} + +// kv_edit, tensor_edit and patch turn the valid file into a negative case; data_edit sets values after the random fill +static void write_dfly(dfly_file & f, const dfly_dims & d, const kv_edit_fn & kv_edit = {}, const tensor_edit_fn & tensor_edit = {}, + ggml_type mat = GGML_TYPE_BF16, const patch_fn & patch = {}, const tensor_edit_fn & data_edit = {}) { + gguf_context_ptr ctx(gguf_init_empty()); + kv_writer kv(arch, ctx.get()); + + kv.add_kv(LLM_KV_GENERAL_ARCHITECTURE, "hy_v4_next_dfly"); + kv.add_kv(LLM_KV_DFLY_SCHEMA_VERSION, uint32_t(1)); + kv.add_kv(LLM_KV_DFLASH_BLOCK_SIZE, d.block_size); + kv.add_kv(LLM_KV_ATTENTION_CAUSAL, true); + kv.add_kv(LLM_KV_BLOCK_COUNT, uint32_t(n_layer)); + kv.add_kv(LLM_KV_CONTEXT_LENGTH, d.n_ctx); + kv.add_kv(LLM_KV_EMBEDDING_LENGTH, d.n_embd); + kv.add_kv(LLM_KV_FEED_FORWARD_LENGTH, d.n_ff); + kv.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, d.n_head); + kv.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, uint32_t(1)); + kv.add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, d.n_lora_q); + kv.add_kv(LLM_KV_ATTENTION_KV_LORA_RANK, d.n_lora_kv); + kv.add_kv(LLM_KV_ATTENTION_KEY_LENGTH, d.n_lora_kv + d.n_rot); + kv.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH, d.n_lora_kv); + kv.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA, d.n_nope + d.n_rot); + kv.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, d.n_v); + kv.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, d.n_rot); + kv.add_kv(LLM_KV_ROPE_FREQ_BASE, d.theta); + kv.add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, d.eps); + kv.add_kv(LLM_KV_DFLY_TARGET_KV_LAYERS, d.target_layers); + kv.add_kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS, d.target_layers); + kv.add_kv(LLM_KV_DFLY_TARGET_INDEX_TOP_K, d.top_k); + kv.add_kv(LLM_KV_DFLY_HIDDEN_CORRECTION_LENGTH, d.n_corr); + kv.add_kv(LLM_KV_HAS_CONFIDENCE_HEAD, true); + kv.add_kv(LLM_KV_DFLY_MTP_FUSION, "slot0"); + kv.add_kv(LLM_KV_DFLY_ROPE_LAYOUT, "norm_adjacent"); + kv.add_kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, d.mrope_sections); + + // the dummy tokenizer of test-llama-archs, plus the mask id + std::vector tokens(d.n_vocab); + for (uint32_t i = 0; i < d.n_vocab; ++i) { + tokens[i] = "tok_" + std::to_string(i); + } + kv.add_kv(LLM_KV_TOKENIZER_MODEL, "test"); + kv.add_kv(LLM_KV_TOKENIZER_LIST, tokens); + kv.add_kv(LLM_KV_TOKENIZER_SCORES, std::vector(d.n_vocab, 0.0f)); + kv.add_kv(LLM_KV_TOKENIZER_MASK_ID, d.mask); + + if (kv_edit) { + kv_edit(ctx.get(), kv); + } + + f.tensors = dfly_shapes(d, mat); + if (tensor_edit) { + tensor_edit(f.tensors); + } + + // normal values: constant data hides a swapped field or a transpose, random bits give NaN/Inf + std::mt19937 rng(42); + std::normal_distribution dist(0.0f, 1.0f); + + ggml_init_params params = { ggml_tensor_overhead()*f.tensors.size(), nullptr, true }; + ggml_context_ptr meta(ggml_init(params)); + + for (auto & t : f.tensors) { + const int64_t n = n_elements(t.ne); + std::vector values(n); + for (float & v : values) { + v = dist(rng); + } + t.data.resize(ggml_row_size(t.type, n)); + switch (t.type) { + case GGML_TYPE_F32: memcpy(t.data.data(), values.data(), t.data.size()); break; + case GGML_TYPE_BF16: ggml_fp32_to_bf16_row(values.data(), (ggml_bf16_t *) t.data.data(), n); break; + case GGML_TYPE_F16: ggml_fp32_to_fp16_row(values.data(), (ggml_fp16_t *) t.data.data(), n); break; + case GGML_TYPE_Q8_0: + ggml_quantize_chunk(t.type, values.data(), t.data.data(), 0, n / t.ne[0], t.ne[0], nullptr); + break; + default: GGML_ABORT("unsupported fixture type %s", ggml_type_name(t.type)); + } + } + if (data_edit) { + data_edit(f.tensors); + } + + for (auto & t : f.tensors) { + + ggml_tensor * tensor = ggml_new_tensor(meta.get(), t.type, (int) t.ne.size(), t.ne.data()); + ggml_set_name(tensor, t.name.c_str()); + gguf_add_tensor(ctx.get(), tensor); + // gguf keeps this pointer until the file is written + gguf_set_tensor_data(ctx.get(), t.name.c_str(), t.data.data()); + } + + f.path = dfly_tmp_path(); + if (!gguf_write_to_file(ctx.get(), f.path.c_str(), false)) { + throw std::runtime_error("failed to write " + f.path); + } + + if (patch) { + std::vector bytes(std::filesystem::file_size(f.path)); + FILE * file = fopen(f.path.c_str(), "rb"); + GGML_ASSERT(file && fread(bytes.data(), 1, bytes.size(), file) == bytes.size()); + fclose(file); + patch(bytes); + file = fopen(f.path.c_str(), "wb"); + GGML_ASSERT(file && fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size()); + fclose(file); + } +} + +static bool dfly_progress(float, void *) { + return true; +} + +// CPU only unless dev is given, and then only dev +static llama_model_ptr load_dfly(const std::string & path, ggml_backend_dev_t dev = nullptr) { + ggml_backend_dev_t devs[] = { dev, nullptr }; + + llama_model_params params = llama_model_default_params(); + params.devices = devs; + // Byte comparisons require the original tensor layout. + params.use_extra_bufts = false; + params.progress_callback = dfly_progress; + + return llama_model_ptr(llama_model_load_from_file(path.c_str(), params)); +} + +// collects the log by level while alive, and still passes it on to the previous callback +struct log_capture { + ggml_log_callback prev_cb = nullptr; + void * prev_ud = nullptr; + + std::mutex mutex; + ggml_log_level last = GGML_LOG_LEVEL_NONE; + std::map> lines; + + log_capture() { + llama_log_get(&prev_cb, &prev_ud); + llama_log_set(callback, this); + } + + ~log_capture() { + llama_log_set(prev_cb, prev_ud); + } + + static void callback(ggml_log_level level, const char * text, void * user_data) { + auto * self = (log_capture *) user_data; + { + std::lock_guard lock(self->mutex); + if (level == GGML_LOG_LEVEL_CONT) { + auto & list = self->lines[self->last]; + if (list.empty()) { + list.emplace_back(); + } + list.back() += text; + } else { + self->lines[level].push_back(text); + self->last = level; + } + } + if (self->prev_cb) { + self->prev_cb(level, text, self->prev_ud); + } + } + + std::vector get(ggml_log_level level) { + std::lock_guard lock(mutex); + return lines[level]; + } +}; + +static bool has_line(const std::vector & lines, const std::vector & needles) { + return std::any_of(lines.begin(), lines.end(), [&](const std::string & line) { + return std::all_of(needles.begin(), needles.end(), [&](const std::string & needle) { + return line.find(needle) != std::string::npos; + }); + }); +} + +static void print_lines(testing & t, const char * what, const std::vector & lines) { + for (const auto & line : lines) { + t.out << t.indent() << " " << what << ": " << line << (line.empty() || line.back() != '\n' ? "\n" : ""); + } +} + +// the load must fail with one ERROR line that names the key or tensor and the broken rule; +// INFO and DEBUG list every key and tensor name on any load, so they must not be searched +static void expect_fail(testing & t, const dfly_file & f, const std::vector & needles) { + log_capture logs; + llama_model_ptr model = load_dfly(f.path); + + t.assert_true("load fails", model == nullptr); + + const std::vector errors = logs.get(GGML_LOG_LEVEL_ERROR); + if (!t.assert_true("one ERROR line has the name and the rule", has_line(errors, needles))) { + print_lines(t, "want", needles); + print_lines(t, "ERROR", errors); + } +} + +static void check_fail(testing & t, const std::vector & needles, const kv_edit_fn & kv_edit, + const tensor_edit_fn & tensor_edit = {}, const patch_fn & patch = {}, const dfly_dims & d = dfly_dims()) { + dfly_file f; + write_dfly(f, d, kv_edit, tensor_edit, GGML_TYPE_BF16, patch); + expect_fail(t, f, needles); +} + +static kv_edit_fn remove_key(llm_kv kv) { + return [kv](gguf_context * ctx, kv_writer &) { + gguf_remove_key(ctx, key_name(kv).c_str()); + }; +} + +static std::map tensor_map(const llama_model & model) { + std::map map; + for (const auto & it : model.tensors_by_name) { + map[it.first] = it.second; + } + return map; +} + +static std::map> prod_ne() { + std::map> map; + for (int il = 0; il < n_layer; ++il) { + for (const auto & it : prod_layer_ne) { + map["blk." + std::to_string(il) + "." + it.first] = it.second; + } + } + for (const auto & it : prod_global_ne) { + map[it.first] = it.second; + } + return map; +} + +// ne padded to GGML_MAX_DIMS, so that [3072, 1] and [3072] compare as ggml sees them +static std::vector pad_ne(std::vector ne) { + ne.resize(GGML_MAX_DIMS, 1); + return ne; +} + +// the device of the buffer the tensor really sits in; the CPU buffer type may have no device +static ggml_backend_dev_t tensor_dev(const ggml_tensor * t) { + if (t->buffer == nullptr) { + return nullptr; + } + ggml_backend_dev_t dev = ggml_backend_buft_get_device(ggml_backend_buffer_get_type(t->buffer)); + return dev ? dev : ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); +} + +// all 92 on the CPU, or with gpu: layer i on dev_layer(i), the 12 globals on dev_output(), both gpu +static void check_devices(testing & t, const llama_model & model, ggml_backend_dev_t gpu, bool print) { + auto check = [&](const ggml_tensor * tensor, ggml_backend_dev_t want, const char * where) { + if (!t.assert_true("tensor is not null", tensor != nullptr)) { + return; + } + ggml_backend_dev_t dev = tensor_dev(tensor); + if (print) { + t.out << t.indent() << " " << tensor->name << " -> " << (dev ? ggml_backend_dev_name(dev) : "none") << "\n"; + } + if (gpu) { + t.assert_true(std::string(tensor->name) + " on " + where, dev != nullptr && dev == want && dev == gpu); + } else { + t.assert_true(std::string(tensor->name) + " on the CPU", dev != nullptr && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU); + } + }; + + for (int il = 0; il < n_layer; ++il) { + for (const auto & field : layer_fields) { + check(model.layers[il].*field.first, model.dev_layer(il), "dev_layer"); + } + } + for (const auto & field : global_fields) { + check(model.*field.first, model.dev_output(), "dev_output"); + } +} + +static void check_bytes(testing & t, const llama_model & model, const std::vector & tensors) { + const auto map = tensor_map(model); + for (const auto & expected : tensors) { + const auto it = map.find(expected.name); + if (!t.assert_true(expected.name + " is loaded", it != map.end())) { + continue; + } + const ggml_tensor * tensor = it->second; + if (!t.assert_equal(expected.name + " size", expected.data.size(), ggml_nbytes(tensor))) { + continue; + } + std::vector got(ggml_nbytes(tensor)); + ggml_backend_tensor_get(tensor, got.data(), 0, got.size()); + t.assert_true(expected.name + " bytes", got == expected.data); + } +} + +// the DFly summary of llama_model::print_info, at INFO level +static void check_print_info(testing & t, const std::vector & infos, const dfly_dims & d) { + const std::vector expected = { + "n_lora_q = " + std::to_string(d.n_lora_q), + "n_lora_kv = " + std::to_string(d.n_lora_kv), + "n_embd_head_k_mla = " + std::to_string(d.n_nope + d.n_rot), + "n_embd_head_v_mla = " + std::to_string(d.n_v), + "dfly_schema_version = 1", + "dfly_block_size = " + std::to_string(d.block_size), + "dfly_target_kv_layers = " + list_str(d.target_layers), + "dfly_index_layers = " + list_str(d.target_layers), + "dfly_index_top_k = " + std::to_string(d.top_k), + "dfly_correction_len = " + std::to_string(d.n_corr), + "dfly_confidence_head = present", + "dfly_source_mrope = " + list_str(d.mrope_sections), + }; + for (const auto & line : expected) { + if (!t.assert_true("print_info: " + line, has_line(infos, { "print_info: " + line + "\n" }))) { + print_lines(t, "INFO", infos); + return; + } + } +} + +static void test_load_pos(testing & t) { + const dfly_dims d; + dfly_file f; + write_dfly(f, d); + + llama_model_ptr model; + std::vector infos; + std::vector warnings; + std::vector errors; + bool tried = false; + + // loaded once, by the first test that needs it (LP-01 unless filtered out) + auto load = [&](testing & t) { + if (!tried) { + tried = true; + log_capture logs; + model = load_dfly(f.path); + infos = logs.get(GGML_LOG_LEVEL_INFO); + warnings = logs.get(GGML_LOG_LEVEL_WARN); + errors = logs.get(GGML_LOG_LEVEL_ERROR); + } + if (!t.assert_true("the tiny model loads", model != nullptr)) { + print_lines(t, "ERROR", errors); + return false; + } + return true; + }; + + t.test("LP-01_hparams", [&](testing & t) { + if (!load(t)) { + return; + } + const llama_hparams & hp = model->hparams; + const llama_vocab * vocab = llama_model_get_vocab(model.get()); + + t.assert_equal("schema_version", 1u, hp.dfly_schema_version); + t.assert_equal("block_size", d.block_size, hp.dfly_block_size); + t.assert_true ("attention.causal", hp.causal_attn); + t.assert_equal("block_count", (uint32_t) n_layer, hp.n_layer_all); + t.assert_equal("context_length", d.n_ctx, hp.n_ctx_train); + t.assert_equal("embedding_length", d.n_embd, hp.n_embd); + t.assert_equal("feed_forward_length", d.n_ff, hp.n_ff()); + t.assert_equal("head_count", d.n_head, hp.n_head()); + t.assert_equal("head_count_kv", 1u, hp.n_head_kv()); + t.assert_equal("q_lora_rank", d.n_lora_q, hp.n_lora_q); + t.assert_equal("kv_lora_rank", d.n_lora_kv, hp.n_lora_kv); + t.assert_equal("key_length", d.n_lora_kv + d.n_rot, hp.n_embd_head_k()); + t.assert_equal("value_length", d.n_lora_kv, hp.n_embd_head_v()); + t.assert_equal("key_length_mla", d.n_nope + d.n_rot, hp.n_embd_head_k_mla()); + t.assert_equal("value_length_mla", d.n_v, hp.n_embd_head_v_mla()); + t.assert_equal("rope.dimension_count", d.n_rot, hp.n_rot()); + t.assert_equal("rope.freq_base", d.theta, hp.rope_freq_base_train); + t.assert_equal("layer_norm_rms_epsilon", d.eps, hp.f_norm_rms_eps); + t.assert_equal("target_kv_layers", list_str(d.target_layers), list_str(hp.dfly_target_kv_layers)); + t.assert_equal("target_index_layers", list_str(d.target_layers), list_str(hp.dfly_target_index_layers)); + t.assert_equal("target_index_top_k", d.top_k, hp.dfly_target_index_top_k); + t.assert_equal("hidden_correction_length", d.n_corr, hp.dfly_hidden_correction_length); + t.assert_true ("has_confidence_head", hp.dfly_has_confidence_head); + t.assert_equal("source_mrope_sections", list_str(d.mrope_sections), list_str(hp.dfly_source_mrope_sections)); + t.assert_equal("n_vocab", (int32_t) d.n_vocab, llama_vocab_n_tokens(vocab)); + t.assert_equal("mask", (llama_token) d.mask, llama_vocab_mask(vocab)); + t.assert_equal("rope type", (int) LLAMA_ROPE_TYPE_NORM, (int) hp.rope_type); + + // fields with another meaning in other drafts stay unset + t.assert_equal("dflash_block_size", 0u, hp.dflash_block_size); + t.assert_equal("indexer_top_k", 0u, hp.indexer_top_k); + t.assert_equal("rope_sections", list_str(std::vector(4, 0)), list_str(hp.rope_sections)); + t.assert_true ("target_layer_ids", model->target_layer_ids.empty()); + }); + + t.test("LP-02_fields", [&](testing & t) { + if (!load(t)) { + return; + } + for (int il = 0; il < n_layer; ++il) { + for (const auto & field : layer_fields) { + const ggml_tensor * tensor = model->layers[il].*field.first; + const std::string name = "blk." + std::to_string(il) + "." + field.second; + if (t.assert_true(name + " is set", tensor != nullptr)) { + t.assert_equal(name, name, std::string(tensor->name)); + } + } + } + for (const auto & field : global_fields) { + const ggml_tensor * tensor = model.get()->*field.first; + if (t.assert_true(std::string(field.second) + " is set", tensor != nullptr)) { + t.assert_equal(field.second, std::string(field.second), std::string(tensor->name)); + } + } + // borrowed from the target in S5b + t.assert_true("tok_embd is null", model->tok_embd == nullptr); + t.assert_true("output is null", model->output == nullptr); + }); + + t.test("LP-03_bytes", [&](testing & t) { + if (!load(t)) { + return; + } + check_bytes(t, *model, f.tensors); + }); + + t.test("LP-04_n_params", [&](testing & t) { + if (!load(t)) { + return; + } + t.assert_equal("formula", dfly_n_params(d), llama_model_n_params(model.get())); + // plan appendix A at the tiny dims: 5 x 6,843 + 5,161 + t.assert_equal("literal", (uint64_t) 39376, llama_model_n_params(model.get())); + t.assert_equal("tensors", (size_t) 92, model->tensors_by_name.size()); + + int n_f32 = 0; + int n_bf16 = 0; + for (const auto & it : model->tensors_by_name) { + n_f32 += it.second->type == GGML_TYPE_F32; + n_bf16 += it.second->type == GGML_TYPE_BF16; + } + t.assert_equal("F32", 38, n_f32); + t.assert_equal("BF16", 54, n_bf16); + }); + + t.test("LP-05_warnings", [&](testing & t) { + if (!load(t)) { + return; + } + const std::string prefix = "hy_v4_next_dfly: "; + std::multiset keys; + for (const auto & line : warnings) { + if (line.rfind(prefix, 0) == 0) { + const size_t end = line.find(' ', prefix.size()); + keys.insert(line.substr(prefix.size(), end - prefix.size())); + } + } + const std::multiset expected = { + key_name(LLM_KV_EMBEDDING_LENGTH), + key_name(LLM_KV_FEED_FORWARD_LENGTH), + key_name(LLM_KV_ATTENTION_HEAD_COUNT), + key_name(LLM_KV_ATTENTION_Q_LORA_RANK), + key_name(LLM_KV_ATTENTION_KV_LORA_RANK), + key_name(LLM_KV_ATTENTION_KEY_LENGTH_MLA), // Dn + key_name(LLM_KV_ROPE_DIMENSION_COUNT), + key_name(LLM_KV_ATTENTION_VALUE_LENGTH_MLA), + key_name(LLM_KV_DFLY_TARGET_KV_LAYERS), + key_name(LLM_KV_DFLY_TARGET_INDEX_LAYERS), + key_name(LLM_KV_DFLY_TARGET_INDEX_TOP_K), + key_name(LLM_KV_TOKENIZER_MASK_ID), + "tokenizer.ggml.tokens", + }; + if (!t.assert_true("warned keys", keys == expected)) { + print_lines(t, "WARN", warnings); + } + }); + + t.test("LP-06_block_size_and_f16", [&](testing & t) { + for (uint32_t b : { 2u, 5u }) { + dfly_dims db; + db.block_size = b; + dfly_file fb; + write_dfly(fb, db); + llama_model_ptr mb = load_dfly(fb.path); + if (t.assert_true("B=" + std::to_string(b) + " loads", mb != nullptr)) { + t.assert_equal("block_size", b, mb->hparams.dfly_block_size); + } + } + + dfly_file fh; + write_dfly(fh, d, {}, {}, GGML_TYPE_F16); + llama_model_ptr mh = load_dfly(fh.path); + if (t.assert_true("F16 loads", mh != nullptr)) { + int n_f32 = 0; + int n_f16 = 0; + for (const auto & it : mh->tensors_by_name) { + n_f32 += it.second->type == GGML_TYPE_F32; + n_f16 += it.second->type == GGML_TYPE_F16; + } + t.assert_equal("F32", 38, n_f32); + t.assert_equal("F16", 54, n_f16); + check_bytes(t, *mh, fh.tensors); + } + }); + + t.test("LP-06b_q8_0", [&](testing & t) { + dfly_file fq; + write_dfly(fq, dfly_dims_second(), {}, {}, GGML_TYPE_Q8_0); + llama_model_ptr mq = load_dfly(fq.path); + if (t.assert_true("Q8_0 loads", mq != nullptr)) { + int n_f32 = 0; + int n_q8 = 0; + for (const auto & it : mq->tensors_by_name) { + n_f32 += it.second->type == GGML_TYPE_F32; + n_q8 += it.second->type == GGML_TYPE_Q8_0; + } + t.assert_equal("F32", 38, n_f32); + t.assert_equal("Q8_0", 54, n_q8); + check_bytes(t, *mq, fq.tensors); + } + }); + + t.test("LP-07_second_dims", [&](testing & t) { + const dfly_dims d2 = dfly_dims_second(); + dfly_file f2; + write_dfly(f2, d2); + llama_model_ptr m2 = load_dfly(f2.path); + if (t.assert_true("loads", m2 != nullptr)) { + t.assert_equal("n_params", dfly_n_params(d2), llama_model_n_params(m2.get())); + t.assert_equal("target_kv_layers", list_str(d2.target_layers), list_str(m2->hparams.dfly_target_kv_layers)); + t.assert_equal("target_index_top_k", d2.top_k, m2->hparams.dfly_target_index_top_k); + } + }); + + t.test("LP-08a_devices_cpu", [&](testing & t) { + if (!load(t)) { + return; + } + check_devices(t, *model, nullptr, t.verbose); + }); + + t.test("LP-08b_devices_gpu", [&](testing & t) { + ggml_backend_dev_t gpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); + if (gpu == nullptr) { + t.skip("no GPU"); + return; + } + llama_model_ptr mg = load_dfly(f.path, gpu); + if (t.assert_true("loads on " + std::string(ggml_backend_dev_name(gpu)), mg != nullptr)) { + check_devices(t, *mg, gpu, t.verbose); + } + }); + + t.test("LP-09_no_memory", [&](testing & t) { + if (!load(t)) { + return; + } + llama_memory_params mparams = {}; + mparams.type_k = GGML_TYPE_F16; + mparams.type_v = GGML_TYPE_F16; + mparams.ctx_type = LLAMA_CONTEXT_TYPE_DEFAULT; + llama_cparams cparams = {}; + std::unique_ptr mem(model->create_memory(mparams, cparams)); + t.assert_true("create_memory returns null", mem == nullptr); + }); + + t.test("LP-10_production_shapes", [&](testing & t) { + const auto shapes = dfly_shapes(dfly_dims_production()); + const auto prod = prod_ne(); + t.assert_equal("count", (size_t) 92, shapes.size()); + for (size_t i = 0; i < shapes.size(); ++i) { + t.assert_equal("name " + std::to_string(i), expected_tensor_names.at(i), shapes[i].name); + const auto it = prod.find(shapes[i].name); + if (t.assert_true(shapes[i].name + " has a production ne", it != prod.end())) { + t.assert_equal(shapes[i].name, list_str(it->second), list_str(shapes[i].ne)); + } + } + t.assert_equal("n_params", prod_n_params, dfly_n_params(dfly_dims_production())); + }); + + t.test("LP-11_print_info", [&](testing & t) { + if (!load(t)) { + return; + } + check_print_info(t, infos, d); + }); +} + +static void test_load_neg(testing & t) { + const dfly_dims d; + + t.test("LN-01_no_schema_version", [](testing & t) { + check_fail(t, { "missing key hy_v4_next_dfly.schema_version" }, remove_key(LLM_KV_DFLY_SCHEMA_VERSION)); + }); + t.test("LN-01b_all_key_errors_listed", [](testing & t) { + check_fail(t, { "missing key hy_v4_next_dfly.schema_version", "unknown key hy_v4_next_dfly.foo" }, + [](gguf_context * ctx, kv_writer &) { + gguf_remove_key(ctx, key_name(LLM_KV_DFLY_SCHEMA_VERSION).c_str()); + gguf_set_val_u32(ctx, "hy_v4_next_dfly.foo", 1); + }); + }); + t.test("LN-02_schema_version_2", [](testing & t) { + check_fail(t, { "unknown schema: hy_v4_next_dfly.schema_version = 2" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_SCHEMA_VERSION, uint32_t(2)); + }); + }); + t.test("LN-03_no_block_size", [](testing & t) { + check_fail(t, { "missing key hy_v4_next_dfly.block_size" }, remove_key(LLM_KV_DFLASH_BLOCK_SIZE)); + }); + t.test("LN-04_block_size_1", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.block_size = 1 must be >= 2" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLASH_BLOCK_SIZE, uint32_t(1)); + }); + }); + t.test("LN-05_no_causal", [](testing & t) { + check_fail(t, { "missing key hy_v4_next_dfly.attention.causal" }, remove_key(LLM_KV_ATTENTION_CAUSAL)); + }); + t.test("LN-06_causal_false", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.attention.causal = false", "non-causal" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_CAUSAL, false); + }); + }); + t.test("LN-07_block_count_4", [](testing & t) { + // the lists shrink too, so only the block count rule can fail; blk.4.* stays in the file + check_fail(t, { "hy_v4_next_dfly.block_count = 4 must be 5" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_BLOCK_COUNT, uint32_t(4)); + kv.add_kv(LLM_KV_DFLY_TARGET_KV_LAYERS, std::vector{ 3, 5, 7, 9 }); + kv.add_kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS, std::vector{ 3, 5, 7, 9 }); + }); + }); + t.test("LN-07b_block_count_0", [](testing & t) { + // without the early check the generic loader asserts on this + check_fail(t, { "hy_v4_next_dfly.block_count = 0 must be 5" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_BLOCK_COUNT, uint32_t(0)); + }); + }); + t.test("LN-08a_no_context_length", [](testing & t) { + check_fail(t, { "missing key hy_v4_next_dfly.context_length" }, remove_key(LLM_KV_CONTEXT_LENGTH)); + }); + t.test("LN-08b_context_length_0", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.context_length = 0 must be > 0" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_CONTEXT_LENGTH, uint32_t(0)); + }); + }); + t.test("LN-09_head_count_kv_2", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.attention.head_count_kv = 2 must be 1" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, uint32_t(2)); + }); + }); + t.test("LN-10_key_length", [&](testing & t) { + check_fail(t, { "hy_v4_next_dfly.attention.key_length = 27 must be kv_lora_rank + rope.dimension_count = 26" }, + [&](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_KEY_LENGTH, d.n_lora_kv + d.n_rot + 1); + }); + }); + t.test("LN-11_value_length", [&](testing & t) { + check_fail(t, { "hy_v4_next_dfly.attention.value_length = 23 must be kv_lora_rank = 22" }, [&](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH, d.n_lora_kv + 1); + }); + }); + t.test("LN-12_no_nope", [&](testing & t) { + check_fail(t, { "hy_v4_next_dfly.attention.key_length_mla = 4 must be larger than rope.dimension_count = 4" }, + [&](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA, d.n_rot); + }); + }); + t.test("LN-13_odd_rope", [](testing & t) { + // key_length, key_length_mla and the shapes follow Dr + dfly_dims dr; + dr.n_rot = 5; + check_fail(t, { "hy_v4_next_dfly.rope.dimension_count = 5 must be even" }, {}, {}, {}, dr); + }); + t.test("LN-14_kv_layers_int32", [&](testing & t) { + check_fail(t, { "key hy_v4_next_dfly.target_kv_layers has type arr[i32], expected arr[u32]" }, [&](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_TARGET_KV_LAYERS, std::vector(d.target_layers.begin(), d.target_layers.end())); + }); + }); + t.test("LN-15_layers_length_4", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.target_kv_layers has 4 entries, expected block_count = 5" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_TARGET_KV_LAYERS, std::vector{ 3, 5, 7, 9 }); + kv.add_kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS, std::vector{ 3, 5, 7, 9 }); + }); + }); + t.test("LN-16_layers_duplicate", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.target_kv_layers has duplicate layer 5" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_TARGET_KV_LAYERS, std::vector{ 3, 5, 5, 9, 11 }); + kv.add_kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS, std::vector{ 3, 5, 5, 9, 11 }); + }); + }); + t.test("LN-17_index_layers_differ", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.target_index_layers = [3, 5, 7, 9, 13] must equal hy_v4_next_dfly.target_kv_layers" }, + [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_TARGET_INDEX_LAYERS, std::vector{ 3, 5, 7, 9, 13 }); + }); + }); + t.test("LN-18a_mrope_int32", [](testing & t) { + check_fail(t, { "key hy_v4_next_dfly.source_mrope_sections has type arr[i32], expected arr[u32]" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, std::vector{ 1, 1, 0 }); + }); + }); + t.test("LN-18b_mrope_length_2", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.source_mrope_sections has 2 entries, expected 3" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, std::vector{ 1, 1 }); + }); + }); + t.test("LN-18c_mrope_sum", [](testing & t) { + // the training M-RoPE needs the sections to sum to Dr/2 = 2 + check_fail(t, { "hy_v4_next_dfly.source_mrope_sections = [1, 1, 1] sums to 3, expected rope.dimension_count / 2 = 2" }, + [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, std::vector{ 1, 1, 1 }); + }); + }); + t.test("LN-18d_mrope_sum_overflow", [](testing & t) { + // wraps to 2 in uint32 + check_fail(t, { "hy_v4_next_dfly.source_mrope_sections = [4294967295, 3, 0] sums to 4294967298" }, + [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_SOURCE_MROPE_SECTIONS, std::vector{ 4294967295u, 3, 0 }); + }); + }); + t.test("LN-19_no_confidence_head", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.has_confidence_head = false must be true" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_HAS_CONFIDENCE_HEAD, false); + }); + }); + t.test("LN-20a_mtp_fusion", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.mtp_fusion = 'slot1' must be 'slot0'" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_MTP_FUSION, "slot1"); + }); + }); + t.test("LN-20b_rope_layout", [](testing & t) { + check_fail(t, { "hy_v4_next_dfly.rope_layout = 'neox' must be 'norm_adjacent'" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLY_ROPE_LAYOUT, "neox"); + }); + }); + t.test("LN-21_expert_used_count", [](testing & t) { + // without the key set check first, the generic loader aborts on this + check_fail(t, { "unknown key hy_v4_next_dfly.expert_used_count" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_EXPERT_USED_COUNT, uint32_t(2)); + }); + }); + t.test("LN-22_indexer_top_k", [](testing & t) { + check_fail(t, { "unknown key hy_v4_next_dfly.attention.indexer.top_k" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_INDEXER_TOP_K, uint32_t(16)); + }); + }); + t.test("LN-23_head_count_per_layer", [&](testing & t) { + check_fail(t, { "key hy_v4_next_dfly.attention.head_count has type arr[u32], expected u32" }, [&](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, std::vector(n_layer, d.n_head)); + }); + }); + t.test("LN-24_block_size_int32", [](testing & t) { + check_fail(t, { "key hy_v4_next_dfly.block_size has type i32, expected u32" }, [](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_DFLASH_BLOCK_SIZE, int32_t(8)); + }); + }); + t.test("LN-25_prism", [](testing & t) { + check_fail(t, { "prism.hadamard is not supported: prism.hadamard.version" }, [](gguf_context * ctx, kv_writer &) { + gguf_set_val_u32(ctx, "prism.hadamard.version", 1); + }); + }); + t.test("LN-26_no_mask", [](testing & t) { + check_fail(t, { "missing key tokenizer.ggml.mask_token_id" }, remove_key(LLM_KV_TOKENIZER_MASK_ID)); + }); + t.test("LN-27_mask_out_of_vocab", [&](testing & t) { + // the vocab only warns and drops it + check_fail(t, { "tokenizer.ggml.mask_token_id = 40 is out of the vocab of 40 tokens" }, [&](gguf_context *, kv_writer & kv) { + kv.add_kv(LLM_KV_TOKENIZER_MASK_ID, d.n_vocab); + }); + }); + t.test("LN-28_missing_tensor", [](testing & t) { + check_fail(t, { "tensor 'blk.4.attn_sinks.weight' not found" }, {}, [](std::vector & tensors) { + tensors.erase(std::find_if(tensors.begin(), tensors.end(), [](const dfly_tensor & x) { return x.name == "blk.4.attn_sinks.weight"; })); + }); + }); + t.test("LN-29_k_b_transposed", [&](testing & t) { + check_fail(t, { "tensor 'blk.2.attn_k_b.weight' has wrong shape" }, {}, [&](std::vector & tensors) { + for (auto & x : tensors) { + if (x.name == "blk.2.attn_k_b.weight") { + x.ne = { d.n_lora_kv, d.n_nope, d.n_head }; + } + } + }); + }); + t.test("LN-30_correction_down_transposed", [&](testing & t) { + check_fail(t, { "tensor 'dfly_correction_down.weight' has wrong shape" }, {}, [&](std::vector & tensors) { + for (auto & x : tensors) { + if (x.name == "dfly_correction_down.weight") { + x.ne = { d.n_embd, d.n_corr }; + } + } + }); + }); + t.test("LN-31_extra_token_embd", [&](testing & t) { + check_fail(t, { "unknown tensors: token_embd.weight" }, {}, [&](std::vector & tensors) { + tensors.push_back({ "token_embd.weight", { d.n_embd, d.n_vocab }, GGML_TYPE_BF16, {} }); + }); + }); + t.test("LN-32_extra_ffn_gate_inp", [&](testing & t) { + check_fail(t, { "unknown tensors: blk.0.ffn_gate_inp.weight" }, {}, [&](std::vector & tensors) { + tensors.push_back({ "blk.0.ffn_gate_inp.weight", { d.n_embd, 8 }, GGML_TYPE_F32, {} }); + }); + }); + t.test("LN-33_ffn_up_f32", [](testing & t) { + check_fail(t, { "tensor blk.0.ffn_up.weight has type f32, expected bf16, f16 or q8_0" }, {}, [](std::vector & tensors) { + for (auto & x : tensors) { + if (x.name == "blk.0.ffn_up.weight") { + x.type = GGML_TYPE_F32; + } + } + }); + }); + t.test("LN-34_fusion_gate_bf16", [](testing & t) { + check_fail(t, { "tensor dfly_fusion_gate.weight has type bf16, expected f32" }, {}, [](std::vector & tensors) { + for (auto & x : tensors) { + if (x.name == "dfly_fusion_gate.weight") { + x.type = GGML_TYPE_BF16; + } + } + }); + }); + t.test("LN-35_duplicate_tensor", [](testing & t) { + // gguf_add_tensor aborts on a duplicate, so rename q_b to q_a in the written header; the gguf reader rejects it + check_fail(t, { "duplicate tensor name 'blk.0.attn_q_a.weight'" }, {}, {}, [](std::vector & bytes) { + const std::string from = "blk.0.attn_q_b.weight"; + const std::string to = "blk.0.attn_q_a.weight"; + const auto it = std::search(bytes.begin(), bytes.end(), from.begin(), from.end()); + GGML_ASSERT(it != bytes.end()); + std::copy(to.begin(), to.end(), it); + }); + }); +} + +template +static void expect_throw(testing & t, const std::string & what, F f, const std::string & needle) { + try { + f(); + t.assert_true(what + " throws", false); + } catch (const std::exception & e) { + t.assert_true(what + " names " + needle, std::string(e.what()).find(needle) != std::string::npos); + } +} + +static void test_checks(testing & t) { + t.test("LV-01_real_table", [](testing & t) { + t.assert_equal("bad types", (size_t) 0, hy_v4_next_dfly_check_tensor_infos(llm_tensor_info_for).size()); + }); + + t.test("LV-02_op_none", [](testing & t) { + const auto bad = hy_v4_next_dfly_check_tensor_infos([](llm_tensor type) { + llm_tensor_info info = llm_tensor_info_for(type); + if (type == LLM_TENSOR_ATTN_Q_B) { + info.op = GGML_OP_NONE; + } + return info; + }); + t.assert_true("only attn_q_b", bad == std::vector{ LLM_TENSOR_ATTN_Q_B }); + }); + + t.test("LV-03_wrong_layer", [](testing & t) { + const auto bad = hy_v4_next_dfly_check_tensor_infos([](llm_tensor type) { + llm_tensor_info info = llm_tensor_info_for(type); + if (type == LLM_TENSOR_DFLY_FUSION_EH) { + info.layer = LLM_TENSOR_LAYER_INPUT; + } + if (type == LLM_TENSOR_OUTPUT_NORM) { + info.layer = LLM_TENSOR_LAYER_REPEATING; + } + return info; + }); + const std::set got(bad.begin(), bad.end()); + t.assert_equal("count", (size_t) 2, bad.size()); + t.assert_true("dfly_fusion_eh and output_norm", got == std::set{ LLM_TENSOR_DFLY_FUSION_EH, LLM_TENSOR_OUTPUT_NORM }); + }); + + t.test("LV-04_no_entry", [](testing & t) { + const auto bad = hy_v4_next_dfly_check_tensor_infos([](llm_tensor type) { + if (type == LLM_TENSOR_DFLY_CORRECTION_UP) { + throw std::out_of_range("no entry"); + } + return llm_tensor_info_for(type); + }); + t.assert_true("only dfly_correction_up", bad == std::vector{ LLM_TENSOR_DFLY_CORRECTION_UP }); + }); + + t.test("LV-05_bounds", [](testing & t) { + const uint32_t v_max = 1u << 24; + try { + hy_v4_next_dfly_check_vocab(v_max, 37, 37); + t.assert_true("V = 2^24 passes", true); + } catch (const std::exception & e) { + t.assert_true(std::string("V = 2^24 passes: ") + e.what(), false); + } + expect_throw(t, "V = 2^24 + 1", [&] { hy_v4_next_dfly_check_vocab(v_max + 1, 37, 37); }, "tokenizer.ggml.tokens"); + expect_throw(t, "V = 0", [&] { hy_v4_next_dfly_check_vocab(0, 0, -1); }, "tokenizer.ggml.tokens"); + + // the tiny dims with Dr = 0 and the derived lengths following it + const dfly_dims d; + hy_v4_next_dfly_dims dims; + dims.n_layer = n_layer; + dims.n_ctx_train = d.n_ctx; + dims.n_embd = d.n_embd; + dims.n_ff = d.n_ff; + dims.n_head = d.n_head; + dims.n_head_kv = 1; + dims.n_lora_q = d.n_lora_q; + dims.n_lora_kv = d.n_lora_kv; + dims.n_embd_head_k = d.n_lora_kv; + dims.n_embd_head_v = d.n_lora_kv; + dims.n_embd_head_k_mla = d.n_nope; + dims.n_embd_head_v_mla = d.n_v; + dims.n_rot = 0; + dims.rope_freq_base = d.theta; + dims.norm_rms_eps = d.eps; + dims.target_kv_layers = d.target_layers; + dims.target_index_layers = d.target_layers; + dims.source_mrope_sections = d.mrope_sections; + dims.target_index_top_k = d.top_k; + dims.hidden_correction_length = d.n_corr; + expect_throw(t, "Dr = 0", [&] { hy_v4_next_dfly_check_dims(dims); }, "hy_v4_next_dfly.rope.dimension_count"); + + dims.n_rot = d.n_rot; + dims.n_embd_head_k = d.n_lora_kv + d.n_rot; + dims.n_embd_head_k_mla = d.n_nope + d.n_rot; + try { + t.assert_equal("tiny dims warn 11 times", (size_t) 11, hy_v4_next_dfly_check_dims(dims).size()); + } catch (const std::exception & e) { + t.assert_true(std::string("tiny dims pass: ") + e.what(), false); + } + }); +} + +// +// the target's top-k normalized into the DFly context (llama-dfly.h), and kpool_copy_refs +// + +using kpool_refs = llama_memory_idx_iswa::kpool_refs; + +// the memory's kpool_pad: max(64, GGML_PAD(n + 1, 64)), whose last pool is never used +static uint32_t sel_pad(int64_t n_pool_real) { + return std::max(64u, GGML_PAD((uint32_t) n_pool_real + 1, 64u)); +} + +// a test model of one sequence as kpool_copy_refs reports it: positions 0..n_pos-1, cut into groups of 4 +struct sel_seq { + int64_t n_pos = 0; + int id_map = 0; // 0: id = group, 1: another sequence owns pools 0..4 first, 2: as 1 with the groups reversed + bool bij = false; // cell = (37*pos + 11) % 1000003 instead of cell = pos + uint32_t strm = 0; + + int64_t n_groups() const { return n_pos / 4; } + int64_t pool_begin() const { return id_map == 0 ? 0 : 5; } + int64_t n_pool_real() const { return pool_begin() + n_groups(); } + + int32_t id_of(int64_t h) const { + return (int32_t) (pool_begin() + (id_map == 2 ? n_groups() - 1 - h : h)); + } + + // -1 when id is no pool of this sequence + int64_t group_of(int64_t id) const { + const int64_t k = id - pool_begin(); + if (k < 0 || k >= n_groups()) { + return -1; + } + return id_map == 2 ? n_groups() - 1 - k : k; + } + + uint32_t cell_of(int64_t pos) const { + return bij ? (uint32_t) ((37*pos + 11) % 1000003) : (uint32_t) pos; + } +}; + +static kpool_refs sel_refs(const sel_seq & sq, llama_pos p, const std::vector & ids) { + kpool_refs r; + r.kpool = 4; + r.strm = sq.strm; + r.pool_begin = (uint32_t) sq.pool_begin(); + r.n_pools = (uint32_t) sq.n_groups(); + + r.found.assign(ids.size(), 0); + r.pos .assign(ids.size()*4, 0); + r.cell .assign(ids.size()*4, 0); + for (size_t i = 0; i < ids.size(); ++i) { + const int64_t h = sq.group_of(ids[i]); + if (h < 0) { + continue; + } + r.found[i] = 1; + for (int64_t k = 0; k < 4; ++k) { + r.pos [i*4 + k] = (llama_pos) (4*h + k); + r.cell[i*4 + k] = sq.cell_of(4*h + k); + } + } + + const int64_t g = p / 4; + r.n_hist_avail = (uint32_t) std::min(g, sq.n_groups()); + r.n_cells_upto_p = (uint32_t) std::min((int64_t) p + 1, sq.n_pos); + for (int64_t x = 4*g; x <= std::min(p, sq.n_pos - 1); ++x) { + r.cur_pos .push_back((llama_pos) x); + r.cur_cell.push_back(sq.cell_of(x)); + } + + return r; +} + +// one row of the target's top-k as it would be exported +struct sel_export { + std::vector ids; + std::vector scores; + + void add(int32_t id, float score) { + ids.push_back(id); + scores.push_back(score); + } + + void insert(size_t at, int32_t id, float score) { + ids .insert(ids .begin() + at, id); + scores.insert(scores.begin() + at, score); + } + + void shuffle(std::mt19937 & rng) { + std::vector perm(ids.size()); + std::iota(perm.begin(), perm.end(), 0); + std::shuffle(perm.begin(), perm.end(), rng); + sel_export res; + for (size_t i : perm) { + res.add(ids[i], scores[i]); + } + *this = res; + } +}; + +// as ggml_top_k gives it: the n_top best of [0, pad(n_pool_real)), unordered, ties broken at random +// score_of returns -inf for every pool the row cannot see +static sel_export sel_topk(std::mt19937 & rng, int64_t n_pool_real, uint32_t S, const std::function & score_of) { + const uint32_t n_pad = sel_pad(n_pool_real); + const uint32_t n_top = std::min(n_pad, S/4); + + std::vector> cand; + cand.reserve(n_pad); + for (uint32_t id = 0; id < n_pad; ++id) { + cand.emplace_back((int32_t) id, score_of((int32_t) id)); + } + std::shuffle(cand.begin(), cand.end(), rng); + std::stable_sort(cand.begin(), cand.end(), [](const auto & a, const auto & b) { return a.second > b.second; }); + cand.resize(n_top); + std::shuffle(cand.begin(), cand.end(), rng); + + sel_export e; + for (const auto & c : cand) { + e.add(c.first, c.second); + } + return e; +} + +// integer scores in [-8, 8], so that many tie, for the groups of sq that end at or before p; -inf for the rest +static std::vector sel_scores(std::mt19937 & rng, const sel_seq & sq, llama_pos p) { + std::uniform_int_distribution dist(-8, 8); + std::vector gs(sq.n_groups(), -INFINITY); + for (int64_t h = 0; h < sq.n_groups() && 4*h + 3 <= p; ++h) { + gs[h] = (float) dist(rng); + } + return gs; +} + +static std::function sel_score_of(const sel_seq & sq, const std::vector & gs) { + return [sq, gs](int32_t id) { + const int64_t h = sq.group_of(id); + return h < 0 ? -INFINITY : gs[h]; + }; +} + +struct sel_result { + llama_dfly_sel_status status = LLAMA_DFLY_SEL_STATUS_INTERNAL; + llama_dfly_ctx_set out; + std::string err; +}; + +static sel_result sel_run(const sel_export & e, llama_pos p, uint32_t S, const kpool_refs & refs) { + sel_result r; + r.status = llama_dfly_normalize_selection(e.ids.data(), e.scores.data(), e.ids.size(), p, S, refs, r.out, r.err); + return r; +} + +// the history groups of a result, the whole groups below p's own one +static std::vector sel_hist(const llama_dfly_ctx_set & out, llama_pos p) { + std::vector res; + for (size_t k = 0; k < out.pos.size() && out.pos[k] < 4*(p/4); k += 4) { + res.push_back(out.pos[k] / 4); + } + return res; +} + +// TG-01 and the score rule for one row, "" when they hold +// group_of: the group of an exported id in this sequence or -1, gs[h]: the score the target gave group h +static std::string sel_check(const sel_result & r, llama_pos p, uint32_t S, const sel_export & e, + const std::function & group_of, const std::vector & gs, + const std::function & cell_of, uint32_t strm) { + if (r.status != LLAMA_DFLY_SEL_STATUS_OK) { + return "status " + std::to_string((int) r.status) + ": " + r.err; + } + const auto & pos = r.out.pos; + if (r.out.cell.size() != pos.size()) { + return "cell count"; + } + if (r.out.strm != strm) { + return "strm " + std::to_string(r.out.strm); + } + + const int64_t g = p / 4; + const int64_t H = S/4 - 1; + const size_t n_want = (size_t) (4*std::min(H, g) + p % 4 + 1); + if (pos.size() != n_want) { + return "count " + std::to_string(pos.size()) + ", want " + std::to_string(n_want); + } + for (size_t k = 0; k < pos.size(); ++k) { + if (pos[k] < 0 || pos[k] > p || (k > 0 && pos[k - 1] >= pos[k])) { + return "position " + std::to_string(pos[k]) + " at " + std::to_string(k); + } + if (r.out.cell[k] != cell_of(pos[k])) { + return "cell of position " + std::to_string(pos[k]); + } + } + + // ends with all of p's own group + const size_t n_cur = (size_t) (p % 4 + 1); + for (size_t k = 0; k < n_cur; ++k) { + if (pos[pos.size() - n_cur + k] != 4*g + (int64_t) k) { + return "p's own group"; + } + } + if (p < (llama_pos) S) { + for (size_t k = 0; k < pos.size(); ++k) { + if (pos[k] != (llama_pos) k) { + return "not [0, p]"; + } + } + } + + std::set sel; + for (size_t k = 0; k + n_cur < pos.size(); k += 4) { + const int64_t h = pos[k] / 4; + for (int64_t m = 0; m < 4; ++m) { + if (pos[k + m] != 4*h + m) { + return "partial group at " + std::to_string(pos[k]); + } + } + sel.insert(h); + } + if ((int64_t) sel.size() != std::min(H, g)) { + return "history groups " + std::to_string(sel.size()); + } + + std::set exported; + for (size_t i = 0; i < e.ids.size(); ++i) { + const int64_t h = group_of(e.ids[i]); + if (e.scores[i] != -INFINITY && h >= 0 && h < g) { + exported.insert(h); + } + } + for (int64_t h : sel) { + if (!exported.count(h)) { + return "group " + std::to_string(h) + " was not exported"; + } + } + if (sel.empty()) { + return ""; + } + + // the worst kept group: lowest score, then highest group + int64_t w = -1; + for (int64_t h : sel) { + if (w < 0 || gs[h] < gs[w] || (gs[h] == gs[w] && h > w)) { + w = h; + } + } + for (int64_t h = 0; h < g; ++h) { + if (sel.count(h) || gs[h] == -INFINITY) { + continue; + } + if (exported.count(h) && !(gs[h] < gs[w] || (gs[h] == gs[w] && h > w))) { + return "dropped group " + std::to_string(h) + " ranks above kept group " + std::to_string(w); + } + if (!exported.count(h) && gs[h] > gs[w]) { + return "unexported group " + std::to_string(h) + " scores above kept group " + std::to_string(w); + } + } + + return ""; +} + +static std::string sel_check_seq(const sel_result & r, llama_pos p, uint32_t S, const sel_export & e, + const sel_seq & sq, const std::vector & gs) { + return sel_check(r, p, S, e, [&](int32_t id) { return sq.group_of(id); }, gs, + [&](llama_pos x) { return sq.cell_of(x); }, sq.strm); +} + +// p, the positions the target selects itself, and the DFly count; from dfly-r4/selection-original.log +static const int32_t sn02_rows[][3] = { + { 0, 1, 1 }, + { 1, 2, 2 }, + { 2, 3, 3 }, + { 3, 4, 4 }, + { 4, 5, 5 }, + { 63, 64, 64 }, + { 2043, 2044, 2044 }, + { 2044, 2045, 2045 }, + { 2045, 2046, 2046 }, + { 2046, 2047, 2047 }, + { 2047, 2048, 2048 }, + { 2048, 2049, 2045 }, + { 2049, 2050, 2046 }, + { 2050, 2051, 2047 }, + { 2051, 2048, 2048 }, + { 2052, 2049, 2045 }, + { 2055, 2048, 2048 }, +}; + +static void test_selection(testing & t) { + t.test("SN-01_tg01_sweep", [](testing & t) { + const uint32_t seed = 8540; + std::mt19937 rng(seed); + + std::vector ps; + for (llama_pos p = 0; p < 2100; ++p) { + ps.push_back(p); + } + for (llama_pos p : { 4095, 8191, 8192, 131071 }) { + ps.push_back(p); + } + + int n_case = 0; + int n_bad = 0; + const auto t_start = std::chrono::steady_clock::now(); + for (uint32_t S : { 8u, 16u, 2048u }) { + for (llama_pos p : ps) { + const int idx = n_case++; + // up to 8 later rows of a verify batch are already in the layout + sel_seq sq; + sq.n_pos = (int64_t) p + 1 + std::uniform_int_distribution(0, 7)(rng); + sq.id_map = idx % 3; + sq.bij = (idx / 3) % 2 == 1; + sq.strm = 1 + idx % 3; + + const auto gs = sel_scores(rng, sq, p); + const auto e = sel_topk(rng, sq.n_pool_real(), S, sel_score_of(sq, gs)); + const auto r = sel_run(e, p, S, sel_refs(sq, p, e.ids)); + + const std::string bad = sel_check_seq(r, p, S, e, sq, gs); + if (!bad.empty() && n_bad++ < 10) { + t.out << t.indent() << " case " << idx << " S=" << S << " p=" << p << " seed=" << seed << ": " << bad << "\n"; + } + } + } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t_start).count(); + t.out << t.indent() << " " << n_case << " cases in " << ms << " ms\n"; + + t.assert_equal("cases", 6312, n_case); + t.assert_equal("bad cases", 0, n_bad); + }); + + t.test("SN-02_production_bounds", [](testing & t) { + std::mt19937 rng(2048); + for (const auto & row : sn02_rows) { + const llama_pos p = row[0]; + const std::string what = "p=" + std::to_string(p); + + // the log models a layout that ends at p + sel_seq sq; + sq.n_pos = p + 1; + sq.bij = true; + + const auto gs = sel_scores(rng, sq, p); + const auto e = sel_topk(rng, sq.n_pool_real(), 2048, sel_score_of(sq, gs)); + const auto r = sel_run(e, p, 2048, sel_refs(sq, p, e.ids)); + + // what the target attends itself: its finite complete groups and its own tail of (p + 1) % 4 cells + const int64_t n_finite = std::count_if(e.scores.begin(), e.scores.end(), [](float s) { return s != -INFINITY; }); + t.assert_equal(what + " target count", (int64_t) row[1], 4*n_finite + (p + 1) % 4); + t.assert_equal(what + " DFly count", (size_t) row[2], r.out.pos.size()); + t.assert_equal(what + " TG-01", std::string(), sel_check_seq(r, p, 2048, e, sq, gs)); + } + + for (llama_pos p : { 4095, 8191, 8192, 131071 }) { + sel_seq sq; + sq.n_pos = p + 1; + const auto gs = sel_scores(rng, sq, p); + const auto e = sel_topk(rng, sq.n_pool_real(), 2048, sel_score_of(sq, gs)); + const auto r = sel_run(e, p, 2048, sel_refs(sq, p, e.ids)); + t.assert_equal("p=" + std::to_string(p) + " count", (size_t) (4*511 + p % 4 + 1), r.out.pos.size()); + } + }); + + // TG-02: p's own group is complete but scores lowest, so the target's top-k leaves it out + t.test("SN-03_tg02_complete_group_back", [](testing & t) { + for (uint32_t S : { 2048u, 8u, 16u }) { + const llama_pos p = (llama_pos) S + 3; + const int64_t g = p / 4; + const std::string what = "S=" + std::to_string(S) + " p=" + std::to_string(p); + + sel_seq sq; + sq.n_pos = p + 1; + sq.bij = true; + sq.strm = 1; + + // distinct history scores 0..g-1, so the kept set is unique + std::mt19937 rng(S); + std::vector gs(g + 1); + std::iota(gs.begin(), gs.begin() + g, 0.0f); + std::shuffle(gs.begin(), gs.begin() + g, rng); + gs[g] = -1.0f; + + const auto e = sel_topk(rng, sq.n_pool_real(), S, sel_score_of(sq, gs)); + std::set exported; + for (size_t i = 0; i < e.ids.size(); ++i) { + if (e.scores[i] != -INFINITY) { + exported.insert(sq.group_of(e.ids[i])); + } + } + std::set history; + for (int64_t h = 0; h < g; ++h) { + history.insert(h); + } + t.assert_true(what + ": the target keeps groups 0..g-1 and drops g", exported == history); + + const auto r = sel_run(e, p, S, sel_refs(sq, p, e.ids)); + t.assert_equal(what + " count", (size_t) S, r.out.pos.size()); + t.assert_true(what + ": ends with p's own group", r.out.pos.size() >= 4 && + std::vector(r.out.pos.end() - 4, r.out.pos.end()) == std::vector{ p - 3, p - 2, p - 1, p }); + + std::vector want; + for (int64_t h = 0; h < g; ++h) { + if (gs[h] != 0.0f) { + want.push_back(h); + } + } + t.assert_true(what + ": history is every group but the lowest", sel_hist(r.out, p) == want); + t.assert_equal(what + " TG-01", std::string(), sel_check_seq(r, p, S, e, sq, gs)); + } + }); + + t.test("SN-04_tg02_p_2050", [](testing & t) { + for (uint32_t S : { 2048u, 8u, 16u }) { + const llama_pos p = (llama_pos) S + 2; + const int64_t g = p / 4; + const std::string what = "S=" + std::to_string(S) + " p=" + std::to_string(p); + + sel_seq sq; + sq.n_pos = p + 1; + sq.bij = true; + + std::mt19937 rng(S + 1); + std::vector gs(g); + std::iota(gs.begin(), gs.end(), 0.0f); + std::shuffle(gs.begin(), gs.end(), rng); + + const auto e = sel_topk(rng, sq.n_pool_real(), S, sel_score_of(sq, gs)); + const int64_t n_finite = std::count_if(e.scores.begin(), e.scores.end(), [](float s) { return s != -INFINITY; }); + t.assert_equal(what + " target count", (int64_t) S + 3, 4*n_finite + (p + 1) % 4); + + const auto r = sel_run(e, p, S, sel_refs(sq, p, e.ids)); + t.assert_equal(what + " count", (size_t) S - 1, r.out.pos.size()); + + std::vector want; + for (int64_t h = 0; h < g; ++h) { + if (gs[h] != 0.0f) { + want.push_back(h); + } + } + t.assert_true(what + ": the lowest history group is dropped", sel_hist(r.out, p) == want); + t.assert_equal(what + " TG-01", std::string(), sel_check_seq(r, p, S, e, sq, gs)); + } + }); + + t.test("SN-05_ties_by_group", [](testing & t) { + // every history group exported with one score, ids in reverse group order: only the group decides + for (uint32_t S : { 16u, 2048u }) { + const llama_pos p = S == 16 ? 40 : 4095; + const int64_t g = p / 4; + + sel_seq sq; + sq.n_pos = p + 1; + sq.id_map = 2; + sq.bij = true; + sq.strm = 2; + + std::vector want(S/4 - 1); + std::iota(want.begin(), want.end(), 0); + + for (bool shuffled : { false, true }) { + const std::string what = "S=" + std::to_string(S) + (shuffled ? " shuffled" : " groups descending"); + + sel_export e; + for (int64_t h = g - 1; h >= 0; --h) { + e.add(sq.id_of(h), 1.0f); + } + if (shuffled) { + std::mt19937 rng(S); + e.shuffle(rng); + } + + const auto r = sel_run(e, p, S, sel_refs(sq, p, e.ids)); + t.assert_equal(what + " status", (int) LLAMA_DFLY_SEL_STATUS_OK, (int) r.status); + t.assert_true(what + ": the lowest groups are kept", sel_hist(r.out, p) == want); + } + } + + // the seed's limit case: a tie with an unexported group cannot be undone + sel_seq sq; + sq.n_pos = 4*((2051 + 8)/4); + const llama_pos p = 2051; + + sel_export e; + for (int32_t h = 1; h <= 512; ++h) { + e.add(h, 1.0f); + } + const auto r = sel_run(e, p, 2048, sel_refs(sq, p, e.ids)); + + std::vector want(511); + std::iota(want.begin(), want.end(), 1); + t.assert_equal("p=2051 status", (int) LLAMA_DFLY_SEL_STATUS_OK, (int) r.status); + t.assert_true("p=2051: history is 1..511", sel_hist(r.out, p) == want); + t.assert_true("p=2051: ends with 2048..2051", r.out.pos.size() >= 4 && + std::vector(r.out.pos.end() - 4, r.out.pos.end()) == std::vector{ 2048, 2049, 2050, 2051 }); + }); + + t.test("SN-06_no_epsilon", [](testing & t) { + // groups 0 and 1 of p = 8 compete for the one history slot of S = 8 + sel_seq sq; + sq.n_pos = 9; + sq.bij = true; + + auto kept = [&](float s0, float s1, bool reverse) { + sel_export e; + e.add(0, s0); + e.add(1, s1); + if (reverse) { + std::reverse(e.ids.begin(), e.ids.end()); + std::reverse(e.scores.begin(), e.scores.end()); + } + const auto r = sel_run(e, 8, 8, sel_refs(sq, 8, e.ids)); + return r.status == LLAMA_DFLY_SEL_STATUS_OK ? sel_hist(r.out, 8) : std::vector{ -1 }; + }; + + for (float x : { 1.0f, 0.0f }) { + const float y = std::nextafter(x, std::numeric_limits::infinity()); + t.assert_true("y is above x", y > x); + for (bool reverse : { false, true }) { + const std::string what = "x=" + std::to_string(x) + (reverse ? " reversed" : ""); + t.assert_true(what + ": group 1 is 1 ulp higher and wins", kept(x, y, reverse) == std::vector{ 1 }); + } + } + + // -0 and +0 are one score, so the lower group wins + for (bool reverse : { false, true }) { + const std::string what = reverse ? " reversed" : ""; + t.assert_true("-0, +0" + what, kept(-0.0f, 0.0f, reverse) == std::vector{ 0 }); + t.assert_true("+0, -0" + what, kept(0.0f, -0.0f, reverse) == std::vector{ 0 }); + } + }); + + t.test("SN-07_minus_inf_ignored", [](testing & t) { + // p = 21 of S = 16; another sequence owns pools 0..4, and later rows wrote groups 5 and 6 + sel_seq sq; + sq.n_pos = 28; + sq.id_map = 1; + sq.bij = true; + sq.strm = 3; + const llama_pos p = 21; + + sel_export e; + const float scores[] = { 3.0f, 1.0f, 4.0f, 1.5f, 2.0f }; + for (int64_t h = 0; h < 5; ++h) { + e.add(sq.id_of(h), scores[h]); + } + const auto r0 = sel_run(e, p, 16, sel_refs(sq, p, e.ids)); + t.assert_equal("clean status", (int) LLAMA_DFLY_SEL_STATUS_OK, (int) r0.status); + + const int32_t extra[] = { + (int32_t) sq.n_pool_real(), // first padding pool + (int32_t) sel_pad(sq.n_pool_real()) - 1, + -1, INT32_MIN, INT32_MAX, + 2, // a pool of the other sequence + sq.id_of(5), sq.id_of(6), // groups that end after p + sq.id_of(3), // a repeat + }; + for (int32_t id : extra) { + e.add(id, -INFINITY); + } + std::mt19937 rng(7); + e.shuffle(rng); + + const auto r1 = sel_run(e, p, 16, sel_refs(sq, p, e.ids)); + t.assert_equal("noisy status", (int) LLAMA_DFLY_SEL_STATUS_OK, (int) r1.status); + t.assert_true("same positions", r1.out.pos == r0.out.pos); + t.assert_true("same cells", r1.out.cell == r0.out.cell); + t.assert_equal("same stream", r0.out.strm, r1.out.strm); + }); + + t.test("SN-08_S_4", [](testing & t) { + // no history budget: only p's own group + std::mt19937 rng(4); + for (llama_pos p = 0; p < 12; ++p) { + sel_seq sq; + sq.n_pos = p + 5; + sq.bij = true; + const auto gs = sel_scores(rng, sq, p); + const auto e = sel_topk(rng, sq.n_pool_real(), 4, sel_score_of(sq, gs)); + const auto r = sel_run(e, p, 4, sel_refs(sq, p, e.ids)); + + std::vector want; + for (llama_pos x = 4*(p/4); x <= p; ++x) { + want.push_back(x); + } + t.assert_true("p=" + std::to_string(p) + ": p's own group only: " + r.err, r.out.pos == want); + t.assert_equal("p=" + std::to_string(p) + " TG-01", std::string(), sel_check_seq(r, p, 4, e, sq, gs)); + } + + // p = INT32_MAX: 2^31 cells up to p, by hand + const llama_pos p = INT32_MAX; + const int64_t g = p / 4; + + kpool_refs refs; + refs.kpool = 4; + refs.n_pools = (uint32_t) g + 1; + refs.n_hist_avail = (uint32_t) g; + refs.n_cells_upto_p = (uint32_t) ((int64_t) p + 1); + + sel_export e; + e.add((int32_t) g - 1, 2.0f); + e.add((int32_t) g, 1.0f); + for (int64_t h : { g - 1, g }) { + refs.found.push_back(1); + for (int64_t k = 0; k < 4; ++k) { + refs.pos .push_back((llama_pos) (4*h + k)); + refs.cell.push_back((uint32_t) k); + } + } + for (int64_t x = 4*g; x <= p; ++x) { + refs.cur_pos .push_back((llama_pos) x); + refs.cur_cell.push_back((uint32_t) (x - 4*g)); + } + + const auto r = sel_run(e, p, 4, refs); + t.assert_equal("p=INT32_MAX status: " + r.err, (int) LLAMA_DFLY_SEL_STATUS_OK, (int) r.status); + t.assert_true("p=INT32_MAX: p-3..p", r.out.pos == std::vector{ p - 3, p - 2, p - 1, p }); + }); + + t.test("SN-09_complete_group_exported", [](testing & t) { + // p % 4 == 3: p's own complete group is exported with the top score, it is not history + std::mt19937 rng(9); + for (uint32_t S : { 8u, 16u, 2048u }) { + for (llama_pos p : { 3, 11, 19, 2047, 2051, 4095 }) { + const std::string what = "S=" + std::to_string(S) + " p=" + std::to_string(p); + + sel_seq sq; + sq.n_pos = p + 1; + sq.id_map = 1; + sq.bij = true; + sq.strm = 1; + + auto gs = sel_scores(rng, sq, p); + gs[p/4] = 100.0f; + const auto e = sel_topk(rng, sq.n_pool_real(), S, sel_score_of(sq, gs)); + + bool exported = false; + for (size_t i = 0; i < e.ids.size(); ++i) { + exported = exported || (e.ids[i] == sq.id_of(p/4) && e.scores[i] == 100.0f); + } + t.assert_true(what + ": p's own group is exported", exported); + + const auto r = sel_run(e, p, S, sel_refs(sq, p, e.ids)); + t.assert_equal(what + " TG-01", std::string(), sel_check_seq(r, p, S, e, sq, gs)); + } + } + }); +} + +// a valid row for the negative tests: p = 21 of S = 16, history groups 0..4, p's own group 5 incomplete +// another sequence owns pools 0..4, and later rows of the batch already wrote groups 5 and 6 +struct sel_row { + sel_seq sq; + llama_pos p = 21; + uint32_t S = 16; + sel_export e; + + sel_row() { + sq.n_pos = 28; + sq.id_map = 1; + sq.bij = true; + sq.strm = 2; + + const float scores[] = { 3.0f, 1.0f, 4.0f, 1.5f, 2.0f }; + for (int64_t h = 0; h < 5; ++h) { + e.add(sq.id_of(h), scores[h]); + } + // padding pools, as the target exports them + e.add(40, -INFINITY); + e.add(41, -INFINITY); + } + + kpool_refs refs() const { + return sel_refs(sq, p, e.ids); + } +}; + +static std::vector sel_fields(const std::string & s) { + std::vector res; + size_t i = 0; + while (i < s.size()) { + const size_t j = s.find(' ', i); + res.push_back(s.substr(i, j == std::string::npos ? std::string::npos : j - i)); + i = j == std::string::npos ? s.size() : j + 1; + } + return res; +} + +// must fail with this status, start err with ":", name the item or row in a whole field, and leave out empty +static void expect_sel_fail(testing & t, const std::string & what, + const int32_t * ids, const float * scores, size_t n_ids, llama_pos p, uint32_t S, const kpool_refs & refs, + llama_dfly_sel_status want, const std::string & rule, const std::string & field) { + llama_dfly_ctx_set out; + out.strm = 7; + out.pos = { 1, 2, 3 }; + out.cell = { 4, 5, 6 }; + std::string err; + + const auto status = llama_dfly_normalize_selection(ids, scores, n_ids, p, S, refs, out, err); + + const auto f = sel_fields(err); + t.assert_equal(what + ": status (err: " + err + ")", (int) want, (int) status); + t.assert_true(what + ": err starts with " + rule + ": " + err, !f.empty() && f[0] == rule + ":"); + t.assert_true(what + ": err has the field " + field + ": " + err, std::find(f.begin(), f.end(), field) != f.end()); + t.assert_true(what + ": err is one line", err.find('\n') == std::string::npos); + t.assert_true(what + ": out is empty", out.pos.empty() && out.cell.empty() && out.strm == 0); +} + +static void expect_sel_fail(testing & t, const std::string & what, const sel_export & e, llama_pos p, uint32_t S, + const kpool_refs & refs, llama_dfly_sel_status want, const std::string & rule, const std::string & field) { + expect_sel_fail(t, what, e.ids.data(), e.scores.data(), e.ids.size(), p, S, refs, want, rule, field); +} + +static std::string id_field(int32_t id) { + return "id=" + std::to_string(id); +} + +// v as the last item, after every -inf one, and as item 256 of 512 +static void sel_non_finite_spots(testing & t, float v) { + { + // p = 10 of S = 2048: 2 finite groups, 62 -inf items, then v on the last padding pool + sel_seq sq; + sq.n_pos = 11; + sq.bij = true; + std::mt19937 rng(10); + const auto e0 = sel_topk(rng, sq.n_pool_real(), 2048, sel_score_of(sq, sel_scores(rng, sq, 10))); + sel_export e; + for (size_t i = 0; i < e0.ids.size(); ++i) { + if (e0.scores[i] != -INFINITY) { + e.add(e0.ids[i], e0.scores[i]); + } + } + for (size_t i = 0; i < e0.ids.size(); ++i) { + if (e0.scores[i] == -INFINITY) { + e.add(e0.ids[i], e0.scores[i]); + } + } + e.add(63, v); + expect_sel_fail(t, "after every -inf item", e, 10, 2048, sel_refs(sq, 10, e.ids), + LLAMA_DFLY_SEL_STATUS_NON_FINITE, "non_finite", id_field(63)); + } + { + sel_seq sq; + sq.n_pos = 4096; + sq.bij = true; + std::mt19937 rng(4095); + auto e = sel_topk(rng, sq.n_pool_real(), 2048, sel_score_of(sq, sel_scores(rng, sq, 4095))); + t.assert_equal("512 items", (size_t) 512, e.ids.size()); + e.scores[256] = v; + expect_sel_fail(t, "item 256 of 512", e, 4095, 2048, sel_refs(sq, 4095, e.ids), + LLAMA_DFLY_SEL_STATUS_NON_FINITE, "non_finite", id_field(e.ids[256])); + } +} + +static void test_selection_neg(testing & t) { + t.test("SE-00_base_row", [](testing & t) { + const sel_row c; + const auto r = sel_run(c.e, c.p, c.S, c.refs()); + t.assert_equal("status: " + r.err, (int) LLAMA_DFLY_SEL_STATUS_OK, (int) r.status); + t.assert_equal("count", (size_t) 14, r.out.pos.size()); + }); + + t.test("SE-01_nan", [](testing & t) { + const float v = std::numeric_limits::quiet_NaN(); + sel_row c; + c.e.scores[2] = v; + expect_sel_fail(t, "on a history group", c.e, c.p, c.S, c.refs(), + LLAMA_DFLY_SEL_STATUS_NON_FINITE, "non_finite", id_field(c.e.ids[2])); + sel_non_finite_spots(t, v); + }); + + t.test("SE-02_plus_inf", [](testing & t) { + sel_row c; + c.e.scores[2] = INFINITY; + expect_sel_fail(t, "on a history group", c.e, c.p, c.S, c.refs(), + LLAMA_DFLY_SEL_STATUS_NON_FINITE, "non_finite", id_field(c.e.ids[2])); + sel_non_finite_spots(t, INFINITY); + }); + + t.test("SE-03_bad_pool", [](testing & t) { + const sel_row base; + const int64_t n_pool_real = base.sq.n_pool_real(); + const int32_t pad = (int32_t) sel_pad(n_pool_real); + + const std::pair bad[] = { + { (int32_t) n_pool_real, "first padding pool" }, + { pad - 1, "last padding pool" }, + { pad + 7, "past the padding" }, + { -1, "-1" }, + { INT32_MIN, "INT32_MIN" }, + { INT32_MAX, "INT32_MAX" }, + { 2, "pool of another sequence" }, + }; + for (const auto & b : bad) { + sel_row c; + c.e.insert(2, b.first, 0.5f); + expect_sel_fail(t, b.second, c.e, c.p, c.S, c.refs(), LLAMA_DFLY_SEL_STATUS_BAD_POOL, "bad_pool", id_field(b.first)); + } + + const auto refs = sel_refs(base.sq, base.p, { INT32_MIN, INT32_MAX }); + t.assert_true("the test model does not find INT32_MIN and INT32_MAX", refs.found == std::vector{ 0, 0 }); + }); + + t.test("SE-04_future_group", [](testing & t) { + { + // the seed's negative control + sel_seq sq; + sq.n_pos = 8; + sel_export e; + e.add(1, 0.0f); + expect_sel_fail(t, "SE-04a p=1 group 1", e, 1, 2048, sel_refs(sq, 1, e.ids), + LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP, "future_group", id_field(1)); + } + { + sel_row c; + const int32_t id = c.sq.id_of(6); + c.e.insert(3, id, 0.5f); + expect_sel_fail(t, "SE-04b group g+1", c.e, c.p, c.S, c.refs(), + LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP, "future_group", id_field(id)); + } + { + // p % 4 != 3: p's own group g is in the layout because later rows completed it + sel_row c; + const int32_t id = c.sq.id_of(5); + c.e.insert(0, id, 0.5f); + expect_sel_fail(t, "SE-04c p=21 group g", c.e, c.p, c.S, c.refs(), + LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP, "future_group", id_field(id)); + } + for (llama_pos p : { 4, 5, 6 }) { + sel_seq sq; + sq.n_pos = 8; + sq.bij = true; + sel_export e; + e.add(0, 1.0f); + e.add(1, 0.25f); + expect_sel_fail(t, "SE-04c p=" + std::to_string(p) + " group g", e, p, 16, sel_refs(sq, p, e.ids), + LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP, "future_group", id_field(1)); + } + }); + + t.test("SE-05_dup_group", [](testing & t) { + { + sel_row c; + c.e.insert(5, c.e.ids[1], 0.5f); + expect_sel_fail(t, "one id twice", c.e, c.p, c.S, c.refs(), LLAMA_DFLY_SEL_STATUS_DUP_GROUP, "dup_group", id_field(c.e.ids[1])); + } + { + // two ids whose pools hold the same group + sel_row c; + auto refs = c.refs(); + for (size_t k = 0; k < 4; ++k) { + refs.pos [3*4 + k] = refs.pos [1*4 + k]; + refs.cell[3*4 + k] = refs.cell[1*4 + k]; + } + expect_sel_fail(t, "two ids, one group", c.e, c.p, c.S, refs, LLAMA_DFLY_SEL_STATUS_DUP_GROUP, "dup_group", id_field(c.e.ids[3])); + } + { + // SE-05c: p % 4 == 3, p's own complete group twice + sel_row c; + c.p = 23; + const int32_t id = c.sq.id_of(5); + c.e.add(id, 1.0f); + c.e.add(id, 2.0f); + expect_sel_fail(t, "SE-05c p's own group twice", c.e, c.p, c.S, c.refs(), LLAMA_DFLY_SEL_STATUS_DUP_GROUP, "dup_group", id_field(id)); + } + }); + + t.test("SE-06_member_layout", [](testing & t) { + const std::pair, const char *> bad[] = { + { { 5, 6, 7, 8 }, "start not a multiple of 4" }, + { { 4, 5, 6, 8 }, "members not consecutive" }, + { { -4, -3, -2, -1 }, "negative start" }, + }; + for (const auto & b : bad) { + sel_row c; + auto refs = c.refs(); + std::copy(b.first.begin(), b.first.end(), refs.pos.begin() + 2*4); + expect_sel_fail(t, b.second, c.e, c.p, c.S, refs, LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT, "bad_layout", id_field(c.e.ids[2])); + const auto r = sel_run(c.e, c.p, c.S, refs); + const auto f = sel_fields(r.err); + t.assert_true(std::string(b.second) + ": err names the first member: " + r.err, + std::count(f.begin(), f.end(), "pos=" + std::to_string(b.first[0])) == 1); + } + }); + + t.test("SE-07_layout", [](testing & t) { + { + sel_row c; + auto refs = c.refs(); + refs.pos_min = 4; + expect_sel_fail(t, "SE-07a pos_min = 4", c.e, c.p, c.S, refs, LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT, "bad_layout", "p=21"); + } + // SE-07b: kpool = 8 on a row that breaks nothing else + for (size_t n_ids : { (size_t) 2, (size_t) 0 }) { + sel_export e; + for (size_t i = 0; i < n_ids; ++i) { + e.add((int32_t) i, -INFINITY); + } + kpool_refs refs; + refs.kpool = 8; + refs.n_cells_upto_p = 3; + refs.found.assign(n_ids, 0); + refs.pos .assign(n_ids*8, 0); + refs.cell .assign(n_ids*8, 0); + refs.cur_pos = { 0, 1, 2 }; + refs.cur_cell = { 0, 1, 2 }; + expect_sel_fail(t, "SE-07b kpool = 8, n_ids = " + std::to_string(n_ids), e, 2, 16, refs, + LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT, "bad_layout", "p=2"); + } + }); + + t.test("SE-08_not_contiguous", [](testing & t) { + { + sel_row c; + auto refs = c.refs(); + refs.cur_pos .erase(refs.cur_pos .begin()); + refs.cur_cell.erase(refs.cur_cell.begin()); + expect_sel_fail(t, "a member of p's own group is missing", c.e, c.p, c.S, refs, + LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS, "not_contiguous", "p=21"); + } + { + sel_row c; + auto refs = c.refs(); + refs.n_hist_avail -= 1; + expect_sel_fail(t, "a history group is missing", c.e, c.p, c.S, refs, + LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS, "not_contiguous", "p=21"); + } + { + sel_row c; + auto refs = c.refs(); + refs.n_cells_upto_p += 1; + expect_sel_fail(t, "a position is repeated", c.e, c.p, c.S, refs, + LLAMA_DFLY_SEL_STATUS_NOT_CONTIGUOUS, "not_contiguous", "p=21"); + } + }); + + t.test("SE-09_short_export", [](testing & t) { + { + // S = 16, p = 40 needs 3 history groups + sel_seq sq; + sq.n_pos = 41; + sel_export e; + e.add(0, 1.0f); + e.add(1, 2.0f); + e.add(50, -INFINITY); + e.add(51, -INFINITY); + expect_sel_fail(t, "2 of 3", e, 40, 16, sel_refs(sq, 40, e.ids), + LLAMA_DFLY_SEL_STATUS_SHORT_EXPORT, "short_export", "p=40"); + } + { + sel_seq sq; + sq.n_pos = 4096; + sel_export e; + for (int32_t h = 0; h < 300; ++h) { + e.add(h, (float) (h % 7)); + } + for (int32_t id = 1100; id < 1312; ++id) { + e.add(id, -INFINITY); + } + expect_sel_fail(t, "300 of 511", e, 4095, 2048, sel_refs(sq, 4095, e.ids), + LLAMA_DFLY_SEL_STATUS_SHORT_EXPORT, "short_export", "p=4095"); + } + }); + + t.test("SE-10_bad_arg", [](testing & t) { + const sel_row c; + // 131072 is the indexer_top_k of the test-llama-archs hy_v4_flash, the value a caller must not pass + for (uint32_t S : { 0u, 2u, 6u, 2052u, 131072u }) { + expect_sel_fail(t, "S=" + std::to_string(S), c.e, c.p, S, c.refs(), LLAMA_DFLY_SEL_STATUS_BAD_ARG, "bad_arg", "p=21"); + } + expect_sel_fail(t, "p=-1", c.e, -1, c.S, c.refs(), LLAMA_DFLY_SEL_STATUS_BAD_ARG, "bad_arg", "p=-1"); + + const std::pair, const char *> edits[] = { + { [](kpool_refs & r) { r.found.pop_back(); }, "found too short" }, + { [](kpool_refs & r) { r.pos.pop_back(); }, "pos too short" }, + { [](kpool_refs & r) { r.cell.push_back(0); }, "cell too long" }, + { [](kpool_refs & r) { r.cur_cell.pop_back(); }, "cur_cell too short" }, + }; + for (const auto & edit : edits) { + auto refs = c.refs(); + edit.first(refs); + expect_sel_fail(t, edit.second, c.e, c.p, c.S, refs, LLAMA_DFLY_SEL_STATUS_BAD_ARG, "bad_arg", "p=21"); + } + + expect_sel_fail(t, "ids null", nullptr, c.e.scores.data(), c.e.ids.size(), c.p, c.S, c.refs(), + LLAMA_DFLY_SEL_STATUS_BAD_ARG, "bad_arg", "p=21"); + expect_sel_fail(t, "scores null", c.e.ids.data(), nullptr, c.e.ids.size(), c.p, c.S, c.refs(), + LLAMA_DFLY_SEL_STATUS_BAD_ARG, "bad_arg", "p=21"); + }); +} + +static bool sel_parse_i64(const std::string & s, int64_t & v) { + if (s.empty()) { + return false; + } + char * end = nullptr; + errno = 0; + const long long x = strtoll(s.c_str(), &end, 10); + if (errno != 0 || end != s.c_str() + s.size()) { + return false; + } + v = x; + return true; +} + +static bool sel_parse_i32(const std::string & s, int32_t & v) { + int64_t x = 0; + if (!sel_parse_i64(s, x) || x < INT32_MIN || x > INT32_MAX) { + return false; + } + v = (int32_t) x; + return true; +} + +// strtof, since istream >> float cannot read -inf +static bool sel_parse_f32(const std::string & s, float & v) { + if (s.empty()) { + return false; + } + char * end = nullptr; + errno = 0; + v = strtof(s.c_str(), &end); + return errno == 0 && end == s.c_str() + s.size(); +} + +// the case file of logs/S4a/tools/gen_selection_cases.py, one record per normalize() call of check_selection.py +static void test_selection_oracle(testing & t) { + const char * path = getenv("LLAMA_DFLY_TEST_SELECTION_CASES"); + if (path == nullptr) { + t.skip("set LLAMA_DFLY_TEST_SELECTION_CASES= to run"); + return; + } + + t.test("SC-01_check_selection_cases", [&](testing & t) { + std::ifstream file(path); + if (!t.assert_true(std::string("opens ") + path, file.good())) { + return; + } + const auto t_start = std::chrono::steady_clock::now(); + + int n_rec = 0; + int n_ok = 0; + int n_err = 0; + int n_bad = 0; + int n_line = 0; + std::string parse_error; + int64_t end_rec = -1; + int64_t end_ok = -1; + int64_t end_err = -1; + + std::string line; + std::vector tok; + // the next line that is not a comment, split at spaces + auto next = [&]() { + while (std::getline(file, line)) { + ++n_line; + if (!line.empty() && line[0] != '#') { + tok = sel_fields(line); + return true; + } + } + tok.clear(); + return false; + }; + auto fail = [&](const std::string & why) { + parse_error = "line " + std::to_string(n_line) + ": " + why; + }; + // the next line must be followed by n numbers + auto numbers = [&](const char * key, int64_t n, auto parse, auto & dst) { + if (!next() || tok[0] != key) { + fail(std::string("expected ") + key); + return false; + } + if ((int64_t) tok.size() != n + 1) { + fail(std::string(key) + " has " + std::to_string(tok.size() - 1) + " values, want " + std::to_string(n)); + return false; + } + dst.resize(n); + for (int64_t i = 0; i < n; ++i) { + if (!parse(tok[i + 1], dst[i])) { + fail("bad number '" + tok[i + 1] + "'"); + return false; + } + } + return true; + }; + + while (parse_error.empty()) { + if (!next()) { + fail("no end line"); + break; + } + if (tok[0] == "end") { + if (tok.size() != 4 || !sel_parse_i64(tok[1], end_rec) || !sel_parse_i64(tok[2], end_ok) || !sel_parse_i64(tok[3], end_err)) { + fail("bad end line"); + } + break; + } + + int64_t idx = 0, S = 0, p = 0, total = 0, n_ids = 0; + if (tok.size() != 7 || tok[0] != "case" || !sel_parse_i64(tok[1], idx) || !sel_parse_i64(tok[2], S) || + !sel_parse_i64(tok[3], p) || !sel_parse_i64(tok[4], total) || !sel_parse_i64(tok[5], n_ids) || + (tok[6] != "ok" && tok[6] != "err")) { + fail("bad case line"); + break; + } + if (idx != n_rec || S < 0 || S > UINT32_MAX || p < 0 || p > INT32_MAX || total != (p + 8)/4 || n_ids < 0) { + fail("bad case values"); + break; + } + const bool want_ok = tok[6] == "ok"; + + std::vector ids; + std::vector scores; + if (!numbers("ids", n_ids, sel_parse_i32, ids) || !numbers("scores", n_ids, sel_parse_f32, scores)) { + break; + } + + std::vector want_pos; + std::vector want_hist; + if (want_ok) { + int64_t n = 0; + if (!next() || tok[0] != "want_pos" || tok.size() < 2 || !sel_parse_i64(tok[1], n)) { + fail("expected want_pos"); + break; + } + std::vector rest(tok.begin() + 2, tok.end()); + if ((int64_t) rest.size() != n) { + fail("want_pos count"); + break; + } + want_pos.resize(n); + bool good = true; + for (int64_t i = 0; good && i < n; ++i) { + good = sel_parse_i64(rest[i], want_pos[i]); + } + if (!good || !next() || tok[0] != "want_hist" || tok.size() < 2 || !sel_parse_i64(tok[1], n) || + (int64_t) tok.size() != n + 2) { + fail("bad want_pos or want_hist"); + break; + } + want_hist.resize(n); + for (int64_t i = 0; good && i < n; ++i) { + good = sel_parse_i64(tok[i + 2], want_hist[i]); + } + if (!good) { + fail("bad want_hist"); + break; + } + } else if (!next() || tok.size() != 2 || tok[0] != "want_err" || tok[1] != "future_group") { + fail("expected want_err future_group"); + break; + } + + // the seed's ids are groups, its layout holds total complete groups + sel_seq sq; + sq.n_pos = 4*total; + sq.bij = true; + sq.strm = 2; + const auto r = sel_run({ ids, scores }, (llama_pos) p, (uint32_t) S, sel_refs(sq, (llama_pos) p, ids)); + + std::string bad; + if (want_ok) { + ++n_ok; + std::vector got(r.out.pos.begin(), r.out.pos.end()); + std::vector want_cell; + for (int64_t x : want_pos) { + want_cell.push_back(sq.cell_of(x)); + } + if (r.status != LLAMA_DFLY_SEL_STATUS_OK) { + bad = "status " + std::to_string((int) r.status) + ": " + r.err; + } else if (got != want_pos) { + bad = "positions differ, " + std::to_string(got.size()) + " vs " + std::to_string(want_pos.size()); + } else if (r.out.cell != want_cell) { + bad = "cells differ"; + } else if (sel_hist(r.out, (llama_pos) p) != want_hist) { + bad = "history groups differ"; + } else if (r.out.strm != sq.strm) { + bad = "strm"; + } + } else { + ++n_err; + if (r.status != LLAMA_DFLY_SEL_STATUS_FUTURE_GROUP) { + bad = "status " + std::to_string((int) r.status) + ", want future_group"; + } else if (!r.out.pos.empty() || !r.out.cell.empty() || r.out.strm != 0) { + bad = "out is not empty"; + } + } + if (!bad.empty() && n_bad++ < 10) { + t.out << t.indent() << " case " << idx << " S=" << S << " p=" << p << ": " << bad << "\n"; + } + ++n_rec; + } + + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t_start).count(); + t.out << t.indent() << " records " << n_rec << ", ok " << n_ok << ", err " << n_err << ", mismatches " << n_bad + << " in " << ms << " ms\n"; + + t.assert_equal("parse error", std::string(), parse_error); + t.assert_equal("records", 6314, n_rec); + t.assert_equal("ok records", 6313, n_ok); + t.assert_equal("err records", 1, n_err); + t.assert_equal("mismatches", 0, n_bad); + t.assert_true ("the end line agrees", end_rec == n_rec && end_ok == n_ok && end_err == n_err); + }); +} + +// LH: kpool_copy_refs on real memory, with the 10-layer tiny target of gguf-fixture.h, CPU only +// every expected value comes from the base cache, never from the layout or the helper + +using lh_cells = std::vector>; + +static llama_context_ptr lh_context(llama_model * model, uint32_t n_seq_max, bool unified) { + llama_context_params params = llama_context_default_params(); + params.n_ctx = 256; + params.n_batch = 64; + params.n_ubatch = 64; + params.n_seq_max = n_seq_max; + params.kv_unified = unified; + + return llama_context_ptr(llama_init_from_model(model, params)); +} + +static llama_memory_idx_iswa * lh_mem(testing & t, const llama_context_ptr & ctx) { + if (!t.assert_true("context", ctx != nullptr)) { + return nullptr; + } + auto * mem = dynamic_cast(llama_get_memory(ctx.get())); + t.assert_true("the memory is a llama_memory_idx_iswa", mem != nullptr); + return mem; +} + +// one batch: positions [p0, p1) of each listed sequence { seq, p0, p1 }, one token per sequence in turn +static int lh_decode(llama_context * ctx, const std::vector> & spans) { + llama_batch batch = llama_batch_init(64, 0, 1); + batch.n_tokens = 0; + for (int k = 0; ; ++k) { + bool any = false; + for (const auto & s : spans) { + const int p = s[1] + k; + if (p >= s[2]) { + continue; + } + const int i = batch.n_tokens++; + batch.token [i] = (p*7 + 3 + 5*s[0]) % 100; + batch.pos [i] = p; + batch.n_seq_id[i] = 1; + batch.seq_id [i][0] = s[0]; + batch.logits [i] = p == s[2] - 1; + any = true; + } + if (!any) { + break; + } + } + const int rc = llama_decode(ctx, batch); + llama_batch_free(batch); + return rc; +} + +// a sequence as the base cache holds it, which must have no hole: pools are 4 positions from its first one +struct lh_seq { + lh_cells cells; + uint32_t strm = 0; + int64_t pool_begin = 0; + + llama_pos pos_min() const { return cells.empty() ? 0 : cells.front().first; } + int64_t n_groups() const { return (int64_t) cells.size() / 4; } + uint32_t cell_at(llama_pos x) const { return cells[x - pos_min()].second; } + + bool no_hole() const { + for (size_t k = 0; k < cells.size(); ++k) { + if (cells[k].first != pos_min() + (llama_pos) k) { + return false; + } + } + return true; + } +}; + +static lh_seq lh_get(llama_memory_idx_iswa * mem, llama_seq_id s, int64_t pool_begin) { + const auto * base = mem->get_mem_attn()->get_base(); + const auto & sp = base->get_cells(s).seq_pos_get(s); + + lh_seq res; + res.cells.assign(sp.begin(), sp.end()); + res.strm = base->get_stream(s); + res.pool_begin = pool_begin; + return res; +} + +// base and indexer cells are paired, so both caches hold the same (pos, cell) of a sequence +static bool lh_base_is_idx(llama_memory_idx_iswa * mem, llama_seq_id s) { + return mem->get_mem_attn()->get_base()->get_cells(s).seq_pos_get(s) == mem->get_mem_idx()->get_cells(s).seq_pos_get(s); +} + +// refs against the base cache: ids[i] is pool k = ids[i] - pool_begin of the sequence when 0 <= k < n_groups +static std::string lh_check(const kpool_refs & r, const lh_seq & sq, llama_pos p, const std::vector & ids) { + if (r.kpool != 4 || r.strm != sq.strm || r.pos_min != sq.pos_min() || r.pool_begin != sq.pool_begin || r.n_pools != sq.n_groups()) { + return "kpool " + std::to_string(r.kpool) + " strm " + std::to_string(r.strm) + " pos_min " + std::to_string(r.pos_min) + + " pool_begin " + std::to_string(r.pool_begin) + " n_pools " + std::to_string(r.n_pools); + } + if (r.found.size() != ids.size() || r.pos.size() != 4*ids.size() || r.cell.size() != 4*ids.size()) { + return "sizes"; + } + for (size_t i = 0; i < ids.size(); ++i) { + const int64_t k = (int64_t) ids[i] - sq.pool_begin; + const bool found = k >= 0 && k < sq.n_groups(); + if ((r.found[i] != 0) != found) { + return "found of id " + std::to_string(ids[i]); + } + for (int64_t m = 0; m < 4; ++m) { + const llama_pos x = found ? (llama_pos) (sq.pos_min() + 4*k + m) : 0; + if (r.pos[i*4 + m] != x || r.cell[i*4 + m] != (found ? sq.cell_at(x) : 0)) { + return "member " + std::to_string(m) + " of id " + std::to_string(ids[i]); + } + } + } + + const llama_pos pm = sq.pos_min(); + int64_t n_hist = 0; + lh_cells cur; + if (p >= pm) { + const int64_t c0 = pm + 4*((p - pm)/4); + n_hist = std::min((c0 - pm)/4, sq.n_groups()); + for (const auto & pc : sq.cells) { + if (pc.first >= c0 && pc.first <= p) { + cur.push_back(pc); + } + } + } + const int64_t n_upto = std::count_if(sq.cells.begin(), sq.cells.end(), [&](const auto & pc) { return pc.first <= p; }); + if (r.n_hist_avail != n_hist || r.n_cells_upto_p != n_upto) { + return "n_hist_avail " + std::to_string(r.n_hist_avail) + " n_cells_upto_p " + std::to_string(r.n_cells_upto_p); + } + if (r.cur_pos.size() != cur.size() || r.cur_cell.size() != cur.size()) { + return "cur size " + std::to_string(r.cur_pos.size()); + } + for (size_t k = 0; k < cur.size(); ++k) { + if (r.cur_pos[k] != cur[k].first || r.cur_cell[k] != cur[k].second) { + return "cur at " + std::to_string(k); + } + } + + return ""; +} + +static bool lh_empty(const kpool_refs & r) { + return r.kpool == 0 && r.strm == 0 && r.pos_min == 0 && r.pool_begin == 0 && r.n_pools == 0 && r.n_hist_avail == 0 && + r.n_cells_upto_p == 0 && r.found.empty() && r.pos.empty() && r.cell.empty() && r.cur_pos.empty() && r.cur_cell.empty(); +} + +static kpool_refs lh_garbage() { + kpool_refs r; + r.kpool = 9; + r.strm = 9; + r.n_pools = 9; + r.found = { 1 }; + r.cur_pos = { 9 }; + return r; +} + +static std::vector lh_ids(int32_t lo, int32_t hi) { + std::vector ids; + for (int32_t id = lo; id <= hi; ++id) { + ids.push_back(id); + } + return ids; +} + +// kpool_copy_refs that must succeed +static bool lh_copy(testing & t, llama_memory_idx_iswa * mem, llama_seq_id s, llama_pos p, const std::vector & ids, + kpool_refs & r, const std::string & what) { + std::string err; + const bool ok = mem->kpool_copy_refs(s, p, ids.data(), ids.size(), r, err); + return t.assert_true(what + " copies: " + err, ok); +} + +static void test_kpool_refs(testing & t) { + llama_model_ptr model_ptr = hy_v4_flash_tiny_target(hy_v4_flash_tiny{}); + if (!t.assert_true("the tiny target builds", model_ptr != nullptr)) { + return; + } + llama_model * model = model_ptr.get(); + { + auto ctx = lh_context(model, 1, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr) { + return; + } + t.assert_equal("kpool", 4u, mem->get_kpool()); + t.assert_true("pools by position", !mem->get_kpool_by_order()); + } + + t.test("LH-01_one_sequence", [&](testing & t) { + auto ctx = lh_context(model, 1, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode 0..36", 0, lh_decode(ctx.get(), { { 0, 0, 37 } }))) { + return; + } + const lh_seq sq = lh_get(mem, 0, 0); + t.assert_equal("37 cells", (size_t) 37, sq.cells.size()); + t.assert_true ("no hole", sq.no_hole()); + t.assert_equal("9 groups", (int64_t) 9, sq.n_groups()); + t.assert_equal("stream", 0u, sq.strm); + t.assert_true ("base and indexer hold the same cells", lh_base_is_idx(mem, 0)); + + auto ids = lh_ids(-2, 13); + ids.push_back(INT32_MIN); + ids.push_back(INT32_MAX); + + std::vector ps; + for (llama_pos p = 0; p <= 36; ++p) { + ps.push_back(p); + } + ps.push_back(40); + for (llama_pos p : ps) { + const std::string what = "p=" + std::to_string(p); + kpool_refs r = lh_garbage(); + if (!lh_copy(t, mem, 0, p, ids, r, what)) { + continue; + } + t.assert_equal(what, std::string(), lh_check(r, sq, p, ids)); + + std::vector found; + for (size_t i = 0; i < ids.size(); ++i) { + if (r.found[i]) { + found.push_back(ids[i]); + } + } + t.assert_true(what + ": ids 0..8 found", found == lh_ids(0, 8)); + t.assert_equal(what + " n_hist_avail", (uint32_t) std::min(p/4, 9), r.n_hist_avail); + t.assert_equal(what + " n_cells_upto_p", (uint32_t) std::min(p + 1, 37), r.n_cells_upto_p); + t.assert_true (what + " pool_begin 0, 9 pools, pos_min 0", r.pool_begin == 0 && r.n_pools == 9 && r.pos_min == 0); + } + }); + + // seq0 has 37 tokens and seq1 22, interleaved in one batch, which split_equal cuts into 2 ubatches + auto two_seqs = [&](testing & t, bool unified, llama_context_ptr & ctx, lh_seq & s0, lh_seq & s1) { + ctx = lh_context(model, 2, unified); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode", 0, lh_decode(ctx.get(), { { 0, 0, 37 }, { 1, 0, 22 } }))) { + return (llama_memory_idx_iswa *) nullptr; + } + s0 = lh_get(mem, 0, 0); + s1 = lh_get(mem, 1, s0.n_groups()); + t.assert_true("seq0: 37 cells, no hole, 9 groups", s0.cells.size() == 37 && s0.no_hole() && s0.n_groups() == 9); + t.assert_true("seq1: 22 cells, no hole, 5 groups", s1.cells.size() == 22 && s1.no_hole() && s1.n_groups() == 5); + t.assert_true("base and indexer hold the same cells", lh_base_is_idx(mem, 0) && lh_base_is_idx(mem, 1)); + + const auto ids = lh_ids(-1, 14); + for (llama_seq_id s : { 0, 1 }) { + const lh_seq & sq = s == 0 ? s0 : s1; + for (const auto & pc : sq.cells) { + const llama_pos p = pc.first; + const std::string what = "seq" + std::to_string(s) + " p=" + std::to_string(p); + kpool_refs r = lh_garbage(); + if (!lh_copy(t, mem, s, p, ids, r, what)) { + continue; + } + t.assert_equal(what, std::string(), lh_check(r, sq, p, ids)); + + // the global numbering: seq0 has ids 0..8, seq1 ids 9..13 + std::vector found; + for (size_t i = 0; i < ids.size(); ++i) { + if (r.found[i]) { + found.push_back(ids[i]); + } + } + t.assert_true(what + ": found ids", found == (s == 0 ? lh_ids(0, 8) : lh_ids(9, 13))); + t.assert_true(what + ": pool_begin and n_pools", s == 0 ? (r.pool_begin == 0 && r.n_pools == 9) : (r.pool_begin == 9 && r.n_pools == 5)); + } + } + return mem; + }; + + t.test("LH-02_two_sequences_unified", [&](testing & t) { + llama_context_ptr ctx; + lh_seq s0, s1; + if (two_seqs(t, true, ctx, s0, s1) == nullptr) { + return; + } + const int64_t n_moved = std::count_if(s0.cells.begin(), s0.cells.end(), [](const auto & pc) { return pc.first != (llama_pos) pc.second; }); + t.out << t.indent() << " seq0 positions whose cell differs: " << n_moved << "\n"; + t.assert_true("some seq0 cell differs from its position", n_moved > 0); + t.assert_true("one stream", s0.strm == 0 && s1.strm == 0); + }); + + t.test("LH-03_two_sequences_split", [&](testing & t) { + llama_context_ptr ctx; + lh_seq s0, s1; + auto * mem = two_seqs(t, false, ctx, s0, s1); + if (mem == nullptr) { + return; + } + const uint32_t kv_size = mem->get_mem_attn()->get_base()->get_size(); + t.assert_equal("seq1 stream", 1u, s1.strm); + bool local = true; + for (const auto & pc : s1.cells) { + local = local && pc.second < kv_size; + } + t.assert_true("seq1 cells are stream local", local); + + const auto ids = lh_ids(9, 13); + kpool_refs r; + if (lh_copy(t, mem, 1, 21, ids, r, "seq1 p=21")) { + t.assert_equal("strm", 1u, r.strm); + t.assert_true("cells below kv_size", std::all_of(r.cell.begin(), r.cell.end(), [&](uint32_t c) { return c < kv_size; })); + } + }); + + t.test("LH-04_stale", [&](testing & t) { + auto ctx = lh_context(model, 1, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode 0..36", 0, lh_decode(ctx.get(), { { 0, 0, 37 } }))) { + return; + } + const auto ids = lh_ids(0, 9); + kpool_refs r0; + std::string err; + lh_copy(t, mem, 0, 36, ids, r0, "before the edit"); + + t.assert_true("seq_rm 30..", llama_memory_seq_rm(llama_get_memory(ctx.get()), 0, 30, -1)); + { + kpool_refs r = lh_garbage(); + err.clear(); + t.assert_true("refused after seq_rm", !mem->kpool_copy_refs(0, 29, ids.data(), ids.size(), r, err)); + t.assert_true("err says the sequence was edited: " + err, err.find("edited") != std::string::npos); + t.assert_true("out is empty", lh_empty(r)); + } + + if (!t.assert_equal("decode 30..32", 0, lh_decode(ctx.get(), { { 0, 30, 33 } }))) { + return; + } + const lh_seq sq = lh_get(mem, 0, 0); + t.assert_true("33 cells, no hole", sq.cells.size() == 33 && sq.no_hole()); + kpool_refs r; + if (lh_copy(t, mem, 0, 32, ids, r, "after the next batch")) { + t.assert_equal("refs", std::string(), lh_check(r, sq, 32, ids)); + t.assert_true("pools 0..6 as before", + std::equal(r.pos.begin(), r.pos.begin() + 28, r0.pos.begin()) && std::equal(r.cell.begin(), r.cell.begin() + 28, r0.cell.begin())); + bool pool7 = r.found[7] != 0; + for (int m = 0; m < 4; ++m) { + pool7 = pool7 && r.pos[28 + m] == 28 + m && r.cell[28 + m] == sq.cell_at(28 + m); + } + t.assert_true("pool 7 is 28..31 in the base cells", pool7); + t.assert_true("p's own group is [32]", r.cur_pos == std::vector{ 32 } && r.cur_cell == std::vector{ sq.cell_at(32) }); + } + + llama_memory_clear(llama_get_memory(ctx.get()), true); + r = lh_garbage(); + err.clear(); + t.assert_true("refused after clear", !mem->kpool_copy_refs(0, 0, ids.data(), ids.size(), r, err)); + t.assert_true("err after clear: " + err, !err.empty() && lh_empty(r)); + }); + + t.test("LH-05_arguments", [&](testing & t) { + auto ctx = lh_context(model, 1, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr) { + return; + } + const auto ids = lh_ids(0, 1); + { + // no decode yet: the reserve already built a layout, which is empty + kpool_refs r = lh_garbage(); + if (lh_copy(t, mem, 0, 5, ids, r, "fresh context")) { + t.assert_true("nothing found", r.found == std::vector{ 0, 0 } && r.cur_pos.empty() && r.n_pools == 0); + } + } + if (!t.assert_equal("decode 0..7", 0, lh_decode(ctx.get(), { { 0, 0, 8 } }))) { + return; + } + const struct { + llama_seq_id s; + llama_pos p; + const int32_t * id_ptr; + const char * what; + } bad[] = { + { -1, 4, ids.data(), "seq_id -1" }, + { (llama_seq_id) LLAMA_MAX_SEQ, 4, ids.data(), "seq_id LLAMA_MAX_SEQ" }, + { 0, -1, ids.data(), "p -1" }, + { 0, 4, nullptr, "ids null" }, + }; + for (const auto & b : bad) { + kpool_refs r = lh_garbage(); + std::string err; + t.assert_true(std::string(b.what) + " is refused", !mem->kpool_copy_refs(b.s, b.p, b.id_ptr, ids.size(), r, err)); + t.assert_true(std::string(b.what) + " err: " + err, !err.empty()); + t.assert_true(std::string(b.what) + " out is empty", lh_empty(r)); + } + }); + + t.test("LH-06_end_to_end", [&](testing & t) { + std::mt19937 rng(6); + int n_rows = 0; + int n_bad = 0; + + auto run = [&](llama_memory_idx_iswa * mem, const std::vector & seqs) { + int64_t n_pool_real = 0; + for (const auto & sq : seqs) { + n_pool_real += sq.n_groups(); + } + for (size_t s = 0; s < seqs.size(); ++s) { + const lh_seq & sq = seqs[s]; + auto group_of = [&](int32_t id) { + const int64_t k = (int64_t) id - sq.pool_begin; + return k >= 0 && k < sq.n_groups() ? k : (int64_t) -1; + }; + for (const auto & pc : sq.cells) { + const llama_pos p = pc.first; + for (uint32_t S : { 8u, 16u, 2048u }) { + std::uniform_int_distribution dist(-8, 8); + std::vector gs(sq.n_groups(), -INFINITY); + for (int64_t h = 0; h < sq.n_groups() && 4*h + 3 <= p; ++h) { + gs[h] = (float) dist(rng); + } + const auto e = sel_topk(rng, n_pool_real, S, [&](int32_t id) { + const int64_t h = group_of(id); + return h < 0 ? -INFINITY : gs[h]; + }); + + kpool_refs refs; + std::string err; + std::string bad; + if (!mem->kpool_copy_refs((llama_seq_id) s, p, e.ids.data(), e.ids.size(), refs, err)) { + bad = "refused: " + err; + } else { + bad = sel_check(sel_run(e, p, S, refs), p, S, e, group_of, gs, + [&](llama_pos x) { return sq.cell_at(x); }, sq.strm); + } + ++n_rows; + if (!bad.empty() && n_bad++ < 10) { + t.out << t.indent() << " seq" << s << " p=" << p << " S=" << S << ": " << bad << "\n"; + } + } + } + } + }; + + { + auto ctx = lh_context(model, 1, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode one sequence", 0, lh_decode(ctx.get(), { { 0, 0, 37 } }))) { + return; + } + run(mem, { lh_get(mem, 0, 0) }); + } + { + auto ctx = lh_context(model, 2, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode two sequences", 0, lh_decode(ctx.get(), { { 0, 0, 37 }, { 1, 0, 22 } }))) { + return; + } + const lh_seq s0 = lh_get(mem, 0, 0); + run(mem, { s0, lh_get(mem, 1, s0.n_groups()) }); + } + t.out << t.indent() << " rows " << n_rows << ", bad " << n_bad << "\n"; + t.assert_equal("rows", 3*(37 + 37 + 22), n_rows); + t.assert_equal("bad rows", 0, n_bad); + }); + + t.test("LH-07_numbering_of_the_latest_layout", [&](testing & t) { + auto ctx = lh_context(model, 2, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode seq1 0..21", 0, lh_decode(ctx.get(), { { 1, 0, 22 } }))) { + return; + } + const auto ids = lh_ids(0, 4); + { + const lh_seq s1 = lh_get(mem, 1, 0); + kpool_refs r; + if (lh_copy(t, mem, 1, 21, ids, r, "seq1 alone")) { + t.assert_equal("seq1 alone", std::string(), lh_check(r, s1, 21, ids)); + t.assert_true("seq1 alone: ids 0..4, pool_begin 0", r.found == std::vector(5, 1) && r.pool_begin == 0); + } + } + + if (!t.assert_equal("decode seq0 0..7", 0, lh_decode(ctx.get(), { { 0, 0, 8 } }))) { + return; + } + const lh_seq s0 = lh_get(mem, 0, 0); + const lh_seq s1 = lh_get(mem, 1, s0.n_groups()); + t.assert_equal("seq0 has 2 groups", (int64_t) 2, s0.n_groups()); + + kpool_refs r; + if (lh_copy(t, mem, 1, 21, ids, r, "seq1 after seq0")) { + t.assert_equal("seq1 after seq0", std::string(), lh_check(r, s1, 21, ids)); + t.assert_equal("pool_begin", 2u, r.pool_begin); + t.assert_true("only ids 2..4 found", r.found == std::vector{ 0, 0, 1, 1, 1 }); + std::vector want(12); + std::iota(want.begin(), want.end(), 0); + t.assert_true("ids 2..4 are seq1 pools 0..2, positions 0..11", std::vector(r.pos.begin() + 8, r.pos.end()) == want); + } + }); + + t.test("LH-08_pos_min", [&](testing & t) { + auto ctx = lh_context(model, 1, true); + auto * mem = lh_mem(t, ctx); + if (mem == nullptr || !t.assert_equal("decode 0..36", 0, lh_decode(ctx.get(), { { 0, 0, 37 } }))) { + return; + } + t.assert_true("seq_rm 0..5", llama_memory_seq_rm(llama_get_memory(ctx.get()), 0, 0, 6)); + const auto ids = lh_ids(0, 8); + { + kpool_refs r; + std::string err; + t.assert_true("refused after seq_rm", !mem->kpool_copy_refs(0, 13, ids.data(), ids.size(), r, err)); + } + if (!t.assert_equal("decode 37", 0, lh_decode(ctx.get(), { { 0, 37, 38 } }))) { + return; + } + const lh_seq sq = lh_get(mem, 0, 0); + t.assert_true("6..37 in the base cells", sq.pos_min() == 6 && sq.cells.size() == 32 && sq.no_hole()); + + for (llama_pos p : { 3, 13 }) { + kpool_refs r; + if (lh_copy(t, mem, 0, p, ids, r, "p=" + std::to_string(p))) { + t.assert_equal("p=" + std::to_string(p), std::string(), lh_check(r, sq, p, ids)); + } + } + + kpool_refs r; + if (!lh_copy(t, mem, 0, 3, ids, r, "p=3")) { + return; + } + t.assert_true("p=3 is before pos_min", r.pos_min == 6 && r.cur_pos.empty() && r.n_hist_avail == 0 && r.n_cells_upto_p == 0); + + if (!lh_copy(t, mem, 0, 13, ids, r, "p=13")) { + return; + } + t.assert_true("p=13: p's own pool is 10..13", r.cur_pos == std::vector{ 10, 11, 12, 13 }); + t.assert_true("p=13: one pool before it, 8 cells up to p", r.n_hist_avail == 1 && r.n_cells_upto_p == 8); + t.assert_true("id 0 is 6..9", r.found[0] && std::vector(r.pos.begin(), r.pos.begin() + 4) == std::vector{ 6, 7, 8, 9 }); + + // the DFly groups start at position 0 + sel_export e; + e.add(0, 1.0f); + if (lh_copy(t, mem, 0, 13, e.ids, r, "id 0 at p=13")) { + expect_sel_fail(t, "pos_min 6", e, 13, 16, r, LLAMA_DFLY_SEL_STATUS_BAD_LAYOUT, "bad_layout", "p=13"); + } + }); +} + +// the official artifact, only with LLAMA_DFLY_TEST_GGUF=; gpu == nullptr means CPU only +static void check_real(testing & t, const std::string & path, ggml_backend_dev_t gpu) { + const dfly_dims d = dfly_dims_production(); + + log_capture logs; + const auto t_start = std::chrono::steady_clock::now(); + llama_model_ptr model = load_dfly(path, gpu); + const double t_load_ms = std::chrono::duration(std::chrono::steady_clock::now() - t_start).count(); + + if (!t.assert_true("loads", model != nullptr)) { + print_lines(t, "ERROR", logs.get(GGML_LOG_LEVEL_ERROR)); + return; + } + + t.out << t.indent() << " load time: " << t_load_ms << " ms\n"; + check_print_info(t, logs.get(GGML_LOG_LEVEL_INFO), d); + for (const auto & line : logs.get(GGML_LOG_LEVEL_INFO)) { + if (line.find("model buffer size") != std::string::npos) { + t.out << t.indent() << " " << line; + } + } + + for (const auto & line : logs.get(GGML_LOG_LEVEL_WARN)) { + t.assert_true("no DFly warning: " + line, line.rfind("hy_v4_next_dfly: ", 0) != 0); + t.assert_true("no unused tensor: " + line, line.find("model has unused tensor") == std::string::npos); + } + + const llama_hparams & hp = model->hparams; + const llama_vocab * vocab = llama_model_get_vocab(model.get()); + + t.assert_equal("schema_version", 1u, hp.dfly_schema_version); + t.assert_equal("block_size", d.block_size, hp.dfly_block_size); + t.assert_true ("attention.causal", hp.causal_attn); + t.assert_equal("block_count", (uint32_t) n_layer, hp.n_layer_all); + t.assert_equal("context_length", d.n_ctx, hp.n_ctx_train); + t.assert_equal("embedding_length", d.n_embd, hp.n_embd); + t.assert_equal("feed_forward_length", d.n_ff, hp.n_ff()); + t.assert_equal("head_count", d.n_head, hp.n_head()); + t.assert_equal("head_count_kv", 1u, hp.n_head_kv()); + t.assert_equal("q_lora_rank", d.n_lora_q, hp.n_lora_q); + t.assert_equal("kv_lora_rank", d.n_lora_kv, hp.n_lora_kv); + t.assert_equal("key_length", 576u, hp.n_embd_head_k()); + t.assert_equal("value_length", 512u, hp.n_embd_head_v()); + t.assert_equal("key_length_mla", 256u, hp.n_embd_head_k_mla()); + t.assert_equal("value_length_mla", 256u, hp.n_embd_head_v_mla()); + t.assert_equal("rope.dimension_count", d.n_rot, hp.n_rot()); + t.assert_equal("rope.freq_base", d.theta, hp.rope_freq_base_train); + t.assert_equal("layer_norm_rms_epsilon", d.eps, hp.f_norm_rms_eps); + t.assert_equal("target_kv_layers", list_str(d.target_layers), list_str(hp.dfly_target_kv_layers)); + t.assert_equal("target_index_layers", list_str(d.target_layers), list_str(hp.dfly_target_index_layers)); + t.assert_equal("target_index_top_k", d.top_k, hp.dfly_target_index_top_k); + t.assert_equal("hidden_correction_length", d.n_corr, hp.dfly_hidden_correction_length); + t.assert_true ("has_confidence_head", hp.dfly_has_confidence_head); + t.assert_equal("source_mrope_sections", list_str(d.mrope_sections), list_str(hp.dfly_source_mrope_sections)); + t.assert_equal("n_vocab", (int32_t) d.n_vocab, llama_vocab_n_tokens(vocab)); + t.assert_equal("mask", (llama_token) d.mask, llama_vocab_mask(vocab)); + + char file_type[32] = {}; + llama_model_meta_val_str(model.get(), "general.file_type", file_type, sizeof(file_type)); + t.assert_equal("general.file_type", std::string("32"), std::string(file_type)); + + t.assert_equal("n_params", prod_n_params, llama_model_n_params(model.get())); + t.assert_equal("tensors", (size_t) 92, model->tensors_by_name.size()); + + int n_f32 = 0; + int n_bf16 = 0; + const auto prod = prod_ne(); + for (const auto & it : model->tensors_by_name) { + n_f32 += it.second->type == GGML_TYPE_F32; + n_bf16 += it.second->type == GGML_TYPE_BF16; + const auto ne = prod.find(it.first); + if (t.assert_true(it.first + " is a schema tensor", ne != prod.end())) { + t.assert_equal(it.first + " ne", list_str(pad_ne(ne->second)), list_str(std::vector(it.second->ne, it.second->ne + GGML_MAX_DIMS))); + } + } + t.assert_equal("F32", 38, n_f32); + t.assert_equal("BF16", 54, n_bf16); + + check_devices(t, *model, gpu, true); + + // the loaded bytes against the file, with offsets read here and not through the loader + gguf_init_params params = { true, nullptr }; + gguf_context_ptr ctx(gguf_init_from_file(path.c_str(), params)); + if (!t.assert_true("gguf header reads", ctx != nullptr)) { + return; + } + std::ifstream file(path, std::ios::binary); + if (!t.assert_true("file opens", file.good())) { + return; + } + for (const auto & it : model->tensors_by_name) { + const int64_t id = gguf_find_tensor(ctx.get(), it.first.c_str()); + if (!t.assert_true(it.first + " is in the file", id >= 0)) { + continue; + } + const size_t offset = gguf_get_data_offset(ctx.get()) + gguf_get_tensor_offset(ctx.get(), id); + const size_t size = ggml_nbytes(it.second); + std::vector want(size); + std::vector got(size); + file.seekg((std::streamoff) offset); + file.read((char *) want.data(), (std::streamsize) size); + const bool read_ok = file.good(); + if (!t.assert_true(it.first + " file read", read_ok)) { + continue; + } + ggml_backend_tensor_get(it.second, got.data(), 0, size); + t.assert_true(it.first + " bytes", got == want); + } +} + +static void test_real_gguf(testing & t) { + const char * path = getenv("LLAMA_DFLY_TEST_GGUF"); + if (path == nullptr) { + t.skip("set LLAMA_DFLY_TEST_GGUF= to run"); + return; + } + + t.test("LR-01_cpu", [&](testing & t) { + check_real(t, path, nullptr); + }); + + t.test("LR-02_gpu", [&](testing & t) { + ggml_backend_dev_t gpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); + if (gpu == nullptr) { + t.skip("no GPU"); + return; + } + check_real(t, path, gpu); + }); +} + +// +// S5b: the DFly draft bound to the 10-layer tiny target of gguf-fixture.h (graph, propose, binding) +// + +static const size_t PF_SEED = 4321; + +enum class pf_variant { + plain, + sinks, // T5: sinks of very different finite values + gate_zero, // DF-04: fusion gate all 0 + gate_neg, // T6: negative fusion gate, different per channel +}; + +static std::map, llama_model_ptr> g_pf_targets; + +static llama_model * pf_target(uint32_t top_k, ggml_backend_dev_t dev, uint32_t n_layer_tgt = 10) { + llama_model_ptr & m = g_pf_targets[{ top_k, dev, n_layer_tgt }]; + if (!m) { + // the draft reads E where the rest is: the input layer would stay on the CPU + const llama_model_tensor_buft_override overrides[] = { + { "token_embd\\.weight", dev ? ggml_backend_dev_buffer_type(dev) : nullptr }, + { nullptr, nullptr }, + }; + hy_v4_flash_tiny p; + p.n_layer = n_layer_tgt; + p.top_k = top_k; + p.dev = dev; + p.overrides = dev ? overrides : nullptr; + m = hy_v4_flash_tiny_target(p); + } + return m.get(); +} + +// the model is freed before the file is removed +struct pf_draft { + dfly_file file; + llama_model_ptr model; +}; + +static std::map, std::unique_ptr> g_pf_drafts; + +static bool pf_ends_with(const std::string & s, const std::string & end) { + return s.size() >= end.size() && s.compare(s.size() - end.size(), end.size(), end) == 0; +} + +// N(0, 1) entries blow the activations up to 1e3 and saturate the softmax; scale like a trained model: +// matrices by 1/sqrt(fan in), norms around 1, fusion gate small +static tensor_edit_fn pf_weight_edit(pf_variant v) { + return [v](std::vector & ts) { + for (auto & t : ts) { + const int64_t n = n_elements(t.ne); + if (t.type == GGML_TYPE_BF16) { + std::vector x(n); + ggml_bf16_to_fp32_row((const ggml_bf16_t *) t.data.data(), x.data(), n); + for (float & y : x) { + y /= sqrtf((float) t.ne[0]); + } + ggml_fp32_to_bf16_row(x.data(), (ggml_bf16_t *) t.data.data(), n); + } else if (pf_ends_with(t.name, "norm.weight")) { + for (int64_t k = 0; k < n; ++k) { + ((float *) t.data.data())[k] = 1.0f + 0.1f*((float *) t.data.data())[k]; + } + } else if (t.name == "dfly_fusion_gate.weight") { + for (int64_t k = 0; k < n; ++k) { + ((float *) t.data.data())[k] *= 0.1f; + } + } + float * f = (float *) t.data.data(); + if (v == pf_variant::sinks && pf_ends_with(t.name, "attn_sinks.weight")) { + static const float vals[] = { -20.0f, 0.0f, 5.0f }; + const int il = t.name[4] - '0'; + for (int64_t h = 0; h < n; ++h) { + f[h] = vals[(il + h) % 3]; + } + } + if ((v == pf_variant::gate_zero || v == pf_variant::gate_neg) && t.name == "dfly_fusion_gate.weight") { + for (int64_t c = 0; c < n; ++c) { + f[c] = v == pf_variant::gate_zero ? 0.0f : -0.25f - 0.01f*(float) c; + } + } + } + }; +} + +// shifted: target layers 2..10 of a 12-layer target, the reference code of the oracle takes no layer 0 +static pf_draft * pf_draft_get(uint32_t B, uint32_t S, pf_variant v, ggml_backend_dev_t dev, bool shifted = false) { + std::unique_ptr & d = g_pf_drafts[{ B, S, (int) v, dev, shifted }]; + if (!d) { + d = std::make_unique(); + dfly_dims dims = dfly_dims_second(); + dims.block_size = B; + dims.top_k = S; + if (shifted) { + dims.target_layers = { 2, 4, 6, 8, 10 }; + } + + const tensor_edit_fn edit = pf_weight_edit(v); + write_dfly(d->file, dims, {}, {}, GGML_TYPE_BF16, {}, edit); + d->model = load_dfly(d->file.path, dev); + if (!d->model) { + throw std::runtime_error("failed to load the tiny DFly draft"); + } + } + return d.get(); +} + +// one captured graph tensor, values in ggml element order +struct pf_tensor { + std::array ne = {}; + ggml_type type = GGML_TYPE_F32; + std::vector f; + std::vector i; +}; + +struct pf_eval { + std::map t; +}; + +// named dfly_* nodes only, by their whole name: a view is named " (reshaped)" and is skipped +static bool pf_eval_cb(struct ggml_tensor * t, bool ask, void * user_data) { + const bool want = strncmp(t->name, "dfly_", 5) == 0 && strchr(t->name, ' ') == nullptr && + (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_I32); + if (ask) { + return want; + } + if (!want) { + return true; + } + auto * ev = (pf_eval *) user_data; + pf_tensor & o = ev->t[t->name]; + std::copy(t->ne, t->ne + 4, o.ne.begin()); + o.type = t->type; + + std::vector raw(ggml_nbytes(t)); + ggml_backend_tensor_get(t, raw.data(), 0, raw.size()); + const int64_t n = ggml_nelements(t); + o.f.clear(); + o.i.clear(); + for (int64_t i3 = 0; i3 < t->ne[3]; ++i3) { + for (int64_t i2 = 0; i2 < t->ne[2]; ++i2) { + for (int64_t i1 = 0; i1 < t->ne[1]; ++i1) { + for (int64_t i0 = 0; i0 < t->ne[0]; ++i0) { + const uint8_t * p = raw.data() + i0*t->nb[0] + i1*t->nb[1] + i2*t->nb[2] + i3*t->nb[3]; + if (t->type == GGML_TYPE_F32) { + o.f.push_back(*(const float *) p); + } else { + o.i.push_back(*(const int32_t *) p); + } + } + } + } + } + GGML_ASSERT((int64_t) (o.f.size() + o.i.size()) == n); + return true; +} + +static llama_kv_cache * pf_base(llama_context * tgt) { + auto * mem = dynamic_cast(llama_get_memory(tgt)); + GGML_ASSERT(mem != nullptr); + return mem->get_mem_attn()->get_base(); +} + +static std::vector pf_to_f32(const ggml_tensor * t, const uint8_t * p, int64_t n) { + std::vector out(n); + switch (t->type) { + case GGML_TYPE_F32: memcpy(out.data(), p, n*sizeof(float)); break; + case GGML_TYPE_F16: ggml_fp16_to_fp32_row((const ggml_fp16_t *) p, out.data(), n); break; + case GGML_TYPE_BF16: ggml_bf16_to_fp32_row((const ggml_bf16_t *) p, out.data(), n); break; + default: GGML_ABORT("unsupported type %s", ggml_type_name(t->type)); + } + return out; +} + +// one row of the target K storage, read on the host, F16/BF16 -> F32 +static std::vector pf_k_row(llama_context * tgt, int32_t il, uint32_t strm, uint32_t cell) { + ggml_tensor * k = pf_base(tgt)->get_k_storage(il); + std::vector buf(k->nb[1]); + ggml_backend_tensor_get(k, buf.data(), strm*k->nb[2] + cell*k->nb[1], k->nb[1]); + return pf_to_f32(k, buf.data(), k->ne[0]); +} + +static std::vector pf_bytes(const ggml_tensor * t) { + std::vector b(ggml_nbytes(t)); + ggml_backend_tensor_get(t, b.data(), 0, b.size()); + return b; +} + +static std::vector pf_weight_f32(const ggml_tensor * t) { + const std::vector b = pf_bytes(t); + return pf_to_f32(t, b.data(), ggml_nelements(t)); +} + +// a target with the DFly capture on, prefilled, and a draft bound to it holding the snapshot of the last row +struct pf_session { + llama_model * target = nullptr; + pf_draft * draft = nullptr; + llama_context_ptr tgt; + llama_context_ptr dft; + pf_eval ev; + + std::vector T; + std::vector snaps; + + llama_token anchor = 0; + llama_pos a = 0; + uint32_t S = 0; + uint32_t w_cap = 0; + std::string backend; + + std::array layers = {}; +}; + +static const uint64_t PF_EPOCH = 3; + +static llama_context_ptr pf_target_ctx(llama_model * m, uint32_t n_ctx, uint32_t n_batch, uint32_t n_ubatch) { + llama_context_params params = llama_context_default_params(); + params.n_ctx = n_ctx; + params.n_batch = n_batch; + params.n_ubatch = n_ubatch; + params.n_seq_max = 1; + params.swa_full = false; + params.type_k = GGML_TYPE_F16; + params.type_v = GGML_TYPE_F16; + params.n_threads = 4; + params.n_threads_batch = 4; + return llama_context_ptr(llama_init_from_model(m, params)); +} + +static llama_context_params pf_draft_params(llama_context * tgt, uint32_t w_cap, pf_eval * ev) { + llama_context_params params = llama_context_default_params(); + params.n_ctx = 0; + params.n_batch = w_cap; + params.n_ubatch = w_cap; + params.n_seq_max = 1; + params.ctx_other = tgt; + params.n_threads = 4; + params.n_threads_batch = 4; + if (ev != nullptr) { + params.cb_eval = pf_eval_cb; + params.cb_eval_user_data = ev; + } + return params; +} + +static int pf_decode(llama_context * ctx, const std::vector & T, llama_pos p0, llama_pos p1, bool all_out) { + llama_batch b = llama_batch_init(p1 - p0, 0, 1); + for (llama_pos p = p0; p < p1; ++p) { + const int i = b.n_tokens++; + b.token[i] = T[p]; + b.pos[i] = p; + b.n_seq_id[i] = 1; + b.seq_id[i][0] = 0; + b.logits[i] = all_out || p == p1 - 1; + } + const int ret = llama_decode(ctx, b); + llama_batch_free(b); + return ret; +} + +static llama_token pf_argmax(const float * logits, int n) { + return (llama_token) (std::max_element(logits, logits + n) - logits); +} + +// n_prefill target rows, then a draft of width w_cap on the same backend; false on any failure +static bool pf_open(testing & t, pf_session & s, uint32_t B, uint32_t S, pf_variant v, ggml_backend_dev_t dev, + uint32_t n_prefill, uint32_t w_cap, uint32_t n_ctx = 1024, bool shifted = false) { + s.target = pf_target(S, dev, shifted ? 12 : 10); + s.draft = pf_draft_get(B, S, v, dev, shifted); + for (int i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + s.layers[i] = (int32_t) s.draft->model->hparams.dfly_target_kv_layers[i]; + } + s.S = S; + s.w_cap = w_cap; + s.backend = dev ? ggml_backend_dev_name(dev) : "CPU"; + + const uint32_t n_batch = std::max(n_prefill, 64); + s.tgt = pf_target_ctx(s.target, n_ctx, n_batch, std::min(n_batch, 512)); + if (!t.assert_true("target context", s.tgt != nullptr)) { + return false; + } + std::string err; + if (!t.assert_true("capture configure: " + err, s.tgt->dfly_capture_configure(s.layers.data(), LLAMA_DFLY_N_LAYER, S, err))) { + return false; + } + + s.T = get_tokens(n_prefill + 16, 128, PF_SEED); + if (!t.assert_equal("prefill", 0, pf_decode(s.tgt.get(), s.T, 0, n_prefill, false))) { + return false; + } + s.anchor = pf_argmax(llama_get_logits_ith(s.tgt.get(), -1), 128); + s.a = (llama_pos) n_prefill; + + const auto st = s.tgt->dfly_capture_take(PF_EPOCH, s.snaps, err); + if (!t.assert_true("take: " + err, st == LLAMA_DFLY_CAPTURE_STATUS_OK && s.snaps.size() == 1)) { + return false; + } + + s.dft = llama_context_ptr(llama_init_from_model(s.draft->model.get(), pf_draft_params(s.tgt.get(), w_cap, &s.ev))); + if (!t.assert_true("draft context", s.dft != nullptr)) { + return false; + } + s.dft->dfly_set_snapshots_for_test(s.snaps, PF_EPOCH); + return true; +} + +static llama_dfly_status pf_propose(llama_context * d, llama_token anchor, llama_pos a, int32_t K, std::vector & out, + int32_t * n_tokens = nullptr) { + out.assign(std::max(K, 1), -7); + llama_dfly_request rq = { 0, anchor, a, K }; + llama_dfly_result rs = { out.data(), K, -5 }; + const llama_dfly_status st = llama_dfly_propose(d, &rq, &rs); + if (n_tokens) { + *n_tokens = rs.n_tokens; + } + out.resize(std::max(rs.n_tokens, 0)); + return st; +} + +// the snapshot of a successful propose is consumed, so the tests that run several rounds on it rearm it +static llama_dfly_status pf_run(pf_session & s, int32_t K, std::vector & out) { + s.ev.t.clear(); + s.dft->dfly_rearm_for_test(); + return pf_propose(s.dft.get(), s.anchor, s.a, K, out); +} + +static const pf_tensor * pf_find(const pf_eval & ev, const std::string & name) { + const auto it = ev.t.find(name); + return it == ev.t.end() ? nullptr : &it->second; +} + +static std::string pf_lname(const char * name, int il) { + return std::string("dfly_") + name + "-" + std::to_string(il); +} + +static std::string pf_sname(int j, const char * name) { + return "dfly_s" + std::to_string(j) + "." + name; +} + +static bool pf_same(const pf_tensor * a, const pf_tensor * b) { + return a && b && a->ne == b->ne && a->f.size() == b->f.size() && a->i == b->i && + (a->f.empty() || memcmp(a->f.data(), b->f.data(), a->f.size()*sizeof(float)) == 0); +} + +// the first n_rows rows of a tensor whose outermost axis is the slot (n_rows of W) +static bool pf_same_rows(const pf_tensor * a, const pf_tensor * b, int64_t n_rows, int64_t W) { + if (!a || !b || a->ne != b->ne || a->f.size() != b->f.size() || a->f.size() % W != 0) { + return false; + } + const size_t n = a->f.size()/W*n_rows; + return n == 0 || memcmp(a->f.data(), b->f.data(), n*sizeof(float)) == 0; +} + +static double pf_rel_l2(const float * a, const float * b, size_t n) { + double num = 0, den = 0; + for (size_t i = 0; i < n; ++i) { + num += ((double) a[i] - b[i])*((double) a[i] - b[i]); + den += (double) b[i]*b[i]; + } + return den > 0 ? std::sqrt(num/den) : std::sqrt(num); +} + +// the per-token tensors, slot outermost +static std::vector pf_token_major(int n_layer_) { + std::vector names = { "dfly_x_embd", "dfly_x0", "dfly_h_d" }; + for (int il = 0; il < n_layer_; ++il) { + for (const char * n : { "u", "qr", "qp", "q", "c_block", "kp_block", "gate", "attn_out", "post_proj", "x_mid", "ffn_out", "x_out" }) { + names.push_back(pf_lname(n, il)); + } + } + return names; +} + +// +// IN-01..04: init through llama_init_from_model +// + +static int pf_count_op(ggml_cgraph * gf, ggml_op op) { + int n = 0; + for (int i = 0; i < ggml_graph_n_nodes(gf); ++i) { + n += ggml_graph_node(gf, i)->op == op; + } + return n; +} + +static void test_pair_init(testing & t) { + t.test("IN-01_widths", [](testing & t) { + pf_session s; + llama_model * target = pf_target(8, nullptr); + pf_draft * draft = pf_draft_get(8, 8, pf_variant::plain, nullptr); + llama_context_ptr tgt = pf_target_ctx(target, 1024, 64, 64); + if (!t.assert_true("target", tgt != nullptr)) { + return; + } + for (llama_flash_attn_type fa : { LLAMA_FLASH_ATTN_TYPE_AUTO, LLAMA_FLASH_ATTN_TYPE_ENABLED, LLAMA_FLASH_ATTN_TYPE_DISABLED }) { + for (uint32_t w = 1; w <= 8; ++w) { + llama_context_params params = pf_draft_params(tgt.get(), w, nullptr); + params.flash_attn_type = fa; + llama_context_ptr d(llama_init_from_model(draft->model.get(), params)); + const std::string where = std::string(llama_flash_attn_type_name(fa)) + " W_cap=" + std::to_string(w); + if (!t.assert_true(where + " init", d != nullptr)) { + continue; + } + t.assert_true(where + " flash_attn off", !d->get_cparams().flash_attn); + // every width up to W_cap reserves, with mctx = nullptr and no snapshot + for (uint32_t W = 1; W <= w; ++W) { + ggml_cgraph * gf = d->graph_reserve(W, 1, 1, nullptr); + if (!t.assert_true(where + " reserve W=" + std::to_string(W), gf != nullptr)) { + continue; + } + const llm_graph_result * res = d->get_gf_res_reserve(); + const int n_nodes = ggml_graph_n_nodes(gf); + t.assert_equal(where + " no FLASH_ATTN_EXT", 0, pf_count_op(gf, GGML_OP_FLASH_ATTN_EXT)); + t.assert_true(where + " nodes <= graph_max_nodes", n_nodes <= (int) d->graph_max_nodes(W)); + t.assert_true(where + " no logits/embd", res->get_logits() == nullptr && res->get_embd() == nullptr); + t.assert_equal(where + " outputs", (size_t) (W - 1), res->t_dfly_tokens.size()); + t.assert_equal(where + " probes", (size_t) (W - 1), res->t_dfly_finite.size()); + for (size_t j = 0; j < res->t_dfly_tokens.size(); ++j) { + t.assert_true(where + " output flags", (res->t_dfly_tokens[j]->flags & GGML_TENSOR_FLAG_OUTPUT) && + (res->t_dfly_finite[j]->flags & GGML_TENSOR_FLAG_OUTPUT)); + } + // 5 gathers, the block embedding, one prev embedding per slot after the first + t.assert_equal(where + " get_rows", 6 + (int) (W > 2 ? W - 2 : 0), pf_count_op(gf, GGML_OP_GET_ROWS)); + if (fa == LLAMA_FLASH_ATTN_TYPE_AUTO && w == 8) { + t.out << t.indent() << " W=" << W << ": nodes " << n_nodes << " (max " << d->graph_max_nodes(W) << ")\n"; + } + } + } + } + }); + + t.test("IN-02_reject", [](testing & t) { + llama_model * target = pf_target(8, nullptr); + pf_draft * draft = pf_draft_get(5, 8, pf_variant::plain, nullptr); + pf_draft * draft16 = pf_draft_get(5, 16, pf_variant::plain, nullptr); + llama_context_ptr tgt = pf_target_ctx(target, 1024, 64, 64); + + auto expect = [&](const std::string & what, llama_model * m, llama_context_params params, const std::vector & needles) { + log_capture logs; + llama_context_ptr d(llama_init_from_model(m, params)); + t.assert_true(what + ": nullptr", d == nullptr); + const auto errors = logs.get(GGML_LOG_LEVEL_ERROR); + if (!t.assert_true(what + ": ERROR names the field", has_line(errors, needles))) { + print_lines(t, "want", needles); + print_lines(t, "ERROR", errors); + } + }; + + llama_context_params p = pf_draft_params(tgt.get(), 5, nullptr); + + llama_context_params q = p; q.ctx_other = nullptr; + expect("no ctx_other", draft->model.get(), q, { "ctx_other" }); + + // the defaults with only n_ctx matched to the target + q = llama_context_default_params(); q.ctx_other = tgt.get(); q.n_ctx = 1024; + expect("default n_ubatch 512", draft->model.get(), q, { "n_ubatch = 512" }); + + q = p; q.n_batch = 6; q.n_ubatch = 6; + expect("n_ubatch > B", draft->model.get(), q, { "n_ubatch = 6", "block_size 5" }); + + q = p; q.n_batch = 3; q.n_ubatch = 4; + expect("n_batch < n_ubatch", draft->model.get(), q, { "n_batch = 3", "n_ubatch = 4" }); + + q = p; q.n_batch = 4; q.n_ubatch = 0; + { + log_capture logs; + llama_context_ptr d(llama_init_from_model(draft->model.get(), q)); + t.assert_true("n_ubatch 0 resolves to n_batch 4", d != nullptr && d->n_ubatch() == 4); + } + + q = p; q.n_ctx = 2048; + expect("n_ctx differs", draft->model.get(), q, { "n_ctx = 2048", "1024" }); + + q = p; q.n_seq_max = 2; + expect("n_seq_max 2", draft->model.get(), q, { "n_seq_max = 2" }); + + q = p; q.ctx_type = LLAMA_CONTEXT_TYPE_MTP; + expect("MTP", draft->model.get(), q, { "ctx_type" }); + + q = p; q.embeddings = true; + expect("embeddings", draft->model.get(), q, { "embeddings" }); + + q = p; q.rope_freq_base = 1e6f; + expect("rope override", draft->model.get(), q, { "rope_freq_base" }); + + q = p; q.yarn_attn_factor = 0.5f; + expect("attn_factor override", draft->model.get(), q, { "yarn_attn_factor" }); + + // S = 16 against the target's top_k 8: the binding check + expect("S vs top_k", draft16->model.get(), p, { "hy_v4_next_dfly.target_index_top_k = 16", "top_k 8" }); + + // a draft cannot bind a draft + llama_context_ptr d(llama_init_from_model(draft->model.get(), p)); + if (t.assert_true("valid draft", d != nullptr)) { + q = p; q.ctx_other = d.get(); + expect("draft as target", draft->model.get(), q, { "hy_v4_next_dfly", "architecture" }); + } + }); + + t.test("IN-03_forced", [](testing & t) { + llama_model * target = pf_target(8, nullptr); + pf_draft * draft = pf_draft_get(5, 8, pf_variant::plain, nullptr); + llama_context_ptr tgt = pf_target_ctx(target, 1024, 64, 64); + + llama_context_params p = pf_draft_params(tgt.get(), 5, nullptr); + p.n_ctx = 1024; + p.type_k = GGML_TYPE_Q8_0; + p.type_v = GGML_TYPE_F16; + p.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; + p.offload_kqv = false; + + log_capture logs; + llama_context_ptr d(llama_init_from_model(draft->model.get(), p)); + if (!t.assert_true("init", d != nullptr)) { + print_lines(t, "ERROR", logs.get(GGML_LOG_LEVEL_ERROR)); + return; + } + const auto warns = logs.get(GGML_LOG_LEVEL_WARN); + t.assert_true("forcing type_k logged", has_line(warns, { "forcing type_k = f16", "q8_0" })); + t.assert_true("forcing flash_attn logged", has_line(warns, { "forcing flash_attn_type = disabled" })); + t.assert_true("forcing offload_kqv logged", has_line(warns, { "forcing offload_kqv = true" })); + t.assert_true("no FA", !d->get_cparams().flash_attn); + t.assert_true("no logits buffer", llama_get_logits(d.get()) == nullptr); + t.assert_true("no output buffer reserved", !has_line(logs.get(GGML_LOG_LEVEL_INFO), { "output buffer size" })); + }); + + t.test("IN-04_decode", [](testing & t) { + llama_model * target = pf_target(8, nullptr); + pf_draft * draft = pf_draft_get(5, 8, pf_variant::plain, nullptr); + llama_context_ptr tgt = pf_target_ctx(target, 1024, 64, 64); + llama_context_ptr d(llama_init_from_model(draft->model.get(), pf_draft_params(tgt.get(), 5, nullptr))); + if (!t.assert_true("init", d != nullptr)) { + return; + } + llama_batch b = llama_batch_init(2, 0, 1); + for (int i = 0; i < 2; ++i) { + b.token[i] = 3 + i; b.pos[i] = i; b.n_seq_id[i] = 1; b.seq_id[i][0] = 0; b.logits[i] = true; + } + b.n_tokens = 2; + log_capture logs; + t.assert_true("decode fails", llama_decode(d.get(), b) < 0); + t.assert_true("encode fails", llama_encode(d.get(), b) < 0); + t.assert_true("ERROR says propose", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { "llama_dfly_propose" })); + llama_batch_free(b); + }); +} + +// +// BD-01: the binding check as a pure function +// + +static hy_v4_next_dfly_binding bd_valid() { + hy_v4_next_dfly_binding b; + b.n_embd = 128; + b.n_lora_kv = 512; + b.n_rot = 64; + b.top_k = 8; + b.mask_id = 120; + b.rope_base = 1e7f; + b.kv_layers = { 0, 2, 4, 6, 8 }; + b.index_layers = b.kv_layers; + for (int i = 0; i < 128; ++i) { + b.vocab.text.push_back("tok_" + std::to_string(i)); + } + b.vocab.score.assign(128, 0.0f); + b.vocab.attr.assign(128, 1); + b.vocab.special = { { "tokenizer.ggml.bos_token_id", -1 }, { "tokenizer.ggml.eos_token_id", 5 } }; + b.weight_dev = { { "blk.0.attn_norm.weight", "CPU" }, { "output_norm.weight", "CPU" } }; + + b.arch = "hy_v4_flash"; + b.t_n_embd = 128; + b.t_n_lora_kv = 512; + b.t_n_rot = 64; + b.t_top_k = 8; + b.t_kpool = 4; + b.t_select_tail = true; + for (int il = 0; il < 10; ++il) { + hy_v4_next_dfly_target_layer l; + l.swa = il % 2 == 1; + l.has_indexer = il % 2 == 0; + l.rope_base = l.swa ? 1e4f : 1e7f; + l.rope_scale = 1.0f; + b.t_layers.push_back(l); + } + b.t_vocab = b.vocab; + b.e_ne = { 128, 128, 1, 1 }; + b.o_ne = { 128, 128, 1, 1 }; + b.e_dev = "CPU"; + b.o_dev = "CPU"; + for (int i = 0; i < 5; ++i) { + hy_v4_next_dfly_target_k k; + k.found = true; + k.type = GGML_TYPE_F16; + k.width = 576; + k.dev = "CPU"; + b.k.push_back(k); + } + return b; +} + +static void test_binding(testing & t) { + t.test("BD-01_valid", [](testing & t) { + bool ok = true; + try { + hy_v4_next_dfly_check_binding(bd_valid()); + } catch (const std::exception & e) { + ok = false; + t.out << t.indent() << " " << e.what() << "\n"; + } + t.assert_true("valid binding passes", ok); + hy_v4_next_dfly_binding b = bd_valid(); + b.k[0].type = GGML_TYPE_BF16; + ok = true; + try { + hy_v4_next_dfly_check_binding(b); + } catch (const std::exception &) { + ok = false; + } + t.assert_true("BF16 K passes", ok); + }); + + using edit_fn = std::function; + const std::vector> cases = { + { "arch", [](auto & b) { b.arch = "deepseek2"; }, "general.architecture" }, + { "D", [](auto & b) { b.t_n_embd = 64; }, "embedding_length" }, + { "vocab_size", [](auto & b) { b.t_vocab.text.pop_back(); }, "tokenizer.ggml.tokens has 128 tokens" }, + { "token_text", [](auto & b) { b.t_vocab.text[17] = "x"; }, "tokenizer.ggml.tokens[17]" }, + { "token_score", [](auto & b) { b.t_vocab.score[3] = 1.0f; }, "tokenizer.ggml.scores[3]" }, + { "token_attr", [](auto & b) { b.t_vocab.attr[4] = 2; }, "tokenizer.ggml.token_type[4]" }, + { "vocab_type", [](auto & b) { b.t_vocab.type = 2; }, "tokenizer.ggml.model" }, + { "special", [](auto & b) { b.t_vocab.special[1].second = 6; }, "tokenizer.ggml.eos_token_id" }, + { "add_bos", [](auto & b) { b.t_vocab.add_bos = true; }, "add_bos_token" }, + { "mask", [](auto & b) { b.mask_id = 128; }, "mask_token_id" }, + { "E_shape", [](auto & b) { b.e_ne = { 128, 64, 1, 1 }; }, "token_embd.weight" }, + { "O_missing", [](auto & b) { b.o_ne.clear(); }, "output.weight" }, + { "Rkv", [](auto & b) { b.t_n_lora_kv = 256; }, "kv_lora_rank" }, + { "Dr", [](auto & b) { b.t_n_rot = 32; }, "rope.dimension_count" }, + { "yarn", [](auto & b) { b.t_ext_factor = 1.0f; }, "YaRN" }, + { "attn_factor", [](auto & b) { b.t_attn_factor = 0.5f; }, "attn_factor" }, + { "theta", [](auto & b) { b.t_layers[4].rope_base = 1e6f; }, "target_kv_layers[2] = 4" }, + { "rope_scale", [](auto & b) { b.t_layers[8].rope_scale = 0.5f; }, "target_kv_layers[4] = 8" }, + { "dup_layer", [](auto & b) { b.kv_layers[3] = 2; b.index_layers[3] = 2; }, "is listed twice" }, + { "out_layer", [](auto & b) { b.kv_layers[4] = 10; b.index_layers[4] = 10; }, "not a trunk layer" }, + { "swa_layer", [](auto & b) { b.kv_layers[1] = 3; b.index_layers[1] = 3; }, "sliding window" }, + { "no_indexer", [](auto & b) { b.t_layers[6].has_indexer = false; }, "has no indexer" }, + { "kv_vs_index", [](auto & b) { std::swap(b.index_layers[0], b.index_layers[1]); }, "target_index_layers must equal" }, + { "S_not_4x", [](auto & b) { b.top_k = 6; b.t_top_k = 6; }, "target_index_top_k = 6" }, + { "S_too_big", [](auto & b) { b.top_k = 2052; b.t_top_k = 2052; }, "target_index_top_k = 2052" }, + { "S_vs_top_k", [](auto & b) { b.t_top_k = 16; }, "differs from the target's indexer top_k 16" }, + { "kpool", [](auto & b) { b.t_kpool = 3; }, "kpool is 3" }, + { "by_order", [](auto & b) { b.t_kpool_by_order = true; }, "by order" }, + { "select_tail", [](auto & b) { b.t_select_tail = false; }, "kpool_select_tail" }, + { "prism", [](auto & b) { b.t_prism = true; }, "prism.hadamard" }, + { "lora", [](auto & b) { b.t_lora = true; }, "LoRA" }, + { "K_missing", [](auto & b) { b.k[1].found = false; }, "target layer 2 is not in" }, + { "K_quant", [](auto & b) { b.k[2].type = GGML_TYPE_Q8_0; }, "type q8_0" }, + { "K_rotated", [](auto & b) { b.k[3].rotated = true; }, "rotated" }, + { "K_width", [](auto & b) { b.k[0].width = 512; }, "rows of 512" }, + { "dev_E", [](auto & b) { b.e_dev = "CUDA0"; }, "token_embd.weight is on CUDA0" }, + { "dev_O", [](auto & b) { b.o_dev = "CUDA0"; }, "output.weight is on CUDA0" }, + { "dev_K", [](auto & b) { b.k[4].dev = "CUDA0"; }, "target layer 8 is on CUDA0" }, + { "dev_draft", [](auto & b) { b.weight_dev[1].second = "CUDA0"; }, "output_norm.weight is on CUDA0" }, + }; + for (const auto & [name, edit, needle] : cases) { + t.test("BD-01_" + name, [&](testing & t) { + hy_v4_next_dfly_binding b = bd_valid(); + edit(b); + expect_throw(t, name, [&]() { hy_v4_next_dfly_check_binding(b); }, needle); + }); + } +} + +// +// AB-01, SN-01: the propose entry and the snapshot identity checks +// + +static void test_propose_abi(testing & t) { + t.test("AB-01", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + llama_context * d = s.dft.get(); + llama_token buf[8]; + llama_dfly_request rq = { 0, s.anchor, s.a, 4 }; + llama_dfly_result rs = { buf, 8, 9 }; + + auto run = [&](const std::string & what, llama_context * ctx, const llama_dfly_request * q, llama_dfly_result * r, + llama_dfly_status want, const char * log) { + if (r) { + r->n_tokens = 9; + } + log_capture logs; + const llama_dfly_status st = llama_dfly_propose(ctx, q, r); + t.assert_equal(what + " status", (int) want, (int) st); + if (r) { + t.assert_equal(what + " n_tokens", want == LLAMA_DFLY_OK ? q->k_step : 0, r->n_tokens); + } + if (log) { + t.assert_true(what + " log", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { log })); + } + }; + + run("null request", d, nullptr, &rs, LLAMA_DFLY_BAD_REQUEST, "must not be null"); + run("null result", d, &rq, nullptr, LLAMA_DFLY_BAD_REQUEST, "must not be null"); + // the null pointer comes first, then the context + run("target ctx, null request", s.tgt.get(), nullptr, &rs, LLAMA_DFLY_BAD_REQUEST, "must not be null"); + run("target ctx", s.tgt.get(), &rq, &rs, LLAMA_DFLY_BAD_REQUEST, "not a DFly context"); + run("null ctx", nullptr, &rq, &rs, LLAMA_DFLY_BAD_REQUEST, "not a DFly context"); + + llama_dfly_request q = rq; + q.k_step = -1; + run("k_step < 0", d, &q, &rs, LLAMA_DFLY_BAD_REQUEST, "k_step"); + q = rq; + llama_dfly_result r = rs; + r.capacity = 3; + run("capacity < k_step", d, &q, &r, LLAMA_DFLY_BAD_REQUEST, "capacity"); + r = rs; + r.tokens = nullptr; + run("tokens null", d, &q, &r, LLAMA_DFLY_BAD_REQUEST, "tokens"); + q = rq; q.k_step = 5; + run("k_step + 1 > W_cap", d, &q, &rs, LLAMA_DFLY_BAD_REQUEST, "n_ubatch"); + q = rq; q.anchor_token = 128; + run("anchor out of vocab", d, &q, &rs, LLAMA_DFLY_BAD_REQUEST, "anchor_token"); + q = rq; q.seq_id = 1; + run("seq 1", d, &q, &rs, LLAMA_DFLY_BAD_REQUEST, "seq_id"); + q = rq; q.anchor_pos = -1; + run("anchor_pos < 0", d, &q, &rs, LLAMA_DFLY_BAD_REQUEST, "anchor_pos"); + // k_step + 1 must not overflow past the width check + q = rq; q.k_step = INT32_MAX; + r = rs; r.capacity = INT32_MAX; + run("k_step INT32_MAX", d, &q, &r, LLAMA_DFLY_BAD_REQUEST, "n_ubatch"); + + // embeddings turned on after init: the draft has none to give + llama_set_embeddings(d, true); + run("embeddings on", d, &rq, &rs, LLAMA_DFLY_BAD_REQUEST, "embeddings"); + llama_set_embeddings(d, false); + + // a forced prev outside the vocab never reaches get_rows + s.dft->dfly_set_prev_for_test({ s.anchor, 5, 128, 7 }); + run("forced prev out of vocab", d, &rq, &rs, LLAMA_DFLY_BAD_REQUEST, "forced prev"); + s.dft->dfly_set_prev_for_test({}); + + // k_step 0: no snapshot needed and no graph + q = rq; q.k_step = 0; q.anchor_pos = 1000; + r = rs; r.tokens = nullptr; r.capacity = 0; + run("k_step 0", d, &q, &r, LLAMA_DFLY_OK, nullptr); + + run("valid", d, &rq, &rs, LLAMA_DFLY_OK, nullptr); + }); +} + +static void test_snapshot_check(testing & t) { + pf_session s; + t.test("SN-01", [&](testing & t) { + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + std::vector out; + t.assert_equal("valid snapshot", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.anchor, s.a, 4, out)); + + int32_t n = -1; + t.assert_equal("no snapshot at a+1", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) pf_propose(s.dft.get(), s.anchor, s.a + 1, 4, out, &n)); + t.assert_equal("no snapshot: n_tokens", 0, n); + + const auto & cells = pf_base(s.tgt.get())->get_cells(0); + const llama_dfly_snapshot & ok = s.snaps[0]; + // a cell that holds another position of the sequence, and an empty one + uint32_t other = UINT32_MAX; + uint32_t empty = UINT32_MAX; + for (uint32_t c = 0; c < cells.size(); ++c) { + if (cells.is_empty(c)) { + if (empty == UINT32_MAX) { + empty = c; + } + } else if (cells.pos_get(c) != ok.layer[0].pos[0] && std::find(ok.layer[0].cell.begin(), ok.layer[0].cell.end(), c) == ok.layer[0].cell.end()) { + other = c; + } + } + t.assert_true("fixture cells", other != UINT32_MAX && empty != UINT32_MAX && ok.layer[0].pos.size() == 8); + + using snap_edit = std::function; + const std::vector> cases = { + { "ctx_id", [](auto & x) { x.target_ctx_id += 1000; }, PF_EPOCH, "target context" }, + { "old_decode", [](auto & x) { x.decode_id -= 1; }, PF_EPOCH, "last successful decode" }, + { "epoch", [](auto &) {}, PF_EPOCH + 1, "epoch" }, + { "h_final", [](auto & x) { x.h_final.pop_back(); }, PF_EPOCH, "hidden state" }, + { "layer_id", [](auto & x) { x.layer[1].target_layer = 3; }, PF_EPOCH, "is target layer 3" }, + { "stream", [](auto & x) { x.layer[2].strm = 1; }, PF_EPOCH, "stream 1" }, + { "not_owned", [&](auto & x) { x.layer[0].cell[0] = empty; }, PF_EPOCH, "no longer holds" }, + { "pos_differs", [&](auto & x) { x.layer[0].cell[0] = other; }, PF_EPOCH, "no longer holds" }, + { "pos_after_p", [](auto & x) { x.layer[3].pos.back() += 1; }, PF_EPOCH, "last position" }, + { "dup_cell", [](auto & x) { x.layer[4].cell[1] = x.layer[4].cell[0]; }, PF_EPOCH, "repeated" }, + { "dup_pos", [](auto & x) { x.layer[4].pos[1] = x.layer[4].pos[0]; }, PF_EPOCH, "not increasing" }, + { "no_p", [](auto & x) { x.layer[1].pos.pop_back(); x.layer[1].cell.pop_back(); }, PF_EPOCH, "last position" }, + { "count_0", [](auto & x) { x.layer[2].pos.clear(); x.layer[2].cell.clear(); }, PF_EPOCH, "count 0" }, + { "count_gt_S", [&](auto & x) { x.layer[0].pos.insert(x.layer[0].pos.begin(), -1); x.layer[0].cell.insert(x.layer[0].cell.begin(), other); }, PF_EPOCH, "count 9" }, + { "cell_range", [&](auto & x) { x.layer[0].cell[0] = cells.size(); }, PF_EPOCH, "out of range" }, + }; + for (const auto & [name, edit, epoch, needle] : cases) { + llama_dfly_snapshot bad = ok; + edit(bad); + s.dft->dfly_set_snapshots_for_test({ bad }, epoch); + log_capture logs; + n = -1; + const llama_dfly_status st = pf_propose(s.dft.get(), s.anchor, s.a, 4, out, &n); + t.assert_equal(name + " BAD_SNAPSHOT", (int) LLAMA_DFLY_BAD_SNAPSHOT, (int) st); + t.assert_equal(name + " n_tokens", 0, n); + if (!t.assert_true(name + " log", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { "bad snapshot", needle }))) { + print_lines(t, "ERROR", logs.get(GGML_LOG_LEVEL_ERROR)); + } + } + + // design 4.6: the lookup is by (seq, query position), another sequence's snapshot is not selected + { + llama_dfly_snapshot other_seq = ok; + other_seq.seq_id = 1; + s.dft->dfly_set_snapshots_for_test({ other_seq }, PF_EPOCH); + n = -1; + t.assert_equal("seq 1 snapshot, seq 0 request: NO_SNAPSHOT", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) pf_propose(s.dft.get(), s.anchor, s.a, 4, out, &n)); + } + + // a later target decode makes the old snapshot stale + s.dft->dfly_set_snapshots_for_test(s.snaps, PF_EPOCH); + t.assert_equal("verify decode", 0, pf_decode(s.tgt.get(), s.T, s.a, s.a + 5, true)); + t.assert_equal("stale after decode", (int) LLAMA_DFLY_BAD_SNAPSHOT, (int) pf_propose(s.dft.get(), s.anchor, s.a, 4, out)); + }); +} + +// +// C3/C4/C5, DF-01..08, PR-01 on CPU +// + +static void test_graph(testing & t) { + t.test("C3_gather", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + std::vector out; + auto check = [&](const std::string & what, const llama_dfly_snapshot & snap) { + s.dft->dfly_set_snapshots_for_test({ snap }, PF_EPOCH); + if (!t.assert_equal(what + " propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out))) { + return; + } + const auto & inp = s.dft->dfly_input_for_test(); + for (int i = 0; i < n_layer; ++i) { + const auto & l = snap.layer[i]; + const pf_tensor * g = pf_find(s.ev, pf_lname("kctx", i)); + if (!t.assert_true(what + " kctx captured", g && g->ne[0] == 576 && g->ne[1] == 8)) { + continue; + } + bool same = true; + for (int64_t r = 0; r < 8; ++r) { + const uint32_t c = r < (int64_t) l.cell.size() ? l.cell[r] : l.cell.back(); + same &= inp.cell[i][r] == (int32_t) c; + const std::vector want = pf_k_row(s.tgt.get(), s.layers[i], l.strm, c); + same &= memcmp(want.data(), g->f.data() + r*576, 576*sizeof(float)) == 0; + } + t.assert_true(what + " layer " + std::to_string(i) + " gather == host rows, padding = query cell", same); + bool masked = true; + for (int64_t j = 0; j < 5; ++j) { + for (int64_t r = 0; r < 8 + 5; ++r) { + const bool vis = r < (int64_t) l.cell.size() || (r >= 8 && r - 8 <= j); + masked &= vis ? inp.mask[i][j*13 + r] == 0.0f : inp.mask[i][j*13 + r] == -INFINITY; + } + } + t.assert_true(what + " layer " + std::to_string(i) + " mask", masked); + t.assert_true(what + " no -1", std::all_of(inp.cell[i].begin(), inp.cell[i].end(), [](int32_t c) { return c >= 0; })); + } + }; + check("real", s.snaps[0]); + + // single-sequence memory keeps cell == position; inject cell != position (the identity check is skipped) + llama_dfly_snapshot inj = s.snaps[0]; + bool differs = false; + for (auto & l : inj.layer) { + for (auto & c : l.cell) { + c = (uint32_t) (s.a - 1) - c; + } + for (size_t k = 0; k < l.cell.size(); ++k) { + differs |= (llama_pos) l.cell[k] != l.pos[k]; + } + } + t.assert_true("injected cells differ from the positions", differs); + s.dft->dfly_skip_cell_check_for_test(true); + check("injected", inj); + s.dft->dfly_skip_cell_check_for_test(false); + }); + + t.test("C4_no_write", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + llama_context_ptr other = pf_target_ctx(s.target, 1024, 64, 64); + std::string err; + t.assert_true("other configure", other->dfly_capture_configure(s.layers.data(), LLAMA_DFLY_N_LAYER, 8, err)); + t.assert_equal("other prefill", 0, pf_decode(other.get(), s.T, 0, s.a, false)); + + auto k_bytes = [&](llama_context * c) { + std::vector> v; + for (int32_t il : s.layers) { + v.push_back(pf_bytes(pf_base(c)->get_k_storage(il))); + } + return v; + }; + auto cell_map = [&](llama_context * c) { + const auto & sp = pf_base(c)->get_cells(0).seq_pos_get(0); + return std::vector>(sp.begin(), sp.end()); + }; + const auto k_before = k_bytes(s.tgt.get()); + const auto cells_before = cell_map(s.tgt.get()); + + std::vector out; + t.assert_equal("propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + + t.assert_true("K storage unchanged by propose", k_bytes(s.tgt.get()) == k_before); + t.assert_true("K storage equals the untouched context", k_bytes(s.tgt.get()) == k_bytes(other.get())); + t.assert_true("cells unchanged", cell_map(s.tgt.get()) == cells_before && cells_before == cell_map(other.get())); + + t.assert_equal("verify A", 0, pf_decode(s.tgt.get(), s.T, s.a, s.a + 5, true)); + t.assert_equal("verify B", 0, pf_decode(other.get(), s.T, s.a, s.a + 5, true)); + bool same = true; + for (int i = 0; i < 5; ++i) { + same &= memcmp(llama_get_logits_ith(s.tgt.get(), i), llama_get_logits_ith(other.get(), i), 128*sizeof(float)) == 0; + } + t.assert_true("verify logits bitwise equal", same); + }); + + t.test("C5_latent", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + std::vector out; + if (!t.assert_equal("base", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out))) { + return; + } + const pf_eval base = s.ev; + const int il = 2; + const auto & l = s.snaps[0].layer[il]; + ggml_tensor * k = pf_base(s.tgt.get())->get_k_storage(s.layers[il]); + + auto poke = [&](uint32_t cell, const std::function & f) { + std::vector row(k->nb[1]); + const size_t off = l.strm*k->nb[2] + cell*k->nb[1]; + ggml_backend_tensor_get(k, row.data(), off, row.size()); + std::vector mod((const ggml_fp16_t *) row.data(), (const ggml_fp16_t *) row.data() + k->ne[0]); + for (auto & v : mod) { + v = ggml_fp32_to_fp16(ggml_fp16_to_fp32(v) + 0.5f); + } + ggml_backend_tensor_set(k, mod.data(), off, row.size()); + f(); + ggml_backend_tensor_set(k, row.data(), off, row.size()); + }; + + uint32_t unsel = UINT32_MAX; + for (llama_pos q = 0; q < s.a; ++q) { + if (std::find(l.pos.begin(), l.pos.end(), q) == l.pos.end()) { + unsel = (uint32_t) q; + } + } + t.assert_true("an unselected cell", unsel != UINT32_MAX); + poke(unsel, [&]() { + t.assert_equal("propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + bool all = base.t.size() == s.ev.t.size(); + for (const auto & [name, v] : base.t) { + all &= pf_same(&v, pf_find(s.ev, name)); + } + t.assert_true("unselected latent: every intermediate bitwise unchanged", all); + }); + poke(l.cell[0], [&]() { + t.assert_equal("propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + bool before = pf_same(pf_find(base, "dfly_x0"), pf_find(s.ev, "dfly_x0")); + for (const auto & [name, v] : base.t) { + const size_t dash = name.rfind('-'); + if (dash != std::string::npos && name.find(".") == std::string::npos && std::stoi(name.substr(dash + 1)) < il) { + before &= pf_same(&v, pf_find(s.ev, name)); + } + } + t.assert_true("selected latent of layer 2: layers 0..1 bitwise unchanged", before); + t.assert_true("layer 2 kctx changed", !pf_same(pf_find(base, pf_lname("kctx", il)), pf_find(s.ev, pf_lname("kctx", il)))); + t.assert_true("layer 2 probs changed", !pf_same(pf_find(base, pf_lname("probs", il)), pf_find(s.ev, pf_lname("probs", il)))); + t.assert_true("layer 2 x_out changed", !pf_same(pf_find(base, pf_lname("x_out", il)), pf_find(s.ev, pf_lname("x_out", il)))); + t.assert_true("h_d changed", !pf_same(pf_find(base, "dfly_h_d"), pf_find(s.ev, "dfly_h_d"))); + }); + }); + + t.test("DF-01_width", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 8, 8, pf_variant::plain, nullptr, 40, 8)) { + return; + } + std::vector o5, o8; + if (!t.assert_equal("W=5", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, o5))) { + return; + } + const pf_eval e5 = s.ev; + if (!t.assert_equal("W=8", (int) LLAMA_DFLY_OK, (int) pf_run(s, 7, o8))) { + return; + } + t.assert_true("same first 4 tokens", std::equal(o5.begin(), o5.end(), o8.begin())); + double worst = 0; + std::string worst_name; + auto cmp = [&](const std::string & name, size_t n5) { + const pf_tensor * a = pf_find(e5, name); + const pf_tensor * b = pf_find(s.ev, name); + if (!t.assert_true(name + " captured", a && b && a->f.size() >= n5 && b->f.size() >= n5)) { + return; + } + const double r = pf_rel_l2(a->f.data(), b->f.data(), n5); + if (r > worst) { + worst = r; + worst_name = name; + } + }; + for (const auto & name : pf_token_major(n_layer)) { + const pf_tensor * a = pf_find(e5, name); + if (a) { + cmp(name, a->f.size()); + } + } + for (int j = 1; j <= 4; ++j) { + for (const char * n : { "h_corr", "logits" }) { + cmp(pf_sname(j, n), pf_find(e5, pf_sname(j, n)) ? pf_find(e5, pf_sname(j, n))->f.size() : 0); + } + } + t.out << t.indent() << " max rel-L2 W=5 vs W=8 first 5 slots: " << worst << " (" << worst_name << ")\n"; + // the judgment is oracle case t3 (both widths against one reference); here only a bound far below a semantic error: + // the act control floor of t3 is ~1e-2 on s.h_corr; the Debug CPU build gives 2.7e-3, Release 0 + t.assert_true("within 2e-2", worst <= 2e-2); + }); + + t.test("DF-02_future_token", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + std::vector out; + t.assert_equal("base", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + const pf_eval base = s.ev; + s.dft->dfly_set_block_tokens_for_test({ 120, 120, 7, 9 }); + t.assert_equal("slots 3, 4 changed", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + s.dft->dfly_set_block_tokens_for_test({}); + bool same = true; + for (const auto & name : pf_token_major(n_layer)) { + same &= pf_same_rows(pf_find(base, name), pf_find(s.ev, name), 3, 5); + } + t.assert_true("rows 0..2 of every backbone tensor bitwise unchanged", same); + t.assert_true("row 3 of x_embd changed", !pf_same_rows(pf_find(base, "dfly_x_embd"), pf_find(s.ev, "dfly_x_embd"), 4, 5)); + }); + + t.test("DF-04_gate", [](testing & t) { + for (pf_variant v : { pf_variant::gate_zero, pf_variant::gate_neg }) { + const std::string what = v == pf_variant::gate_zero ? "gate 0" : "gate < 0"; + pf_session s; + if (!pf_open(t, s, 5, 8, v, nullptr, 40, 5)) { + return; + } + std::vector out; + t.assert_equal(what + " propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + const pf_tensor * xe = pf_find(s.ev, "dfly_x_embd"); + const pf_tensor * x0 = pf_find(s.ev, "dfly_x0"); + const pf_tensor * dl = pf_find(s.ev, "dfly_fusion_delta"); + if (!t.assert_true(what + " captured", xe && x0 && dl)) { + continue; + } + const int64_t D = 128; + t.assert_true(what + ": rows 1.. bitwise x_embd", memcmp(xe->f.data() + D, x0->f.data() + D, 4*D*sizeof(float)) == 0); + const bool row0_same = memcmp(xe->f.data(), x0->f.data(), D*sizeof(float)) == 0; + if (v == pf_variant::gate_zero) { + t.assert_true("gate 0: x0 == x_embd bitwise", row0_same); + } else { + t.assert_true("gate < 0: row 0 changed", !row0_same); + double err = 0; + for (int64_t c = 0; c < D; ++c) { + const float g = -0.25f - 0.01f*(float) c; + err = std::max(err, std::fabs((double) x0->f[c] - ((double) xe->f[c] + (double) g*dl->f[c]))); + } + t.assert_true("gate < 0: row 0 = e0 + gate*delta (raw gate)", err <= 1e-5); + } + } + }); + + t.test("DF-05_prev", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + std::vector out; + t.assert_equal("base", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + const pf_eval base = s.ev; + const std::vector chain = { s.anchor, out[0], out[1], out[2] }; + + // forcing the graph's own chain changes nothing + s.dft->dfly_set_prev_for_test(chain); + t.assert_equal("forced same chain", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + bool same = true; + for (const auto & [name, v] : base.t) { + if (name.find("safe_id") == std::string::npos) { + same &= pf_same(&v, pf_find(s.ev, name)); + } + } + t.assert_true("the forced own chain is bitwise the in-graph chain", same); + + std::vector alt = chain; + alt[2] = (alt[2] + 11) % 128; + s.dft->dfly_set_prev_for_test(alt); + t.assert_equal("forced other chain", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + s.dft->dfly_set_prev_for_test({}); + bool backbone = true; + for (const auto & name : pf_token_major(n_layer)) { + backbone &= pf_same(pf_find(base, name), pf_find(s.ev, name)); + } + t.assert_true("backbone and h_d bitwise unchanged", backbone); + for (int j = 1; j <= 4; ++j) { + const bool eq = pf_same(pf_find(base, pf_sname(j, "h_corr")), pf_find(s.ev, pf_sname(j, "h_corr"))) && + pf_same(pf_find(base, pf_sname(j, "logits")), pf_find(s.ev, pf_sname(j, "logits"))); + t.assert_true("slot " + std::to_string(j) + (j == 3 ? " changes" : " unchanged"), j == 3 ? !eq : eq); + } + }); + + t.test("DF-07_count", [](testing & t) { + { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 1, 5)) { + return; + } + bool one = true; + for (const auto & l : s.snaps[0].layer) { + one &= l.pos.size() == 1; + } + t.assert_true("prefill 1: count 1 in every layer", one); + std::vector out; + t.assert_equal("count 1 propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + t.assert_equal("count 1 tokens", (size_t) 4, out.size()); + } + { + pf_session s; + if (!pf_open(t, s, 5, 2048, pf_variant::plain, nullptr, 2052, 5, 4096)) { + return; + } + size_t n_max = 0; + for (const auto & l : s.snaps[0].layer) { + n_max = std::max(n_max, l.pos.size()); + } + t.assert_equal("S = 2048: a layer has count 2048", (size_t) 2048, n_max); + std::vector out; + t.assert_equal("count 2048 propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + bool finite = true; + for (const auto & [name, v] : s.ev.t) { + finite &= std::all_of(v.f.begin(), v.f.end(), [](float x) { return std::isfinite(x); }) || name.find("probs") != std::string::npos; + } + t.assert_true("finite intermediates", finite); + } + }); + + t.test("DF-08_target_kv_b", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + std::vector base_out, out; + t.assert_equal("base", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, base_out)); + const pf_eval base = s.ev; + std::vector>> saved; + for (int32_t il : s.layers) { + for (ggml_tensor * w : { s.target->layers[il].wk_b, s.target->layers[il].wv_b }) { + saved.emplace_back(w, pf_bytes(w)); + std::vector junk(ggml_nbytes(w), 0x3c); + ggml_backend_tensor_set(w, junk.data(), 0, junk.size()); + } + } + t.assert_equal("propose", (int) LLAMA_DFLY_OK, (int) pf_run(s, 4, out)); + for (auto & [w, b] : saved) { + ggml_backend_tensor_set(w, b.data(), 0, b.size()); + } + bool same = out == base_out; + for (const auto & [name, v] : base.t) { + same &= pf_same(&v, pf_find(s.ev, name)); + } + t.assert_true("target wk_b/wv_b changed: DFly bitwise unchanged", same); + }); + + t.test("PR-01_propose", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + for (int32_t K = 1; K <= 4; ++K) { + std::vector out; + int32_t n = -1; + s.ev.t.clear(); + s.dft->dfly_rearm_for_test(); + const auto st = pf_propose(s.dft.get(), s.anchor, s.a, K, out, &n); + const std::string w = "K=" + std::to_string(K); + t.assert_equal(w + " OK", (int) LLAMA_DFLY_OK, (int) st); + t.assert_equal(w + " n_tokens", K, n); + bool match = (int32_t) out.size() == K; + for (int32_t j = 1; match && j <= K; ++j) { + const pf_tensor * r = pf_find(s.ev, pf_sname(j, "raw_id")); + match = r && r->i.size() == 1 && r->i[0] == out[j - 1]; + } + t.assert_true(w + " tokens == t_dfly_tokens", match); + const int32_t reused = llama_perf_context(s.dft.get()).n_reused; + std::vector out2; + s.dft->dfly_rearm_for_test(); + t.assert_equal(w + " again", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.anchor, s.a, K, out2)); + t.assert_equal(w + " graph reused", reused + 1, llama_perf_context(s.dft.get()).n_reused); + t.assert_true(w + " same tokens", out2 == out); + } + }); +} + +// +// DF-09: the raw/safe id chain and the finite probe, per backend +// + +static void df09_backend(testing & t, ggml_backend_dev_t dev) { + const bool cuda = ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU; + ggml_backend_ptr be(ggml_backend_dev_init(dev, nullptr)); + const int V = 128; + const int D = 8; + const int R = 5; + + ggml_init_params ip = { 64*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true }; + ggml_context_ptr ctx(ggml_init(ip)); + ggml_tensor * E = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, D, V); + ggml_tensor * raw_in = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, 6); + ggml_tensor * L = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, V, R); + ggml_tensor * safe = hy_v4_next_dfly_build_safe_id(ctx.get(), raw_in, V); + ggml_tensor * rows = ggml_get_rows(ctx.get(), E, safe); + const hy_v4_next_dfly_ids ids = hy_v4_next_dfly_build_ids(ctx.get(), L, V); + + ggml_cgraph * gf = ggml_new_graph(ctx.get()); + for (ggml_tensor * x : { rows, safe, ids.raw, ids.finite }) { + ggml_build_forward_expand(gf, x); + } + for (int i = 0; i < ggml_graph_n_nodes(gf); ++i) { + ggml_tensor * n = ggml_graph_node(gf, i); + t.assert_true(std::string("supports ") + ggml_op_desc(n), ggml_backend_supports_op(be.get(), n)); + } + ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors(ctx.get(), be.get())); + + std::vector e(D*V); + for (int i = 0; i < D*V; ++i) { + e[i] = (float) (i / D) + 0.125f*(float) (i % D); + } + ggml_backend_tensor_set(E, e.data(), 0, ggml_nbytes(E)); + const int32_t in[6] = { -1, 0, 1, V - 1, V, V + 2 }; + ggml_backend_tensor_set(raw_in, in, 0, sizeof(in)); + + const float inf = INFINITY; + const float nan = NAN; + std::vector l(V*R); + for (int i = 0; i < V; ++i) { + l[0*V + i] = i == 77 ? 3.0f : 0.01f*(float) (i % 13); // finite, max at 77 + l[1*V + i] = -inf; // all -inf + l[2*V + i] = nan; // all NaN + l[3*V + i] = i == 7 ? nan : (i == 50 ? 5.0f : 1.0f); // mixed NaN + l[4*V + i] = i == 33 ? inf : 1.0f; // +inf + } + ggml_backend_tensor_set(L, l.data(), 0, ggml_nbytes(L)); + + t.assert_equal("compute", (int) GGML_STATUS_SUCCESS, (int) ggml_backend_graph_compute(be.get(), gf)); + + int32_t s_out[6]; + ggml_backend_tensor_get(safe, s_out, 0, sizeof(s_out)); + std::vector r(6*D); + ggml_backend_tensor_get(rows, r.data(), 0, r.size()*sizeof(float)); + int32_t raw_back[6]; + ggml_backend_tensor_get(raw_in, raw_back, 0, sizeof(raw_back)); + const int32_t want[6] = { 0, 0, 1, V - 1, V - 1, V - 1 }; + for (int k = 0; k < 6; ++k) { + t.assert_equal("safe(" + std::to_string(in[k]) + ")", want[k], s_out[k]); + t.assert_true("row of safe(" + std::to_string(in[k]) + ")", memcmp(r.data() + k*D, e.data() + want[k]*D, D*sizeof(float)) == 0); + } + t.assert_true("raw ids not rewritten", memcmp(raw_back, in, sizeof(in)) == 0); + + int32_t am[R]; + float fp[R]; + ggml_backend_tensor_get(ids.raw, am, 0, sizeof(am)); + ggml_backend_tensor_get(ids.finite, fp, 0, sizeof(fp)); + t.out << t.indent() << " " << ggml_backend_dev_name(dev) << " argmax: finite " << am[0] << ", all -inf " << am[1] << ", all NaN " << am[2] + << ", mixed NaN " << am[3] << ", +inf " << am[4] << "\n"; + t.assert_equal("finite: raw", 77, am[0]); + t.assert_equal("all -inf: raw", cuda ? -1 : V - 1, am[1]); + t.assert_equal("all NaN: raw", cuda ? -1 : 0, am[2]); + t.assert_true("finite: probe 0", fp[0] == 0.0f); + for (int k = 1; k < R; ++k) { + t.assert_true("row " + std::to_string(k) + ": probe NaN", std::isnan(fp[k])); + } + // the host drops the whole round on any of them + std::string err; + t.assert_true("host keeps the finite row", llama_dfly_check_draft(&am[0], &fp[0], 1, V, err)); + for (int k = 1; k < R; ++k) { + t.assert_true("host drops row " + std::to_string(k), !llama_dfly_check_draft(&am[k], &fp[k], 1, V, err)); + } + const int32_t bad_ids[3] = { -1, V, V + 2 }; + const float zero[3] = { 0.0f, 0.0f, 0.0f }; + for (int k = 0; k < 3; ++k) { + t.assert_true("host drops raw " + std::to_string(bad_ids[k]), !llama_dfly_check_draft(&bad_ids[k], &zero[k], 1, V, err)); + } + const int32_t two[2] = { 5, V }; + t.assert_true("one bad slot drops the round", !llama_dfly_check_draft(two, zero, 2, V, err) && err.find("slot 2") != std::string::npos); +} + +static void test_ids(testing & t) { + t.test("DF-09_cpu", [](testing & t) { + df09_backend(t, ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU)); + }); + t.test("DF-09_cuda", [](testing & t) { + ggml_backend_dev_t gpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); + if (gpu == nullptr) { + t.skip("no GPU"); + return; + } + df09_backend(t, gpu); + }); + t.test("DF-09_propose", [](testing & t) { + pf_session s; + if (!pf_open(t, s, 5, 8, pf_variant::plain, nullptr, 40, 5)) { + return; + } + ggml_tensor * o = s.target->output; + const std::vector saved = pf_bytes(o); + std::vector nan_f32(ggml_nelements(o), NAN); + std::vector nan_f16(ggml_nelements(o), ggml_fp32_to_fp16(NAN)); + t.assert_true("O is F32 or F16", o->type == GGML_TYPE_F32 || o->type == GGML_TYPE_F16); + ggml_backend_tensor_set(o, o->type == GGML_TYPE_F32 ? (const void *) nan_f32.data() : (const void *) nan_f16.data(), 0, ggml_nbytes(o)); + std::vector out; + int32_t n = -1; + log_capture logs; + const auto st = pf_propose(s.dft.get(), s.anchor, s.a, 4, out, &n); + ggml_backend_tensor_set(o, saved.data(), 0, saved.size()); + t.assert_equal("NaN logits: BAD_TOKEN", (int) LLAMA_DFLY_BAD_TOKEN, (int) st); + t.assert_equal("NaN logits: n_tokens 0", 0, n); + t.assert_true("log names the slot", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { "draft dropped", "slot 1" })); + // a failed round does not consume the snapshot + t.assert_equal("restored: OK", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.anchor, s.a, 4, out)); + }); +} + +// +// OR: dfly-io-1 cases for the S5a oracle, with LLAMA_DFLY_TEST_ORACLE_DIR= +// + +static void pf_write_bin(const std::string & path, const void * data, size_t n) { + std::ofstream f(path, std::ios::binary); + f.write((const char *) data, (std::streamsize) n); + if (!f.good()) { + throw std::runtime_error("failed to write " + path); + } +} + +struct pf_json_tensors { + std::string dir; + std::vector entries; + + void add_f32(const std::string & name, const std::vector & v, const std::vector & shape) { + GGML_ASSERT((int64_t) v.size() == n_elements(shape)); + pf_write_bin(dir + "/" + name + ".f32", v.data(), v.size()*sizeof(float)); + entries.push_back("\"" + name + "\": {\"file\": \"" + name + ".f32\", \"dtype\": \"f32\", \"shape\": " + list_str(shape) + "}"); + } + void add_i32(const std::string & name, const std::vector & v, const std::vector & shape) { + GGML_ASSERT((int64_t) v.size() == n_elements(shape)); + pf_write_bin(dir + "/" + name + ".i32", v.data(), v.size()*sizeof(int32_t)); + entries.push_back("\"" + name + "\": {\"file\": \"" + name + ".i32\", \"dtype\": \"i32\", \"shape\": " + list_str(shape) + "}"); + } + std::string json() const { + std::string s = "{\n"; + for (size_t i = 0; i < entries.size(); ++i) { + s += " " + entries[i] + (i + 1 < entries.size() ? ",\n" : "\n"); + } + return s + " }"; + } +}; + +static std::string pf_commit() { + const char * c = getenv("LLAMA_DFLY_TEST_COMMIT"); + return c ? c : "unknown"; +} + +// the case of the last propose of s (k_step K); kctx inputs read from the target K storage on the host +static bool pf_write_case(testing & t, pf_session & s, int32_t K, const std::string & dir, const std::string & note) { + namespace fs = std::filesystem; + fs::remove_all(dir); + fs::create_directories(dir + "/cpp"); + + const llama_dfly_snapshot & snap = s.snaps[0]; + const int64_t W = K + 1, D = 128, V = 128, S = s.S, R = 576, Rkv = 512, H = 2, Dv = 128; + const auto & inp = s.dft->dfly_input_for_test(); + + fs::copy_file(s.draft->file.path, dir + "/dfly.gguf"); + const std::vector e = pf_weight_f32(s.target->tok_embd); + const std::vector o = pf_weight_f32(s.target->output); + pf_write_bin(dir + "/tok_embd.f32", e.data(), e.size()*sizeof(float)); + pf_write_bin(dir + "/output.f32", o.data(), o.size()*sizeof(float)); + + pf_json_tensors in; + in.dir = dir; + in.add_f32("h_t", snap.h_final, { D }); + std::string ctx_json; + for (int i = 0; i < n_layer; ++i) { + const auto & l = snap.layer[i]; + std::vector rows; + for (uint32_t c : l.cell) { + const auto r = pf_k_row(s.tgt.get(), s.layers[i], l.strm, c); + rows.insert(rows.end(), r.begin(), r.end()); + } + in.add_f32("l" + std::to_string(i) + ".kctx", rows, { (int64_t) l.cell.size(), R }); + ctx_json += std::string(i ? ",\n " : " ") + "{\"target_layer\": " + std::to_string(s.layers[i]) + ", \"count\": " + + std::to_string(l.pos.size()) + ", \"pos\": " + list_str(l.pos) + "}"; + } + + // the chain the graph used: [anchor, safe_1, ..., safe_{K-1}] + std::vector block(W, 120), prev = { s.anchor }; + block[0] = s.anchor; + for (int j = 1; j < K; ++j) { + const pf_tensor * r = pf_find(s.ev, pf_sname(j, "raw_id")); + if (!t.assert_true("raw_id captured", r && r->i.size() == 1)) { + return false; + } + prev.push_back(std::min(std::max(r->i[0], 0), V - 1)); + } + + std::string json = "{\n \"format\": \"dfly-io-1\",\n \"note\": \"" + note + "; tiny; backend " + s.backend + "; commit " + pf_commit() + + "; test-dfly OR\",\n \"dfly\": {\"kind\": \"gguf\", \"path\": \"dfly.gguf\"},\n" + + " \"eo\": {\"kind\": \"files\", \"tok_embd\": \"tok_embd.f32\", \"output\": \"output.f32\"},\n" + + " \"anchor_token\": " + std::to_string(s.anchor) + ",\n \"anchor_pos\": " + std::to_string(s.a) + ",\n \"W\": " + std::to_string(W) + + ",\n \"mask_token\": 120,\n \"block_tokens\": " + list_str(block) + ",\n \"prev_tokens\": " + list_str(prev) + + ",\n \"ctx\": [\n" + ctx_json + "\n ],\n \"tensors\": " + in.json() + "\n}\n"; + std::ofstream(dir + "/inputs.json") << json; + + pf_json_tensors cp; + cp.dir = dir + "/cpp"; + bool ok = true; + auto get = [&](const std::string & name) -> const pf_tensor * { + const pf_tensor * x = pf_find(s.ev, name); + ok &= t.assert_true(name + " captured", x != nullptr); + return x; + }; + // ggml [a, b, ...] is torch [..., b, a], so slot-outermost tensors are already in torch order + auto direct = [&](const std::string & io, const std::string & name, const std::vector & shape) { + const pf_tensor * x = get(name); + if (x) { + cp.add_f32(io, x->f, shape); + } + }; + direct("x_embd", "dfly_x_embd", { W, D }); + direct("fusion_in", "dfly_fusion_in", { 2*D }); + direct("fusion_delta", "dfly_fusion_delta", { D }); + direct("x0", "dfly_x0", { W, D }); + for (int i = 0; i < n_layer; ++i) { + const std::string p = "l" + std::to_string(i) + "."; + const int64_t n = (int64_t) snap.layer[i].cell.size(); + const int64_t N = S + W; + direct(p + "u", pf_lname("u", i), { W, D }); + direct(p + "qr", pf_lname("qr", i), { W, 512 }); + direct(p + "qp", pf_lname("qp", i), { W, H, 64 }); + direct(p + "q", pf_lname("q", i), { W, H, R }); + direct(p + "c_block", pf_lname("c_block", i), { W, Rkv }); + direct(p + "kp_block", pf_lname("kp_block", i), { W, 64 }); + direct(p + "gate", pf_lname("gate", i), { W, H, Dv }); + direct(p + "attn_out", pf_lname("attn_out", i), { W, D }); + direct(p + "post_proj", pf_lname("post_proj", i), { W, D }); + direct(p + "x_mid", pf_lname("x_mid", i), { W, D }); + direct(p + "ffn_out", pf_lname("ffn_out", i), { W, D }); + direct(p + "x_out", pf_lname("x_out", i), { W, D }); + if (const pf_tensor * x = get(pf_lname("kctx", i))) { + cp.add_f32(p + "kctx", std::vector(x->f.begin(), x->f.begin() + n*R), { n, R }); + } + // the context columns 0..n-1 and the block columns S..S+W-1 + auto col = [&](int64_t c) { return c < n ? c : S + (c - n); }; + std::vector mask; + for (int64_t j = 0; j < W; ++j) { + for (int64_t c = 0; c < n + W; ++c) { + mask.push_back(inp.mask[i][j*N + col(c)]); + } + } + cp.add_f32(p + "mask", mask, { W, n + W }); + if (const pf_tensor * x = get(pf_lname("probs", i))) { // ggml [N, W, H] + std::vector v; + for (int64_t j = 0; j < W; ++j) { + for (int64_t h = 0; h < H; ++h) { + for (int64_t c = 0; c < n + W; ++c) { + v.push_back(x->f[col(c) + N*(j + W*h)]); + } + } + } + cp.add_f32(p + "probs", v, { W, H, n + W }); + } + auto wh = [&](const std::string & io, const std::string & name, int64_t C) { // ggml [C, W, H] -> [W, H, C] + const pf_tensor * x = get(name); + if (!x) { + return; + } + std::vector v; + for (int64_t j = 0; j < W; ++j) { + for (int64_t h = 0; h < H; ++h) { + v.insert(v.end(), x->f.begin() + C*(j + W*h), x->f.begin() + C*(j + W*h + 1)); + } + } + cp.add_f32(io, v, { W, H, C }); + }; + wh(p + "o_latent", pf_lname("o_latent", i), Rkv); + wh(p + "o", pf_lname("o", i), Dv); + } + direct("h_d", "dfly_h_d", { W, D }); + for (int j = 1; j <= K; ++j) { + const std::string p = "s" + std::to_string(j) + "."; + direct(p + "corr_in", pf_sname(j, "corr_in"), { 2*D }); + direct(p + "corr_delta", pf_sname(j, "corr_delta"), { D }); + direct(p + "h_corr", pf_sname(j, "h_corr"), { D }); + direct(p + "logits", pf_sname(j, "logits"), { V }); + direct(p + "finite_probe", pf_sname(j, "finite_probe"), { 1 }); + if (const pf_tensor * x = get(pf_sname(j, "raw_id"))) { + cp.add_i32(p + "raw_id", x->i, { 1 }); + cp.add_i32(p + "safe_id", { std::min(std::max(x->i[0], 0), V - 1) }, { 1 }); + } + } + std::ofstream(dir + "/cpp/tensors.json") << "{\n \"meta\": {\"producer\": \"cpp\", \"mode\": \"ggml\", \"backend\": \"" + s.backend + + "\", \"commit\": \"" + pf_commit() + "\"},\n \"tensors\": " + cp.json() + "\n}\n"; + return ok; +} + +static void test_oracle_cases(testing & t) { + const char * root = getenv("LLAMA_DFLY_TEST_ORACLE_DIR"); + if (root == nullptr) { + t.skip("set LLAMA_DFLY_TEST_ORACLE_DIR= to write the dfly-io-1 cases"); + return; + } + struct pf_case { + std::string name; + uint32_t B, S; + pf_variant v; + uint32_t n_prefill, n_ctx; + std::vector Ks; + }; + const std::vector cases = { + { "t1", 5, 8, pf_variant::plain, 40, 1024, { 1, 2, 3, 4 } }, + { "t2", 5, 8, pf_variant::plain, 1, 1024, { 4 } }, + { "t3", 8, 8, pf_variant::plain, 40, 1024, { 4, 7 } }, + { "t4", 5, 2048, pf_variant::plain, 2052, 4096, { 4 } }, + { "t5", 5, 8, pf_variant::sinks, 40, 1024, { 4 } }, + { "t6", 5, 8, pf_variant::gate_neg, 40, 1024, { 4 } }, + }; + ggml_backend_dev_t gpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); + for (ggml_backend_dev_t dev : { (ggml_backend_dev_t) nullptr, gpu }) { + for (const auto & c : cases) { + if (dev != nullptr && c.name != "t1" && c.name != "t3") { + continue; + } + const std::string bk = dev ? "cuda0" : "cpu"; + t.test(c.name + "_" + bk, [&](testing & t) { + pf_session s; + if (!pf_open(t, s, c.B, c.S, c.v, dev, c.n_prefill, c.B, c.n_ctx, true)) { + return; + } + for (int32_t K : c.Ks) { + std::vector out; + if (!t.assert_equal("propose K=" + std::to_string(K), (int) LLAMA_DFLY_OK, (int) pf_run(s, K, out))) { + continue; + } + const std::string dir = std::string(root) + "/" + c.name + "_w" + std::to_string(K + 1) + "_" + bk; + t.assert_true("case written: " + dir, pf_write_case(t, s, K, dir, + c.name + " B=" + std::to_string(c.B) + " S=" + std::to_string(c.S) + " prefill " + std::to_string(c.n_prefill))); + } + }); + } + if (gpu == nullptr) { + break; + } + } +} + +// +// S5c: the public capture path, llama_dfly_capture_enable/pull/invalidate with llama_dfly_propose +// + +// target + draft through the public calls only; the target is warmed up and probed before capture_enable +static bool pc_open(testing & t, pf_session & s, uint32_t n_ctx, bool enable = true) { + s.target = pf_target(8, nullptr); + s.draft = pf_draft_get(5, 8, pf_variant::plain, nullptr); + s.S = 8; + s.w_cap = 5; + s.backend = "CPU"; + for (int i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + s.layers[i] = (int32_t) s.draft->model->hparams.dfly_target_kv_layers[i]; + } + s.tgt = pf_target_ctx(s.target, n_ctx, 2048, 512); + if (!t.assert_true("target context", s.tgt != nullptr)) { + return false; + } + // what common does before capture_enable: a warmup decode and the seq_rm probe + pf_decode(s.tgt.get(), { 1 }, 0, 1, true); + llama_memory_clear(llama_get_memory(s.tgt.get()), true); + pf_decode(s.tgt.get(), { 0, 0 }, 0, 2, true); + llama_memory_seq_rm(llama_get_memory(s.tgt.get()), 0, 1, -1); + llama_memory_clear(llama_get_memory(s.tgt.get()), true); + + s.dft = llama_context_ptr(llama_init_from_model(s.draft->model.get(), pf_draft_params(s.tgt.get(), 5, &s.ev))); + if (!t.assert_true("draft context", s.dft != nullptr)) { + return false; + } + if (enable) { + return t.assert_equal("capture_enable", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_enable(s.dft.get())); + } + return true; +} + +static bool pc_same_snap(const llama_dfly_snapshot & a, const llama_dfly_snapshot & b) { + bool same = a.target_ctx_id == b.target_ctx_id && a.decode_id == b.decode_id && a.prefix_epoch == b.prefix_epoch && + a.seq_id == b.seq_id && a.batch_row == b.batch_row && a.query_pos == b.query_pos && a.h_final == b.h_final; + for (int i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + same = same && a.layer[i].target_layer == b.layer[i].target_layer && a.layer[i].strm == b.layer[i].strm && + a.layer[i].pos == b.layer[i].pos && a.layer[i].cell == b.layer[i].cell; + } + return same; +} + +static void test_public_capture(testing & t) { + // plan 12.3 item 1: after a verify of W = 5 rows, the propose at anchor_pos = a + r + 1 reads row r + t.test("PC-01_rows", [](testing & t) { + for (uint32_t P : { 16u, 32u, 2047u }) { + const std::string w = "prefill " + std::to_string(P); + pf_session s; + if (!pc_open(t, s, 4096)) { + return; + } + s.T = get_tokens(P + 16, 128, PF_SEED + P); + if (!t.assert_equal(w + ": prefill", 0, pf_decode(s.tgt.get(), s.T, 0, P, false))) { + continue; + } + t.assert_equal(w + ": pull after prefill", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_true(w + ": prefill keeps its last row only", s.dft->dfly_snapshots_for_test().size() == 1 && + s.dft->dfly_snapshots_for_test()[0].query_pos == (llama_pos) P - 1); + + const llama_pos a = P; + t.assert_equal(w + ": verify", 0, pf_decode(s.tgt.get(), s.T, a, a + 5, true)); + t.assert_equal(w + ": pull after verify", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + const auto snaps = s.dft->dfly_snapshots_for_test(); + if (!t.assert_equal(w + ": K + 1 rows", (size_t) 5, snaps.size())) { + continue; + } + for (uint32_t r = 0; r < 5; ++r) { + const std::string wr = w + " r=" + std::to_string(r); + std::vector out; + const auto st = pf_propose(s.dft.get(), s.T[a + r + 1], a + (llama_pos) r + 1, 3, out); + if (!t.assert_equal(wr + ": propose", (int) LLAMA_DFLY_OK, (int) st)) { + continue; + } + const llama_dfly_snapshot * sel = nullptr; + for (const auto & sn : snaps) { + if (sn.query_pos == a + (llama_pos) r) { + sel = &sn; + } + } + const float * h = llama_get_embeddings_nextn_ith(s.tgt.get(), (int32_t) r); + t.assert_true(wr + ": the selected row is verify row r", sel && sel->batch_row == (int32_t) r); + t.assert_true(wr + ": h_t is that row's hidden", + sel && s.dft->dfly_input_for_test().h_t == sel->h_final && + h && memcmp(h, sel->h_final.data(), sel->h_final.size()*sizeof(float)) == 0); + } + } + }); + + // plan 12.3 item 2: owned snapshots survive the target graph reuse; an older decode is never consumed + t.test("PC-02_reuse", [](testing & t) { + pf_session s; + if (!pc_open(t, s, 1024)) { + return; + } + s.T = get_tokens(80, 128, PF_SEED); + t.assert_equal("prefill", 0, pf_decode(s.tgt.get(), s.T, 0, 40, false)); + t.assert_equal("verify 1", 0, pf_decode(s.tgt.get(), s.T, 40, 45, true)); + t.assert_equal("pull 1", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + const auto kept = s.dft->dfly_snapshots_for_test(); + + // same shape again after a full rollback: the target reuses its graph + llama_memory_seq_rm(llama_get_memory(s.tgt.get()), 0, 40, -1); + const int32_t reused = llama_perf_context(s.tgt.get()).n_reused; + t.assert_equal("verify 2", 0, pf_decode(s.tgt.get(), s.T, 40, 45, true)); + t.assert_true("the target graph was reused", llama_perf_context(s.tgt.get()).n_reused > reused); + + const auto & now = s.dft->dfly_snapshots_for_test(); + bool same = now.size() == kept.size(); + for (size_t i = 0; same && i < kept.size(); ++i) { + same = pc_same_snap(kept[i], now[i]); + } + t.assert_true("pulled snapshots bytewise unchanged", same); + + // not pulled: the row of decode 1 at the anchor is still held, the identity check rejects it as stale + std::vector out; + log_capture logs; + t.assert_equal("old decode: BAD_SNAPSHOT", (int) LLAMA_DFLY_BAD_SNAPSHOT, (int) pf_propose(s.dft.get(), s.T[43], 43, 3, out)); + t.assert_true("log: not the last decode", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { "last successful decode" })); + // and a position decode 1 never output has no snapshot at all + t.assert_equal("no row: NO_SNAPSHOT", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) pf_propose(s.dft.get(), s.T[46], 46, 3, out)); + + t.assert_equal("pull 2", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_equal("after pull: OK", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.T[43], 43, 3, out)); + }); + + // plan 12.3 item 8: capture on changes no target logits; a verify keeps K + 1 rows + t.test("PC-03_logits", [](testing & t) { + pf_session s; + if (!pc_open(t, s, 1024, false)) { + return; + } + s.T = get_tokens(80, 128, PF_SEED); + auto run = [&](std::vector & logits) { + llama_memory_clear(llama_get_memory(s.tgt.get()), true); + bool ok = pf_decode(s.tgt.get(), s.T, 0, 40, false) == 0 && pf_decode(s.tgt.get(), s.T, 40, 45, true) == 0; + logits.clear(); + for (int i = 0; ok && i < 5; ++i) { + const float * l = llama_get_logits_ith(s.tgt.get(), i); + logits.insert(logits.end(), l, l + 128); + } + return ok; + }; + std::vector before, after; + t.assert_true("decode before", run(before)); + t.assert_equal("pull before capture_enable", (int) LLAMA_DFLY_BAD_REQUEST, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_equal("capture_enable", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_enable(s.dft.get())); + t.assert_equal("capture_enable again", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_enable(s.dft.get())); + t.assert_true("decode after", run(after)); + t.assert_true("same-shape logits bitwise unchanged", before == after); + t.assert_equal("pull", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_equal("K + 1 rows kept", (size_t) 5, s.dft->dfly_snapshots_for_test().size()); + }); + + t.test("PC-04_states", [](testing & t) { + pf_session s; + if (!pc_open(t, s, 1024)) { + return; + } + s.T = get_tokens(80, 128, PF_SEED); + t.assert_equal("prefill", 0, pf_decode(s.tgt.get(), s.T, 0, 40, false)); + t.assert_equal("pull", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + + std::vector out; + t.assert_equal("first propose", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + t.assert_equal("consumed: NO_SNAPSHOT", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + + // design 4.6: a second pull of the same decode publishes nothing, the consumed snapshot stays consumed + t.assert_equal("pull again", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_equal("pull keeps the snapshot", (size_t) 1, s.dft->dfly_snapshots_for_test().size()); + t.assert_equal("pull again: still consumed", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + + // a failed round does not consume + s.dft->dfly_rearm_for_test(); + ggml_tensor * o = s.target->output; + const std::vector saved = pf_bytes(o); + std::vector nan_f32(ggml_nelements(o), NAN); + ggml_backend_tensor_set(o, nan_f32.data(), 0, ggml_nbytes(o)); + t.assert_equal("BAD_TOKEN", (int) LLAMA_DFLY_BAD_TOKEN, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + ggml_backend_tensor_set(o, saved.data(), 0, saved.size()); + t.assert_equal("not consumed by the failure", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + + // invalidate: new epoch, nothing to propose from until the next pull + t.assert_equal("pull 3", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + const uint64_t e0 = s.dft->dfly_epoch_for_test(); + llama_dfly_invalidate(s.dft.get(), 0); + t.assert_equal("epoch + 1", e0 + 1, s.dft->dfly_epoch_for_test()); + t.assert_equal("invalidated: NO_SNAPSHOT", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + // design 4.6: the rows staged before the invalidate are not published again, a new decode is + t.assert_equal("pull after invalidate", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_true("not published again", s.dft->dfly_snapshots_for_test().empty()); + llama_memory_seq_rm(llama_get_memory(s.tgt.get()), 0, 39, -1); + t.assert_equal("decode row 39 again", 0, pf_decode(s.tgt.get(), s.T, 39, 40, true)); + t.assert_equal("pull after the decode", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_true("new epoch in the snapshot", s.dft->dfly_snapshots_for_test().size() == 1 && + s.dft->dfly_snapshots_for_test()[0].prefix_epoch == e0 + 1); + t.assert_equal("OK in the new epoch", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.T[40], 40, 4, out)); + + // a decode without outputs: NO_SNAPSHOT, and the older rows are dropped + llama_batch b = llama_batch_init(1, 0, 1); + b.token[0] = s.T[40]; b.pos[0] = 40; b.n_seq_id[0] = 1; b.seq_id[0][0] = 0; b.logits[0] = false; b.n_tokens = 1; + t.assert_equal("decode without outputs", 0, llama_decode(s.tgt.get(), b)); + llama_batch_free(b); + t.assert_equal("no rows: NO_SNAPSHOT", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_equal("no rows: set emptied", (size_t) 0, s.dft->dfly_snapshots_for_test().size()); + + // a pull after a seq edit: the take fails; the older rows of the sequence are stale, the epoch stays + t.assert_equal("verify", 0, pf_decode(s.tgt.get(), s.T, 41, 46, true)); + llama_memory_seq_rm(llama_get_memory(s.tgt.get()), 0, 43, -1); + const uint64_t e1 = s.dft->dfly_epoch_for_test(); + log_capture logs; + t.assert_equal("pull after seq_rm: BAD_SNAPSHOT", (int) LLAMA_DFLY_BAD_SNAPSHOT, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_true("dropped", s.dft->dfly_epoch_for_test() == e1 && s.dft->dfly_snapshots_for_test().empty()); + t.assert_true("log", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { "capture failed" })); + + // the public calls check the context first + t.assert_equal("enable on the target", (int) LLAMA_DFLY_BAD_REQUEST, (int) llama_dfly_capture_enable(s.tgt.get())); + t.assert_equal("pull on null", (int) LLAMA_DFLY_BAD_REQUEST, (int) llama_dfly_capture_pull(nullptr)); + llama_dfly_invalidate(nullptr, 0); + }); + + // 20 rounds of prefill/pull/propose/verify/pull/rollback through the public calls only + t.test("PC-05_loop", [](testing & t) { + pf_session s; + if (!pc_open(t, s, 1024)) { + return; + } + const uint32_t K = 4; + std::vector T = get_tokens(32, 128, PF_SEED); + t.assert_equal("prefill", 0, pf_decode(s.tgt.get(), T, 0, 32, false)); + llama_token anchor = pf_argmax(llama_get_logits_ith(s.tgt.get(), -1), 128); + llama_pos a = 32; + int n_ok = 0, n_qpos = 0; + t.assert_equal("pull after prefill", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + for (int rd = 0; rd < 20; ++rd) { + std::vector d; + const auto st = pf_propose(s.dft.get(), anchor, a, (int32_t) K, d); + n_ok += st == LLAMA_DFLY_OK; + const auto & snaps = s.dft->dfly_snapshots_for_test(); + for (const auto & sn : snaps) { + if (sn.h_final == s.dft->dfly_input_for_test().h_t) { + n_qpos += sn.query_pos == a - 1; + break; + } + } + if (st != LLAMA_DFLY_OK) { + break; + } + std::vector verify = { anchor }; + verify.insert(verify.end(), d.begin(), d.end()); + if (T.size() < (size_t) a + K + 1) { + T.resize(a + K + 1); + } + std::copy(verify.begin(), verify.end(), T.begin() + a); + if (!t.assert_equal("verify decode", 0, pf_decode(s.tgt.get(), T, a, a + (llama_pos) K + 1, true))) { + break; + } + // before the rollback + if (!t.assert_equal("pull", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get()))) { + break; + } + const uint32_t r = (uint32_t) (rd*3 + 1) % (K + 1); + anchor = pf_argmax(llama_get_logits_ith(s.tgt.get(), (int32_t) r), 128); + if (r < K) { + llama_memory_seq_rm(llama_get_memory(s.tgt.get()), 0, a + (llama_pos) r + 1, -1); + } + a += (llama_pos) r + 1; + } + t.assert_equal("20 rounds OK", 20, n_ok); + t.assert_equal("each round read query_pos = anchor_pos - 1", 20, n_qpos); + }); + + // plan U05: a state read drops the staged rows; neither they nor a snapshot pulled before the read are used + t.test("PC-06_restore", [](testing & t) { + for (const bool seq : { true, false }) { + const std::string w = seq ? "seq state" : "full state"; + pf_session s; + if (!pc_open(t, s, 1024)) { + return; + } + s.T = get_tokens(80, 128, PF_SEED); + std::vector alt = s.T; + for (llama_pos p = 40; p < 45; ++p) { + alt[p] = (s.T[p] + 1) % 128; + } + llama_context * tgt = s.tgt.get(); + t.assert_equal(w + ": prefill", 0, pf_decode(tgt, s.T, 0, 40, false)); + t.assert_equal(w + ": verify", 0, pf_decode(tgt, s.T, 40, 45, true)); + std::vector state(seq ? llama_state_seq_get_size(tgt, 0) : llama_state_get_size(tgt)); + const size_t n_state = seq ? llama_state_seq_get_data(tgt, state.data(), state.size(), 0) : llama_state_get_data(tgt, state.data(), state.size()); + t.assert_equal(w + ": saved", state.size(), n_state); + + // the same positions with other tokens, pulled, then the saved state read back + llama_memory_seq_rm(llama_get_memory(tgt), 0, 40, -1); + t.assert_equal(w + ": other verify", 0, pf_decode(tgt, alt, 40, 45, true)); + t.assert_equal(w + ": pull", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + const size_t n_read = seq ? llama_state_seq_set_data(tgt, state.data(), state.size(), 0) : llama_state_set_data(tgt, state.data(), state.size()); + t.assert_equal(w + ": read", state.size(), n_read); + t.assert_equal(w + ": memory back at 44", (llama_pos) 44, llama_memory_seq_pos_max(llama_get_memory(tgt), 0)); + + std::vector out; + { + log_capture logs; + t.assert_equal(w + ": snapshot pulled before the read: BAD_SNAPSHOT", (int) LLAMA_DFLY_BAD_SNAPSHOT, (int) pf_propose(s.dft.get(), s.T[44], 44, 3, out)); + t.assert_true(w + ": log: not the last decode", has_line(logs.get(GGML_LOG_LEVEL_ERROR), { "last successful decode" })); + } + t.assert_equal(w + ": pull after the read: NO_SNAPSHOT", (int) LLAMA_DFLY_NO_SNAPSHOT, (int) llama_dfly_capture_pull(s.dft.get())); + + // the next decode gives a new snapshot + t.assert_equal(w + ": decode", 0, pf_decode(tgt, s.T, 45, 46, true)); + t.assert_equal(w + ": pull after the decode", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get())); + t.assert_equal(w + ": propose after the decode", (int) LLAMA_DFLY_OK, (int) pf_propose(s.dft.get(), s.T[46], 46, 3, out)); + } + }); +} + +// +// SS: plan 7.5, a tail decoded after a trim or a checkpoint restore of its prefix equals the tail right after the prefix +// + +enum class ss_how { ref, trim, checkpoint, full, full_ckpt, reloc }; + +struct ss_out { + std::vector> logits; // the rows of T + std::vector snaps; + int st = -1; + std::vector draft; +}; + +static const uint32_t SS_W = 5; + +static std::map ss_cells(const llama_kv_cells & cells) { + std::map res; + for (const auto & pc : cells.seq_pos_get(0)) { + res[pc.first] = pc.second; + } + return res; +} + +// plan 4.9: the prefix back from its full state; full_ckpt saves P + 40 and takes the checkpoint of P, reloc restores over other cells +static bool ss_full(testing & t, const std::string & w, llama_context * tgt, uint32_t P, uint32_t n_junk, ss_how how) { + llama_memory_t mem = llama_get_memory(tgt); + auto * imem = dynamic_cast(mem); + if (!t.assert_true(w + ": idx iswa memory", imem != nullptr)) { + return false; + } + auto swa = [&]() { return ss_cells(imem->get_mem_attn()->get_swa ()->get_cells(0)); }; + auto base = [&]() { return ss_cells(imem->get_mem_attn()->get_base()->get_cells(0)); }; + + std::vector ckpt; + llama_pos E = P; + if (how == ss_how::full_ckpt) { + ckpt.resize(llama_state_seq_get_size_ext(tgt, 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); + std::vector J = get_tokens(P + 40, 128, PF_SEED + P + 2); + if (!t.assert_equal(w + ": checkpoint saved", ckpt.size(), llama_state_seq_get_data_ext(tgt, ckpt.data(), ckpt.size(), 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) || + !t.assert_equal(w + ": 40 more tokens", 0, pf_decode(tgt, J, P, P + 40, false))) { + return false; + } + E = P + 40; + } + std::vector full(llama_state_seq_get_size_ext(tgt, 0, 0)); + if (!t.assert_equal(w + ": full state saved", full.size(), llama_state_seq_get_data_ext(tgt, full.data(), full.size(), 0, 0))) { + return false; + } + const auto swa_saved = swa(); + const auto base_saved = base(); + + std::map before; // cell -> position of the other tokens + if (how == ss_how::reloc) { + llama_memory_seq_rm(mem, 0, -1, -1); + std::vector J = get_tokens(1000 + P + SS_W, 128, PF_SEED + P + 3); + if (!t.assert_equal(w + ": other tokens at 1000", 0, pf_decode(tgt, J, 1000, 1000 + P + SS_W, false))) { + return false; + } + for (const auto & pc : base()) { + before[pc.second] = pc.first; + } + } else { + std::vector J = get_tokens(E + n_junk, 128, PF_SEED + P + 1); + if (n_junk > 0 && !t.assert_equal(w + ": other tokens", 0, pf_decode(tgt, J, E, E + n_junk, false))) { + return false; + } + llama_memory_seq_rm(mem, 0, -1, -1); + } + + if (!t.assert_equal(w + ": full state restored", full.size(), llama_state_seq_set_data_ext(tgt, full.data(), full.size(), 0, 0)) || + !t.assert_equal(w + ": memory ends at E - 1", E - 1, llama_memory_seq_pos_max(mem, 0))) { + return false; + } + // the state keeps the window of E - 1 only (I03) + t.assert_equal(w + ": SWA pos_min after the restore", std::max(0, E - 32), llama_memory_seq_pos_min(mem, 0)); + + if (how == ss_how::reloc) { + const auto swa_now = swa(); + const auto base_now = base(); + size_t n_moved = 0; + for (const auto & pc : swa_now) { + n_moved += swa_saved.count(pc.first) && swa_saved.at(pc.first) != pc.second; + } + t.assert_true(w + ": the SWA rows moved to other cells (" + std::to_string(n_moved) + " of " + std::to_string(swa_now.size()) + ")", + n_moved > 0 && swa_now.size() == (size_t) std::min(P, 32)); + bool reused = base_now.size() == P; + for (const auto & pc : base_now) { + reused = reused && before.count(pc.second) && before.at(pc.second) >= 1000; + } + t.assert_true(w + ": the base rows took the cells of the other tokens", reused); + // n_seq_max 1: the restore clears the sequence first, so the base rows land where they were saved + t.assert_true(w + ": the base cells as saved", base_now == base_saved); + } + + if (how == ss_how::full_ckpt) { + t.assert_true(w + ": the full state alone misses the window of P", llama_memory_seq_pos_min(mem, 0) > (llama_pos) P - 31); + // the server order: the checkpoint, then the positions after it + if (!t.assert_equal(w + ": checkpoint restored", ckpt.size(), llama_state_seq_set_data_ext(tgt, ckpt.data(), ckpt.size(), 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) || + !t.assert_true(w + ": seq_rm", llama_memory_seq_rm(mem, 0, P, -1)) || + !t.assert_equal(w + ": memory ends at P - 1", (llama_pos) P - 1, llama_memory_seq_pos_max(mem, 0))) { + return false; + } + t.assert_true(w + ": the window of P is back", llama_memory_seq_pos_min(mem, 0) <= std::max(0, P - 31)); + } + return true; +} + +// n_junk: the other tokens decoded after P and removed again; as many as T keeps the cell count of the sequence +static bool ss_run(testing & t, ss_how how, uint32_t P, uint32_t n_junk, ss_out & out) { + static const std::map names = { + { ss_how::ref, "ref" }, { ss_how::trim, "trim" }, { ss_how::checkpoint, "checkpoint" }, + { ss_how::full, "full" }, { ss_how::full_ckpt, "full + checkpoint" }, { ss_how::reloc, "relocated full" }, + }; + const std::string w = std::string(names.at(how)) + " P=" + std::to_string(P) + " junk " + std::to_string(n_junk); + pf_session s; + if (!pc_open(t, s, 2048)) { + return false; + } + llama_context * tgt = s.tgt.get(); + llama_memory_t mem = llama_get_memory(tgt); + const std::vector T = get_tokens(P + SS_W, 128, PF_SEED + P); + + if (!t.assert_equal(w + ": prefix", 0, pf_decode(tgt, T, 0, P, false))) { + return false; + } + std::vector ckpt; + if (how == ss_how::checkpoint) { + ckpt.resize(llama_state_seq_get_size_ext(tgt, 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); + if (!t.assert_equal(w + ": checkpoint saved", ckpt.size(), llama_state_seq_get_data_ext(tgt, ckpt.data(), ckpt.size(), 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY))) { + return false; + } + } + if ((how == ss_how::full || how == ss_how::full_ckpt || how == ss_how::reloc) && !ss_full(t, w, tgt, P, n_junk, how)) { + return false; + } + if (how == ss_how::trim || how == ss_how::checkpoint) { + std::vector J = get_tokens(P + n_junk, 128, PF_SEED + P + 1); + std::copy(T.begin(), T.begin() + P, J.begin()); + if (!t.assert_equal(w + ": other tokens", 0, pf_decode(tgt, J, P, P + n_junk, false))) { + return false; + } + // for iswa the memory pos_min is the SWA cache's + const llama_pos pmin = llama_memory_seq_pos_min(mem, 0); + if (how == ss_how::trim) { + t.assert_true(w + ": the SWA cache still holds the window of P (pos_min " + std::to_string(pmin) + ")", pmin <= std::max(0, P - 32)); + } else { + t.assert_true(w + ": the SWA cache no longer holds P - 1 (pos_min " + std::to_string(pmin) + ")", pmin > (llama_pos) P - 1); + } + if (!t.assert_true(w + ": seq_rm", llama_memory_seq_rm(mem, 0, P, -1))) { + return false; + } + } + if (how == ss_how::checkpoint) { + if (!t.assert_equal(w + ": checkpoint restored", ckpt.size(), llama_state_seq_set_data_ext(tgt, ckpt.data(), ckpt.size(), 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) || + !t.assert_equal(w + ": memory ends at P - 1", (llama_pos) P - 1, llama_memory_seq_pos_max(mem, 0))) { + return false; + } + } + + if (!t.assert_equal(w + ": tail", 0, pf_decode(tgt, T, P, P + SS_W, true))) { + return false; + } + for (uint32_t i = 0; i < SS_W; ++i) { + const float * l = llama_get_logits_ith(tgt, i); + out.logits.emplace_back(l, l + 128); + } + if (!t.assert_equal(w + ": pull", (int) LLAMA_DFLY_OK, (int) llama_dfly_capture_pull(s.dft.get()))) { + return false; + } + out.snaps = s.dft->dfly_snapshots_for_test(); + out.st = pf_propose(s.dft.get(), pf_argmax(out.logits.back().data(), 128), P + SS_W, 4, out.draft); + return true; +} + +// the context identity, the decode id, the epoch and the cells differ between two contexts by design +static bool ss_same_snap(const llama_dfly_snapshot & a, const llama_dfly_snapshot & b) { + bool same = a.seq_id == b.seq_id && a.batch_row == b.batch_row && a.query_pos == b.query_pos && + a.h_final.size() == b.h_final.size() && std::memcmp(a.h_final.data(), b.h_final.data(), a.h_final.size() * sizeof(float)) == 0; + for (int i = 0; i < LLAMA_DFLY_N_LAYER; ++i) { + same = same && a.layer[i].target_layer == b.layer[i].target_layer && a.layer[i].pos == b.layer[i].pos; + } + return same; +} + +static void test_same_shape(testing & t) { + static const std::map names = { + { ss_how::trim, "SS-01_trim" }, { ss_how::checkpoint, "SS-02_checkpoint" }, + { ss_how::full, "SS-03_full_state" }, { ss_how::full_ckpt, "SS-03c_full_state_checkpoint" }, { ss_how::reloc, "SS-04_relocated" }, + }; + for (const ss_how how : { ss_how::trim, ss_how::checkpoint, ss_how::full, ss_how::full_ckpt, ss_how::reloc }) { + t.test(names.at(how), [how](testing & t) { + // 4m - 1, 4m, 4m + 1 and a prefix past the SWA window; a trim of 8 or of as many tokens as the tail + const std::vector junks = how == ss_how::trim ? std::vector{ 8, SS_W } : how == ss_how::checkpoint ? std::vector{ 800 } : + how == ss_how::full ? std::vector{ 8 } : std::vector{ 0 }; + const std::vector Ps = how == ss_how::full_ckpt ? std::vector{ 41, 300 } : std::vector{ 39, 40, 41, 300 }; + for (const uint32_t P : Ps) { + ss_out ref; + if (!ss_run(t, ss_how::ref, P, 0, ref)) { + continue; + } + for (const uint32_t n_junk : junks) { + const std::string w = "P=" + std::to_string(P) + " junk " + std::to_string(n_junk); + ss_out got; + if (!ss_run(t, how, P, n_junk, got)) { + continue; + } + size_t n_diff = 0; + for (uint32_t i = 0; i < SS_W; ++i) { + n_diff += std::memcmp(ref.logits[i].data(), got.logits[i].data(), 128 * sizeof(float)) != 0; + } + t.assert_equal(w + ": rows of T with other logits", (size_t) 0, n_diff); + bool same = ref.snaps.size() == got.snaps.size() && ref.snaps.size() == SS_W; + for (size_t i = 0; same && i < ref.snaps.size(); ++i) { + same = ss_same_snap(ref.snaps[i], got.snaps[i]); + } + t.assert_true(w + ": snapshots (query_pos, h_final, five layers' positions) bitwise equal", same); + t.assert_equal(w + ": propose OK", (int) LLAMA_DFLY_OK, got.st); + t.assert_equal(w + ": propose status", ref.st, got.st); + t.assert_true(w + ": draft", ref.draft == got.draft && !got.draft.empty()); + } + } + }); + } +} + +// +// PP: common_dfly_prepare (plan 4.3), through the argument parser and the model handler as the server runs them +// + +// the service settings draft-dfly needs with K > 0 (plan 4.3, 5.2), given unless a case leaves them out +static const std::vector pp_service = { + "--parallel", "1", "--fit", "off", "--cache-ram", "0", +}; + +// the server's argv, parsed; false if the parser rejects it +static bool pp_parse(const std::vector & args, common_params & params, bool service = true) { + std::vector sargs = { "llama-server" }; + if (service) { + sargs.insert(sargs.end(), pp_service.begin(), pp_service.end()); + } + sargs.insert(sargs.end(), args.begin(), args.end()); + std::vector argv; + for (auto & s : sargs) { + argv.push_back(s.data()); + } + params = common_params(); + if (!common_params_parse((int) argv.size(), argv.data(), params, LLAMA_EXAMPLE_SERVER)) { + return false; + } + common_models_handler handler = common_models_handler_init(params, LLAMA_EXAMPLE_SERVER); + common_models_handler_apply(handler, params); + return true; +} + +struct pp_result { + bool ok = false; + std::string err; + std::vector types; + int32_t n_max = -1; + std::string path; // the active draft + int32_t k_req = -1; + int32_t k_eff = -1; + bool active = false; + std::string disabled; + bool cache_prompt = false; + int32_t n_ctx_checkpoints = -1; + int32_t cache_ram_mib = -2; +}; + +static pp_result pp_prepare(common_params & params) { + pp_result r; + r.ok = common_dfly_prepare(params, r.err); + r.types = params.speculative.types; + r.n_max = params.speculative.draft.n_max; + r.path = params.speculative.draft.mparams.path; + r.k_req = params.speculative.dfly.n_max_requested; + r.k_eff = params.speculative.dfly.n_max_effective; + r.active = params.speculative.dfly.active; + r.disabled = params.speculative.dfly.disabled; + r.cache_prompt = params.cache_prompt; + r.n_ctx_checkpoints = params.n_ctx_checkpoints; + r.cache_ram_mib = params.cache_ram_mib; + return r; +} + +static pp_result pp_run(testing & t, const std::vector & args, bool service = true) { + common_params params; + if (!t.assert_true("parse " + string_join(args, " "), pp_parse(args, params, service))) { + return {}; + } + return pp_prepare(params); +} + +static const std::vector pp_dfly = { COMMON_SPECULATIVE_TYPE_DRAFT_DFLY }; +static const std::vector pp_none = { COMMON_SPECULATIVE_TYPE_NONE }; + +// K_effective k: running with the draft (k > 0) or disabled with the draft cleared (k == 0) +static void pp_expect_k(testing & t, const std::string & what, const pp_result & r, const std::string & path, int32_t k_req, int32_t k_eff) { + t.assert_true(what + ": ok (" + r.err + ")", r.ok); + t.assert_equal(what + ": K_requested", k_req, r.k_req); + t.assert_equal(what + ": K_effective", k_eff, r.k_eff); + t.assert_equal(what + ": n_max", k_eff, r.n_max); + if (k_eff > 0) { + t.assert_true(what + ": types", r.types == pp_dfly); + t.assert_equal(what + ": draft", path, r.path); + t.assert_true(what + ": active", r.active); + } else { + t.assert_true(what + ": types", r.types == pp_none); + t.assert_equal(what + ": draft cleared", std::string(), r.path); + t.assert_true(what + ": inactive", !r.active); + } +} + +static void pp_expect_err(testing & t, const std::string & what, const pp_result & r, const std::string & needle) { + t.assert_true(what + ": rejected", !r.ok); + t.assert_true(what + ": error names " + needle + " (" + r.err + ")", r.err.find(needle) != std::string::npos); +} + +static void test_prepare(testing & t) { + // drafts of B = 3, 5, 8 and a target (not a DFly draft) + std::map> f; + for (uint32_t B : { 3u, 5u, 8u }) { + dfly_dims d = dfly_dims_second(); + d.block_size = B; + f[B] = std::make_unique(); + write_dfly(*f[B], d); + } + dfly_file tgt; + tgt.path = dfly_tmp_path(); + llama_model_save_to_file(pf_target(8, nullptr), tgt.path.c_str()); + + const std::string m = tgt.path; // -m, never loaded here + + // the table of plan 4.3, with K unset, 0, 3 and 7 + struct row { uint32_t B; int32_t k; int32_t k_req, k_eff; }; + const row rows[] = { + { 3, -1, 4, 2 }, { 3, 0, 0, 0 }, { 3, 3, 3, 2 }, { 3, 7, 7, 2 }, + { 5, -1, 4, 4 }, { 5, 0, 0, 0 }, { 5, 3, 3, 3 }, { 5, 7, 7, 4 }, + { 8, -1, 4, 4 }, { 8, 0, 0, 0 }, { 8, 3, 3, 3 }, { 8, 7, 7, 7 }, + }; + for (const auto & rw : rows) { + std::vector args = { "-m", m, "-md", f[rw.B]->path, "--spec-type", "draft-dfly" }; + if (rw.k >= 0) { + args.insert(args.end(), { "--spec-draft-n-max", std::to_string(rw.k) }); + } + const std::string what = "B=" + std::to_string(rw.B) + " K=" + (rw.k >= 0 ? std::to_string(rw.k) : "unset"); + pp_expect_k(t, what, pp_run(t, args), f[rw.B]->path, rw.k_req, rw.k_eff); + } + const std::string & p8 = f[8]->path; + + // the type inferred from the GGUF, no --spec-type + pp_expect_k(t, "inferred", pp_run(t, { "-m", m, "-md", p8 }), p8, 4, 4); + // argument order + pp_expect_k(t, "order", pp_run(t, { "--spec-draft-n-max", "3", "--spec-type", "draft-dfly", "-md", p8, "-m", m }), p8, 3, 3); + // the type twice + pp_expect_k(t, "draft-dfly,draft-dfly", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "draft-dfly,draft-dfly" }), p8, 4, 4); + + // environment variables are explicit too + setenv("LLAMA_ARG_SPEC_DRAFT_N_MAX", "3", 1); + pp_expect_k(t, "env K=3", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "draft-dfly" }), p8, 3, 3); + setenv("LLAMA_ARG_SPEC_DRAFT_N_MAX", "0", 1); + pp_expect_k(t, "env K=0", pp_run(t, { "-m", m, "-md", p8 }), p8, 0, 0); + unsetenv("LLAMA_ARG_SPEC_DRAFT_N_MAX"); + setenv("LLAMA_ARG_SPEC_TYPE", "none", 1); + { + const pp_result r = pp_run(t, { "-m", m, "-md", p8 }); + t.assert_true("env none: disabled", r.ok && r.types == pp_none && r.path.empty() && r.disabled == "explicit --spec-type none"); + } + unsetenv("LLAMA_ARG_SPEC_TYPE"); + + // explicit none wins over the GGUF inference, with and without K + for (const auto & args : std::vector> { + { "-m", m, "-md", p8, "--spec-type", "none" }, + { "-m", m, "-md", p8, "--spec-type", "none", "--spec-draft-n-max", "3" } }) { + common_params params; + t.assert_true("parse none", pp_parse(args, params)); + for (int i = 0; i < 2; ++i) { + const pp_result r = pp_prepare(params); + t.assert_true("none: ok", r.ok); + t.assert_true("none: types", r.types == pp_none); + t.assert_equal("none: n_max", 0, r.n_max); + t.assert_equal("none: draft cleared", std::string(), r.path); + t.assert_equal("none: reason", std::string("explicit --spec-type none"), r.disabled); + t.assert_equal("none: draft kept for the next prepare", p8, params.speculative.dfly.mparams.path); + } + } + + // none mixed with draft-dfly, either order and in two arguments + pp_expect_err(t, "draft-dfly,none", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "draft-dfly,none" }), "draft-dfly,none"); + pp_expect_err(t, "none,draft-dfly", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "none,draft-dfly" }), "none,draft-dfly"); + pp_expect_err(t, "two --spec-type", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "draft-dfly", "--spec-type", "none" }), "conflicts"); + // another explicit type on a DFly draft + pp_expect_err(t, "draft-dflash on DFly", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "draft-dflash" }), "draft-dflash"); + pp_expect_err(t, "draft-simple on DFly", pp_run(t, { "-m", m, "-md", p8, "--spec-type", "draft-simple" }), "draft-simple"); + // draft-dfly with another draft, or without one + pp_expect_err(t, "draft-dfly on a target", pp_run(t, { "-m", m, "-md", m, "--spec-type", "draft-dfly" }), "hy_v4_next_dfly"); + pp_expect_err(t, "draft-dfly without draft", pp_run(t, { "-m", m, "--spec-type", "draft-dfly" }), "--spec-draft-model"); + + // an inferred draft-dflash (e.g. from a sidecar) is corrected by the architecture + { + common_params params; + t.assert_true("parse inferred dflash", pp_parse({ "-m", m, "-md", p8 }, params)); + params.speculative.types = { COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH }; + pp_expect_k(t, "inferred dflash", pp_prepare(params), p8, 4, 4); + } + + // prepare twice, and again on a copy of the result (the sleep resume reloads the last params_base) + for (const auto & args : std::vector> { + { "-m", m, "-md", f[5]->path, "--spec-draft-n-max", "7" }, + { "-m", m, "-md", f[5]->path, "--spec-draft-n-max", "0" }, + { "-m", m, "-md", p8 } }) { + common_params params; + t.assert_true("parse reentry", pp_parse(args, params)); + const pp_result r1 = pp_prepare(params); + const pp_result r2 = pp_prepare(params); + common_params resumed = params; + const pp_result r3 = pp_prepare(resumed); + for (const pp_result * r : { &r2, &r3 }) { + t.assert_true("reentry: ok", r->ok); + t.assert_true("reentry: types", r->types == r1.types); + t.assert_equal("reentry: n_max", r1.n_max, r->n_max); + t.assert_equal("reentry: draft", r1.path, r->path); + t.assert_equal("reentry: K_requested", r1.k_req, r->k_req); + t.assert_equal("reentry: K_effective", r1.k_eff, r->k_eff); + } + } + { + common_params params; + pp_parse({ "-m", m, "-md", f[5]->path, "--spec-draft-n-max", "7" }, params); + pp_prepare(params); + common_params resumed = params; + pp_expect_k(t, "B=5 K=7 resumed", pp_prepare(resumed), f[5]->path, 7, 4); + } + + // other types keep their defaults + { + const pp_result r = pp_run(t, { "-m", m, "-md", m, "--spec-type", "draft-simple" }); + t.assert_true("draft-simple: ok", r.ok); + t.assert_equal("draft-simple: n_max stays 3", 3, r.n_max); + t.assert_equal("draft-simple: draft kept", m, r.path); + t.assert_true("draft-simple: types untouched", + std::find(r.types.begin(), r.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE) != r.types.end()); + const pp_result n = pp_run(t, { "-m", m, "--spec-type", "ngram-mod" }); + t.assert_true("ngram-mod: ok and untouched", n.ok && n.n_max == 3 && + std::find(n.types.begin(), n.types.end(), COMMON_SPECULATIVE_TYPE_NGRAM_MOD) != n.types.end()); + const pp_result a = pp_run(t, { "-m", m }); + t.assert_true("no draft: ok and untouched", a.ok && a.n_max == 3 && a.types == pp_none); + } + t.assert_true("negative K is rejected by the parser", [&]() { common_params p; return !pp_parse({ "-m", m, "--spec-draft-n-max", "-1" }, p); }()); + + // the header: missing keys, wrong types, wrong values + const dfly_dims d8 = []() { dfly_dims d = dfly_dims_second(); d.block_size = 8; return d; }(); + struct bad { std::string what; kv_edit_fn edit; std::string needle; }; + const bad bads[] = { + { "schema missing", remove_key(LLM_KV_DFLY_SCHEMA_VERSION), "hy_v4_next_dfly.schema_version is missing" }, + { "B missing", remove_key(LLM_KV_DFLASH_BLOCK_SIZE), "hy_v4_next_dfly.block_size is missing" }, + { "causal missing", remove_key(LLM_KV_ATTENTION_CAUSAL), "hy_v4_next_dfly.attention.causal is missing" }, + { "schema i32", [](gguf_context * c, kv_writer &) { gguf_set_val_i32(c, "hy_v4_next_dfly.schema_version", 1); }, "hy_v4_next_dfly.schema_version has type" }, + { "B string", [](gguf_context * c, kv_writer &) { gguf_set_val_str(c, "hy_v4_next_dfly.block_size", "8"); }, "hy_v4_next_dfly.block_size has type" }, + { "causal u32", [](gguf_context * c, kv_writer &) { gguf_set_val_u32(c, "hy_v4_next_dfly.attention.causal", 1); }, "hy_v4_next_dfly.attention.causal has type" }, + { "schema 2", [](gguf_context * c, kv_writer &) { gguf_set_val_u32(c, "hy_v4_next_dfly.schema_version", 2); }, "schema_version is 2" }, + { "B 1", [](gguf_context * c, kv_writer &) { gguf_set_val_u32(c, "hy_v4_next_dfly.block_size", 1); }, "block_size is 1" }, + { "causal false", [](gguf_context * c, kv_writer &) { gguf_set_val_bool(c, "hy_v4_next_dfly.attention.causal", false); }, "causal is false" }, + }; + for (const auto & b : bads) { + dfly_file fb; + write_dfly(fb, d8, b.edit); + pp_expect_err(t, b.what, pp_run(t, { "-m", m, "-md", fb.path, "--spec-type", "draft-dfly" }), b.needle); + // inferred: the same file is still a DFly draft + pp_expect_err(t, b.what + " inferred", pp_run(t, { "-m", m, "-md", fb.path }), b.needle); + } + // K_effective above the supported maximum + { + dfly_dims d = dfly_dims_second(); + d.block_size = 16; + dfly_file fb; + write_dfly(fb, d); + pp_expect_k(t, "B=16 K unset", pp_run(t, { "-m", m, "-md", fb.path }), fb.path, 4, 4); + pp_expect_err(t, "B=16 K=8", pp_run(t, { "-m", m, "-md", fb.path, "--spec-draft-n-max", "8" }), "supported maximum 7"); + } + + // K > 0: the service configuration is checked, not rewritten (plan 4.3 table rows 2-5); K = 0 checks nothing + { + const std::vector d = { "-m", m, "-md", p8 }; + auto with = [&](std::vector extra) { + std::vector a = d; + a.insert(a.end(), extra.begin(), extra.end()); + return a; + }; + // the parser leaves n_parallel at -1 (unset), the server turns that into 4 + pp_expect_err(t, "defaults", pp_run(t, d, false), "--parallel 1"); + const pp_result r = pp_run(t, d, false); + t.assert_true("defaults: error names --fit off", r.err.find("--fit off") != std::string::npos); + // plan 5.2, 5.3: the prompt cache, the slot checkpoints and the RAM cache are allowed + for (const char * needle : { "cache-prompt", "ctx-checkpoints", "cache-ram" }) { + t.assert_true(std::string("defaults: error does not name ") + needle, r.err.find(needle) == std::string::npos); + } + { + const pp_result rd = pp_run(t, d); + pp_expect_k(t, "cache_prompt and checkpoints by default", rd, p8, 4, 4); + t.assert_true("defaults: cache_prompt on", rd.cache_prompt); + t.assert_equal("defaults: 32 checkpoints", 32, rd.n_ctx_checkpoints); + const pp_result ro = pp_run(t, with({ "--cache-prompt", "--ctx-checkpoints", "4" })); + pp_expect_k(t, "--cache-prompt --ctx-checkpoints 4", ro, p8, 4, 4); + t.assert_true("--cache-prompt: kept", ro.cache_prompt); + t.assert_equal("--ctx-checkpoints 4: kept", 4, ro.n_ctx_checkpoints); + const pp_result rn = pp_run(t, with({ "--no-cache-prompt", "--ctx-checkpoints", "0" })); + pp_expect_k(t, "--no-cache-prompt --ctx-checkpoints 0", rn, p8, 4, 4); + t.assert_true("--no-cache-prompt: kept", !rn.cache_prompt); + t.assert_equal("--ctx-checkpoints 0: kept", 0, rn.n_ctx_checkpoints); + // plan 5.3: the RAM cache, the default size and a given one, kept as given + const pp_result rr = pp_run(t, { "-m", m, "-md", p8, "--parallel", "1", "--fit", "off" }, false); + pp_expect_k(t, "default --cache-ram", rr, p8, 4, 4); + t.assert_equal("default --cache-ram: kept", common_params().cache_ram_mib, rr.cache_ram_mib); + const pp_result r100 = pp_run(t, with({ "--cache-ram", "100" })); + pp_expect_k(t, "--cache-ram 100", r100, p8, 4, 4); + t.assert_equal("--cache-ram 100: kept", 100, r100.cache_ram_mib); + } + pp_expect_k(t, "defaults with K=0", pp_run(t, with({ "--spec-draft-n-max", "0" }), false), p8, 0, 0); + // design 4.2: several slots with one shared KV stream and one ubatch per decode + pp_expect_k(t, "--parallel 4 -kvu -b 512 -ub 512", pp_run(t, with({ "--parallel", "4", "-kvu", "-b", "512", "-ub", "512" })), p8, 4, 4); + const std::vector, std::string>> bads = { + { { "--parallel", "2" }, "-kvu (--kv-unified)" }, + { { "--parallel", "2", "-kvu" }, "--batch-size equal to --ubatch-size" }, + { { "--parallel", "128", "-kvu", "-b", "512", "-ub", "512" }, "n_parallel * (1 + K) = 640" }, + { { "--fit", "on" }, "--fit off" }, + { { "--context-shift" }, "--no-context-shift" }, + { { "--cache-reuse", "8" }, "--cache-reuse 0" }, + { { "--swa-full" }, "no --swa-full" }, + { { "--slot-save-path", "/tmp" }, "no --slot-save-path" }, + { { "--backend-sampling" }, "--backend-sampling" }, + { { "--cache-type-k", "f16", "--cache-type-v", "q8_0" }, "--cache-type-v" }, + { { "--cache-type-k", "q8_0", "--cache-type-v", "q8_0" }, "--cache-type-k" }, + { { "-ub", "4" }, "--ubatch-size of at least 5" }, + { { "-b", "256", "-ub", "512" }, "--batch-size" }, + { { "--mmproj", m }, "--no-mmproj" }, + { { "--spec-draft-n-min", "1" }, "--spec-draft-n-min 0" }, + { { "--spec-draft-p-min", "0.5" }, "--spec-draft-p-min 0" }, + { { "--spec-draft-sampling", "probabilistic" }, "--spec-draft-sampling greedy" }, + { { "--spec-synth-len", "2" }, "synthetic" }, + { { "--lora", m }, "--lora" }, + }; + for (const auto & b : bads) { + const std::string what = string_join(b.first, " "); + pp_expect_err(t, what, pp_run(t, with(b.first)), b.second); + std::vector k0 = b.first; + k0.insert(k0.end(), { "--spec-draft-n-max", "0" }); + pp_expect_k(t, what + " with K=0", pp_run(t, with(k0)), p8, 0, 0); + } + } +} + +// +// DN: dp.n_max in the draft-dfly implementation (plan 4.4): < 0 keeps K_effective, 0 drafts nothing, > 0 caps K first +// + +static void test_draft_n_max(testing & t) { + llama_model * model_tgt = pf_target(8, nullptr); + pf_draft * pd = pf_draft_get(5, 8, pf_variant::plain, nullptr); + llama_context_ptr tgt = pf_target_ctx(model_tgt, 1024, 512, 512); + llama_context_ptr dft(llama_init_from_model(pd->model.get(), pf_draft_params(tgt.get(), 5, nullptr))); + if (!t.assert_true("contexts", tgt && dft)) { + return; + } + + common_params_speculative sp; + sp.types = { COMMON_SPECULATIVE_TYPE_DRAFT_DFLY }; + sp.draft.n_max = 4; + sp.draft.ctx_tgt = tgt.get(); + sp.draft.ctx_dft = dft.get(); + common_speculative_ptr spec(common_speculative_init(sp, 1)); + if (!t.assert_true("implementation", spec != nullptr)) { + return; + } + t.assert_equal("n_max of the implementation", 4, common_speculative_n_max(spec.get())); + t.assert_true("no prompt needed", !common_speculative_needs_prompt(spec.get())); + + std::vector T(16); + for (int i = 0; i < 16; ++i) { + T[i] = 5 + (i*7) % 100; + } + const llama_tokens prompt; + auto prefill = [&]() { + llama_memory_clear(llama_get_memory(tgt.get()), true); + const bool ok = pf_decode(tgt.get(), T, 0, 16, false) == 0; + return ok && common_speculative_process(spec.get(), common_batch()); + }; + auto draft = [&](int32_t n_max) { + llama_tokens result; + common_speculative_get_draft_params(spec.get(), 0) = { true, n_max, 16, 42, &prompt, &result }; + common_speculative_draft(spec.get()); + return result; + }; + + t.assert_true("prefill", prefill()); + t.assert_equal("dp.n_max = 0: no draft", (size_t) 0, draft(0).size()); + t.assert_equal("dp.n_max = 2: K = 2", (size_t) 2, draft(2).size()); + t.assert_true("prefill again", prefill()); + t.assert_equal("dp.n_max = -1: K_effective", (size_t) 4, draft(-1).size()); + t.assert_true("prefill again", prefill()); + t.assert_equal("dp.n_max = 9: K_effective", (size_t) 4, draft(9).size()); + // the snapshot of a successful propose is consumed: the same anchor again gets no draft + t.assert_equal("consumed snapshot: no draft", (size_t) 0, draft(-1).size()); +} + +// +// WP: the tiny pair on disk for the server tests (tests/dfly-server), with LLAMA_DFLY_TEST_WRITE_PAIR= +// + +static void test_write_pair(testing & t) { + namespace fs = std::filesystem; + const char * root = getenv("LLAMA_DFLY_TEST_WRITE_PAIR"); + if (root == nullptr) { + t.skip("set LLAMA_DFLY_TEST_WRITE_PAIR= to write the tiny pair for the server tests"); + return; + } + // optional: the same eos id in both files, the binding compares the special ids + const char * eos_env = getenv("LLAMA_DFLY_TEST_WRITE_PAIR_EOS"); + const int64_t eos = eos_env ? std::stoll(eos_env) : -1; + fs::create_directories(root); + + // the pf_target(8, nullptr) weights + const std::string path_tgt = std::string(root) + "/tiny-target.gguf"; + { + hy_v4_flash_tiny p; + p.top_k = 8; + p.eos_id = eos; + llama_model_ptr m = hy_v4_flash_tiny_target(p); + llama_model_save_to_file(m.get(), path_tgt.c_str()); + } + // on the CPU, like the draft load_dfly gives + ggml_backend_dev_t devs[] = { ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr }; + llama_model_params mp = llama_model_default_params(); + mp.devices = devs; + llama_model_ptr tgt(llama_model_load_from_file(path_tgt.c_str(), mp)); + t.assert_true("target loads", tgt != nullptr); + if (!tgt) { + return; + } + llama_context_ptr ctx_tgt = pf_target_ctx(tgt.get(), 1024, 512, 512); + t.assert_true("target ctx", ctx_tgt != nullptr); + if (eos >= 0) { + t.assert_equal("target eos", (int32_t) eos, llama_vocab_eos(llama_model_get_vocab(tgt.get()))); + } + + for (uint32_t B : { 3u, 5u, 8u }) { + dfly_dims dims = dfly_dims_second(); + dims.block_size = B; + dims.top_k = 8; + const kv_edit_fn kv_edit = [eos](gguf_context *, kv_writer & kv) { + if (eos >= 0) { + kv.add_kv(LLM_KV_TOKENIZER_EOS_ID, uint32_t(eos)); + } + }; + dfly_file f; + write_dfly(f, dims, kv_edit, {}, GGML_TYPE_BF16, {}, pf_weight_edit(pf_variant::plain)); + const std::string path = std::string(root) + "/tiny-dfly-b" + std::to_string(B) + ".gguf"; + fs::copy_file(f.path, path, fs::copy_options::overwrite_existing); + + // the written pair binds: the server gets no further than this otherwise + llama_model_ptr dft = load_dfly(path); + t.assert_true("dfly B=" + std::to_string(B) + " loads", dft != nullptr); + if (!dft) { + continue; + } + llama_context_params cp = pf_draft_params(ctx_tgt.get(), std::min(B, 8u), nullptr); + llama_context_ptr ctx_dft(llama_init_from_model(dft.get(), cp)); + t.assert_true("dfly B=" + std::to_string(B) + " binds", ctx_dft != nullptr); + t.log("wrote " + path); + } + // header errors for the server initialization tests: common_dfly_prepare must reject them by key name + const std::vector> bads = { + { "schema", [](gguf_context * c, kv_writer &) { gguf_set_val_u32(c, "hy_v4_next_dfly.schema_version", 2); } }, + { "b", [](gguf_context * c, kv_writer &) { gguf_set_val_u32(c, "hy_v4_next_dfly.block_size", 1); } }, + { "causal", [](gguf_context * c, kv_writer &) { gguf_set_val_bool(c, "hy_v4_next_dfly.attention.causal", false); } }, + { "nob", remove_key(LLM_KV_DFLASH_BLOCK_SIZE) }, + }; + for (const auto & b : bads) { + dfly_dims dims = dfly_dims_second(); + dims.block_size = 8; + dfly_file f; + write_dfly(f, dims, b.second, {}, GGML_TYPE_BF16, {}, pf_weight_edit(pf_variant::plain)); + const std::string path = std::string(root) + "/tiny-dfly-bad-" + b.first + ".gguf"; + fs::copy_file(f.path, path, fs::copy_options::overwrite_existing); + t.log("wrote " + path); + } + t.log("wrote " + path_tgt); +} + +int main(int argc, char ** argv) { + testing t; + + const char * verbose = getenv("LLAMA_TEST_VERBOSE"); + if (verbose) { + t.verbose = std::string(verbose) == "1"; + } + if (!t.verbose) { + llama_log_set([](ggml_log_level, const char *, void *) {}, nullptr); + } + + llama_backend_init(); + + if (argc > 1) { + t.set_filter(argv[1]); + } + + t.test("arch", test_arch); + t.test("tensor_info", test_tensor_info); + t.test("kv_names", test_kv_names); + t.test("api", test_api); + t.test("load_pos", test_load_pos); + t.test("load_neg", test_load_neg); + t.test("checks", test_checks); + t.test("selection", test_selection); + t.test("selection_neg", test_selection_neg); + t.test("selection_oracle", test_selection_oracle); + t.test("kpool_refs", test_kpool_refs); + t.test("pair_init", test_pair_init); + t.test("binding", test_binding); + t.test("propose_abi", test_propose_abi); + t.test("snapshot_check", test_snapshot_check); + t.test("graph", test_graph); + t.test("ids", test_ids); + t.test("public_capture", test_public_capture); + t.test("same_shape", test_same_shape); + t.test("oracle_cases", test_oracle_cases); + t.test("real_gguf", test_real_gguf); + t.test("prepare", test_prepare); + t.test("draft_n_max", test_draft_n_max); + t.test("write_pair", test_write_pair); + // last, LLM_TN aborts on a missing name entry + t.test("tensor_names", test_tensor_names); + + // the CUDA buffers must go before the backend + g_pf_drafts.clear(); + g_pf_targets.clear(); + + llama_backend_free(); + + return t.summary(); +} diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index 0e61ebab5f4f5195510fe7ef3833ca1535b45769..a80acff2eb5246a0dab335172d8bb42e215e773c 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -7,6 +7,7 @@ #include "llama.h" #include "llama-cpp.h" #include "../src/llama-ext.h" +#include "gguf-fixture.h" #include #include @@ -48,106 +49,6 @@ static double nmse(const std::vector & a, const std::vector & b) { return mse_a_b / mse_a_0; } -struct tensor_data_params { - size_t seed; - float stdev; -}; - -// fills the values of one tensor, the name carries whatever the property needs -typedef void (*tensor_filler)(std::vector & dst, const char * name, const tensor_data_params & params); - -// a pool of normal draws, generated once and reused for every model -static std::vector g_normal_pool; -static const size_t NORMAL_POOL_SIZE = 16 * 1024 * 1024; - -// fill the pool once; each tensor copies a slice of it -static void init_normal_pool(const size_t seed, const float stdev) { - g_normal_pool.resize(NORMAL_POOL_SIZE); - std::mt19937 gen(seed); - std::normal_distribution dist(0.0f, stdev); - for (float & v : g_normal_pool) { - v = dist(gen); - } -} - -// a normal draw keyed on a name, so that tensors which share a draw ask for the same key -static void fill_normal(std::vector & dst, const char * key, const tensor_data_params &) { - const size_t n = dst.size(); - const size_t pool_size = g_normal_pool.size(); - const size_t start = std::hash{}(key) % pool_size; - - // copy a cyclic slice of the pool, so a tensor larger than the pool still fills - size_t i = 0; - size_t pos = start; - while (i < n) { - const size_t chunk = std::min(pool_size - pos, n - i); - std::memcpy(dst.data() + i, g_normal_pool.data() + pos, chunk * sizeof(float)); - i += chunk; - pos = 0; - } -} - -// Mamba A must be negative (state decay) -static void fill_ssm_a(std::vector & dst, const char * name, const tensor_data_params & params) { - fill_normal(dst, name, params); - for (float & v : dst) { - v = -fabsf(v); - } -} - -// a norm preserving residual gate holds alpha^2 + beta^2 == 1, and the conversion resolves both from one raw weight -// the alpha and the beta of a block share that weight, so the key drops the suffix and keeps the block -static void fill_resid_gate(std::vector & dst, const char * name, const tensor_data_params & params) { - const char * suffix = strstr(name, "_resid_"); - const bool is_beta = strstr(suffix, "_resid_beta") != nullptr; - fill_normal(dst, std::string(name, suffix - name).c_str(), params); - for (float & v : dst) { - const float beta = 1.0f / (1.0f + expf(-v)); - v = is_beta ? beta : sqrtf(1.0f - beta*beta); - } -} - -// a random router bias can tie within the noise between the backends, a ramp keeps the top-k selection the same -static void fill_exp_probs_b(std::vector & dst, const char *, const tensor_data_params &) { - for (size_t i = 0; i < dst.size(); i++) { - dst[i] = 2.0f*i; - } -} - -// a tensor whose values hold a property of their own, matched on a substring of its name, first match wins -static const struct { const char * match; tensor_filler fill; } TENSOR_FILLERS[] = { - { "ssm_a", fill_ssm_a }, - { "_resid_", fill_resid_gate }, - { "exp_probs_b", fill_exp_probs_b }, -}; - -static void set_tensor_data(struct ggml_tensor * tensor, void * userdata) { - const tensor_data_params & params = *(const tensor_data_params *) userdata; - - tensor_filler fill = fill_normal; - for (const auto & filler : TENSOR_FILLERS) { - if (strstr(tensor->name, filler.match) != nullptr) { - fill = filler.fill; - break; - } - } - - std::vector tmp(ggml_nelements(tensor)); - fill(tmp, tensor->name, params); - - if (tensor->type == GGML_TYPE_F32) { - ggml_backend_tensor_set(tensor, tmp.data(), 0, ggml_nbytes(tensor)); - } else if (tensor->type == GGML_TYPE_F16) { - std::vector tmp16(tmp.size()); - for (size_t i = 0; i < tmp.size(); i++) { - tmp16[i] = ggml_fp32_to_fp16(tmp[i]); - } - ggml_backend_tensor_set(tensor, tmp16.data(), 0, ggml_nbytes(tensor)); - } else { - GGML_ABORT("fatal error"); - } -} - static void usage(char ** argv) { LOG("Usage: %s [options]\n\n", argv[0]); LOG("Options:\n"); @@ -165,570 +66,6 @@ static void usage(char ** argv) { LOG(" %s -a cohere2moe -v 5\n", argv[0]); } -static std::vector get_tokens(const uint32_t n_tokens, const uint32_t n_vocab, const size_t seed){ - std::mt19937 gen(seed); - std::uniform_int_distribution<> dis(0, n_vocab - 1); - std::vector ret; - ret.reserve(n_tokens); - for (uint32_t i = 0; i < n_tokens; i++) { - ret.push_back(dis(gen)); - } - return ret; -} - -// MoE archs that are also tested with the experts in host memory -static bool host_experts_test(const llm_arch arch) { - switch (arch) { - case LLM_ARCH_DEEPSEEK2: - return true; - default: - return false; - } -} - -// writes arch-resolved GGUF keys into the fixture context, the test-side equivalent of llama_model_saver -struct kv_writer { - struct gguf_context * gguf_ctx; - const llm_arch arch; - - kv_writer(enum llm_arch arch, struct gguf_context * gguf_ctx) : gguf_ctx(gguf_ctx), arch(arch) {} - - void add_kv(enum llm_kv key, uint32_t value) { gguf_set_val_u32 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } - void add_kv(enum llm_kv key, int32_t value) { gguf_set_val_i32 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } - void add_kv(enum llm_kv key, uint64_t value) { gguf_set_val_u64 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } - void add_kv(enum llm_kv key, float value) { gguf_set_val_f32 (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } - void add_kv(enum llm_kv key, bool value) { gguf_set_val_bool(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } - void add_kv(enum llm_kv key, const char * value) { gguf_set_val_str (gguf_ctx, llama_arch_kv_name(arch, key).c_str(), value); } - - template - void add_kv(enum llm_kv key, const std::vector & value) { - if (value.empty()) { - return; - } - if (std::is_same::value) { - gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_UINT32, value.data(), value.size()); - } else if (std::is_same::value) { - gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_INT32, value.data(), value.size()); - } else if (std::is_same::value) { - gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_UINT64, value.data(), value.size()); - } else if (std::is_same::value) { - gguf_set_arr_data(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), GGUF_TYPE_FLOAT32, value.data(), value.size()); - } else { - GGML_ABORT("fatal error"); - } - } - - void add_kv(enum llm_kv key, const std::vector & value) { - std::vector tmp(value.size()); - for (size_t i = 0; i < value.size(); ++i) { - tmp[i] = value[i].c_str(); - } - gguf_set_arr_str(gguf_ctx, llama_arch_kv_name(arch, key).c_str(), tmp.data(), tmp.size()); - } -}; - -static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe) { - gguf_context_ptr ret(gguf_init_empty()); - kv_writer ms(arch, ret.get()); - const uint32_t n_ctx = 256; - - uint32_t n_vocab = 128; - uint32_t n_embd = 256; - uint32_t n_head = 2; - uint32_t n_ff = 384; - uint32_t n_layer = 2; - if (arch == LLM_ARCH_LLAMA4) { - n_layer = 4; // hparams.n_no_rope_layer_step is hard-coded to 4 - } else if (arch == LLM_ARCH_MAION_CODER) { - n_head = 4; - n_layer = 4; // dense and MoE layers, each with local and full attention - } else if (arch == LLM_ARCH_GEMMA4) { - // TODO: expand coverage to both GQA and MQA (see https://github.com/ggml-org/llama.cpp/pull/31401#pullrequestreview-5710165130) - n_head = 4; - n_layer = 10; // last 5 layers reuse KV, both SWA and full attention - } else if (arch == LLM_ARCH_GEMMA3N) { - n_embd = 64; - n_head = 1; - n_ff = 96; - n_layer = 22; // hparams.n_layer_kv_from_start = 20 is hardcoded - } else if (arch == LLM_ARCH_LFM3) { - n_layer = 3; - } else if (arch == LLM_ARCH_DEEPSEEK4) { - // head size 64 so that GPU flash attention kernels support the model - n_embd = 512; - n_head = 8; - n_ff = 1024; - n_layer = 4; - } else if (arch == LLM_ARCH_DEEPSEEK41) { - // window-only, Engram, ratio-2 and ratio-1 sources, top-k reuse and a candidate-masked index layer - n_embd = 512; - n_head = 8; - n_ff = 1024; - n_layer = 6; - } else if (arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_LAGUNA) { - n_embd = 160; // exercise per-head tensor split granularity with head size 80 - } else if (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_AFMOE) { - n_head = 4; - } else if (arch == LLM_ARCH_LIMITE) { - n_head = 4; - n_layer = 4; // dense connections on the last two layers - } else if (arch == LLM_ARCH_DEEPSEEK2 - || arch == LLM_ARCH_DEEPSEEK32 - || arch == LLM_ARCH_GLM_DSA - || arch == LLM_ARCH_DOTS3NOTE - || arch == LLM_ARCH_KIMI_LINEAR - || arch == LLM_ARCH_BAILINGMOE3 - || arch == LLM_ARCH_KIMI_K3 - || arch == LLM_ARCH_GLM5_NEXT - || arch == LLM_ARCH_MISTRAL4 - || arch == LLM_ARCH_MISTRAL_LARGE4 - || arch == LLM_ARCH_HY_V4) { - n_embd = 128; - n_head = 1; - n_ff = 192; - if (arch == LLM_ARCH_MISTRAL_LARGE4) { - n_layer = 4; // cover NoPE, shared indexer and KV sharing layers - } - } else if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { - n_layer = 3; - } else if (arch == LLM_ARCH_CHAMELEON) { - n_vocab = 10240; - } else if (arch == LLM_ARCH_QWEN3TTS) { - //n_vocab = 4096; // must be >= the hard-coded codec head size (3072) - n_vocab = 3072; // TODO: should be 4096, but user code cannot get `n_vocab_out` yet [TAG_LLAMA_N_VOCAB_OUT] - } else if (arch == LLM_ARCH_HRM_TEXT) { - n_layer = 6; // 1 layer per stack x 2 h-cycles x (2 l-cycles + 1) cache slots - } - - uint32_t n_head_kv = n_head; - if (arch == LLM_ARCH_QWEN3) { - n_head_kv = 1; // MQA coverage - } else if (arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_AFMOE || arch == LLM_ARCH_MAION_CODER || - arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_LIMITE || arch == LLM_ARCH_GEMMA4) { - n_head_kv = 2; // GQA coverage - } - if (arch == LLM_ARCH_BEAM) { - n_head = 4; - n_head_kv = 2; - n_layer = 4; - } - const uint32_t n_embd_head = n_embd / n_head; - - ms.add_kv(LLM_KV_GENERAL_ARCHITECTURE, llama_arch_name(arch)); - ms.add_kv(LLM_KV_VOCAB_SIZE, n_vocab); - ms.add_kv(LLM_KV_CONTEXT_LENGTH, n_ctx); - ms.add_kv(LLM_KV_EMBEDDING_LENGTH, n_embd); - ms.add_kv(LLM_KV_FEATURES_LENGTH, n_embd); - ms.add_kv(LLM_KV_BLOCK_COUNT, n_layer); - ms.add_kv(LLM_KV_LEADING_DENSE_BLOCK_COUNT, uint32_t(1)); - - if (arch == LLM_ARCH_K2_HORIZON) { - ms.add_kv(LLM_KV_ROPE_SCALING_YARN_BETA_FAST, 128.0f); - ms.add_kv(LLM_KV_ROPE_SCALING_YARN_BETA_SLOW, 4.0f); - } - - if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { - std::vector n_ff_per_layer; - n_ff_per_layer.reserve(n_layer); - for (uint32_t il = 0; il < n_layer; il++) { - n_ff_per_layer.push_back(il <= 1 ? 0 : n_ff); - } - ms.add_kv(LLM_KV_FEED_FORWARD_LENGTH, n_ff_per_layer); - } else { - ms.add_kv(LLM_KV_FEED_FORWARD_LENGTH, n_ff); - } - - ms.add_kv(LLM_KV_USE_PARALLEL_RESIDUAL, false); - ms.add_kv(LLM_KV_LOGIT_SCALE, 1.0f); - ms.add_kv(LLM_KV_TIME_MIX_EXTRA_DIM, uint32_t(64)); - ms.add_kv(LLM_KV_TIME_DECAY_EXTRA_DIM, uint32_t(128)); - ms.add_kv(LLM_KV_FULL_ATTENTION_INTERVAL, uint32_t(2)); - - if (arch == LLM_ARCH_PLAMO2 || arch == LLM_ARCH_JAMBA || arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE || - arch == LLM_ARCH_GRANITE_HYBRID || arch == LLM_ARCH_LFM2 || arch == LLM_ARCH_LFM2MOE || arch == LLM_ARCH_LFM3 || - arch == LLM_ARCH_KIMI_LINEAR || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_GLM5_NEXT - ) { - GGML_ASSERT(n_layer >= 2); - std::vector n_head_per_layer; - n_head_per_layer.reserve(n_layer); - for (uint32_t il = 0; il < n_layer; il++) { - n_head_per_layer.push_back(il == 1 ? 0 : n_head); - } - // GLM5 next KDA heads come from the uniform head count, only head_count_kv is per layer. - if (arch == LLM_ARCH_GLM5_NEXT) { - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head); - } else { - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head_per_layer); - } - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer); - } else { - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head); - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(1) : n_head_kv); - } - - ms.add_kv(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, 8.0f); - if (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) { - ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH, n_embd_head); - ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH, n_embd_head); - ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, n_embd_head/2); - } else if (arch == LLM_ARCH_DEEPSEEK2 - || arch == LLM_ARCH_DEEPSEEK32 - || arch == LLM_ARCH_GLM_DSA - || arch == LLM_ARCH_DOTS3NOTE - || arch == LLM_ARCH_KIMI_LINEAR - || arch == LLM_ARCH_BAILINGMOE3 - || arch == LLM_ARCH_KIMI_K3 - || arch == LLM_ARCH_GLM5_NEXT - || arch == LLM_ARCH_HY_V4 - || arch == LLM_ARCH_MISTRAL4 - || arch == LLM_ARCH_MISTRAL_LARGE4) { - // GLM5 next MLA is nope only, the cache row is the compressed latent alone. - ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH, arch == LLM_ARCH_GLM5_NEXT ? uint32_t(512) : uint32_t(576)); - ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH, uint32_t(512)); - ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, arch == LLM_ARCH_GLM5_NEXT ? uint32_t(0) : uint32_t(64)); - ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA, uint32_t(192)); - ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, uint32_t(128)); - if (arch == LLM_ARCH_DOTS3NOTE) { - // SWA layers reuse the same MLA geometry as the full layers in this fixture - ms.add_kv(LLM_KV_ATTENTION_KV_LORA_RANK_SWA, uint32_t(512)); - ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, uint32_t(576)); - ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, uint32_t(512)); - ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_MLA_SWA, uint32_t(192)); - ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_MLA_SWA, uint32_t(128)); - ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); - // indexer on the full-attention layers (inverse of the swa pattern) - std::vector indexer_types; - indexer_types.reserve(n_layer); - for (uint32_t il = 0; il < n_layer; il++) { - indexer_types.push_back(il % 2 ? 0 : 1); - } - ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); - } - } else if (arch == LLM_ARCH_MINIMAX_M3) { - // partial rotary: n_rot must not exceed the indexer key length (64) - ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT, uint32_t(64)); - } - if (arch == LLM_ARCH_SENSENOVA_U1) { - ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SPATIAL, 10000.0f); - } - ms.add_kv(LLM_KV_ATTENTION_CLAMP_KQV, 1.0f); - ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, 1e-5f); - ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f); - ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, 1e-5f); - ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, uint32_t(8)); - ms.add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(64) : uint32_t(512)); - ms.add_kv(LLM_KV_ATTENTION_KV_LORA_RANK, uint32_t(512)); - ms.add_kv(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, uint32_t(8)); - ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW, n_ctx/8); - - if (arch == LLM_ARCH_MAION_CODER) { - ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector{1, 1, 0, 0}); - } else if (arch == LLM_ARCH_GEMMA4) { - ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, n_embd/2); - ms.add_kv(LLM_KV_ATTENTION_SHARED_KV_LAYERS, uint32_t(5)); - ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, n_embd_head); - ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, n_embd_head); - ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); - // SWA pattern: every 5th layer is full attention (matches E2B layer_types) - std::vector pattern; - pattern.reserve(n_layer); - for (uint32_t il = 0; il < n_layer; il++) { - pattern.push_back((il + 1) % 5 != 0); - } - ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); - } else if (arch == LLM_ARCH_COHERE2MOE || arch == LLM_ARCH_MIMO2 || arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_SPARK2_5 || - arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_GRANITE_SWA || arch == LLM_ARCH_DOTS3NOTE || - arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM) { - std::vector pattern; - pattern.reserve(n_layer); - for (uint32_t il = 0; il < n_layer; il++) { - pattern.push_back(il % 2); - } - ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); - if (arch == LLM_ARCH_FLINT) { - ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, pattern); - } - } else if (arch == LLM_ARCH_LFM3) { - ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector({0, 0, 1})); - ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); - } else { - ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, uint32_t(2)); - } - - if (arch == LLM_ARCH_MUSE_SPARK) { - ms.add_kv(LLM_KV_POST_NORM_EPS, 1e-5f); - ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); - ms.add_kv(LLM_KV_FINAL_LOGIT_SOFTCAPPING, 30.0f); - ms.add_kv(LLM_KV_MOE_LATENT_SIZE, n_embd/2); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); - } - - if (arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_LIMITE) { - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, false); - } - - // MSA requires one indexer head per GQA (KV) head, unlike the DSA archs where the - // indexer head count is independent of the main attention head count. - if (arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_GLM5_NEXT) { - ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS, uint32_t(2)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); - ms.add_kv(LLM_KV_HYPER_CONNECTION_LOW_RANK, uint32_t(8)); - // without this the QSA layers fall back to dense and go uncovered - ms.add_kv(LLM_KV_ATTENTION_COMPRESS_RATIOS, std::vector(n_layer, 4)); - - // has_cell_ext() needs ple_n_heads here: the indexer cache serializes no ext without it - const uint32_t ple_ngram_size = 3; - const uint32_t ple_heads_per_ngram = 2; - const uint32_t ple_n_heads = (ple_ngram_size - 1)*ple_heads_per_ngram; - GGML_ASSERT(n_embd % ple_n_heads == 0); - const uint32_t ple_head_dim = n_embd/ple_n_heads; - - std::vector ple_head_offsets(ple_n_heads); - std::vector ple_head_vocab_sizes(ple_n_heads, n_vocab); - for (uint32_t h = 0; h < ple_n_heads; h++) { - ple_head_offsets[h] = uint64_t(h)*n_vocab; - } - - // the PLE history lives in the recurrent cache, so it must sit on a linear attention layer - ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({ 0 })); - ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, ple_ngram_size); - ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, ple_heads_per_ngram); - ms.add_kv(LLM_KV_PLE_CONV_KERNEL, uint32_t(4)); - ms.add_kv(LLM_KV_PLE_EOS_TOKEN_ID, uint32_t(0)); - ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, ple_head_dim); - ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({ 1, 3, 5 })); - ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, ple_head_offsets); - ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, ple_head_vocab_sizes); - } - - // minimax-m3 keeps one indexer head per GQA head; the rest use a fixed 64 to match the fused - ms.add_kv(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, arch == LLM_ARCH_MINIMAX_M3 ? n_head : uint32_t(64)); - // qwen4exp ropes indexer keys with the main rotary width, so its head can't be < n_rot - ms.add_kv(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, - arch == LLM_ARCH_QWEN4EXP ? n_embd_head : uint32_t(128)); - - // note: using a realistic top-k here makes the results unstable and hard to match between CPU and GPU - // a large value makes things deterministic since all data is selected by the indexer - //ms.add_kv(LLM_KV_ATTENTION_INDEXER_TOP_K, uint32_t(8)); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_TOP_K, uint32_t(131072)); - - ms.add_kv(LLM_KV_ATTENTION_INDEXER_BLOCK_SIZE, uint32_t(4)); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_KPOOL, uint32_t(4)); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_KPOOL_SELECT_TAIL, true); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, uint32_t(1)); - // mrope sections count rope pairs; Ling 3.0 VL files carry [t, h, w] sections - // summing to n_rot / 2 (n_rot is 64 in this fixture) - if (arch == LLM_ARCH_BAILINGMOE3) { - ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({8, 12, 12, 0})); - } else { - ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({n_embd_head/4, n_embd_head/4, n_embd_head/4, n_embd_head/4})); - } - - if (arch == LLM_ARCH_HY_V4) { - ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); - ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); - ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); - // layer 0 must own an indexer, the odd layers share it - std::vector indexer_types; - indexer_types.reserve(n_layer); - for (uint32_t il = 0; il < n_layer; il++) { - indexer_types.push_back(il % 2 ? 0 : 1); - } - ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); - } - - if (arch == LLM_ARCH_MISTRAL_LARGE4) { - // layer 3 reads the KV cache of layer 2, both are NoPE - ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, std::vector({1, 1, 0, 0})); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, std::vector({1, 0, 1, 1})); - ms.add_kv(LLM_KV_ATTENTION_KV_SOURCE_MAP, std::vector({0, 1, 2, 2})); - ms.add_kv(LLM_KV_FINAL_LOGIT_SOFTCAPPING, 30.0f); - } - - if (arch == LLM_ARCH_DEEPSEEK4) { - ms.add_kv(LLM_KV_ATTENTION_OUTPUT_GROUP_COUNT, uint32_t(8)); - ms.add_kv(LLM_KV_ATTENTION_OUTPUT_LORA_RANK, uint32_t(32)); - ms.add_kv(LLM_KV_ATTENTION_COMPRESS_RATIOS, std::vector({0, 0, 4, 128})); - ms.add_kv(LLM_KV_ATTENTION_COMPRESS_ROPE_FREQ_BASE, 160000.0f); - ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS, uint32_t(2)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); - ms.add_kv(LLM_KV_HASH_LAYER_COUNT, uint32_t(0)); - ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); - } - - if (arch == LLM_ARCH_DEEPSEEK41) { - ms.add_kv(LLM_KV_ATTENTION_OUTPUT_GROUP_COUNT, uint32_t(8)); - ms.add_kv(LLM_KV_ATTENTION_OUTPUT_LORA_RANK, uint32_t(32)); - ms.add_kv(LLM_KV_ATTENTION_COMPRESS_RATIOS, std::vector({0, 0, 2, 2, 1, 1})); - ms.add_kv(LLM_KV_ATTENTION_COMPRESS_ROPE_FREQ_BASE, 160000.0f); - ms.add_kv(LLM_KV_ATTENTION_KV_SOURCE_LAYERS, std::vector({2, 4})); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_SOURCE_LAYERS, std::vector({2, 4, 5})); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_SOURCE_LAYER, int32_t(4)); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_TOP_K_BLOCKS, uint32_t(4096)); - ms.add_kv(LLM_KV_ATTENTION_INDEXER_CANDIDATE_BLOCK_SIZE, uint32_t(4)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_SINKHORN_ITERATIONS, uint32_t(2)); - ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); - ms.add_kv(LLM_KV_HASH_LAYER_COUNT, uint32_t(0)); - ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); - std::vector token_map(n_vocab); - for (uint32_t i = 0; i < n_vocab; ++i) { - token_map[i] = (int32_t) (i % 61); - } - ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({1, 3})); - ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, uint32_t(3)); - ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, uint32_t(2)); - ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, uint32_t(64)); - ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({ 76632096046245ull, 4839876093313ull, 35959672319349ull, - 67716810739261ull, 51510806800915ull, 30921347202721ull })); - ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, std::vector({0, 101, 204, 311, 420, 533, 660, 791})); - ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, std::vector({101, 103, 107, 109, 113, 127, 131, 137})); - ms.add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, uint32_t(2)); - ms.add_kv(LLM_KV_ENGRAM_TOKEN_MAP, token_map); - } - - if (arch == LLM_ARCH_HRM_TEXT) { - // 6 cache slots alias 2 physical blocks: 1 low-stack layer + 1 high-stack layer - ms.add_kv(LLM_KV_HRM_LAYERS_PER_STACK, uint32_t(1)); - ms.add_kv(LLM_KV_HRM_H_CYCLES, uint32_t(2)); - ms.add_kv(LLM_KV_HRM_L_CYCLES, uint32_t(2)); - } - - if (arch == LLM_ARCH_MAPLE) { - ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 7.0f); - } - - if (arch == LLM_ARCH_LIMITE) { - ms.add_kv(LLM_KV_ATTENTION_SCALE, 0.1f); - ms.add_kv(LLM_KV_ATTENTION_XSA_EPS, 1e-4f); - ms.add_kv(LLM_KV_FINAL_LOGIT_SIGMOID_CAPPING, std::vector({23.0f, 5.0f, 7.5f})); - ms.add_kv(LLM_KV_MUDD_FEED_FORWARD_LENGTH, uint32_t(8)); - ms.add_kv(LLM_KV_MUDD_TAP_COUNT, uint32_t(2)); - ms.add_kv(LLM_KV_MUDD_TAP_INDICES, std::vector({-1, -1, -1, -1, 0, 2, 1, 3})); - } - - // dummy tokenizer: token ids are derived from fixed-size chunks and detokenized as hex ids - { - std::vector tokenizer_list(n_vocab); - std::vector tokenizer_scores(n_vocab, 0.0f); - - ms.add_kv(LLM_KV_TOKENIZER_MODEL, "test"); - for (uint32_t i = 0; i < n_vocab; i++) { - tokenizer_list[i] = "tok_" + std::to_string(i); - } - ms.add_kv(LLM_KV_TOKENIZER_LIST, tokenizer_list); - ms.add_kv(LLM_KV_TOKENIZER_SCORES, tokenizer_scores); - } - - // ms.add_kv(LLM_KV_DENSE_2_FEAT_OUT, n_embd); - // ms.add_kv(LLM_KV_DENSE_3_FEAT_IN, n_embd); - - if (moe) { - ms.add_kv(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, n_ff); - ms.add_kv(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, n_ff / 2); // distinct from n_ff so a saver key-clobber surfaces on reload - ms.add_kv(LLM_KV_EXPERT_LATENT_LENGTH, n_ff); - ms.add_kv(LLM_KV_INTERLEAVE_MOE_LAYER_STEP, uint32_t(2)); - // with more experts than a ubatch uses, the copy of the used experts in host memory skips some of them - ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(host_experts_test(arch) ? 64 : arch == LLM_ARCH_CLOVER_MOE ? 4 : 2)); - ms.add_kv(LLM_KV_EXPERT_USED_COUNT, uint32_t(2)); - ms.add_kv(LLM_KV_EXPERT_SHARED_COUNT, uint32_t(1)); - - uint32_t gating_func = 2; - switch (arch) { - case LLM_ARCH_MELLUM: - gating_func = 1; - break; - case LLM_ARCH_DEEPSEEK4: - case LLM_ARCH_DEEPSEEK41: - gating_func = 4; - break; - default: - break; - } - - ms.add_kv(LLM_KV_EXPERT_GATING_FUNC, gating_func); // sigmoid : softmax : sqrtsoftplus - ms.add_kv(LLM_KV_EXPERT_GROUP_SCALE, 1.0f); - ms.add_kv(LLM_KV_EXPERTS_PER_GROUP, uint32_t(1)); - if (arch == LLM_ARCH_FLINT) { - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); - } - if (arch == LLM_ARCH_K2_HORIZON) { - ms.add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_COUNT, uint32_t(2)); - ms.add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_USED_COUNT, uint32_t(2)); - } - } - - if (arch == LLM_ARCH_BEAM) { - ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(8)); - ms.add_kv(LLM_KV_EXPERT_GROUP_COUNT, uint32_t(4)); - ms.add_kv(LLM_KV_EXPERT_GROUP_USED_COUNT, uint32_t(2)); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 2.5f); - ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); - } - - if (arch == LLM_ARCH_MAION_CODER) { - ms.add_kv(LLM_KV_MOE_LATENT_SIZE, n_embd / 2); - ms.add_kv(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, std::vector{n_ff, n_ff / 2, n_ff, n_ff}); - } - - ms.add_kv(LLM_KV_POSNET_EMBEDDING_LENGTH, n_embd); - ms.add_kv(LLM_KV_POSNET_BLOCK_COUNT, n_layer); - ms.add_kv(LLM_KV_CONVNEXT_EMBEDDING_LENGTH, n_embd); - ms.add_kv(LLM_KV_CONVNEXT_BLOCK_COUNT, n_layer); - ms.add_kv(LLM_KV_XIELU_ALPHA_N, 1.0f); - ms.add_kv(LLM_KV_XIELU_ALPHA_P, 1.0f); - ms.add_kv(LLM_KV_XIELU_BETA, 1.0f); - ms.add_kv(LLM_KV_XIELU_EPS, 1.0e-7f); - ms.add_kv(LLM_KV_SSM_INNER_SIZE, arch == LLM_ARCH_QWEN3NEXT || arch == LLM_ARCH_QWEN35 || arch == LLM_ARCH_QWEN35MOE || arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_CLOVER_MOE ? 256 : 2*n_embd); - ms.add_kv(LLM_KV_SSM_CONV_KERNEL, uint32_t(4)); - ms.add_kv(LLM_KV_SSM_STATE_SIZE, uint32_t(128)); - ms.add_kv(LLM_KV_SSM_TIME_STEP_RANK, n_head); - ms.add_kv(LLM_KV_SSM_GROUP_COUNT, arch == LLM_ARCH_PLAMO2 ? 0 : uint32_t(2)); - ms.add_kv(LLM_KV_KDA_HEAD_DIM, uint32_t(128)); - ms.add_kv(LLM_KV_KDA_SAFE_GATE, true); - ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f); - if (arch == LLM_ARCH_BAILINGMOE3) { - ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, std::vector({0.0f, 4.0f})); - ms.add_kv(LLM_KV_SWIGLU_CLAMP_SHEXP, std::vector({0.0f, 5.0f})); - } - ms.add_kv(LLM_KV_WKV_HEAD_SIZE, n_embd/n_head); - ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(3)); - ms.add_kv(LLM_KV_RESIDUAL_SCALE, 3.5565588200778455f); - ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(12)); - ms.add_kv(LLM_KV_ACTIVATION_SITU_BETA, 4.0f); - ms.add_kv(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, 25.0f); - ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f); - - for (uint32_t il = 0; il < n_layer; il++) { - ggml_tensor t; - memset(&t, 0, sizeof(ggml_tensor)); - t.type = GGML_TYPE_F16; - ggml_format_name(&t, "conv%" PRIu32 "d.weight", il); - gguf_add_tensor(ms.gguf_ctx, &t); - ggml_format_name(&t, "posnet.%" PRIu32 ".conv1.weight", il); - gguf_add_tensor(ms.gguf_ctx, &t); - ggml_format_name(&t, "posnet.%" PRIu32 ".conv2.weight", il); - gguf_add_tensor(ms.gguf_ctx, &t); - ggml_format_name(&t, "convnext.%" PRIu32 ".dw.weight", il); - gguf_add_tensor(ms.gguf_ctx, &t); - } - return ret; -} - -static bool silent_model_load_progress(float /*progress*/, void * /*user_data*/) { - return true; -} - static std::string get_tmp_gguf_path() { static size_t id = 0; return (std::filesystem::temp_directory_path() / ("test-llama-archs-" + std::to_string(++id) + ".gguf")).string(); @@ -942,6 +279,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_HUNYUAN_MOE: case LLM_ARCH_HY_V3: case LLM_ARCH_HY_V4: + case LLM_ARCH_HY_V4_FLASH: case LLM_ARCH_OPENAI_MOE: case LLM_ARCH_LFM2MOE: case LLM_ARCH_SMALLTHINKER: @@ -1024,7 +362,7 @@ static bool arch_supported(const llm_arch arch) { // FIXME: these hit scheduler/view-backed-output issues with WebGPU on CI. #ifdef GGML_USE_WEBGPU if (arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_QWEN4EXP || - arch == LLM_ARCH_HY_V4) { + arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH) { return false; } #endif // GGML_USE_WEBGPU @@ -1070,7 +408,7 @@ static int save_models(const std::string & arch_filter, const size_t seed, const if (!arch_matches(arch_filter, arch)) { continue; } - if (arch == LLM_ARCH_EAGLE3 || arch == LLM_ARCH_DFLASH || arch == LLM_ARCH_GEMMA4_ASSISTANT) { + if (arch == LLM_ARCH_EAGLE3 || arch == LLM_ARCH_DFLASH || arch == LLM_ARCH_GEMMA4_ASSISTANT || arch == LLM_ARCH_HY_V4_NEXT_DFLY) { continue; } for (bool moe : {false, true}) { @@ -1227,7 +565,7 @@ static int test_backends(const std::string & arch_filter, const size_t seed, con if (!arch_matches(arch_filter, arch)) { continue; } - if (arch == LLM_ARCH_EAGLE3 || arch == LLM_ARCH_DFLASH || arch == LLM_ARCH_GEMMA4_ASSISTANT) { + if (arch == LLM_ARCH_EAGLE3 || arch == LLM_ARCH_DFLASH || arch == LLM_ARCH_GEMMA4_ASSISTANT || arch == LLM_ARCH_HY_V4_NEXT_DFLY) { continue; } diff --git a/tests/test_conversion_dfly.py b/tests/test_conversion_dfly.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1f8d55296ae67b79723826193671664b96b19e --- /dev/null +++ b/tests/test_conversion_dfly.py @@ -0,0 +1,997 @@ +"""Test the HY4-Next DFly draft conversion (--dfly) with tiny synthetic checkpoints; no GPU or model downloads required. + +Run from the repository root: + python -m unittest discover -s tests -p 'test_conversion_dfly.py' -v + +The real checkpoint, including the real target tokenizer, is checked separately by an independent script. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import io +import json +import os +import re +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from typing import Any +from unittest import mock + +import numpy as np + +import convert_hf_to_gguf +from conversion import get_model_class +from conversion.base import gguf +from conversion.hy_v4_next_dfly import DEFAULT_SOURCE, HYV4NextDFlyModel, is_hy4_dfly_config + +REPO = Path(__file__).resolve().parent.parent +ARCH = "hy_v4_next_dfly" +QT = gguf.GGMLQuantizationType +VT = gguf.GGUFValueType + +# tiny dims: all base and derived dims differ, so a swapped dim or a transpose changes a shape +L, D, F, H, RQ, RKV, DN, DR, DV, V = 5, 24, 36, 2, 18, 22, 6, 4, 8, 40 +KV_LAYERS = [3, 5, 7, 9, 11] +N_TARGET_LAYERS = 12 +INDEX_TOPK = 16 +MASK = 37 +N_CTX = 4096 +THETA = 10000000 +MROPE = [1, 1, 0] + +# the schema's tensor tables written out on purpose: GGUF name, source key, ggml ne in tiny dims +LAYER_TENSORS = [ + ("attn_norm.weight", "input_layernorm.weight", [D]), + ("attn_q_a.weight", "self_attn.q_a_proj.weight", [D, RQ]), + ("attn_q_a_norm.weight", "self_attn.q_a_layernorm.weight", [RQ]), + ("attn_q_b.weight", "self_attn.q_b_proj.weight", [RQ, H * (DN + DR)]), + ("attn_kv_a_mqa.weight", "self_attn.kv_a_proj_with_mqa.weight", [D, RKV + DR]), + ("attn_kv_a_norm.weight", "self_attn.kv_a_layernorm.weight", [RKV]), + ("attn_k_b.weight", "self_attn.kv_b_proj.weight", [DN, RKV, H]), + ("attn_v_b.weight", "self_attn.kv_b_proj.weight", [RKV, DV, H]), + ("attn_sinks.weight", "self_attn.learnable_sink_param", [H]), + ("attn_gate.weight", "self_attn.linear_gate.weight", [D, H * DV]), + ("attn_output.weight", "self_attn.o_proj.weight", [H * DV, D]), + ("post_attention_norm.weight", "self_attn.post_proj_norm.weight", [D]), + ("ffn_norm.weight", "post_attention_layernorm.weight", [D]), + ("ffn_gate.weight", "mlp.gate_proj.weight", [D, F]), + ("ffn_up.weight", "mlp.up_proj.weight", [D, F]), + ("ffn_down.weight", "mlp.down_proj.weight", [F, D]), +] +GLOBAL_TENSORS = [ + ("output_norm.weight", "final_norm.weight", [D]), + ("dfly_fusion_enorm.weight", "mtp_fusion.enorm.weight", [D]), + ("dfly_fusion_hnorm.weight", "mtp_fusion.hnorm.weight", [D]), + ("dfly_fusion_eh.weight", "mtp_fusion.eh_proj.weight", [2 * D, D]), + ("dfly_fusion_gate.weight", "mtp_fusion.gate", [D]), + ("dfly_correction_hnorm.weight", "hidden_correction.hidden_norm.weight", [D]), + ("dfly_correction_enorm.weight", "hidden_correction.embed_norm.weight", [D]), + ("dfly_correction_gate.weight", "hidden_correction.gate_proj.weight", [2 * D, D]), + ("dfly_correction_up.weight", "hidden_correction.up_proj.weight", [2 * D, D]), + ("dfly_correction_down.weight", "hidden_correction.down_proj.weight", [D, D]), + ("dfly_confidence.weight", "confidence_head.proj.weight", [D, 1]), + ("dfly_confidence.bias", "confidence_head.proj.bias", [1]), +] +EXPECTED = {f"blk.{i}.{name}": (f"layers.{i}.{src}", ne) for i in range(L) for name, src, ne in LAYER_TENSORS} +EXPECTED.update({name: (src, ne) for name, src, ne in GLOBAL_TENSORS}) +F32_NAMES = {name for name, (_, ne) in EXPECTED.items() if len(ne) == 1} | {"dfly_confidence.weight"} + +TINY_PROFILE = { + **HYV4NextDFlyModel.PROFILE, + "num_hidden_layers": L, "hidden_size": D, "intermediate_size": F, "num_attention_heads": H, + "q_lora_rank": RQ, "kv_lora_rank": RKV, "qk_nope_head_dim": DN, "qk_rope_head_dim": DR, "v_head_dim": DV, + "target_kv_layers": KV_LAYERS, "target_index_layer": KV_LAYERS, "target_index_topk": INDEX_TOPK, + "vocab_size": V, "mask_token_id": MASK, "max_position_embeddings": N_CTX, + "rope_parameters": {"rope_theta": float(THETA), "rope_type": "default", "mrope_section": MROPE, "mrope_interleaved": True}, +} + + +def tiny_vocab(self): + # the real target tokenizer is compared with the target's own --vocab-only GGUF on the real model + self.gguf_writer.add_tokenizer_model("gpt2") + self.gguf_writer.add_token_list([f"t{i}" for i in range(V)]) + self.gguf_writer.add_token_types([gguf.TokenType.NORMAL] * V) + + +class TinyDFly(HYV4NextDFlyModel): + model_arch = gguf.MODEL_ARCH.HY_V4_NEXT_DFLY + PROFILE = TINY_PROFILE + _set_target_vocab = tiny_vocab + + +def bf16(shape, rng: np.random.Generator, scale: float = 1.0) -> np.ndarray: + x = (rng.standard_normal(shape) * scale).astype(np.float32) + return (x.view(np.uint32) >> 16).astype(np.uint16) + + +def bf16_of(value: float) -> int: + return int(np.array([value], dtype=np.float32).view(np.uint32)[0] >> 16) + + +def f32_of(bits: np.ndarray) -> np.ndarray: + return (bits.astype(np.uint32) << 16).view(np.float32) + + +ST_DTYPES = {np.dtype(np.uint16): "BF16", np.dtype(np.float32): "F32", np.dtype(np.float16): "F16"} + + +def write_safetensors(path: Path, tensors: dict[str, np.ndarray], edit=None) -> None: + """uint16 arrays are BF16 bits; `edit` gets the header dict and may return replacement JSON text.""" + header: dict[str, Any] = {"__metadata__": {"angelspec_version": "unknown"}} + blobs, offset = [], 0 + for name, arr in tensors.items(): + raw = np.ascontiguousarray(arr).tobytes() + header[name] = {"dtype": ST_DTYPES[arr.dtype], "shape": list(arr.shape), "data_offsets": [offset, offset + len(raw)]} + blobs.append(raw) + offset += len(raw) + text = (edit(header) if edit is not None else None) or json.dumps(header) + text += " " * (-len(text) % 8) + path.write_bytes(len(text).to_bytes(8, "little") + text.encode() + b"".join(blobs)) + + +def source_shapes() -> dict[str, list[int]]: + shapes = {} + for _, (src, ne) in EXPECTED.items(): + shapes[src] = [H * (DN + DV), RKV] if src.endswith("kv_b_proj.weight") else list(reversed(ne)) + return shapes + + +def draft_config() -> dict[str, Any]: + return { + "architectures": ["DSparkDraftModel"], "model_type": "dspark", "model_arch": "dflash", "layer_arch": "dflash", + "vocab_size": V, "hidden_size": D, "intermediate_size": F, "num_hidden_layers": L, "num_attention_heads": H, + # decoys: GQA fields that do not drive this MLA graph, and the training taps (KV layers minus one) + "num_key_value_heads": 3, "head_dim": 5, "target_layer_ids": [i - 1 for i in KV_LAYERS], + "hidden_act": "silu", "max_position_embeddings": N_CTX, "rms_norm_eps": 1e-05, + "target_hidden_size": D, "target_num_hidden_layers": N_TARGET_LAYERS, "mask_token_id": MASK, + "context_local_window": None, "target_index_layer": KV_LAYERS, "target_index_topk": INDEX_TOPK, + "target_kv_layers": KV_LAYERS, "target_attn_init_layers": KV_LAYERS, "mtp_fusion": "slot0", + "enable_hidden_correction": True, "hidden_correction_intermediate_size": None, "markov_rank": 0, + "markov_head_type": "vanilla", "enable_confidence_head": True, "attention_type": "mla", "gated_mla": True, + "gating_type": "elementwise", "learnable_sink": True, "attn_post_proj_norm": True, "q_lora_rank": RQ, + "kv_lora_rank": RKV, "qk_nope_head_dim": DN, "qk_rope_head_dim": DR, "qk_head_dim": DN + DR, "v_head_dim": DV, + "rope_parameters": {"rope_theta": THETA, "rope_type": "default", "mrope_section": MROPE, "mrope_interleaved": True}, + "bos_token_id": 30, "eos_token_id": 31, "pad_token_id": 32, "draft_vocab_size": V, + } + + +def target_config() -> dict[str, Any]: + sparse = {0, *KV_LAYERS} + return { + "architectures": ["HYV4NextVLForConditionalGeneration"], + "text_config": { + "architectures": ["HYV4NextForCausalLM"], + "hidden_size": D, "vocab_size": V, "num_hidden_layers": N_TARGET_LAYERS, "kv_lora_rank": RKV, "qk_rope_head_dim": DR, + "layer_types": ["sparse_attention" if i in sparse else "sliding_attention" for i in range(N_TARGET_LAYERS)], + "swa_pattern": [0 if i in sparse else 1 for i in range(N_TARGET_LAYERS)], + "rope_parameters": {"sparse_attention": {"rope_theta": THETA}, "sliding_attention": {"rope_theta": 10000}}, + "index_topk": INDEX_TOPK, "compressed_indexer_compress_ratio": 4, "compressed_indexer_group_topk": INDEX_TOPK // 4, + "bos_token_id": 30, "eos_token_id": 31, "pad_token_id": 32, + }, + } + + +class Fixture: + def __init__(self, root: Path, seed: int = 0): + self.root = root + self.draft, self.target, self.out = root / "draft", root / "target", root / "out" + for d in (self.draft, self.target, self.out): + d.mkdir() + rng = np.random.default_rng(seed) + self.rng = rng + self.config = draft_config() + self.tensors = {name: bf16(shape, rng) for name, shape in source_shapes().items()} + self.target_embd = bf16([V, D], rng) + self.tensors["embed_tokens.weight"] = self.target_embd.copy() + self.target_config = target_config() + self.target_tensors = {"model.embed_tokens.weight": self.target_embd} + for i in KV_LAYERS: + self.target_tensors[f"model.layers.{i}.self_attn.compressed_indexer.query_projection.weight"] = bf16([2, 2], rng) + self.target_index = True + self.edit_header = None + + def write(self): + (self.draft / "config.json").write_text(json.dumps(self.config)) + write_safetensors(self.draft / "model.safetensors", self.tensors, self.edit_header) + (self.target / "config.json").write_text(json.dumps(self.target_config)) + write_safetensors(self.target / "model.safetensors", self.target_tensors) + if self.target_index: + index = {"metadata": {}, "weight_map": dict.fromkeys(self.target_tensors, "model.safetensors")} + (self.target / "model.safetensors.index.json").write_text(json.dumps(index)) + + +def raw_sha256(bits: np.ndarray) -> str: + return hashlib.sha256(np.ascontiguousarray(bits).tobytes()).hexdigest() + + +def rel_l2(draft: np.ndarray, target: np.ndarray) -> float: + a, b = f32_of(draft).astype(np.float64), f32_of(target).astype(np.float64) + return float(np.sqrt(np.sum((a - b) ** 2) / np.sum(b ** 2))) + + +def tensor_bits(t) -> np.ndarray: + return np.asarray(t.data).view(np.uint32 if t.tensor_type == QT.F32 else np.uint16).reshape(-1) + + +class DFlyTestCase(unittest.TestCase): + maxDiff = None + + def fixture(self, seed: int = 0) -> Fixture: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + return Fixture(Path(tmp.name), seed) + + def convert(self, fx: Fixture, model_class=TinyDFly, ftype=gguf.LlamaFileType.MOSTLY_BF16, out: Path | None = None, **kwargs) -> Path: + fx.write() + out = out if out is not None else fx.out / "draft.gguf" + kwargs.setdefault("dfly_block_size", 8) + kwargs.setdefault("dfly_causal", True) + kwargs.setdefault("target_model_dir", fx.target) + model_class(fx.draft, ftype, out, **kwargs).write() + return out + + def assert_fails(self, fx: Fixture, pattern: str, **kwargs): + with self.assertRaisesRegex(ValueError, pattern): + self.convert(fx, **kwargs) + self.assertEqual(sorted(p.name for p in fx.out.iterdir()), []) + + def manifest(self, out: Path) -> dict[str, Any]: + return json.loads(out.with_name(out.name.removesuffix(".gguf") + ".manifest.json").read_text()) + + +class TestDFlyConversion(DFlyTestCase): + def test_end_to_end(self): + fx = self.fixture() + out = self.convert(fx) + r = gguf.GGUFReader(out) + got = {t.name: t for t in r.tensors} + self.assertEqual(len(EXPECTED), 92) + self.assertEqual(sorted(got), sorted(EXPECTED)) + self.assertFalse(any(n.startswith(("token_embd", "output.")) for n in got)) + + for name, (src, ne) in EXPECTED.items(): + t = got[name] + with self.subTest(tensor=name): + self.assertEqual([int(x) for x in t.shape], ne) + self.assertEqual(t.tensor_type, QT.F32 if name in F32_NAMES else QT.BF16) + if src.endswith("kv_b_proj.weight"): + continue + want = fx.tensors[src].reshape(-1) + if t.tensor_type == QT.F32: + want = want.astype(np.uint32) << 16 + np.testing.assert_array_equal(tensor_bits(t), want) + + for i in range(L): + src = fx.tensors[f"layers.{i}.self_attn.kv_b_proj.weight"] + k = tensor_bits(got[f"blk.{i}.attn_k_b.weight"]).reshape(H, RKV, DN) + v = tensor_bits(got[f"blk.{i}.attn_v_b.weight"]).reshape(H, DV, RKV) + restored = np.concatenate([k.transpose(0, 2, 1), v], axis=1).reshape(H * (DN + DV), RKV) + np.testing.assert_array_equal(restored, src) + # the index definition of the per-head split + for h, d, m, j in ((0, 0, 0, 0), (1, DN - 1, RKV - 1, DV - 1), (1, 2, 5, 3), (0, 4, 17, 6)): + self.assertEqual(k[h, m, d], src[h * (DN + DV) + d, m]) + self.assertEqual(v[h, j, m], src[h * (DN + DV) + DN + j, m]) + + n_params = sum(int(np.prod(ne)) for _, ne in EXPECTED.values()) + self.assertEqual(sum(int(t.n_elements) for t in r.tensors), n_params) + + want_keys = { + "general.architecture": ([VT.STRING], ARCH), + f"{ARCH}.schema_version": ([VT.UINT32], 1), + f"{ARCH}.block_size": ([VT.UINT32], 8), + f"{ARCH}.attention.causal": ([VT.BOOL], True), + f"{ARCH}.block_count": ([VT.UINT32], L), + f"{ARCH}.context_length": ([VT.UINT32], N_CTX), + f"{ARCH}.embedding_length": ([VT.UINT32], D), + f"{ARCH}.feed_forward_length": ([VT.UINT32], F), + f"{ARCH}.attention.head_count": ([VT.UINT32], H), + f"{ARCH}.attention.head_count_kv": ([VT.UINT32], 1), + f"{ARCH}.attention.q_lora_rank": ([VT.UINT32], RQ), + f"{ARCH}.attention.kv_lora_rank": ([VT.UINT32], RKV), + f"{ARCH}.attention.key_length": ([VT.UINT32], RKV + DR), + f"{ARCH}.attention.value_length": ([VT.UINT32], RKV), + f"{ARCH}.attention.key_length_mla": ([VT.UINT32], DN + DR), + f"{ARCH}.attention.value_length_mla": ([VT.UINT32], DV), + f"{ARCH}.rope.dimension_count": ([VT.UINT32], DR), + f"{ARCH}.rope.freq_base": ([VT.FLOAT32], float(THETA)), + f"{ARCH}.attention.layer_norm_rms_epsilon": ([VT.FLOAT32], float(np.float32(1e-05))), + f"{ARCH}.target_kv_layers": ([VT.ARRAY, VT.UINT32], KV_LAYERS), + f"{ARCH}.target_index_layers": ([VT.ARRAY, VT.UINT32], KV_LAYERS), + f"{ARCH}.target_index_top_k": ([VT.UINT32], INDEX_TOPK), + f"{ARCH}.hidden_correction_length": ([VT.UINT32], D), + f"{ARCH}.has_confidence_head": ([VT.BOOL], True), + f"{ARCH}.mtp_fusion": ([VT.STRING], "slot0"), + f"{ARCH}.rope_layout": ([VT.STRING], "norm_adjacent"), + f"{ARCH}.source_mrope_sections": ([VT.ARRAY, VT.UINT32], MROPE), + "tokenizer.ggml.mask_token_id": ([VT.UINT32], MASK), + } + self.assertEqual(len(want_keys), 28) + for key, (types, value) in want_keys.items(): + with self.subTest(key=key): + field = r.fields[key] + self.assertEqual(list(field.types), types) + self.assertEqual(field.contents(), value) + self.assertEqual({k for k in r.fields if k.startswith(f"{ARCH}.")}, {k for k in want_keys if k.startswith(f"{ARCH}.")}) + self.assertFalse(any(k.startswith("general.sampling.") for k in r.fields)) + self.assertEqual(r.fields["general.file_type"].contents(), gguf.LlamaFileType.MOSTLY_BF16) + + def test_manifest(self): + fx = self.fixture() + out = self.convert(fx) + m = self.manifest(out) + self.assertEqual(m["converter"]["design_baselines"]["angelspec"], "368069f22d8d3f2ad07ca6dd288e840046bdc63c") + self.assertEqual(m["converter"]["design_baselines"]["vllm"], "ebc72e673771959ac921376c906e183e72c74fc9") + self.assertTrue(m["converter"]["repo_commit"] == "unknown" or len(m["converter"]["repo_commit"]) == 40) + self.assertIn(m["converter"]["repo_dirty"], (True, False, None)) + self.assertEqual(m["command"], sys.argv) + src = m["source"] + self.assertEqual(src["dir"], str(fx.draft.resolve())) + self.assertEqual(src["config"]["sha256"], hashlib.sha256((fx.draft / "config.json").read_bytes()).hexdigest()) + st = fx.draft / "model.safetensors" + self.assertEqual(src["weight_files"], [{"file": "model.safetensors", "size": st.stat().st_size, "sha256": hashlib.sha256(st.read_bytes()).hexdigest()}]) + self.assertTrue({c["field"] for c in src["profile_check"]}.issuperset(TINY_PROFILE)) + self.assertTrue(all(c["result"] == "ok" for c in src["profile_check"])) + self.assertEqual(m["block_size"], {"value": 8, "source": DEFAULT_SOURCE}) + self.assertEqual(m["causal"], {"value": True, "source": DEFAULT_SOURCE}) + tgt = m["target"] + self.assertEqual((tgt["dir"], tgt["architectures"], tgt["text_architecture"]), + (str(fx.target.resolve()), ["HYV4NextVLForConditionalGeneration"], "HYV4NextForCausalLM")) + self.assertEqual(tgt["config_sha256"], hashlib.sha256((fx.target / "config.json").read_bytes()).hexdigest()) + self.assertEqual(tgt["index_sha256"], hashlib.sha256((fx.target / "model.safetensors.index.json").read_bytes()).hexdigest()) + self.assertTrue(tgt["structure_check"] and all(c["result"] == "ok" for c in tgt["structure_check"])) + self.assertEqual(m["tokenizer"], {"files": {}, "pre": None, "n_tokens": V}) + self.assertEqual(m["outtype"], "bf16") + f32_params = sum(int(np.prod(EXPECTED[n][1])) for n in F32_NAMES) + all_params = sum(int(np.prod(ne)) for _, ne in EXPECTED.values()) + self.assertEqual(m["dtype_summary"], {"BF16": {"tensors": 54, "params": all_params - f32_params}, "F32": {"tensors": 38, "params": f32_params}}) + self.assertIsNone(m["f16_check"]) + + tmap = {e["source"]: e for e in m["tensor_map"]} + self.assertEqual(set(tmap), set(fx.tensors)) + self.assertEqual(len(tmap), 88) + for name, (src_key, ne) in EXPECTED.items(): + outs = {o["name"]: o for o in tmap[src_key]["outputs"]} + self.assertEqual(outs[name]["ne"], ne) + self.assertEqual(outs[name]["type"], "F32" if name in F32_NAMES else "BF16") + self.assertTrue(tmap[src_key]["written"]) + self.assertEqual(sum(len(e["outputs"]) for e in tmap.values()), 92) + self.assertEqual((tmap["embed_tokens.weight"]["written"], tmap["embed_tokens.weight"]["outputs"]), (False, [])) + + sc = m["shared_copies"] + self.assertIs(sc["accept_embedding_mismatch"], False) + self.assertEqual(sc["embedding"]["status"], "match") + self.assertEqual(sc["embedding"]["sha256"], raw_sha256(fx.tensors["embed_tokens.weight"])) + self.assertEqual(sc["embedding"]["target_sha256"], raw_sha256(fx.target_embd)) + self.assertEqual(sc["embedding"]["target_file"], "model.safetensors") + self.assertEqual(sc["lm_head"], {"source_key": "lm_head.weight", "target_key": "lm_head.weight", "status": "absent"}) + self.assertEqual(m["output"], {"file": out.name, "size": out.stat().st_size, "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}) + self.assertEqual(m["training_pairing"], "unverified") + + def test_deterministic(self): + fx = self.fixture() + (fx.out / "a").mkdir() + (fx.out / "b").mkdir() + a = self.convert(fx, out=fx.out / "a" / "x.gguf") + b = self.convert(fx, out=fx.out / "b" / "x.gguf") + self.assertEqual(a.read_bytes(), b.read_bytes()) + + def test_polluted_tensor_name_map(self): + cfg = gguf.TensorNameMap.block_mappings_cfg + saved = copy.deepcopy(cfg) + + def restore(): + cfg.clear() + cfg.update(saved) + self.addCleanup(restore) + + gguf.get_tensor_name_map(gguf.MODEL_ARCH.ARCTIC, 2) + # the hazard is real: the generic map now gives post_attention_layernorm the other norm + polluted = gguf.get_tensor_name_map(gguf.MODEL_ARCH.HY_V4_NEXT_DFLY, L) + self.assertEqual(polluted.get_name("model.layers.0.post_attention_layernorm.weight", try_suffixes=(".weight",)), + "blk.0.post_attention_norm.weight") + + fx = self.fixture() + got = {t.name: t for t in gguf.GGUFReader(self.convert(fx)).tensors} + for i in range(L): + np.testing.assert_array_equal(tensor_bits(got[f"blk.{i}.post_attention_norm.weight"]), + fx.tensors[f"layers.{i}.self_attn.post_proj_norm.weight"].astype(np.uint32) << 16) + np.testing.assert_array_equal(tensor_bits(got[f"blk.{i}.ffn_norm.weight"]), + fx.tensors[f"layers.{i}.post_attention_layernorm.weight"].astype(np.uint32) << 16) + + def test_f16(self): + fx = self.fixture() + up = fx.tensors["layers.1.mlp.up_proj.weight"] + # BF16 values that F16 rounds (a subnormal there) or flushes to zero + up[0, 0], up[0, 1], up[0, 2], up[0, 3] = bf16_of(1e-6), bf16_of(1e-9), bf16_of(2e-8), bf16_of(-1e-9) + out = self.convert(fx, ftype=gguf.LlamaFileType.MOSTLY_F16) + m = self.manifest(out) + self.assertEqual(m["outtype"], "f16") + + want: dict[str, dict[str, int]] = {} + for name, (src_key, ne) in EXPECTED.items(): + if name in F32_NAMES: + continue + x = f32_of(fx.tensors[src_key]) + if src_key.endswith("kv_b_proj.weight"): + x = x.reshape(H, DN + DV, RKV) + x = x[:, :DN] if ".attn_k_b." in name else x[:, DN:] + y = x.astype(np.float16) + want[name] = {"rounded": int(np.count_nonzero(y.astype(np.float32) != x)), "flushed_to_zero": int(np.count_nonzero((y == 0) & (x != 0)))} + self.assertEqual(m["f16_check"]["tensors"], want) + self.assertGreaterEqual(want["blk.1.ffn_up.weight"]["flushed_to_zero"], 3) + self.assertGreaterEqual(want["blk.1.ffn_up.weight"]["rounded"], 4) + self.assertEqual(m["f16_check"]["total"], {"rounded": sum(w["rounded"] for w in want.values()), + "flushed_to_zero": sum(w["flushed_to_zero"] for w in want.values()), "overflow": 0}) + r = gguf.GGUFReader(out) + for t in r.tensors: + self.assertEqual(t.tensor_type, QT.F32 if t.name in F32_NAMES else QT.F16, t.name) + self.assertEqual(r.fields["general.file_type"].contents(), gguf.LlamaFileType.MOSTLY_F16) + + def test_f16_overflow(self): + fx = self.fixture() + fx.tensors["layers.2.mlp.down_proj.weight"][3, 4] = bf16_of(70000.0) + self.assert_fails(fx, r"inf: \['blk\.2\.ffn_down\.weight \(1\)'\]", ftype=gguf.LlamaFileType.MOSTLY_F16) + + def test_nan_inf(self): + fx = self.fixture() + fx.tensors["layers.0.mlp.up_proj.weight"][1, 1] = 0x7FC0 + fx.tensors["mtp_fusion.gate"][0] = 0xFF80 + self.assert_fails(fx, r"(?=.*'layers\.0\.mlp\.up_proj\.weight \(1\)')(?=.*'mtp_fusion\.gate \(1\)')NaN or Inf") + + +class TestDFlyOutputFiles(DFlyTestCase): + def files(self, fx: Fixture) -> dict[str, bytes]: + return {p.name: p.read_bytes() for p in sorted(fx.out.iterdir())} + + def test_write_failure(self): + fx = self.fixture() + with mock.patch.object(gguf.GGUFWriter, "write_tensors_to_file", side_effect=OSError("disk full")): + with self.assertRaisesRegex(OSError, "disk full"): + self.convert(fx) + self.assertEqual(self.files(fx), {}) + + def test_close_failure_during_cleanup(self): + fx = self.fixture() + close = gguf.GGUFWriter.close + + def failing_close(writer): + # like a failed final flush + close(writer) + raise OSError("no space left") + with mock.patch.object(gguf.GGUFWriter, "write_tensors_to_file", side_effect=OSError("disk full")), \ + mock.patch.object(gguf.GGUFWriter, "close", failing_close): + with self.assertRaisesRegex(OSError, "disk full"): + self.convert(fx) + self.assertEqual(self.files(fx), {}) + + def test_manifest_failure(self): + fx = self.fixture() + with mock.patch.object(HYV4NextDFlyModel, "_write_manifest", side_effect=RuntimeError("boom")): + with self.assertRaisesRegex(RuntimeError, "boom"): + self.convert(fx) + self.assertEqual(self.files(fx), {}) + + def test_truncated_output(self): + fx = self.fixture() + close = gguf.GGUFWriter.close + + def close_and_truncate(writer): + close(writer) + if writer.path is not None and writer.path.exists(): + os.truncate(writer.path, writer.path.stat().st_size - 100) + with mock.patch.object(gguf.GGUFWriter, "close", close_and_truncate), self.assertRaises(Exception): + self.convert(fx) + self.assertEqual(self.files(fx), {}) + + def test_rerun(self): + fx = self.fixture() + out = self.convert(fx) + before = self.files(fx) + self.assertEqual(sorted(before), ["draft.gguf", "draft.manifest.json"]) + # a failed re-run keeps the earlier pair as it was + with mock.patch.object(gguf.GGUFWriter, "write_tensors_to_file", side_effect=OSError("disk full")), self.assertRaises(OSError): + self.convert(fx, block_size_source="second run") + self.assertEqual(self.files(fx), before) + # a good re-run replaces the manifest; the GGUF bytes do not change + self.convert(fx, block_size_source="third run") + after = self.files(fx) + self.assertEqual(sorted(after), ["draft.gguf", "draft.manifest.json"]) + self.assertEqual(after["draft.gguf"], before["draft.gguf"]) + self.assertEqual(self.manifest(out)["block_size"]["source"], "third run") + + +class TestDFlySharedCopies(DFlyTestCase): + def mismatched(self, fx: Fixture) -> None: + # a quarter of the rows scaled by 2, the rest byte-identical, so the two norms clearly differ + copy_ = fx.target_embd.copy() + rows = np.arange(0, V, 4) + # x2 is exact in BF16 + copy_[rows] = ((f32_of(copy_[rows]) * 2).view(np.uint32) >> 16).astype(np.uint16) + fx.tensors["embed_tokens.weight"] = copy_ + + def test_absent(self): + fx = self.fixture() + del fx.tensors["embed_tokens.weight"] + m = self.manifest(self.convert(fx)) + self.assertEqual(m["shared_copies"]["embedding"]["status"], "absent") + self.assertEqual(len(m["tensor_map"]), 87) + + def test_mismatch_rejected(self): + fx = self.fixture() + self.mismatched(fx) + draft, target = raw_sha256(fx.tensors["embed_tokens.weight"]), raw_sha256(fx.target_embd) + self.assert_fails(fx, f"embed_tokens.weight.*{draft}.*{target}.*--dfly-accept-embedding-mismatch") + + def test_mismatch_accepted(self): + fx = self.fixture() + self.mismatched(fx) + out = self.convert(fx, accept_embedding_mismatch=True) + e = self.manifest(out)["shared_copies"]["embedding"] + self.assertEqual(e["status"], "mismatch_accepted") + self.assertEqual(e["sha256"], raw_sha256(fx.tensors["embed_tokens.weight"])) + self.assertEqual(e["target_sha256"], raw_sha256(fx.target_embd)) + want = rel_l2(fx.tensors["embed_tokens.weight"], fx.target_embd) + self.assertGreater(want, 0.1) + self.assertAlmostEqual(e["rel_l2"] / want, 1.0, delta=1e-9) + same = int(np.count_nonzero(np.all(fx.tensors["embed_tokens.weight"] == fx.target_embd, axis=1))) + self.assertEqual((e["identical_rows"], e["rows"]), (same, V)) + self.assertEqual(same, V - len(range(0, V, 4))) + self.assertTrue(self.manifest(out)["shared_copies"]["accept_embedding_mismatch"]) + names = [t.name for t in gguf.GGUFReader(out).tensors] + self.assertEqual(len(names), 92) + self.assertNotIn("token_embd.weight", names) + + def test_signed_zero(self): + # different bytes, equal values: still a mismatch + fx = self.fixture() + fx.target_embd[3, 5] = 0x0000 + fx.tensors["embed_tokens.weight"] = fx.target_embd.copy() + fx.tensors["embed_tokens.weight"][3, 5] = 0x8000 + self.assert_fails(fx, "differs from the target") + out = self.convert(fx, accept_embedding_mismatch=True) + e = self.manifest(out)["shared_copies"]["embedding"] + self.assertEqual((e["status"], e["identical_rows"], e["rel_l2"]), ("mismatch_accepted", V - 1, 0.0)) + + def test_lm_head(self): + for case in ("match", "mismatch", "accepted", "no target head"): + with self.subTest(case=case): + fx = self.fixture() + head = bf16([V, D], fx.rng) + fx.target_tensors["lm_head.weight"] = head + fx.tensors["lm_head.weight"] = head.copy() + if case != "match": + fx.tensors["lm_head.weight"][0, 0] ^= 1 + if case == "no target head": + del fx.target_tensors["lm_head.weight"] + self.assert_fails(fx, "no lm_head.weight") + elif case == "mismatch": + self.assert_fails(fx, f"lm_head.weight.*{raw_sha256(fx.tensors['lm_head.weight'])}.*{raw_sha256(head)}") + else: + out = self.convert(fx, accept_embedding_mismatch=case == "accepted") + sc = self.manifest(out)["shared_copies"] + self.assertEqual(sc["embedding"]["status"], "match") + self.assertEqual(sc["lm_head"]["status"], "match" if case == "match" else "mismatch_accepted") + self.assertEqual(sc["lm_head"]["sha256"], raw_sha256(fx.tensors["lm_head.weight"])) + self.assertNotIn("output.weight", [t.name for t in gguf.GGUFReader(out).tensors]) + + def test_non_finite_copy(self): + fx = self.fixture() + fx.tensors["embed_tokens.weight"][2, 3] = 0x7F80 + self.assert_fails(fx, "embed_tokens.weight or its target model.embed_tokens.weight holds NaN or Inf", accept_embedding_mismatch=True) + + def test_copy_layout_differs(self): + for case in ("shape", "dtype"): + with self.subTest(case=case): + fx = self.fixture() + if case == "shape": + fx.target_tensors["model.embed_tokens.weight"] = bf16([V + 2, D], fx.rng) + else: + fx.target_tensors["model.embed_tokens.weight"] = f32_of(fx.target_embd) + self.assert_fails(fx, "not accepted even with --dfly-accept-embedding-mismatch", accept_embedding_mismatch=True) + + def test_target_without_index(self): + fx = self.fixture() + fx.target_index = False + m = self.manifest(self.convert(fx)) + self.assertEqual(m["shared_copies"]["embedding"]["status"], "match") + self.assertIsNone(m["target"]["index_sha256"]) + + +class TestDFlyRejects(DFlyTestCase): + def check_config(self, cases): + for name, edit, pattern in cases: + with self.subTest(case=name): + fx = self.fixture() + edit(fx.config) + self.assert_fails(fx, pattern) + + def test_config(self): + def set_(key, value): + return lambda c: c.__setitem__(key, value) + + def set_rope(key, value): + return lambda c: c["rope_parameters"].__setitem__(key, value) + + self.check_config([ + ("no max_position_embeddings", lambda c: c.pop("max_position_embeddings"), "max_position_embeddings"), + ("max_position_embeddings 0", set_("max_position_embeddings", 0), "max_position_embeddings"), + ("bool for int", set_("num_hidden_layers", True), "num_hidden_layers = True"), + ("string number", set_("hidden_size", "24"), "hidden_size = '24'"), + ("float layer id", set_("target_kv_layers", [3, 5, 7.0, 9, 11]), "target_kv_layers must be a list of integers"), + ("string layer id", set_("target_index_layer", ["3", 5, 7, 9, 11]), "target_index_layer must be a list of integers"), + ("mrope_interleaved 1", set_rope("mrope_interleaved", 1), "rope_parameters"), + ("float mrope_section", set_rope("mrope_section", [1.0, 1, 0]), "rope_parameters"), + ("extra rope key", set_rope("factor", 2.0), "rope_parameters"), + ("gated_mla 1", set_("gated_mla", 1), "gated_mla"), + ("float correction size", set_("hidden_correction_intermediate_size", 24.0), "hidden_correction_intermediate_size"), + ("context_local_window 0", set_("context_local_window", 0), "context_local_window"), + ("context_local_window False", set_("context_local_window", False), "context_local_window"), + ("context_local_window 128", set_("context_local_window", 128), "context_local_window"), + ("model_type", set_("model_type", "qwen3"), "model_type"), + ("architectures", set_("architectures", ["DFlashDraftModel"]), "architectures"), + ("attention_type", set_("attention_type", "gqa"), "attention_type"), + ("mtp_fusion", set_("mtp_fusion", "none"), "mtp_fusion"), + ("moe draft", set_("draft_mlp_type", "moe"), "draft_mlp_type"), + ("markov head", set_("markov_rank", 2), "markov_rank"), + ("own index_topk", set_("index_topk", 16), "index_topk"), + ("context kv source", set_("context_kv_source_layers", [1]), "context_kv_source_layers"), + ("path selector", set_("enable_path_selector", True), "enable_path_selector"), + ("draft vocab", set_("draft_vocab_size", 20), "draft_vocab_size"), + ("qk_head_dim", set_("qk_head_dim", 11), "qk_head_dim"), + ("top-level rope_theta", set_("rope_theta", 10000), "rope_theta"), + ("duplicate layers", lambda c: c.update(target_kv_layers=[3, 3, 7, 9, 11], target_index_layer=[3, 3, 7, 9, 11]), "duplicate layer ids"), + ("index differs", set_("target_index_layer", [3, 5, 7, 9, 10]), "target_index_layer .* differs from target_kv_layers"), + ("only target_layer_ids", lambda c: c.pop("target_kv_layers"), "target_kv_layers is required; target_layer_ids"), + ("block size conflict", set_("dflash_block_size", 5), "dflash_block_size = 5 conflicts with --dfly-block-size 8"), + ("block size type", set_("block_size", 8.0), "block_size = 8.0 conflicts"), + ("causal conflict", set_("dflash_causal_attn", False), "dflash_causal_attn = False conflicts"), + ("causal 1", set_("dflash_causal_attn", 1), "dflash_causal_attn = 1 conflicts"), + ("quantized", set_("quantization_config", {"quant_method": "fp8"}), "quantization_config"), + ("nested text config", set_("text_config", {"vocab_size": V + 8}), "text_config is set"), + ]) + + def test_config_duplicate_key(self): + fx = self.fixture() + fx.write() + text = (fx.draft / "config.json").read_text() + (fx.draft / "config.json").write_text(text[:-1] + ', "hidden_size": 24}') + with self.assertRaisesRegex(ValueError, "duplicate key 'hidden_size'"): + TinyDFly(fx.draft, gguf.LlamaFileType.MOSTLY_BF16, fx.out / "x.gguf", dfly_block_size=8, dfly_causal=True, target_model_dir=fx.target) + + def test_arguments(self): + for name, kwargs, pattern in ( + ("f32", {"ftype": gguf.LlamaFileType.ALL_F32}, "outtype must be bf16 or f16"), + ("B 1", {"dfly_block_size": 1}, "--dfly-block-size"), + ("B bool", {"dfly_block_size": True}, "--dfly-block-size"), + ("B float", {"dfly_block_size": 8.0}, "--dfly-block-size"), + ("causal false", {"dfly_causal": False}, "--dfly-causal must be true"), + ("empty source", {"block_size_source": " "}, "--dfly-block-size-source must not be empty"), + ("no target", {"target_model_dir": None}, "--target-model-dir"), + ): + with self.subTest(case=name): + self.assert_fails(self.fixture(), pattern, **kwargs) + + def test_target(self): + def text(key, value): + return lambda fx: fx.target_config["text_config"].__setitem__(key, value) + + def drop_tensor(name): + return lambda fx: fx.target_tensors.pop(name) + + for name, edit, pattern in ( + ("vocab", text("vocab_size", V + 1), "text_config.vocab_size"), + ("hidden", text("hidden_size", D + 1), "text_config.hidden_size"), + ("latent", text("kv_lora_rank", RKV + 2), "text_config.kv_lora_rank"), + ("rope dim", text("qk_rope_head_dim", DR + 2), "text_config.qk_rope_head_dim"), + ("layer count", lambda fx: fx.config.__setitem__("target_num_hidden_layers", N_TARGET_LAYERS + 1), "num_hidden_layers"), + ("target hidden", lambda fx: fx.config.__setitem__("target_hidden_size", D + 1), "target_hidden_size"), + ("sliding layer", lambda fx: fx.target_config["text_config"]["layer_types"].__setitem__(5, "sliding_attention"), r"layer_types\[5\]"), + ("swa layer", lambda fx: fx.target_config["text_config"]["swa_pattern"].__setitem__(7, 1), r"swa_pattern\[7\]"), + ("no indexer", drop_tensor("model.layers.9.self_attn.compressed_indexer.query_projection.weight"), "layers.9.self_attn.compressed_indexer"), + ("no embedding", drop_tensor("model.embed_tokens.weight"), "model.embed_tokens.weight"), + ("rope theta", lambda fx: fx.target_config["text_config"]["rope_parameters"]["sparse_attention"].__setitem__("rope_theta", 10000), "rope_theta"), + ("index topk", text("index_topk", INDEX_TOPK * 2), "text_config.index_topk"), + ("compress ratio", text("compressed_indexer_compress_ratio", 8), "compress_ratio"), + ("group topk", text("compressed_indexer_group_topk", 3), "group_topk"), + ("eos", text("eos_token_id", 33), "eos_token_id"), + ("text arch", text("architectures", ["Qwen3ForCausalLM"]), "text architecture"), + ("arch", lambda fx: fx.target_config.__setitem__("architectures", ["Qwen3VLForConditionalGeneration"]), "architectures"), + ("prism", lambda fx: (fx.target / "hadamard_packing.json").write_text("{}"), "hadamard_packing.json"), + ("empty text arch", text("architectures", []), "text_config.architectures must be a non-empty list"), + ): + with self.subTest(case=name): + fx = self.fixture() + edit(fx) + self.assert_fails(fx, pattern) + + def test_malformed_target_index(self): + fx = self.fixture() + fx.write() + (fx.target / "model.safetensors.index.json").write_text("[]") + with self.assertRaisesRegex(ValueError, "model.safetensors.index.json: no valid weight_map"): + TinyDFly(fx.draft, gguf.LlamaFileType.MOSTLY_BF16, fx.out / "x.gguf", dfly_block_size=8, dfly_causal=True, target_model_dir=fx.target) + + def test_mask(self): + fx = self.fixture() + fx.config["mask_token_id"] = MASK - 1 + self.assert_fails(fx, "mask_token_id = 36, expected 37") + + class OutOfVocab(TinyDFly): + model_arch = gguf.MODEL_ARCH.HY_V4_NEXT_DFLY + PROFILE = {**TINY_PROFILE, "mask_token_id": V} + + fx = self.fixture() + fx.config["mask_token_id"] = V + self.assert_fails(fx, f"mask_token_id = {V}, expected '0 <= id < {V}'", model_class=OutOfVocab) + + def test_tensors(self): + for name, change, pattern in ( + ("kv_b one row short", lambda fx: fx.tensors.__setitem__("layers.1.self_attn.kv_b_proj.weight", bf16([H * (DN + DV) - 1, RKV], fx.rng)), + r"layers\.1\.self_attn\.kv_b_proj\.weight \[27, 22\] \(expected \[28, 22\]\)"), + ("down_proj transposed", lambda fx: fx.tensors.__setitem__("layers.3.mlp.down_proj.weight", bf16([F, D], fx.rng)), + r"layers\.3\.mlp\.down_proj\.weight \[36, 24\] \(expected \[24, 36\]\)"), + ("router", lambda fx: fx.tensors.__setitem__("layers.0.mlp.router.weight", bf16([4, D], fx.rng)), r"unknown tensors \['layers\.0\.mlp\.router\.weight'\]"), + ("markov", lambda fx: fx.tensors.__setitem__("markov_head.weight", bf16([4, D], fx.rng)), r"unknown tensors \['markov_head\.weight'\]"), + ("missing sink", lambda fx: fx.tensors.pop("layers.4.self_attn.learnable_sink_param"), r"missing tensors \['layers\.4\.self_attn\.learnable_sink_param'\]"), + ("f32 tensor", lambda fx: fx.tensors.__setitem__("final_norm.weight", f32_of(fx.tensors["final_norm.weight"])), r"final_norm\.weight \(F32\)"), + ): + with self.subTest(case=name): + fx = self.fixture() + change(fx) + self.assert_fails(fx, pattern) + + def test_headers(self): + def duplicate(header): + text = json.dumps(header) + return text[:-1] + ', "final_norm.weight": ' + json.dumps(header["final_norm.weight"]) + "}" + + def out_of_range(header): + begin, end = header["mtp_fusion.gate"]["data_offsets"] + header["mtp_fusion.gate"]["data_offsets"] = [begin + 10**6, end + 10**6] + + def overlap(header): + begin, end = header["mtp_fusion.gate"]["data_offsets"] + other = header["final_norm.weight"]["data_offsets"] + header["final_norm.weight"]["data_offsets"] = [begin + 2, begin + 2 + other[1] - other[0]] + + for name, fn, pattern in ( + ("duplicate key", duplicate, "duplicate key 'final_norm.weight'"), + ("out of range", out_of_range, r"mtp_fusion\.gate data_offsets .* outside"), + ("overlap", overlap, "overlap"), + ): + with self.subTest(case=name): + fx = self.fixture() + fx.edit_header = fn + self.assert_fails(fx, pattern) + + # json would accept a UTF-16 header if it were given bytes + fx = self.fixture() + fx.write() + st = fx.draft / "model.safetensors" + data = st.read_bytes() + n = int.from_bytes(data[:8], "little") + header = data[8:8 + n].decode().rstrip().encode("utf-16-le") + st.write_bytes(len(header).to_bytes(8, "little") + header + data[8 + n:]) + with self.assertRaisesRegex(ValueError, "bad safetensors header"): + TinyDFly(fx.draft, gguf.LlamaFileType.MOSTLY_BF16, fx.out / "x.gguf", dfly_block_size=8, dfly_causal=True, target_model_dir=fx.target) + + def test_shards(self): + fx = self.fixture() + names = sorted(fx.tensors) + half = len(names) // 2 + dup = names[-1] + parts = {"model-00001-of-00002.safetensors": names[:half] + [dup], + "model-00002-of-00002.safetensors": names[half:]} + fx.write() + (fx.draft / "model.safetensors").unlink() + for part, keys in parts.items(): + write_safetensors(fx.draft / part, {k: fx.tensors[k] for k in keys}) + index = {"weight_map": {k: p for p, keys in parts.items() for k in keys}} + (fx.draft / "model.safetensors.index.json").write_text(json.dumps(index)) + with self.assertRaisesRegex(ValueError, rf"more than one shard: \['{re.escape(dup)}'\]"): + TinyDFly(fx.draft, gguf.LlamaFileType.MOSTLY_BF16, fx.out / "x.gguf", dfly_block_size=8, dfly_causal=True, target_model_dir=fx.target) + + def test_files(self): + for name in ("hadamard_packing.json", "hf_quant_config.json", "pytorch_model.bin"): + with self.subTest(file=name): + fx = self.fixture() + fx.write() + (fx.draft / name).write_text("{}") + with self.assertRaisesRegex(ValueError, name): + TinyDFly(fx.draft, gguf.LlamaFileType.MOSTLY_BF16, fx.out / "x.gguf", dfly_block_size=8, dfly_causal=True, + target_model_dir=fx.target) + + +class TestDFlyNames(DFlyTestCase): + def test_global_source_names(self): + tmap = gguf.TensorNameMap(gguf.MODEL_ARCH.HY_V4_NEXT_DFLY, L) + for src, name in ( + ("mtp_fusion.enorm", "dfly_fusion_enorm"), ("mtp_fusion.hnorm", "dfly_fusion_hnorm"), + ("mtp_fusion.eh_proj", "dfly_fusion_eh"), ("mtp_fusion.gate", "dfly_fusion_gate"), + ("hidden_correction.hidden_norm", "dfly_correction_hnorm"), ("hidden_correction.embed_norm", "dfly_correction_enorm"), + ("hidden_correction.gate_proj", "dfly_correction_gate"), ("hidden_correction.up_proj", "dfly_correction_up"), + ("hidden_correction.down_proj", "dfly_correction_down"), ("confidence_head.proj", "dfly_confidence"), + ): + for suffix in (".weight", ".bias"): + with self.subTest(source=src + suffix): + self.assertEqual(tmap.get_name(src + suffix, try_suffixes=(".weight", ".bias")), name + suffix) + + def test_dspark_route_unchanged(self): + from conversion.qwen import DSparkModel + self.assertIs(get_model_class("DSparkDraftModel"), DSparkModel) + + def test_detect(self): + self.assertTrue(is_hy4_dfly_config(draft_config())) + qwen = {"architectures": ["DSparkDraftModel"], "model_type": "qwen3", "target_layer_ids": [1, 2], "dflash_config": {"mask_token_id": 3}} + self.assertFalse(is_hy4_dfly_config(qwen)) + self.assertFalse(is_hy4_dfly_config({**draft_config(), "attention_type": "gqa"})) + self.assertFalse(is_hy4_dfly_config({**draft_config(), "architectures": ["DFlashDraftModel"]})) + no_layers = draft_config() + del no_layers["target_kv_layers"], no_layers["target_index_layer"] + self.assertFalse(is_hy4_dfly_config(no_layers)) + + def test_set_vocab_delegates(self): + class RealVocab(HYV4NextDFlyModel): + model_arch = gguf.MODEL_ARCH.HY_V4_NEXT_DFLY + PROFILE = TINY_PROFILE + + fx = self.fixture() + fx.write() + model = RealVocab(fx.draft, gguf.LlamaFileType.MOSTLY_BF16, fx.out / "x.gguf", dfly_block_size=8, dfly_causal=True, target_model_dir=fx.target) + seen = [] + + class FakeTarget: + def set_vocab(self_): + seen.append(Path(self_.dir_model)) + self_.gguf_writer.add_tokenizer_model("gpt2") + + with mock.patch("conversion.get_model_class", return_value=FakeTarget) as lookup: + model.set_vocab() + lookup.assert_called_once_with("HYV4NextForCausalLM") + self.assertEqual(seen, [fx.target]) + self.assertEqual(Path(model.dir_model), fx.draft) + kv = model.gguf_writer.kv_data[0] + self.assertEqual(kv[gguf.Keys.Tokenizer.MODEL].value, "gpt2") + self.assertEqual(kv[gguf.Keys.Tokenizer.MASK_ID].value, MASK) + + class Broken: + def set_vocab(self_): + raise RuntimeError("boom") + + with mock.patch("conversion.get_model_class", return_value=Broken), self.assertRaisesRegex(RuntimeError, "boom"): + model.set_vocab() + self.assertEqual(Path(model.dir_model), fx.draft) + + +class TestDFlyCommandLine(DFlyTestCase): + def argv(self, fx: Fixture, *extra: str, drop: tuple[str, ...] = ()) -> list[str]: + args = {"--dfly": None, "--dfly-block-size": "8", "--dfly-causal": "true", "--target-model-dir": str(fx.target), + "--outtype": "bf16", "--outfile": str(fx.out / "x.gguf")} + out = ["convert_hf_to_gguf.py", str(fx.draft)] + for flag, value in args.items(): + if flag not in drop: + out += [flag] if value is None else [flag, value] + return out + list(extra) + + def parse_error(self, argv: list[str]) -> str: + err = io.StringIO() + with mock.patch.object(sys, "argv", argv), contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: + convert_hf_to_gguf.parse_args() + self.assertEqual(cm.exception.code, 2) + return err.getvalue() + + def test_valid(self): + fx = self.fixture() + with mock.patch.object(sys, "argv", self.argv(fx, "--dfly-causal-source", "x")): + args = convert_hf_to_gguf.parse_args() + self.assertEqual((args.dfly_block_size, args.dfly_causal, args.dfly_causal_source), (8, "true", "x")) + + def test_rejects(self): + fx = self.fixture() + (fx.out / "dir.gguf").mkdir() + cases = [ + ("no B", self.argv(fx, drop=("--dfly-block-size",)), "--dfly requires --dfly-block-size"), + ("no causal", self.argv(fx, drop=("--dfly-causal",)), "--dfly requires --dfly-causal"), + ("no target", self.argv(fx, drop=("--target-model-dir",)), "--dfly requires --target-model-dir"), + ("causal false", self.argv(fx, drop=("--dfly-causal",)) + ["--dfly-causal", "false"], "non-causal"), + ("empty source", self.argv(fx, "--dfly-block-size-source", ""), "--dfly-block-size-source must not be empty"), + ("outtype auto", self.argv(fx, drop=("--outtype",)), "--outtype bf16 or f16, got auto"), + ("no outfile", self.argv(fx, drop=("--outfile",)), "--dfly requires --outfile"), + ("outfile suffix", self.argv(fx, drop=("--outfile",)) + ["--outfile", str(fx.out / "x.bin")], "--outfile must be a .gguf"), + ("outfile template", self.argv(fx, drop=("--outfile",)) + ["--outfile", str(fx.out / "x-{ftype}.gguf")], "--outfile must be a .gguf"), + ("outfile dir", self.argv(fx, drop=("--outfile",)) + ["--outfile", str(fx.out / "dir.gguf")], "--outfile must be a .gguf"), + ("outfile in draft", self.argv(fx, drop=("--outfile",)) + ["--outfile", str(fx.draft / "x.gguf")], "inside the model directory"), + ("outfile in target", self.argv(fx, drop=("--outfile",)) + ["--outfile", str(fx.target / "x.gguf")], "inside the --target-model-dir directory"), + ("outfile parent", self.argv(fx, drop=("--outfile",)) + ["--outfile", str(fx.out / "missing" / "x.gguf")], "does not exist"), + ("empty target", self.argv(fx, drop=("--target-model-dir",)) + ["--target-model-dir", ""], "--target-model-dir must be an existing directory, got ''"), + ("missing target", self.argv(fx, drop=("--target-model-dir",)) + ["--target-model-dir", str(fx.root / "nope")], "--target-model-dir must be an existing directory"), + ("missing model", ["convert_hf_to_gguf.py", str(fx.root / "nope")] + self.argv(fx)[2:], "model must be an existing directory"), + ] + for value in ("0", "1", "-1", "8.0", "abc", "8_0", "+8", " 8", "4294967296"): + cases.append((f"B {value!r}", self.argv(fx, drop=("--dfly-block-size",)) + [f"--dfly-block-size={value}"], "argument --dfly-block-size")) + for value in ("True", "1", "yes"): + cases.append((f"causal {value!r}", self.argv(fx, drop=("--dfly-causal",)) + ["--dfly-causal", value], "argument --dfly-causal: invalid choice")) + for flag in ("--mtp", "--dspark", "--no-mtp", "--no-nextn", "--mmproj", "--remote", "--mistral-format", "--vocab-only", + "--dry-run", "--bigendian", "--fuse-qkv", "--fuse-gate-up-exps", "--fp8-as-q8", "--no-tensor-first-split"): + shown = "--no-mtp/--no-nextn" if flag in ("--no-mtp", "--no-nextn") else flag + cases.append((flag, self.argv(fx, flag), f"--dfly cannot be combined with {shown}")) + cases.append(("split tensors", self.argv(fx, "--split-max-tensors", "10"), "--dfly cannot be combined with --split-max-tensors")) + cases.append(("split size", self.argv(fx, "--split-max-size", "1G"), "--dfly cannot be combined with --split-max-size")) + for flag, value in (("--dfly-block-size", "8"), ("--dfly-causal", "true"), ("--dfly-accept-embedding-mismatch", None), + ("--dfly-block-size-source", "x"), ("--dfly-causal-source", "")): + argv = ["convert_hf_to_gguf.py", str(fx.draft), "--outtype", "bf16", flag] + ([] if value is None else [value]) + cases.append((f"{flag} without --dfly", argv, f"{flag} can only be used with --dfly")) + for name, argv, pattern in cases: + with self.subTest(case=name): + self.assertIn(pattern, self.parse_error(argv)) + + +class TestDFlyMain(DFlyTestCase): + def run_main(self, argv: list[str]): + with mock.patch.object(sys, "argv", argv), mock.patch.object(HYV4NextDFlyModel, "PROFILE", TINY_PROFILE), \ + mock.patch.object(HYV4NextDFlyModel, "_set_target_vocab", tiny_vocab), \ + mock.patch.object(convert_hf_to_gguf.logging, "basicConfig"): + convert_hf_to_gguf.main() + + def test_dispatch(self): + fx = self.fixture() + fx.write() + out = fx.out / "main.gguf" + argv = ["convert_hf_to_gguf.py", str(fx.draft), "--dfly", "--dfly-block-size", "5", "--dfly-causal", "true", + "--target-model-dir", str(fx.target), "--dfly-block-size-source", "block size from x", "--dfly-causal-source", "causal from y", + "--dfly-accept-embedding-mismatch", "--outtype", "bf16", "--outfile", str(out)] + self.run_main(argv) + m = self.manifest(out) + self.assertEqual(m["block_size"], {"value": 5, "source": "block size from x"}) + self.assertEqual(m["causal"], {"value": True, "source": "causal from y"}) + self.assertIs(m["shared_copies"]["accept_embedding_mismatch"], True) + self.assertEqual(m["command"], argv) + self.assertEqual(gguf.GGUFReader(out).fields[f"{ARCH}.block_size"].contents(), 5) + + def test_not_a_dspark_draft(self): + fx = self.fixture() + fx.config["architectures"] = ["LlamaForCausalLM"] + fx.write() + argv = ["convert_hf_to_gguf.py", str(fx.draft), "--dfly", "--dfly-block-size", "8", "--dfly-causal", "true", + "--target-model-dir", str(fx.target), "--outtype", "bf16", "--outfile", str(fx.out / "x.gguf")] + with self.assertLogs("hf-to-gguf", "ERROR") as logs, self.assertRaises(SystemExit) as cm: + self.run_main(argv) + self.assertEqual(cm.exception.code, 1) + self.assertIn("--dfly is only supported for the HY4-Next DFly draft", "\n".join(logs.output)) + + def test_directed_error(self): + fx = self.fixture() + fx.write() + argv = ["convert_hf_to_gguf.py", str(fx.draft), "--outtype", "bf16", "--outfile", str(fx.out / "x.gguf")] + with self.assertLogs("hf-to-gguf", "ERROR") as logs, self.assertRaises(SystemExit) as cm: + self.run_main(argv) + self.assertEqual(cm.exception.code, 1) + self.assertIn("convert it with --dfly", "\n".join(logs.output)) + self.assertEqual(list(fx.out.iterdir()), []) + + def test_subprocess(self): + fx = self.fixture() + fx.write() + script = str(REPO / "convert_hf_to_gguf.py") + out = str(fx.out / "x.gguf") + for argv, code, text in ( + ([fx.draft, "--dfly-causal", "true", "--outtype", "bf16", "--outfile", out], 2, "--dfly-causal can only be used with --dfly"), + ([fx.draft, "--dfly", "--dfly-causal", "true", "--target-model-dir", fx.target, "--outtype", "bf16", "--outfile", out], 2, + "--dfly requires --dfly-block-size"), + ([fx.draft, "--outtype", "bf16", "--outfile", out], 1, "convert it with --dfly"), + ): + with self.subTest(argv=argv[1:]): + res = subprocess.run([sys.executable, script, *map(str, argv)], capture_output=True, text=True, cwd=REPO, timeout=600) + self.assertEqual(res.returncode, code, res.stderr[-2000:]) + self.assertIn(text, res.stderr) + self.assertEqual(list(fx.out.iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index f1ec3c456645c34aecbf418e1f847a14291968f6..6ed391ce4833d29f61c2f768145a5444d0512f46 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -42,6 +42,7 @@ add_library(mtmd models/granite-speech.cpp models/granite4-vision.cpp models/hunyuanvl.cpp + models/hy-v4-flash.cpp models/internvl.cpp models/kimivl.cpp models/kimik25.cpp diff --git a/tools/mtmd/clip-impl.h b/tools/mtmd/clip-impl.h index 0504e8fdcc4c3ad980037dcdef6d3d627d483b18..5da9e7358c4e974cd5daf71b053d058982a2d908 100644 --- a/tools/mtmd/clip-impl.h +++ b/tools/mtmd/clip-impl.h @@ -561,6 +561,7 @@ enum projector_type { PROJECTOR_TYPE_NEMOTRON_V2_VL, PROJECTOR_TYPE_NEMOTRON_OMNI, PROJECTOR_TYPE_HUNYUANVL, + PROJECTOR_TYPE_HY_V4_FLASH, PROJECTOR_TYPE_PARAKEET, PROJECTOR_TYPE_EXAONE4_5, PROJECTOR_TYPE_MINICPMV4_6, @@ -643,6 +644,7 @@ static std::map PROJECTOR_TYPE_NAMES = { { PROJECTOR_TYPE_NEMOTRON_OMNI, "nemotron_omni"}, { PROJECTOR_TYPE_EXAONE4_5, "exaone4_5"}, { PROJECTOR_TYPE_HUNYUANVL, "hunyuanvl"}, + { PROJECTOR_TYPE_HY_V4_FLASH, "hy_v4_flash"}, { PROJECTOR_TYPE_MINICPMV4_6, "minicpmv4_6"}, { PROJECTOR_TYPE_MINICPMV4_7, "minicpmv4_7"}, { PROJECTOR_TYPE_MINICPM_OCR_1_0, "minicpm_ocr_1_0"}, diff --git a/tools/mtmd/clip.cpp b/tools/mtmd/clip.cpp index 9a043d7f9ca32d5df2a78ab4e65026ae15399646..ce67f196128ee0468823d08bd6fcf208820be43c 100644 --- a/tools/mtmd/clip.cpp +++ b/tools/mtmd/clip.cpp @@ -1127,6 +1127,10 @@ static std::unique_ptr clip_get_graph_builder(clip_ctx * ctx, const { builder = std::make_unique(ctx, img); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + builder = std::make_unique(ctx, img); + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: case PROJECTOR_TYPE_LDP: @@ -2281,6 +2285,22 @@ struct clip_model_loader { get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false); hparams.set_warmup_n_tokens(32*32); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + hparams.n_merge = 2; + hparams.image_resize_algo = RESIZE_ALGO_LANCZOS; + hparams.image_resize_pad = PAD_NONE; + // the encoder ffn fuses the bias with the tanh gelu, see bias_activation_fusion + hparams.ffn_op = FFN_GELU; + get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false); + // n_merge divides the patch grid in clip_n_output_tokens, reject 0 + GGML_ASSERT(hparams.n_merge > 0); + // HF processor defaults, the gguf keys below carry the real values + hparams.set_limit_image_tokens(4, 4096); + get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels, false); + get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false); + hparams.set_warmup_n_tokens(16*16); // vision_config.min_image_size + } break; case PROJECTOR_TYPE_LFM2A: case PROJECTOR_TYPE_D1OMNI_A: { @@ -3793,6 +3813,16 @@ struct clip_model_loader { model.image_newline = get_tensor(TN_IMAGE_NEWLINE); model.view_seperator = get_tensor(TN_IMAGE_SEPERATOR, false); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + // perceive.proj.0 -> mm.0 (conv1), perceive.proj.2 -> mm.2 (conv2) + model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight")); + model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias")); + model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight")); + model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias")); + model.mm_pre_norm_w = get_tensor(string_format(TN_MM_PRE_NORM, "weight")); + model.image_newline = get_tensor(TN_IMAGE_NEWLINE); + } break; case PROJECTOR_TYPE_JANUS_PRO: { model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight")); @@ -4704,6 +4734,9 @@ int clip_n_output_tokens_x(const clip_ctx * ctx, const clip_image_f32 * img) { case PROJECTOR_TYPE_MUSE_GLIMMER: case PROJECTOR_TYPE_LFM3VL: return (img->nx() / params.patch_size) / 2; + case PROJECTOR_TYPE_HY_V4_FLASH: + // the projector appends one newline embedding per token row + return (img->nx() / params.patch_size) / params.n_merge + 1; case PROJECTOR_TYPE_STEP3VL: case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: @@ -4737,6 +4770,8 @@ int clip_n_output_tokens_y(const clip_ctx * ctx, const clip_image_f32 * img) { case PROJECTOR_TYPE_MUSE_GLIMMER: case PROJECTOR_TYPE_LFM3VL: return (img->ny() / params.patch_size) / 2; + case PROJECTOR_TYPE_HY_V4_FLASH: + return (img->ny() / params.patch_size) / params.n_merge; case PROJECTOR_TYPE_STEP3VL: case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: @@ -4988,6 +5023,14 @@ int clip_n_output_tokens(const clip_ctx * ctx, const clip_image_f32 * img) { int oh = (img->ny() / patch_size) / merge; n_patches = (ow + 1) * oh + 2; } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + // no begin/end embeddings, the prompt carries the image start/end tokens + int merge = ctx->model.hparams.n_merge; + int ow = (img->nx() / patch_size) / merge; + int oh = (img->ny() / patch_size) / merge; + n_patches = (ow + 1) * oh; + } break; case PROJECTOR_TYPE_DEEPSEEKOCR2: { // 1024 global view -> 256 query tokens + 1 view separator = 257; @@ -6354,6 +6397,7 @@ bool clip_encode(struct clip_ctx * ctx, struct clip_encode_params * params) { } } break; case PROJECTOR_TYPE_HUNYUANVL: + case PROJECTOR_TYPE_HY_V4_FLASH: { // Compute the HunyuanVL 2D position embedding on CPU (with the // custom sf=(target+0.1)/n_grid bilinear sampling that the @@ -7073,6 +7117,8 @@ int clip_n_mmproj_embd(const struct clip_ctx * ctx) { return ctx->model.mm_2_w->ne[1]; case PROJECTOR_TYPE_HUNYUANVL: return ctx->model.mm_model_proj->ne[1]; + case PROJECTOR_TYPE_HY_V4_FLASH: + return ctx->model.mm_1_w->ne[3]; // conv2d kernel is [1, 1, IC, OC] case PROJECTOR_TYPE_COGVLM: return ctx->model.mm_4h_to_h_w->ne[1]; case PROJECTOR_TYPE_DEEPSEEKOCR: diff --git a/tools/mtmd/models/hy-v4-flash.cpp b/tools/mtmd/models/hy-v4-flash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8753f7d5644ff2677767406b188bcecccdc6e9d --- /dev/null +++ b/tools/mtmd/models/hy-v4-flash.cpp @@ -0,0 +1,47 @@ +#include "models.h" + +ggml_cgraph * clip_graph_hy_v4_flash::build() { + const int merge = hparams.n_merge; + const int pw = n_patches_x; + const int ph = n_patches_y; + + // position embedding: a graph input, interpolated on CPU in clip_encode + // (same name and interpolation as hunyuanvl, see the branch there) + ggml_tensor * pos_embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, ph * pw); + ggml_set_name(pos_embd, "hunyuanvl_pos_embd"); + ggml_set_input(pos_embd); + + ggml_tensor * inp = build_inp(); + ggml_tensor * cur = build_vit(inp, n_patches, NORM_TYPE_NORMAL, hparams.ffn_op, pos_embd, nullptr); + + // rmsnorm mlp adapter + cur = build_norm(cur, model.mm_pre_norm_w, nullptr, NORM_TYPE_RMS, eps, -1); + + // [C, W*H] -> [W, H, C] for conv2d + cur = ggml_reshape_3d(ctx0, cur, n_embd, pw, ph); + cur = ggml_permute(ctx0, cur, 2, 0, 1, 3); + cur = ggml_cont(ctx0, cur); + + // Conv2d(1152->4608, k=2, s=2) + GELU + Conv2d(4608->3072, k=1, s=1) + cur = ggml_conv_2d(ctx0, model.mm_0_w, cur, merge, merge, 0, 0, 1, 1); + cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.mm_0_b, 1, 1, model.mm_0_b->ne[0])); + cur = ggml_gelu_erf(ctx0, cur); // nn.GELU(), not the tanh approximation of the encoder ffn + cur = ggml_conv_2d(ctx0, model.mm_1_w, cur, 1, 1, 0, 0, 1, 1); + cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.mm_1_b, 1, 1, model.mm_1_b->ne[0])); + + const int ow = pw / merge; + const int oh = ph / merge; + const int idim = (int)cur->ne[2]; // OC = n_mmproj_embd + + // append newline along W (dim 0) + ggml_tensor * nl = ggml_reshape_4d(ctx0, model.image_newline, 1, 1, idim, 1); + nl = ggml_repeat_4d(ctx0, nl, 1, oh, idim, 1); + cur = ggml_concat(ctx0, cur, nl, 0); + + // [OW+1, OH, OC] -> [OC, (OW+1)*OH] + cur = ggml_permute(ctx0, cur, 1, 2, 0, 3); + cur = ggml_cont_2d(ctx0, cur, idim, (ow + 1) * oh); + + ggml_build_forward_expand(gf, cur); + return gf; +} diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index c75004d4372545db179cb36a48a4d0be80c46a52..a87a0d0ef2b7f2298ff8b736a145926dcf17a789 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -226,6 +226,11 @@ struct clip_graph_hunyuanvl : clip_graph { ggml_cgraph * build() override; }; +struct clip_graph_hy_v4_flash : clip_graph { + clip_graph_hy_v4_flash(clip_ctx * ctx, const clip_image_f32 & img) : clip_graph(ctx, img) {} + ggml_cgraph * build() override; +}; + struct clip_graph_mobilenetv5 : clip_graph { clip_graph_mobilenetv5(clip_ctx * ctx, const clip_image_f32 & img) : clip_graph(ctx, img) {} ggml_cgraph * build() override; diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index d4ea2385258c79d575f11477bf1cd19781bee239..ace9bf4ec8d57a4a63c3eb0d67c080881d565052 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -1048,6 +1048,14 @@ struct mtmd_context { img_end = "<|hy_place▁holder▁no▁101|>"; image_preproc = std::make_unique(ctx_v); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + // <|hy_image▁start:HASH|> ... (image embeddings) ... <|hy_image▁end:HASH|> + // the trailing hash follows the tokenizer revision, so take it from the vocab + img_beg = lookup_token_text_prefix("<|hy_image▁start"); + img_end = lookup_token_text_prefix("<|hy_image▁end"); + image_preproc = std::make_unique(ctx_v); + } break; case PROJECTOR_TYPE_EXAONE4_5: { // ... (image embeddings) ... @@ -1245,6 +1253,22 @@ private: return LLAMA_TOKEN_NULL; } + // returns the full text of the first token starting with prefix, for vocabularies + // where the marker tokens embed a per-revision tokenizer hash (hy-v4) + std::string lookup_token_text_prefix(const std::string & prefix) { + if (vocab == nullptr) { + return ""; + } + const int n_vocab = llama_vocab_n_tokens(vocab); + for (int i = 0; i < n_vocab; i++) { + std::string piece = token_to_piece(vocab, i, true); + if (piece.rfind(prefix, 0) == 0) { + return piece; + } + } + return ""; + } + std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) { if (vocab == nullptr) { throw std::runtime_error("llama_vocab is not provided"); diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 4f3fa2458bc3bcf031f8d0396278f6445cc43b71..5e346827d0e0690b7803416752d4902d02c16a0c 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -37,6 +37,11 @@ target_include_directories(${TARGET} PRIVATE ../mtmd) target_include_directories(${TARGET} PRIVATE ${PROJECT_SOURCE_DIR}) target_link_libraries(${TARGET} PUBLIC llama-common mtmd ${CMAKE_THREAD_LIBS_INIT}) +# see common/CMakeLists.txt +if (LLAMA_DFLY_TEST_HOOKS) + target_compile_definitions(${TARGET} PRIVATE LLAMA_DFLY_TEST_HOOKS) +endif() + # llama-server-impl: server logic, reusable by app set(TARGET llama-server-impl) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 48f1e93a21b3049f920d1d68f691cb9f7c979ee2..c0a09f915b2669e3cec561fedd0da21856061460 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -19,6 +19,9 @@ #include "log.h" #include "sampling.h" #include "speculative.h" +#include "../../src/llama-ext.h" // staging API: llama_dfly_invalidate +#include "ggml-cpp.h" +#include "gguf.h" #include "mtmd.h" #include "mtmd-helper.h" #include "base64.hpp" @@ -45,6 +48,15 @@ constexpr int HTTP_POLLING_SECONDS = 1; +#ifdef LLAMA_DFLY_TEST_HOOKS +// $LLAMA_DFLY_TEST_MIXED_ABORT: the abort callback of the target aborts the compute while this is set +static std::atomic g_dfly_test_abort{false}; + +static bool dfly_test_abort_cb(void * /*data*/) { + return g_dfly_test_abort.load(); +} +#endif + static common_speculative_output_limits server_output_limits(const common_params & params) { if (!params.mmproj.path.empty()) { const auto mcaps = mtmd_get_cap_from_file(params.mmproj.path.c_str()); @@ -340,39 +352,85 @@ struct server_slot { server_prompt prompt; - bool prompt_save(server_prompt_cache & prompt_cache) const { + // the task took its state from the prompt cache: 1 loaded, -1 the restore failed + int ram_load = 0; + + // the task took the prompt of this slot, see get_available_slot(), -1 none + int copy_src = -1; + + bool memory_matches_tokens() const { + const llama_pos pos_max = llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), id); + + // media chunks can take fewer positions than they add to pos_next (M-RoPE), and a context without memory has no positions + if (llama_get_memory(ctx_tgt) == nullptr || prompt.tokens.has_mtmd || pos_max + 1 == prompt.tokens.pos_next()) { + return true; + } + + SLT_WRN(*this, "memory pos_max = %d, tokens pos_next = %d\n", pos_max, prompt.tokens.pos_next()); + return false; + } + + // decision: saved, or why not + bool prompt_save(server_prompt_cache & prompt_cache, const char ** decision = nullptr) const { + auto done = [decision](const char * res, bool ok) { + if (decision) { + *decision = res; + } + return ok; + }; + if (prompt.tokens.size() == 0) { - return false; + return done("empty", false); + } + + if (!memory_matches_tokens()) { + SLT_WRN(*this, "%s", "not saving the prompt, the memory does not match the tokens\n"); + return done("refused", false); } - const size_t cur_size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); + size_t cur_size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); const size_t cur_size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + size_t n_write_tgt = cur_size_tgt; +#ifdef LLAMA_DFLY_TEST_HOOKS + // fake an empty state, or a write one byte short + if (const char * how = getenv("LLAMA_DFLY_TEST_RAM_SAVE"); how != nullptr) { + if (std::string(how) == "zero") { + cur_size_tgt = 0; + } + n_write_tgt = std::string(how) == "short" ? cur_size_tgt - 1 : cur_size_tgt; + } +#endif + const size_t cur_size = cur_size_tgt + cur_size_dft; SRV_TRC(" - saving prompt with length %d, total state size = %.3f MiB (draft: %.3f MiB)\n", (int) prompt.tokens.size(), cur_size / (1024.0 * 1024.0), cur_size_dft / (1024.0 * 1024.0)); - auto * cur = prompt_cache.alloc(prompt, cur_size_tgt, cur_size_dft); - if (cur == nullptr) { - return false; + // a standard SWA state keeps only the cells that the window of pos_max sees + llama_pos swa_pos_min = llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), id); + if (prompt_cache.n_swa > 0) { + swa_pos_min = std::max(swa_pos_min, llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), id) - prompt_cache.n_swa + 1); } - llama_state_seq_get_data_ext(ctx_tgt, cur->data.main.data(), cur_size_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); - if (ctx_dft) { - llama_state_seq_get_data_ext(ctx_dft, cur->data.drft.data(), cur_size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE); + const char * reason = "budget"; + auto * cur = prompt_cache.alloc(prompt, swa_pos_min, cur_size_tgt, cur_size_dft, &reason); + if (cur == nullptr) { + return done(reason, false); } - return true; - } + const size_t n_tgt = llama_state_seq_get_data_ext(ctx_tgt, cur->data.main.data(), n_write_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); + const size_t n_dft = ctx_dft ? llama_state_seq_get_data_ext(ctx_dft, cur->data.drft.data(), cur_size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + if (n_tgt != cur_size_tgt || n_dft != cur_size_dft) { + SLT_WRN(*this, "failed to save the prompt, wrote %zu of %zu bytes (draft: %zu of %zu)\n", n_tgt, cur_size_tgt, n_dft, cur_size_dft); + + // alloc() put the new state last + prompt_cache.states.pop_back(); - bool prompt_load(server_prompt_cache & prompt_cache, const server_tokens & tokens) { - bool res = prompt_cache.load(prompt, tokens, ctx_tgt, ctx_dft, id); - if (!res) { - SLT_WRN(*this, "%s", "failed to load prompt from cache\n"); + return done("write_failed", false); } - return res; + return done("saved", true); } void prompt_clear() { @@ -383,6 +441,39 @@ struct server_slot { prompt.clear(); } + // take the prompt of another slot: the full KV cells are shared, the SWA window is copied because shared cells + // are never reused by the window, and only the checkpoints the first n_keep tokens can restore are kept + bool copy_prompt_from(const server_slot & src, int n_keep) { + common_prompt_checkpoint swa; + swa.update_tgt(ctx_tgt, src.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + + mem.seq_rm(id, -1, -1); + mem.seq_cp(src.id, id, -1, -1); + + prompt.tokens = src.prompt.tokens.clone(); + prompt.checkpoints.clear(); + + if (!swa.load_tgt(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) { + SLT_WRN(*this, "failed to copy the SWA window of slot %d\n", src.id); + prompt_clear(); + return false; + } + + for (const auto & cur : src.prompt.checkpoints) { + // the prompt path also restores one ending a token past the match, see [TAG_PROMPT_LOGITS] + if (cur.n_tokens <= n_keep + 1) { + prompt.checkpoints.push_back(cur); + } + } + + if (!memory_matches_tokens()) { + prompt_clear(); + return false; + } + + return true; + } + std::vector lora; int32_t alora_invocation_start = -1; @@ -412,6 +503,9 @@ struct server_slot { // not in server_slot_stats to avoid copying to every task result std::vector n_accepted_per_pos; + // draft-dfly: tokens output by the verify rounds (sum of M, plan 9.5), a stopping round can output r rather than r + 1 + uint64_t n_draft_out = 0; + std::function callback_on_release; std::function callback_on_reset; // called before reset() @@ -447,6 +541,7 @@ struct server_slot { // note: callback_on_reset() must have run before this, see release() stats = {}; n_accepted_per_pos.clear(); + n_draft_out = 0; n_predict_max = -1; @@ -678,6 +773,13 @@ struct server_slot { reset(); +#ifdef LLAMA_DFLY_TEST_HOOKS + // drop tokens from the metadata only, to test the save checks + if (const char * s = getenv("LLAMA_DFLY_TEST_META_DROP"); s != nullptr && prompt.n_tokens() > atoi(s)) { + prompt.tokens.keep_first(prompt.n_tokens() - atoi(s)); + } +#endif + callback_on_release(id); } } @@ -795,9 +897,18 @@ struct server_slot { } } - SLT_INF(*this, - "draft acceptance = %0.5f (%5d accepted / %5d generated), mean len = %5.2f\n", - draft_ratio, n_draft_accepted, n_draft_total, mean_acc_len); + if (n_draft_out > 0) { + // draft-dfly: 1 + r over-counts a round that stops on a matched draft, report what was output too + SLT_INF(*this, + "draft acceptance = %0.5f (%5d accepted / %5d generated), mean len (acceptance span estimate, 1 + sum r / rounds) = %5.2f, " + "tokens per round (sum M / rounds) = %5.2f\n", + draft_ratio, n_draft_accepted, n_draft_total, mean_acc_len, + n_draft_verif_steps > 0 ? (double) n_draft_out / (double) n_draft_verif_steps : 0.0); + } else { + SLT_INF(*this, + "draft acceptance = %0.5f (%5d accepted / %5d generated), mean len = %5.2f\n", + draft_ratio, n_draft_accepted, n_draft_total, mean_acc_len); + } SLT_TRC(*this, " acc per pos = (%s)\n", acceptance_rates_per_pos.c_str()); } @@ -1039,6 +1150,11 @@ public: return mtmd_cap.chat; } + // draft-dfly is the active speculative type + bool has_dfly() const { + return dfly; + } + server_decision_context decision; server_queue queue_tasks; @@ -1092,6 +1208,20 @@ private: common_speculative_ptr spec; + // draft-dfly is the active speculative type: the verify rounds go through dfly_verify() + bool dfly = false; + + // --prompt-quota: the slot whose prompt goes first in the next batch + int32_t prompt_next = 0; + +#ifdef LLAMA_DFLY_TEST_HOOKS + std::ofstream dfly_test_out; // H4, $LLAMA_DFLY_TEST_LOG + std::vector dfly_test_n_verify; // per slot: DFly verifies of its request, for H3 + bool dfly_test_mixed = false; // a decode with verify and prompt rows was failed, see decode() + int32_t dfly_test_n_round = 0; // DFly verify rounds, for $LLAMA_DFLY_TEST_VERIFY_THROW + int32_t dfly_test_n_prompt = 0; // prompt chunks, for $LLAMA_DFLY_TEST_PROMPT_THROW +#endif + bool add_bos_token = true; int32_t n_ctx; // total context for all clients / slots @@ -1100,6 +1230,12 @@ private: // if swa_full is enabled, this is set to 0 to simulate a non-SWA model int32_t n_swa; + // window of a standard SWA model, also with swa_full; 0 for the other models + int32_t n_swa_model = 0; + + // server_prompt_restorable() gives the n_past of a completion on this model + bool cache_exact = false; + // slots / clients std::vector slots; @@ -1198,6 +1334,41 @@ private: return true; } + // plan 10.5: the DFly configuration in one line, after the DFly context bound to the target + void dfly_print_info() const { + const auto & sp = params_base.speculative; + + std::string layers; + for (size_t i = 0; i < sp.dfly.target_layers.size(); ++i) { + layers += (i > 0 ? ", " : "") + std::to_string(sp.dfly.target_layers[i]); + } + + // the shared LM head: output.weight of the target, token_embd.weight if tied (first split only) + std::string output_type = "unknown"; + { + gguf_init_params gparams = { /* .no_alloc = */ true, /* .ctx = */ nullptr }; + gguf_context_ptr gctx(gguf_init_from_file(params_base.model.path.c_str(), gparams)); + if (gctx) { + for (const char * name : { "output.weight", "token_embd.weight" }) { + const int64_t id = gguf_find_tensor(gctx.get(), name); + if (id >= 0) { + output_type = ggml_type_name(gguf_get_tensor_type(gctx.get(), id)); + break; + } + } + } + } + + SRV_INF("DFly: B = %d, causal = %s, K_requested = %d (%s), K_effective = %d, W_max = %d, target layers = [%s], " + "target K cache = %s, shared output = %s, target outputs = %d, DFly n_ubatch = %u, DFly attention = FA off, " + "pairing = bound (llama binding check passed; the embedding precheck is in the conversion manifest, not in the GGUF)\n", + sp.dfly.block_size, sp.dfly.causal ? "true" : "false", + sp.dfly.n_max_requested, sp.draft.n_max_explicit ? sp.draft.n_max_source.c_str() : "default", + sp.dfly.n_max_effective, sp.dfly.n_max_effective + 1, layers.c_str(), + ggml_type_name(params_base.cache_type_k), output_type.c_str(), + params_base.n_outputs_max, llama_n_ubatch(ctx_dft)); + } + // load the model and initialize llama_context // this may also be called to resume from sleeping state bool load_model(common_params & params) { @@ -1207,6 +1378,16 @@ private: const bool is_resume = sleeping; + // plan 4.3: resolve draft-dfly before the output limits; on resume params is the previous params_base, + // whose request fields the last prepare kept + { + std::string err; + if (!common_dfly_prepare(params, err)) { + SRV_ERR("%s\n", err.c_str()); + return false; + } + } + params_base = params; const auto output_limits = server_output_limits(params_base); params_base.n_outputs_max = output_limits.total; @@ -1319,6 +1500,41 @@ private: vocab = llama_model_get_vocab(model_tgt); + // plan 4.3: a DFly verify must fit in one ubatch of the target as created + if (params_base.speculative.dfly.active) { + const uint32_t w_max = 1 + params_base.speculative.draft.n_max; + if (llama_n_ubatch(ctx_tgt) < w_max || llama_n_ubatch(ctx_tgt) > llama_n_batch(ctx_tgt)) { + SRV_ERR("draft-dfly needs a target ubatch of at least %u that is not larger than the batch, the target has n_ubatch = %u, n_batch = %u\n", + w_max, llama_n_ubatch(ctx_tgt), llama_n_batch(ctx_tgt)); + return false; + } + + // design 4.2: several slots share one KV pool; every decode is one ubatch and the slots fit in the pool + const int32_t n_par = params_base.n_parallel; + if (n_par > 1) { + if (llama_n_ubatch(ctx_tgt) != llama_n_batch(ctx_tgt) || llama_n_ubatch(ctx_tgt) < n_par*w_max) { + SRV_ERR("draft-dfly with %d slots needs n_batch == n_ubatch >= %u, the target has n_ubatch = %u, n_batch = %u\n", + n_par, n_par*w_max, llama_n_ubatch(ctx_tgt), llama_n_batch(ctx_tgt)); + return false; + } + if ((int64_t) n_par*n_ctx_slot() > (int64_t) llama_n_ctx(ctx_tgt)) { + SRV_ERR("draft-dfly with %d slots needs --kv-unified-per-slot of at most n_ctx / n_parallel = %u: the slots share " + "one KV pool of n_ctx = %u cells and a slot may use %d\n", + n_par, llama_n_ctx(ctx_tgt) / n_par, llama_n_ctx(ctx_tgt), n_ctx_slot()); + return false; + } + if (params_base.cache_idle_slots && params_base.cache_ram_mib != 0) { + SRV_WRN("draft-dfly with %d slots: idle slots are saved and cleared at every new task, " + "--no-cache-idle-slots keeps them in the pool\n", n_par); + } + } +#ifdef LLAMA_DFLY_TEST_HOOKS + if (getenv("LLAMA_DFLY_TEST_MIXED_ABORT") != nullptr) { + llama_set_abort_callback(ctx_tgt, dfly_test_abort_cb, nullptr); + } +#endif + } + try { decision.init(model_tgt); } catch (const std::exception & e) { @@ -1434,6 +1650,11 @@ private: } n_swa = params_base.swa_full ? 0 : llama_model_n_swa(model_tgt); + n_swa_model = llama_model_swa_type(model_tgt) == 1 ? llama_model_n_swa(model_tgt) : 0; + + // the n_past of a text prompt follows from the tokens, the checkpoints and the SWA pos_min alone + cache_exact = n_swa_model > 0 && !params_base.swa_full && mctx == nullptr && params_base.lora_adapters.empty() && + !llama_model_is_recurrent(model_tgt) && !llama_model_is_hybrid(model_tgt); // Necessary similarity of prompt for slot selection slot_prompt_similarity = params_base.slot_prompt_similarity; @@ -1487,18 +1708,39 @@ private: slots.emplace_back(); } + const bool spec_dfly = std::find(params_base.speculative.types.begin(), params_base.speculative.types.end(), + COMMON_SPECULATIVE_TYPE_DRAFT_DFLY) != params_base.speculative.types.end(); + + // a DFly round removes the rejected drafts from the target in place + if (spec_dfly && ctx_tgt_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_PART) { + SRV_ERR("draft-dfly needs a target context that removes the end of a sequence in place (seq_rm type %d)\n", + (int) ctx_tgt_seq_rm_type); + return false; + } + // try speculative decoding if (ctx_tgt_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_NO) { try { spec.reset(common_speculative_init(params_base.speculative, params_base.n_parallel)); } catch (const std::exception & e) { SRV_ERR("failed to initialize speculative decoding context: %s\n", e.what()); - if (params_base.speculative.has_synth()) { + // plan 4.3 fatal: a DFly draft that does not start must not leave a server that runs the target alone + if (params_base.speculative.has_synth() || spec_dfly) { return false; } } } + if (spec_dfly && !spec) { + SRV_ERR("%s", "draft-dfly: no speculative implementation was initialized\n"); + return false; + } + dfly = spec_dfly; + + if (dfly) { + dfly_print_info(); + } + if (ctx_dft) { ctx_dft_seq_rm_type = common_context_can_seq_rm(ctx_dft); } @@ -1600,6 +1842,8 @@ private: SRV_TRC("%s", "use `--cache-ram 0` to disable the prompt cache\n"); prompt_cache = std::make_unique(params_base.cache_ram_mib, n_ctx); + prompt_cache->exact = cache_exact; + prompt_cache->n_swa = n_swa_model; } else { SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); } @@ -1794,10 +2038,139 @@ private: return nullptr; } + // a completion whose n_past is the plain LCP of the slot tokens, see server_prompt_restorable() + bool cache_exact_task(const server_task & task) const { + return cache_exact && task.type == SERVER_TASK_TYPE_COMPLETION && task.n_tokens_shared == 0 && task.params.n_cache_reuse == 0; + } + + // plan 4.5: save the slot state if asked, then load the cached prompt that restores the most of the task + // r_copy: what another slot restores, see slot_copy_source(), a cached prompt must restore more + void update_prompt_cache(server_slot & slot, const server_task & task, bool save, int n_drop, int r_copy) { + const int64_t t_start = ggml_time_us(); + + const char * save_decision = "skipped"; + if (save) { + SRV_TRC("%s", "updating prompt cache\n"); + + slot.prompt_save(*prompt_cache, &save_decision); + } + + const int64_t t_saved = ggml_time_us(); + + const char * load_decision = "not_tried"; + int r_slot = -1; + int r_entry = -1; + int res = 0; + + if (cache_exact_task(task)) { + if (task.params.cache_prompt) { + r_slot = server_prompt_restorable(slot.prompt, llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), slot.id), task.tokens, n_swa); + + const auto it = prompt_cache->find(task.tokens, std::max(r_slot, r_copy), params_base.cache_ram_min_gain, r_entry); + if (it != prompt_cache->states.end()) { + res = prompt_cache->restore(it, slot.prompt, ctx_tgt, ctx_dft, slot.id) ? 1 : -1; + } + load_decision = res > 0 ? "loaded" : res < 0 ? "failed" : r_entry < 0 ? "no_entry" : "low_gain"; + } + } else if (save) { + res = prompt_cache->load(slot.prompt, task.tokens, ctx_tgt, ctx_dft, slot.id); + load_decision = res > 0 ? "loaded" : res < 0 ? "failed" : prompt_cache->states.empty() ? "no_entry" : "low_gain"; + } + + if (res < 0) { + SLT_WRN(slot, "%s", "failed to load prompt from cache\n"); + + slot.prompt_clear(); + } + + slot.ram_load = res; + + const int64_t t_loaded = ggml_time_us(); + + if (save || res != 0) { + prompt_cache->update(); + } + + SLT_INF(slot, "prompt cache: cache_save_decision = %s, n_drop = %d, cache_save_ms = %.3f, cache_load_decision = %s, r_slot = %d, r_entry = %d, cache_restore_ms = %.3f, n_entries = %zu\n", + save_decision, n_drop, (t_saved - t_start) / 1000.0, load_decision, r_slot, r_entry, (t_loaded - t_saved) / 1000.0, prompt_cache->states.size()); + + SRV_TRC("prompt cache update took %.2f ms\n", (ggml_time_us() - t_start) / 1000.0); + } + +#ifdef LLAMA_DFLY_TEST_HOOKS + // the slot after the prompt cache update, the n_past server_prompt_restorable() expects, and the cached prompts + void dfly_test_log_prompt_cache(const server_slot & slot, const server_task & task, bool by_lru, int n_tokens, int lcp) const { + const llama_pos pos_min = llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), slot.id); + const int r_after = cache_exact_task(task) && task.params.cache_prompt ? server_prompt_restorable(slot.prompt, pos_min, task.tokens, n_swa) : -1; + + auto ckpts = [](const std::list & list) { + std::string res; + for (const auto & c : list) { + res += string_format("(%d,%d,%" PRId64 ")", c.pos_min, c.pos_max, c.n_tokens); + } + return res; + }; + + std::string entries; + if (prompt_cache) { + for (const auto & st : prompt_cache->states) { + entries += string_format("%d:%d:%zu:%zu:%s;", st.prompt.n_tokens(), st.swa_pos_min, st.data.main.size(), st.data.drft.size(), ckpts(st.prompt.checkpoints).c_str()); + } + } + + SLT_INF(slot, "test hook: prompt cache: exact = %d, by = %s, n_tokens = %d, lcp = %d, r_after = %d, slot n_tokens = %d, pos_min = %d, ckpts [%s], entries %zu [%s]\n", + cache_exact_task(task) ? 1 : 0, by_lru ? "lru" : "sim", n_tokens, lcp, r_after, slot.prompt.n_tokens(), pos_min, ckpts(slot.prompt.checkpoints).c_str(), + prompt_cache ? prompt_cache->states.size() : (size_t) 0, entries.c_str()); + } +#endif + + // the other slot whose prompt restores the most of the task, if that beats dst's own by cache_ram_min_gain + // the full KV cells are shared by seq_cp, so only a unified KV cache, and only a draft without memory of its own + server_slot * slot_copy_source(const server_slot & dst, const server_task & task, int & r_best) { + r_best = 0; + + if (!params_base.cache_slot_copy || !params_base.kv_unified || slots.size() < 2 || !cache_exact_task(task) || !task.params.cache_prompt) { + return nullptr; + } + if (spec && !(dfly && ctx_dft != nullptr && llama_get_memory(ctx_dft) == nullptr)) { + return nullptr; + } + + auto * mem = llama_get_memory(ctx_tgt); + + auto restorable = [&](const server_slot & slot) { + // the copy holds the SWA window of pos_max only, as a saved state does + const llama_pos pos_max = llama_memory_seq_pos_max(mem, slot.id); + const llama_pos pos_min = std::max(llama_memory_seq_pos_min(mem, slot.id), n_swa > 0 ? pos_max - n_swa + 1 : 0); + return server_prompt_restorable(slot.prompt, pos_min, task.tokens, n_swa); + }; + + server_slot * ret = nullptr; + for (server_slot & slot : slots) { + if (slot.id == dst.id || slot.prompt.n_tokens() == 0 || slot.state == SLOT_STATE_WAIT_OTHER || slot.prompt.tokens.has_mtmd) { + continue; + } + const int r = restorable(slot); + if (r > r_best && slot.memory_matches_tokens()) { + r_best = r; + ret = &slot; + } + } + + const int r_dst = server_prompt_restorable(dst.prompt, llama_memory_seq_pos_min(mem, dst.id), task.tokens, n_swa); + if (ret == nullptr || r_best - r_dst < std::max(1, params_base.cache_ram_min_gain)) { + r_best = 0; + return nullptr; + } + + return ret; + } + server_slot * get_available_slot(const server_task & task) { server_slot * ret = nullptr; bool update_cache = false; + bool by_lru = false; // if a specific slot is requested, use it (still goes through cache update logic below) if (task.id_slot != -1) { @@ -1858,7 +2231,9 @@ private: } // if we are about to lose a large portion of the existing context - save it in the prompt cache - if (f_keep < 0.5f) { + // plan 4.9: also if it would drop many computed tokens, a long shared prefix keeps f_keep high (I13) + const int n_drop = ret->prompt.n_tokens() - (int) ret->prompt.tokens.get_common_prefix(task.tokens); + if (f_keep < 0.5f || (params_base.cache_ram_min_drop > 0 && n_drop >= params_base.cache_ram_min_drop)) { update_cache = true; } } @@ -1874,30 +2249,40 @@ private: SLT_INF(*ret, "selected slot by LRU, n_tokens = %d, t_last = %" PRId64 "\n", ret->prompt.n_tokens(), ret->t_last_used); update_cache = true; + by_lru = true; } } if (ret) { - update_cache = update_cache && prompt_cache; - - // cache prompts only for the tasks that reuse them - update_cache = update_cache && !task.is_stateless(); + const int n_tokens = ret->prompt.n_tokens(); + const int lcp = (int) ret->prompt.tokens.get_common_prefix(task.tokens); - if (update_cache) { - SRV_TRC("%s", "updating prompt cache\n"); + ret->ram_load = 0; + ret->copy_src = -1; - const int64_t t_start = ggml_time_us(); - - ret->prompt_save(*prompt_cache); + // another slot may hold more of the prompt, e.g. the shared prefix of parallel agents + int r_copy = 0; + const server_slot * src = slot_copy_source(*ret, task, r_copy); - if (!ret->prompt_load(*prompt_cache, task.tokens)) { - ret->prompt_clear(); - } - - prompt_cache->update(); + // cache prompts only for the tasks that reuse them + if (prompt_cache && !task.is_stateless()) { + update_prompt_cache(*ret, task, update_cache, n_tokens - lcp, r_copy); + } - SRV_TRC("prompt cache update took %.2f ms\n", (ggml_time_us() - t_start) / 1000.0); + if (src != nullptr && ret->ram_load == 0) { + const int64_t t_start = ggml_time_us(); + const int n_keep = (int) src->prompt.tokens.get_common_prefix(task.tokens); + const bool ok = ret->copy_prompt_from(*src, n_keep); + ret->copy_src = ok ? src->id : -1; + SLT_INF(*ret, "prompt cache: slot_copy = %s, src = %d, r_copy = %d, n_keep = %d, n_ckpt = %zu, copy_ms = %.3f\n", + ok ? "copied" : "failed", src->id, r_copy, n_keep, ret->prompt.checkpoints.size(), (ggml_time_us() - t_start) / 1000.0); } + +#ifdef LLAMA_DFLY_TEST_HOOKS + dfly_test_log_prompt_cache(*ret, task, by_lru, n_tokens, lcp); +#else + GGML_UNUSED(by_lru); +#endif } return ret; @@ -2130,6 +2515,16 @@ private: // reset server kill-switch counter n_empty_consecutive = 0; + // plan 10.2: no snapshot of an earlier request survives into this one, however that one ended + if (dfly) { + llama_dfly_invalidate(ctx_dft, slot.id); +#ifdef LLAMA_DFLY_TEST_HOOKS + common_speculative_dfly_test_begin_request(spec.get(), slot.id); + dfly_test_n_verify.resize(std::max(dfly_test_n_verify.size(), slots.size()), 0); + dfly_test_n_verify[slot.id] = 0; +#endif + } + SLT_INF(slot, "processing task, is_child = %d\n", slot.task->is_child()); return true; } @@ -2701,6 +3096,9 @@ private: prompt_cache->update(); } + // a child takes its state from the parent, not from the RAM cache + slot->ram_load = 0; + int id_child = parent_task.child_tasks[idx].id; if (!launch_slot_with_task(*slot, std::move(parent_task.child_tasks[idx]))) { SRV_ERR("failed to launch slot with child task, id_task = %d\n", id_child); @@ -2771,8 +3169,10 @@ private: cur.id_task = id_task; // [TAG_CHECKPOINTS_FIX_POS_MIN] - // TODO: here we incorrectly deterimne that the saved checkpoint data covers the [pos_min, pos_max] range - // this is not true for SWA models: https://github.com/ggml-org/llama.cpp/pull/24411#issuecomment-4677983225 + // a SWA state keeps only the cells that the window of pos_max sees + if (n_swa_model > 0) { + pos_min = std::max(pos_min, pos_max - n_swa_model + 1); + } cur.update_pos(slot.prompt.n_tokens() - n_tokens_cur, pos_min, pos_max); cur.update_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); @@ -3239,6 +3639,12 @@ private: break; } + if (!slot->memory_matches_tokens()) { + SLT_WRN(*slot, "%s", "not saving the slot, the memory does not match the tokens\n"); + send_error(task, "Unable to save slot: the memory does not match the tokens", ERROR_TYPE_SERVER); + break; + } + GGML_ASSERT(packed.size() % sizeof(llama_token) == 0); const size_t nwrite = llama_state_seq_save_file( ctx_tgt, filepath.c_str(), slot->id, @@ -3445,6 +3851,31 @@ private: } } + // design 4.11: after a failed decode the slots with rows in the view hold tokens that the KV does not; + // clear them (also a slot that was released after it added its rows) before the error is sent + void fail_view(int32_t off, int32_t n_tokens, const std::string & err) { + std::vector hit(slots.size(), false); + for (int32_t i = off; i < off + n_tokens; ++i) { + const int32_t id = batch.tokens[i].id_slot; + if (id >= 0 && id < (int32_t) hit.size()) { + hit[id] = true; + } + } + for (auto & slot : slots) { + if (!hit[slot.id]) { + continue; + } + if (dfly) { + llama_dfly_invalidate(ctx_dft, slot.id); + } + slot.prompt_clear(); + if (slot.is_processing()) { + send_error(slot, err); + slot.release(); + } + } + } + // @ngxson : for debugging only int64_t t_pre_decode = 0; int64_t t_decode = 0; @@ -3886,7 +4317,10 @@ private: slot.spec_ckpt.update_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } - slot.spec_prompt = slot.prompt.tokens.get_text_tokens(); + // spared when no implementation reads the prompt, spec_prompt then stays empty + if (common_speculative_needs_prompt(spec.get())) { + slot.spec_prompt = slot.prompt.tokens.get_text_tokens(); + } const bool spec_reject = slot.use_spec_rejection(); @@ -3979,8 +4413,13 @@ private: if (params_base.cont_batching || batch.size() == 0) { bool add_ok = true; // false means the batch is full, skip remaining slots - iterate(slots, [&](server_slot & slot) { - if (!add_ok || batch.size() >= n_batch) { + // design 4.16: while slots generate, the prompts add at most --prompt-quota rows, so that a long prompt + // does not hold the generating slots back for a whole batch + const int32_t quota = params_base.prompt_quota; + const int32_t n_prompt_max = quota > 0 && batch.size() > 0 ? std::min(n_batch, batch.size() + quota) : n_batch; + + auto add_prompt = [&](server_slot & slot) { + if (!add_ok || batch.size() >= n_prompt_max) { return; // batch is full, skip remaining slots } @@ -4036,6 +4475,11 @@ private: // keep track how many tokens we can reuse from the previous state int n_past = 0; + // plan 6.3: the LCP, whether a checkpoint gave the reused state, and why less than the LCP was reused + int n_match = 0; + bool ck_restored = false; + const char * ck_reason = "none"; + // empty prompt passed -> release the slot and send empty response if (input_tokens.empty()) { SLT_WRN(slot, "%s", "empty prompt - releasing slot\n"); @@ -4056,6 +4500,7 @@ private: } if (!slot.can_split()) { + ck_reason = "not_splittable"; if (slot.task->n_tokens() > n_ubatch) { send_error(slot, string_format( @@ -4179,15 +4624,21 @@ private: SLT_DBG(slot, "after context reuse, new n_past = %d\n", n_past); } + + if (n_past == 0) { + ck_reason = "no_match"; + } } else { // if we don't cache the prompt, we have to remove all previous tokens n_past = 0; + ck_reason = slot.task->params.cache_prompt ? "stateless" : "cache_off"; } llama_pos pos_next = slot.prompt.tokens.pos_next(n_past); // number of cached tokens shared with the new prompt, before any checkpoint is restored const int n_prefix = n_past; + n_match = n_prefix; // ref: https://github.com/ggml-org/llama.cpp/pull/24110 const bool has_new_tokens = (n_past < slot.task->n_tokens()); @@ -4257,8 +4708,12 @@ private: [&](const auto & cur) { // guarantee that a checkpoint will result in at least one token being processed [TAG_PROMPT_LOGITS] SLT_TRC(slot, "checking checkpoint with [%d, %d] against %d...\n", cur.pos_min, cur.pos_max, pos_min_thold); - // workaround for [TAG_CHECKPOINTS_FIX_POS_MIN] - if (cur.pos_max > pos_next) { + // the first evaluated token must not come before the end of the checkpoint + if (cur.pos_max > pos_eval) { + return false; + } + // the slot resumes at pos_max: a checkpoint made right after a resume can miss the start of its window + if (n_swa > 0 && cur.pos_min > 0 && cur.pos_min > cur.pos_max - n_swa + 1) { return false; } return cur.pos_min < pos_min_thold || cur.pos_min == 0; @@ -4266,27 +4721,45 @@ private: ); bool do_reset = it == slot.prompt.checkpoints.rend(); + ck_reason = do_reset ? "no_checkpoint" : "window_check"; if (!do_reset) { +#ifdef LLAMA_DFLY_TEST_HOOKS + // break the target data so that the restore below fails + if (const char * how = getenv("LLAMA_DFLY_TEST_CKPT_CORRUPT"); how != nullptr && it->data_tgt.size() >= 4) { + if (std::string(how) == "magic") { + memset(it->data_tgt.data(), 0xff, 4); + } else { + it->data_tgt.resize(it->data_tgt.size() / 2); + } + } +#endif // restore the context checkpoint if (!it->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) || !it->load_dft(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) { - if (it->id_task != -1) { - GGML_ABORT("failed to restore context checkpoint\n"); - } - // restored from a slot file, not guaranteed to load - fall back to full prompt re-processing - SLT_WRN(slot, "%s", "failed to load context checkpoint restored from a slot file\n"); + // the failed restore may have dropped the sequence - fall back to full prompt re-processing + SLT_ERR(slot, "failed to restore context checkpoint (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", from %s), falling back to full prompt re-processing\n", + it->pos_min, it->pos_max, it->n_tokens, it->id_task != -1 ? "a task" : "a slot file"); do_reset = true; + ck_reason = "restore_failed"; } } if (!do_reset) { // restore the draft's speculative state common_speculative_set_state(spec.get(), slot.id, it->data_spec); + ck_restored = true; pos_next = std::min(pos_next, std::max(it->pos_min + 1, it->pos_max)); n_past = std::min(slot.prompt.tokens.size_up_to_pos(pos_next), (size_t) it->n_tokens); SLT_TRC(slot, "restored context checkpoint (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", n_past = %d, size = %.3f MiB)\n", it->pos_min, it->pos_max, it->n_tokens, n_past, (float) it->size() / 1024 / 1024); +#ifdef LLAMA_DFLY_TEST_HOOKS + // the recorded range against what the restore put back; for iswa the memory pos is the SWA cache's + SLT_INF(slot, "test hook: checkpoint restored: recorded pos_min = %d, pos_max = %d, memory pos_min = %d, pos_max = %d\n", + it->pos_min, it->pos_max, + llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), slot.id), + llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), slot.id)); +#endif } if (do_reset) { @@ -4322,6 +4795,21 @@ private: slot.stats.n_prompt_cached = n_past; slot.stats.n_prompt_processed = 0; + // a failed RAM restore cleared the slot + if (slot.ram_load < 0 && strcmp(ck_reason, "no_match") == 0) { + ck_reason = "entry_corrupt"; + } + + const char * ck_source = n_past == 0 ? "none" : + slot.ram_load > 0 ? (ck_restored ? "ram_checkpoint" : "ram") : + slot.copy_src >= 0 ? (ck_restored ? "copy_checkpoint" : "copy") : (ck_restored ? "checkpoint" : "slot"); + + SLT_INF(slot, "prefix cache: prefix_match_tokens = %d, prefix_reused_tokens = %d, prefix_replayed_tokens = %d, restore_source = %s, cache_fallback_reason = %s\n", + n_match, n_past, slot.task->n_tokens() - n_past, ck_source, ck_reason); + + slot.ram_load = 0; + slot.copy_src = -1; + metrics.add_prompt_cached(n_past); slot.prompt.tokens.keep_first(n_past); @@ -4355,6 +4843,12 @@ private: SLT_TRC(slot, "cached n_tokens = %d, memory_seq_rm [%d, end)\n", slot.prompt.n_tokens(), p0); slot.mem.seq_rm(slot.id, p0, -1); +#ifdef LLAMA_DFLY_TEST_HOOKS + // the first position this batch evaluates and the memory it attends to + SLT_INF(slot, "test hook: before prompt decode: q = %d, memory pos_min = %d, pos_max = %d, model n_swa = %d\n", + p0, llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), slot.id), + llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), slot.id), llama_model_n_swa(model_tgt)); +#endif // shared prompt prefix: once it is processed, the children continue from it with their own prompt bool wait_shared = false; @@ -4461,7 +4955,7 @@ private: const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; // add prompt tokens for processing in the current batch - while (slot.prompt.n_tokens() < slot.task->n_tokens() && batch.size() < n_batch) { + while (slot.prompt.n_tokens() < slot.task->n_tokens() && batch.size() < n_prompt_max) { // get next token to process llama_token cur_tok = input_tokens[slot.prompt.n_tokens()]; if (cur_tok == LLAMA_TOKEN_NULL) { @@ -4533,6 +5027,11 @@ private: // the number of tokens added to the batch for the current slot const auto n_tokens_cur = batch.size() - n_tokens_prev; +#ifdef LLAMA_DFLY_TEST_HOOKS + if (const char * s = getenv("LLAMA_DFLY_TEST_PROMPT_THROW"); s != nullptr && n_tokens_cur > 0 && ++dfly_test_n_prompt == atoi(s)) { + throw std::runtime_error("test hook: prompt chunk throws after adding its rows"); + } +#endif const auto n_tokens_start = slot.prompt.n_tokens() - n_tokens_cur; @@ -4591,6 +5090,33 @@ private: if (!slot_batched) { slot_batched = &slot; } + }; + + // with a quota the prompts take turns: start after the slot that got prompt rows last + std::vector order; + for (size_t i = 0; i < slots.size(); ++i) { + order.push_back(&slots[(quota > 0 ? prompt_next + i : i) % slots.size()]); + } + + // design 4.11: a slot that fails after it added rows takes them out of the batch (they are last) and + // clears its state, its tokens would otherwise hold rows that are never decoded; iterate() ends the request + iterate(order, [&](server_slot & slot) { + const int32_t n_prev = batch.size(); + try { + add_prompt(slot); + } catch (...) { + if (batch.size() > n_prev) { + batch.truncate(n_prev); + if (dfly) { + llama_dfly_invalidate(ctx_dft, slot.id); + } + slot.prompt_clear(); + } + throw; + } + if (quota > 0 && batch.size() > n_prev) { + prompt_next = (slot.id + 1) % (int32_t) slots.size(); + } }); } } @@ -4686,15 +5212,68 @@ private: has_output |= batch.tokens[i].output; } + // whether DFly verify rows are in this view + int32_t n_slots_dfly = 0; +#ifdef LLAMA_DFLY_TEST_HOOKS + int32_t test_ret = 0; +#endif + if (dfly) { + for (auto & slot : slots) { + if (!slot.spec_i_batch.empty() && slot.spec_i_batch.front() >= off && slot.spec_i_batch.front() < off + batch.view.size()) { + n_slots_dfly++; +#ifdef LLAMA_DFLY_TEST_HOOKS + // H3: the script fails the n-th verify of a request without decoding it + dfly_test_n_verify.resize(std::max(dfly_test_n_verify.size(), slots.size()), 0); + const int32_t r = common_speculative_dfly_test_verify_ret(spec.get(), ++dfly_test_n_verify[slot.id]); + test_ret = test_ret != 0 ? test_ret : r; +#endif + } + } + } + // yield to the queue, so we can still handle metrics tasks while decoding // note: the sync is done here too, so that the wait is also covered by the yield int ret = 0; +#ifdef LLAMA_DFLY_TEST_HOOKS + ret = test_ret; + // the first decode with verify rows and prompt rows fails before it runs ($LLAMA_DFLY_TEST_MIXED_FAIL=), + // or its compute is aborted ($LLAMA_DFLY_TEST_MIXED_ABORT, see dfly_test_abort_cb()) + if (n_slots_dfly > 0 && !dfly_test_mixed) { + bool has_prompt = false; + for (int i = off; i < off + batch.view.size(); ++i) { + has_prompt |= batch.tokens[i].is_prompt; + } + if (has_prompt && getenv("LLAMA_DFLY_TEST_MIXED_FAIL") != nullptr) { + ret = atoi(getenv("LLAMA_DFLY_TEST_MIXED_FAIL")); + dfly_test_mixed = true; + } else if (has_prompt && getenv("LLAMA_DFLY_TEST_MIXED_ABORT") != nullptr) { + g_dfly_test_abort = true; + dfly_test_mixed = true; + } + } + if (ret == 0) +#endif queue_tasks.yield_to_queue([&]() { ret = llama_process(ctx_tgt, LLAMA_PROCESS_TYPE_DECODE, batch.view.get()); if (ret == 0 && has_output) { llama_synchronize(ctx_tgt); } }); +#ifdef LLAMA_DFLY_TEST_HOOKS + g_dfly_test_abort = false; +#endif + + // plan 7.7: a failed DFly verify ends the requests here, before the retry below halves n_batch; + // nothing repairs the target state a verify may have left half applied + if (ret != 0 && n_slots_dfly > 0) { + const std::string err = string_format("DFly verify failed, llama_decode returned %d", ret); + SRV_ERR("%s, off = %d, n_batch = %d\n", err.c_str(), off, n_batch); + + fail_view(off, batch.view.size(), err); + + // the caller ends the update; the other processing slots end with this error too + throw std::runtime_error(err); + } if (ret != 0) { { @@ -4794,6 +5373,212 @@ private: return true; } +#ifdef LLAMA_DFLY_TEST_HOOKS + // H4: one JSON line per round of a DFly slot, to $LLAMA_DFLY_TEST_LOG; kind is prefill, ar or spec + void dfly_test_log(const server_slot & slot, const char * kind, llama_pos a, llama_token anchor, const llama_tokens & draft, int32_t r, + const llama_tokens & ids, int32_t n_sample, int32_t n_accept, bool stopped) { + const int32_t K = (int32_t) draft.size(); + if (!dfly_test_out.is_open()) { + const char * path = getenv("LLAMA_DFLY_TEST_LOG"); + if (path == nullptr) { + return; + } + dfly_test_out.open(path, std::ios::app); + } + common_speculative_dfly_test_round round; + common_speculative_dfly_test_take_round(spec.get(), slot.id, round); + const json j = { + {"req", slot.task->id}, + {"slot", slot.id}, + {"kind", kind}, + {"a", a}, + {"anchor", anchor}, + {"K", K}, + {"W", K + 1}, + {"r", r}, + {"M", (int32_t) ids.size()}, + {"n_sample", n_sample}, + {"n_accept", n_accept}, + {"propose", round.status}, + {"k_step", round.k_step}, + {"n_draft_max", round.n_max}, + {"query_pos", round.status == LLAMA_DFLY_OK ? round.pos0 - 1 : -1}, + {"seq_pos_max", llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), slot.id)}, + {"n_tokens", slot.prompt.n_tokens()}, + {"stopped", stopped}, + {"stop", (int) slot.stop}, + {"tokens", ids}, + {"draft", draft}, + }; + dfly_test_out << j.dump() << "\n"; + dfly_test_out.flush(); + } + + // the slot state after a stop and its release + void dfly_test_log_release(const server_slot & slot) { + if (!dfly_test_out.is_open()) { + return; + } + const json j = { + {"kind", "release"}, + {"seq_pos_max", llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), slot.id)}, + {"n_tokens", slot.prompt.n_tokens()}, + {"pos_next", slot.prompt.tokens.pos_next()}, + }; + dfly_test_out << j.dump() << "\n"; + dfly_test_out.flush(); + } +#endif + + // plan 9.2: the rows of a DFly verify; each row is sampled and accepted once and goes through process_token, + // which alone decides a stop, after which nothing more is sampled + template + void dfly_verify(server_slot & slot, int32_t off, const F & accept_special_token) { + // take the round: a non-empty spec_draft would be replayed as a pending draft by the next pre_decode + const llama_tokens draft = std::move(slot.spec_draft); + const std::vector rows = std::move(slot.spec_i_batch); + slot.spec_draft.clear(); + slot.spec_i_batch.clear(); + slot.spec_draft_q.clear(); + slot.spec_is_replay = false; + + const int32_t K = (int32_t) draft.size(); + GGML_ASSERT((int32_t) rows.size() == K + 1); +#ifdef LLAMA_DFLY_TEST_HOOKS + ++dfly_test_n_round; +#endif + + // the prompt now holds the anchor and the K drafts; back to the state in which AR samples after the anchor + const llama_pos a = slot.prompt.n_tokens() - (K + 1); + const llama_token anchor = slot.sampled; + slot.prompt.tokens.keep_first(a + 1); + + int32_t r = 0; + int32_t n_sample = 0; + int32_t n_accept = 0; + bool stopped = false; + llama_tokens ids; + + for (int32_t j = 0; j <= K; ++j) { + // the row in this llama_decode call, not a position + const int32_t row = rows[j] - off; + + llama_token y; + { + scoped_timer timer(t_sampl, n_sampl); + y = common_sampler_sample(slot.smpl.get(), slot.ctx_tgt, row); + } + n_sample++; + common_sampler_accept(slot.smpl.get(), y, true); + n_accept++; + ids.push_back(y); + + slot.stats.n_gen += 1; + if (slot.stats.n_gen == 1) { + slot.stats.update_prompt_last(); + slot.t_print_last = ggml_time_us(); + slot.n_gen_last = 0; + } + // process_token checks the time limit against this timestamp + slot.stats.update_gen_last(); + + completion_token_output result; + result.tok = y; + result.text_to_send = common_token_to_piece(slot.ctx_tgt, y, accept_special_token(slot, y)); + result.prob = 1.0f; + + if (slot.task->params.sampling.n_probs > 0) { + populate_token_probs(slot, result, slot.task->params.post_sampling_probs, params_base.special, row); + } + + // a matched draft that stops the request still counts + const bool matched = j < K && y == draft[j]; + if (matched) { + r++; + } + if (!process_token(result, slot)) { + stopped = true; + break; + } +#ifdef LLAMA_DFLY_TEST_HOOKS + // $LLAMA_DFLY_TEST_VERIFY_THROW = :: the round (1-based, all slots) throws after its row j + if (const char * s = getenv("LLAMA_DFLY_TEST_VERIFY_THROW"); s != nullptr) { + int n_round = 0; + int j_throw = -1; + if (sscanf(s, "%d:%d", &n_round, &j_throw) == 2 && n_round == dfly_test_n_round && j_throw == j) { + throw std::runtime_error("test hook: verify throws after a row"); + } + } +#endif + if (!matched) { + break; // y is the correction, or the bonus for j == K + } + // y is in the target KV at a + 1 + j already + slot.prompt.tokens.push_back(y); + } + + const int32_t M = (int32_t) ids.size(); + + // plan 9.5: K was counted when drafted (n_draft_tokens, and n_gen_tokens in common), n_gen per token above; + // release() adds the slot statistics to the metrics + auto record = [&]() { + common_speculative_accept(spec.get(), slot.id, r); + slot.stats.n_draft_accepted += r; + slot.stats.n_draft_verif_steps += 1; + slot.n_draft_out += M; + + auto & n_accepted_per_pos = slot.n_accepted_per_pos; + if (n_accepted_per_pos.empty()) { + n_accepted_per_pos.resize(common_speculative_n_max(spec.get()), 0); + } + for (int32_t i = 0; i < r && i < (int32_t) n_accepted_per_pos.size(); ++i) { + n_accepted_per_pos[i]++; + } + }; + + SLT_DBG(slot, "DFly round: a = %d, anchor = %d, K = %d, r = %d, M = %d, stopped = %d\n", a, anchor, K, r, M, stopped); + + if (stopped) { + // no next snapshot; drop the rows after the kept tokens, so that the memory matches them + record(); + const bool trimmed = llama_memory_seq_rm(llama_get_memory(slot.ctx_tgt), slot.id, slot.prompt.tokens.pos_next(), -1); +#ifdef LLAMA_DFLY_TEST_HOOKS + dfly_test_log(slot, "spec", a, anchor, draft, r, ids, n_sample, n_accept, true); +#endif + slot.print_timings(); + send_final_response(slot); + llama_dfly_invalidate(ctx_dft, slot.id); + slot.release(); + if (!trimmed) { + SLT_ERR(slot, "DFly: failed to remove the rows after position %d, clearing the slot\n", slot.prompt.tokens.pos_next()); + slot.prompt_clear(); + } +#ifdef LLAMA_DFLY_TEST_HOOKS + dfly_test_log_release(slot); +#endif + return; + } + + GGML_ASSERT(M == r + 1); + slot.sampled = ids.back(); // the next anchor, not in the target KV yet + GGML_ASSERT(slot.prompt.n_tokens() == a + 1 + r); + + // keep a .. a + r: the next propose reads the row of a + r, which this verify captured + if (r < K && !llama_memory_seq_rm(llama_get_memory(slot.ctx_tgt), slot.id, a + r + 1, -1)) { + send_error(slot, "DFly: failed to remove the rejected drafts from the target"); + llama_dfly_invalidate(ctx_dft, slot.id); + slot.release(); + slot.prompt_clear(); + return; + } + + record(); +#ifdef LLAMA_DFLY_TEST_HOOKS + dfly_test_log(slot, "spec", a, anchor, draft, r, ids, n_sample, n_accept, false); +#endif + slot.print_timings_tg(); + } + void post_decode(int32_t n_batch_tokens, int32_t off) { // for checking if a given batch index is inside the current sub-batch auto is_inside_view = [&](int32_t idx) { @@ -4828,6 +5613,10 @@ private: return; } +#ifdef LLAMA_DFLY_TEST_HOOKS + const bool test_prefill = slot.state == SLOT_STATE_DONE_PROMPT; +#endif + if (slot.state == SLOT_STATE_DONE_PROMPT) { if (slot.task->type == SERVER_TASK_TYPE_EMBEDDING) { // prompt evaluated for embedding @@ -4902,15 +5691,35 @@ private: populate_token_probs(slot, result, slot.task->params.post_sampling_probs, params_base.special, tok_idx); } +#ifdef LLAMA_DFLY_TEST_HOOKS + const llama_token test_anchor = slot.sampled; +#endif + if (!process_token(result, slot)) { +#ifdef LLAMA_DFLY_TEST_HOOKS + if (dfly) { + dfly_test_log(slot, test_prefill ? "prefill" : "ar", slot.prompt.n_tokens() - 1, test_anchor, {}, 0, { id }, 1, 1, true); + } +#endif // release slot because of stop condition slot.print_timings(); send_final_response(slot); slot.release(); +#ifdef LLAMA_DFLY_TEST_HOOKS + if (dfly) { + dfly_test_log_release(slot); + } +#endif return; } +#ifdef LLAMA_DFLY_TEST_HOOKS + if (dfly) { + dfly_test_log(slot, test_prefill ? "prefill" : "ar", slot.prompt.n_tokens() - 1, test_anchor, {}, 0, { id }, 1, 1, false); + } +#endif + slot.print_timings_tg(); }); @@ -4921,6 +5730,19 @@ private: return; } + // draft-dfly verifies row by row, see dfly_verify() + if (dfly) { + try { + dfly_verify(slot, off, accept_special_token); + } catch (...) { + // design 4.11: the target holds every row of the round, the metadata does not; iterate() ends the request + llama_dfly_invalidate(ctx_dft, slot.id); + slot.prompt_clear(); + throw; + } + return; + } + // save the original draft size const size_t n_draft = slot.spec_draft.size(); @@ -5375,6 +6197,30 @@ std::unique_ptr server_routes::handle_completions_impl( task.id_slot = json_value(data, "id_slot", -1); sse_ping_interval = task.params.sse_ping_interval; + // plan 5.2: a request may not ask draft-dfly for cache reuse, backend sampling, several sequences or media + if (ctx_server.has_dfly()) { + std::vector bad; + if (task.params.n_cache_reuse != 0) { + bad.push_back("n_cache_reuse"); + } + if (task.params.sampling.backend_sampling) { + bad.push_back("backend_sampling"); + } + if (task.params.n_cmpl > 1) { + bad.push_back("n_cmpl > 1"); + } + // a media chunk takes LLAMA_TOKEN_NULL positions in the prompt + for (size_t i = 0; i < task.tokens.size(); ++i) { + if (task.tokens[i] == LLAMA_TOKEN_NULL) { + bad.push_back("media"); + break; + } + } + if (!bad.empty()) { + throw std::invalid_argument("draft-dfly does not support " + string_join(bad, ", ") + " in a request"); + } + } + // OAI-compat task.params.res_type = res_type; task.params.oaicompat_cmpl_id = completion_id; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 1a0d434a1f3169bd591a662874de5d8096fa94e3..d0ec3d2ed6aba14ceaaa7705adcdfeae1da9741b 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1733,6 +1733,45 @@ json server_task_result_apply_lora::to_json() { // // server_prompt_cache // + +// mirrors the prompt path of server_context: the SWA check of pos_min, the checkpoint search and [TAG_PROMPT_LOGITS] +int server_prompt_restorable(const server_prompt & prompt, llama_pos pos_min, const server_tokens & tokens_new, int32_t n_swa) { + int n_past = (int) prompt.tokens.get_common_prefix(tokens_new); + if (n_past == 0) { + return 0; + } + + llama_pos pos_next = prompt.tokens.pos_next(n_past); + + const llama_pos pos_eval = pos_next - (n_past < (int) tokens_new.size() ? 0 : 1); + const llama_pos pos_min_thold = std::max(0, n_swa > 0 ? pos_eval - n_swa + 2 : pos_eval); + + if (pos_min >= pos_min_thold) { + const auto it = std::find_if(prompt.checkpoints.rbegin(), prompt.checkpoints.rend(), [&](const auto & cur) { + if (cur.pos_max > pos_eval) { + return false; + } + if (n_swa > 0 && cur.pos_min > 0 && cur.pos_min > cur.pos_max - n_swa + 1) { + return false; + } + return cur.pos_min < pos_min_thold || cur.pos_min == 0; + }); + + if (it == prompt.checkpoints.rend()) { + return 0; + } + + pos_next = std::min(pos_next, std::max(it->pos_min + 1, it->pos_max)); + n_past = (int) std::min(prompt.tokens.size_up_to_pos(pos_next), (size_t) it->n_tokens); + } + + if (n_past == (int) tokens_new.size() && n_past > 0) { + n_past--; + } + + return n_past; +} + size_t server_prompt_cache::size() const { size_t res = 0; @@ -1753,13 +1792,27 @@ size_t server_prompt_cache::n_tokens() const { return res; } -server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, size_t state_size_tgt, size_t state_size_dft) { +server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, llama_pos swa_pos_min, size_t state_size_tgt, size_t state_size_dft, const char ** reason) { + const char * reason_ignored = nullptr; + const char ** why = reason ? reason : &reason_ignored; + + // an empty state reads back as a success and leaves the memory as it is + if (state_size_tgt == 0) { + SRV_WRN("%s", " - prompt state is empty, skipping\n"); + *why = "refused"; + return nullptr; + } + + const int n_new = (int) prompt.tokens.size(); + // first check if the current state is contained fully in the cache for (auto it = states.begin(); it != states.end(); ++it) { const int cur_lcp_len = it->prompt.tokens.get_common_prefix(prompt.tokens); - if (cur_lcp_len == (int) prompt.tokens.size()) { + // a longer state replaces this one only if it restores all of it but the last token + if (cur_lcp_len == n_new && (!exact || server_prompt_restorable(it->prompt, it->swa_pos_min, prompt.tokens, n_swa) >= n_new - 1)) { SRV_TRC("%s", " - prompt is already in the cache, skipping\n"); + *why = "superseded"; return nullptr; } } @@ -1776,6 +1829,7 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro if (limit_size > 0 && state_size_new > limit_size) { SRV_WRN(" - prompt state size %.3f MiB exceeds cache size limit %.3f MiB, skipping\n", state_size_new / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0)); + *why = "budget"; return nullptr; } @@ -1783,7 +1837,7 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro for (auto it = states.begin(); it != states.end();) { const int len = it->prompt.tokens.get_common_prefix(prompt.tokens); - if (len == (int) it->prompt.tokens.size()) { + if (len == (int) it->prompt.tokens.size() && (!exact || server_prompt_restorable(prompt, swa_pos_min, it->prompt.tokens, n_swa) >= len - 1)) { SRV_TRC(" - removing obsolete cached prompt with length %d\n", len); it = states.erase(it); @@ -1818,6 +1872,7 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro update(); + *why = "budget"; return nullptr; } @@ -1830,12 +1885,13 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro /*.main =*/ std::move(state_data_tgt), /*.drft =*/ std::move(state_data_dft), }, + /*.swa_pos_min =*/ swa_pos_min, }); return &states.back(); } -bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { +int server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { const int lcp_best = prompt.tokens.get_common_prefix(tokens_new); float f_keep_best = prompt.tokens.size() > 0 ? float(lcp_best) / prompt.tokens.size() : -1.0f; // empty slot: any cache entry wins @@ -1867,49 +1923,78 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok } } - if (it_best != states.end()) { - SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + if (it_best == states.end()) { + return 0; + } - { - auto & data = it_best->data.main; + SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); - const size_t size = data.size(); - const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0); - if (n != size) { - SRV_ERR("failed to restore state with size %zu\n", size); + return restore(it_best, prompt, ctx_tgt, ctx_dft, id_slot) ? 1 : -1; +} - return false; - } +std::list::iterator server_prompt_cache::find(const server_tokens & tokens_new, int r_slot, int32_t min_gain, int & r_best) { + auto it_best = states.end(); - data.clear(); - data.shrink_to_fit(); - } + r_best = -1; - { - auto & data = it_best->data.drft; + for (auto it = states.begin(); it != states.end(); ++it) { + const int r_cur = server_prompt_restorable(it->prompt, it->swa_pos_min, tokens_new, n_swa); - if (!data.empty()) { - GGML_ASSERT(ctx_dft); + SRV_TRC(" - prompt with length %7zu, restorable %7d\n", it->prompt.tokens.size(), r_cur); - const size_t size = data.size(); - const size_t n = llama_state_seq_set_data_ext(ctx_dft, data.data(), size, id_slot, 0); - if (n != size) { - SRV_WRN("failed to restore state with size %zu\n", size); + if (r_cur > r_best) { + r_best = r_cur; + it_best = it; + } + } - return false; - } + // a small gain is not worth the slot state it replaces, nor the cached prompt it takes out of the cache + if (it_best == states.end() || r_best - r_slot < std::max(1, min_gain)) { + return states.end(); + } - data.clear(); - data.shrink_to_fit(); - } + return it_best; +} + +bool server_prompt_cache::restore(std::list::iterator it, server_prompt & prompt, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { + size_t n_main = it->data.main.size(); + size_t n_drft = it->data.drft.size(); + +#ifdef LLAMA_DFLY_TEST_HOOKS + // break the first restore of the process so that it fails + static bool corrupted = false; + if (const char * how = getenv("LLAMA_DFLY_TEST_RAM_CORRUPT"); how != nullptr && !corrupted && n_main >= 4) { + corrupted = true; + if (std::string(how) == "magic") { + memset(it->data.main.data(), 0xff, 4); + } else if (std::string(how) == "trunc") { + n_main /= 2; + } else if (n_drft > 0) { + n_drft -= 1; } + } +#endif - prompt = std::move(it_best->prompt); + const auto & data = it->data; - states.erase(it_best); + // the draft state is read only after the target state, both in full + bool ok = !data.main.empty() && llama_state_seq_set_data_ext(ctx_tgt, data.main.data(), n_main, id_slot, 0) == data.main.size(); + if (ok && !data.drft.empty()) { + GGML_ASSERT(ctx_dft); + + ok = llama_state_seq_set_data_ext(ctx_dft, data.drft.data(), n_drft, id_slot, 0) == data.drft.size(); } - return true; + if (ok) { + prompt = std::move(it->prompt); + } else { + SRV_WRN("failed to restore prompt with length %zu (size %zu, draft %zu), removing it\n", it->prompt.tokens.size(), data.main.size(), data.drft.size()); + } + + // the slot took the entry, or the entry is broken + states.erase(it); + + return ok; } void server_prompt_cache::update() { diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 21b649ac429a01b19ef3b52cab5a1fa0e3b99e82..c84aba3b94727bb01ab0ba4f6c52f34dc17b6342 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -718,6 +718,9 @@ struct server_prompt_cache_state { server_prompt prompt; server_prompt_data data; + // the first SWA position the saved state holds, -1 if unknown + llama_pos swa_pos_min = -1; + size_t size() const { size_t res = data.size(); @@ -729,6 +732,9 @@ struct server_prompt_cache_state { } }; +// the n_past the prompt path keeps from a state with these tokens, checkpoints and SWA pos_min, for a text prompt without shared or reused chunks +int server_prompt_restorable(const server_prompt & prompt, llama_pos pos_min, const server_tokens & tokens_new, int32_t n_swa); + struct server_prompt_cache { server_prompt_cache(int32_t limit_size_mib, size_t limit_tokens) { this->limit_size = 1024ull*1024ull*(limit_size_mib < 0 ? 0 : limit_size_mib); @@ -743,13 +749,25 @@ struct server_prompt_cache { // in tokens, 0 = no limit size_t limit_tokens = 0; + // compare the states by server_prompt_restorable(), else by the token ratios + bool exact = false; + int32_t n_swa = 0; + size_t size() const; size_t n_tokens() const; - server_prompt_cache_state * alloc(const server_prompt & prompt, size_t state_size_main, size_t state_size_drft); + // reason: why no state was allocated + server_prompt_cache_state * alloc(const server_prompt & prompt, llama_pos swa_pos_min, size_t state_size_main, size_t state_size_drft, const char ** reason = nullptr); + + // 1 the prompt was loaded, 0 no better prompt, -1 the restore failed + int load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot); + + // the state that restores the most tokens, end() unless it restores at least min_gain more than r_slot + std::list::iterator find(const server_tokens & tokens_new, int r_slot, int32_t min_gain, int & r_best); - bool load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot); + // the prompt takes the state only if the target and the draft states both load, the state is removed either way + bool restore(std::list::iterator it, server_prompt & prompt, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot); void update(); }; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 8b1d426506fdeb0f46b6a5ac225c08766d546399..9105afd4ca1fc750ffe1a64d81372113ba71ffc5 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -439,6 +439,14 @@ static int server_run_measure(common_params & params, server_role & role, common const std::string model_name = params.model.get_name(); + // the measure loads the draft as a plain model, which a DFly draft is not + if (common_dfly_requested(params)) { + const std::string err = "draft-dfly is not supported by the router (memory measure); run a single llama-server instance instead"; + SRV_ERR("%s\n", err.c_str()); + role.notify_to_router(server_state_to_str(SERVER_STATE_MEASURING), { {"result", "failed"}, {"error", err} }); + return 1; + } + // TODO: mmproj is not in llama_get_memory_breakdown, a multimodal model is underestimated json payload; try { @@ -468,6 +476,12 @@ static int server_run_measure(common_params & params, server_role & role, common // static int server_run_router(common_params & params, int argc, char ** argv, const server_run_opts & opts) { + // plan 10.4: draft-dfly runs only in a single llama-server instance + if (common_dfly_requested(params)) { + SRV_ERR("%s", "draft-dfly is not supported in router mode; run llama-server with -m -md --parallel 1\n"); + return 1; + } + SRV_INF("%s", "starting server in router mode. models will be automatically loaded on-demand\n"); // note: this is guaranteed to out-live ctx_http and tools @@ -620,6 +634,12 @@ static int server_run_instance(common_params & params, server_role & role, commo } } + // a model of the router (e.g. from a preset) does not get draft-dfly, see server_run_router + if (role.is_managed_by_router() && common_dfly_requested(params)) { + SRV_ERR("%s", "draft-dfly is not supported for a model of the router; run a single llama-server instance instead\n"); + return 1; + } + // note: this is guaranteed to out-live ctx_http and tools server_mcp mcp_mgr;