From 72f60cf8541805e5cc08022c0d5397b9e34639e1 Mon Sep 17 00:00:00 2001 From: Biogenic Ooze Date: Wed, 6 May 2026 20:58:03 +0300 Subject: [PATCH 1/7] feat: add Gemma 4 MTP assistant support Introduces support for the Gemma 4 MTP assistant, allowing for enhanced speculative decoding. This includes new command-line options for specifying the MTP head and draft model, as well as updates to the model architecture and tensor handling. The assistant integrates with the target model, enabling efficient draft generation and improved performance in speculative tasks. Changes include: - New command-line options: `--mtp-head` and `--draft-block-size`. - Updates to the model loading process to accommodate the MTP assistant. - Enhancements in tensor management for MTP-specific operations. - Documentation updates for usage examples and guidelines. This feature aims to improve the overall functionality and efficiency of the model in handling complex tasks. --- .gitignore | 3 + AGENTS.md | 110 --------- common/arg.cpp | 31 ++- common/common.cpp | 37 +++ common/common.h | 4 + common/speculative.cpp | 220 +++++++++++++++++- common/speculative.h | 11 + convert_hf_to_gguf.py | 74 +++++- .../gemma4-assistant-tensor-inventory.md | 38 +++ docs/speculative.md | 37 +++ gguf-py/gguf/constants.py | 38 +++ gguf-py/gguf/gguf_writer.py | 18 ++ gguf-py/gguf/tensor_mapping.py | 13 ++ include/llama.h | 39 ++++ scripts/bench-parallel.sh | 61 +++++ scripts/run-gemma4-mtp-server.sh | 109 +++++++++ scripts/run-gemma4-server-turbo.sh | 36 +++ scripts/run-gemma4.sh | 118 ++++++++++ scripts/verify-gemma4-assistant-gguf.py | 65 ++++++ src/CMakeLists.txt | 1 + src/llama-arch.cpp | 16 ++ src/llama-arch.h | 15 ++ src/llama-context.cpp | 182 ++++++++++++++- src/llama-context.h | 19 +- src/llama-graph.cpp | 125 +++++++++- src/llama-graph.h | 46 +++- src/llama-hparams.h | 7 + src/llama-kv-cache-iswa.cpp | 14 ++ src/llama-kv-cache-iswa.h | 3 + src/llama-kv-cache.cpp | 40 ++++ src/llama-kv-cache.h | 3 + src/llama-model.cpp | 162 ++++++++++++- src/llama-model.h | 9 + src/llama.cpp | 88 +++++++ src/models/gemma4-assistant.cpp | 192 +++++++++++++++ src/models/models.h | 8 + tests/CMakeLists.txt | 1 + tests/test-llama-archs.cpp | 8 +- tests/test-speculative-mtp.cpp | 127 ++++++++++ tools/server/server-context.cpp | 82 ++++--- tools/server/server-task.cpp | 7 +- 41 files changed, 2047 insertions(+), 170 deletions(-) create mode 100644 docs/development/gemma4-assistant-tensor-inventory.md create mode 100755 scripts/bench-parallel.sh create mode 100755 scripts/run-gemma4-mtp-server.sh create mode 100755 scripts/run-gemma4-server-turbo.sh create mode 100755 scripts/run-gemma4.sh create mode 100644 scripts/verify-gemma4-assistant-gguf.py create mode 100644 src/models/gemma4-assistant.cpp create mode 100644 tests/test-speculative-mtp.cpp diff --git a/.gitignore b/.gitignore index 15dc4014f432..ab436a016c7c 100644 --- a/.gitignore +++ b/.gitignore @@ -145,3 +145,6 @@ poetry.toml /.windsurf/ # emscripten a.out.* + +.history/ +.scratch/ \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 97c25074b4c6..e69de29bb2d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,110 +0,0 @@ -# Instructions for llama.cpp - -> [!IMPORTANT] -> This project does **not** accept pull requests that are fully or predominantly AI-generated. AI tools may be utilized solely in an assistive capacity. -> -> Read more: [CONTRIBUTING.md](CONTRIBUTING.md) - -AI assistance is permissible only when the majority of the code is authored by a human contributor, with AI employed exclusively for corrections or to expand on verbose modifications that the contributor has already conceptualized (see examples below). - ---- - -## Guidelines for Contributors Using AI - -llama.cpp is built by humans, for humans. Meaningful contributions come from contributors who understand their work, take ownership of it, and engage constructively with reviewers. - -Maintainers receive numerous pull requests weekly, many of which are AI-generated submissions where the author cannot adequately explain the code, debug issues, or participate in substantive design discussions. Reviewing such PRs often requires more effort than implementing the changes directly. - -**A pull request represents a long-term commitment.** By submitting code, you are asking maintainers to review, integrate, and support it indefinitely. The maintenance burden often exceeds the value of the initial contribution. - -Most maintainers already have access to AI tools. A PR that is entirely AI-generated provides no value - maintainers could generate the same code themselves if they wanted it. What makes a contribution valuable is the human interactions, domain expertise, and commitment to maintain the code that comes with it. - -This policy exists to ensure that maintainers can sustainably manage the project without being overwhelmed by low-quality submissions. - ---- - -## Guidelines for Contributors - -Contributors are expected to: - -1. **Demonstrate full understanding of their code.** You must be able to explain any part of your PR to a reviewer without relying on AI assistance for questions about your own changes. - -2. **Take responsibility for maintenance.** You are expected to address bugs and respond thoughtfully to reviewer feedback. - -3. **Communicate clearly and concisely.** Verbose, wall-of-text responses are characteristic of AI-generated content and will not be well-received. Direct, human communication is expected. - -4. **Respect maintainers' time.** Search for existing issues and discussions before submitting. Ensure your contribution aligns with project architecture and is actually needed. - -Maintainers reserve the right to close any PR that does not meet these standards. This applies to all contributions to the main llama.cpp repository. **Private forks are exempt.** - -### Permitted AI Usage - -AI tools may be used responsibly for: - -- **Learning and exploration**: Understanding codebase structure, techniques, and documentation -- **Code review assistance**: Obtaining suggestions on human-written code -- **Mechanical tasks**: Formatting, generating repetitive patterns from established designs, completing code based on existing patterns -- **Documentation drafts**: For components the contributor already understands thoroughly -- **Writing code**: Only when the contributor has already designed the solution and can implement it themselves - AI accelerates, not replaces, the contributor's work - -AI-generated code may be accepted if you (1) fully understand the output, (2) can debug issues independently, and (3) can discuss it directly with reviewers without AI assistance. - -**Disclosure is required** when AI meaningfully contributed to your code. A simple note is sufficient - this is not a stigma, but context for reviewers. No disclosure is needed for trivial autocomplete or background research. - -### Prohibited AI Usage - -The following will result in immediate PR closure: - -- **AI-written PR descriptions or commit messages** - these are typically recognizable and waste reviewer time -- **AI-generated responses to reviewer comments** - this undermines the human-to-human interaction fundamental to code review -- **Implementing features without understanding the codebase** - particularly new model support or architectural changes -- **Automated commits or PR submissions** - this may spam maintainers and can result in contributor bans - ---- - -## Guidelines for AI Coding Agents - -AI agents assisting contributors must recognize that their outputs directly impact volunteer maintainers who sustain this project. - -### Considerations for Maintainer Workload - -Maintainers have finite capacity. Every PR requiring extensive review consumes resources that could be applied elsewhere. Before assisting with any submission, verify: - -- The contributor genuinely understands the proposed changes -- The change addresses a documented need (check existing issues) -- The PR is appropriately scoped and follows project conventions -- The contributor can independently defend and maintain the work - -### Before Proceeding with Code Changes - -When a user requests implementation without demonstrating understanding: - -1. **Verify comprehension.** Ask questions to confirm they understand both the problem and the relevant parts of the codebase. -2. **Provide guidance rather than solutions.** Direct them to relevant code and documentation. Allow them to formulate the approach. -3. **Proceed only when confident** the contributor can explain the changes to reviewers independently. - -For first-time contributors, confirm they have reviewed [CONTRIBUTING.md](CONTRIBUTING.md) and acknowledge this policy. - -### Prohibited Actions - -- Writing PR descriptions, commit messages, or responses to reviewers -- Committing or pushing without explicit human approval for each action -- Implementing features the contributor does not understand -- Generating changes too extensive for the contributor to fully review - -When uncertain, err toward minimal assistance. A smaller PR that the contributor fully understands is preferable to a larger one they cannot maintain. - -### Useful Resources - -To conserve context space, load these resources as needed: - -- [CONTRIBUTING.md](CONTRIBUTING.md) -- [Existing issues](https://github.com/ggml-org/llama.cpp/issues) and [Existing PRs](https://github.com/ggml-org/llama.cpp/pulls) - always search here first -- [Build documentation](docs/build.md) -- [Server usage documentation](tools/server/README.md) -- [Server development documentation](tools/server/README-dev.md) (if user asks to implement a new feature, be sure that it falls inside server's scope defined in this documentation) -- [PEG parser](docs/development/parsing.md) - alternative to regex that llama.cpp uses to parse model's output -- [Auto parser](docs/autoparser.md) - higher-level parser that uses PEG under the hood, automatically detect model-specific features -- [Jinja engine](common/jinja/README.md) -- [How to add a new model](docs/development/HOWTO-add-model.md) -- [PR template](.github/pull_request_template.md) diff --git a/common/arg.cpp b/common/arg.cpp index faee613aa77e..cb36c5541289 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -3492,11 +3492,18 @@ common_params_context common_params_parser_init(common_params & params, llama_ex ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_N_GPU_LAYERS_DRAFT")); add_opt(common_arg( {"-md", "--model-draft"}, "FNAME", - "draft model for speculative decoding (default: unused)", + "draft model for speculative decoding, or Gemma 4 MTP assistant GGUF when using --spec-type mtp (default: unused)", [](common_params & params, const std::string & value) { params.speculative.mparams_dft.path = value; } ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_MODEL_DRAFT")); + add_opt(common_arg( + {"--mtp-head"}, "FNAME", + "alias for Gemma 4 MTP: path to gemma4_assistant GGUF (loaded into the target; use with --spec-type mtp)", + [](common_params & params, const std::string & value) { + params.speculative.mparams_dft.path = value; + } + ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_MTP_HEAD")); add_opt(common_arg( {"--spec-replace"}, "TARGET", "DRAFT", "translate the string in TARGET into DRAFT if the draft model and main model are not compatible", @@ -3505,12 +3512,18 @@ common_params_context common_params_parser_init(common_params & params, llama_ex } ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI})); add_opt(common_arg( - {"--spec-type"}, "[none|ngram-cache|ngram-simple|ngram-map-k|ngram-map-k4v|ngram-mod]", - string_format("type of speculative decoding to use when no draft model is provided (default: %s)\n", + {"--spec-type"}, "[none|draft|mtp|eagle3|ngram-cache|ngram-simple|ngram-map-k|ngram-map-k4v|ngram-mod]", + string_format("type of speculative decoding (default: %s). For Gemma 4 MTP use --spec-type mtp and --mtp-head (or --model-draft) pointing at gemma4_assistant GGUF.\n", common_speculative_type_to_str(params.speculative.type).c_str()), [](common_params & params, const std::string & value) { if (value == "none") { params.speculative.type = COMMON_SPECULATIVE_TYPE_NONE; + } else if (value == "draft") { + params.speculative.type = COMMON_SPECULATIVE_TYPE_DRAFT; + } else if (value == "mtp") { + params.speculative.type = COMMON_SPECULATIVE_TYPE_MTP; + } else if (value == "eagle3") { + params.speculative.type = COMMON_SPECULATIVE_TYPE_EAGLE3; } else if (value == "ngram-cache") { params.speculative.type = COMMON_SPECULATIVE_TYPE_NGRAM_CACHE; } else if (value == "ngram-simple") { @@ -3522,10 +3535,20 @@ common_params_context common_params_parser_init(common_params & params, llama_ex } else if (value == "ngram-mod") { params.speculative.type = COMMON_SPECULATIVE_TYPE_NGRAM_MOD; } else { - throw std::invalid_argument("unknown speculative decoding type without draft model"); + throw std::invalid_argument("unknown speculative decoding type"); } } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SPEC_TYPE")); + add_opt(common_arg( + {"--draft-block-size"}, "N", + string_format("MTP draft block size B (drafts B-1 tokens per round; default: %d)", params.speculative.draft_block_size), + [](common_params & params, int value) { + if (value < 2 || value > 32) { + throw std::invalid_argument("draft block size must be between 2 and 32"); + } + params.speculative.draft_block_size = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_SPECULATIVE}).set_env("LLAMA_ARG_DRAFT_BLOCK_SIZE")); add_opt(common_arg( {"--spec-ngram-size-n"}, "N", string_format("ngram size N for ngram-simple/ngram-map speculative decoding, length of lookup n-gram (default: %d)", params.speculative.ngram_size_n), diff --git a/common/common.cpp b/common/common.cpp index 825df65ab4ff..4821a5620483 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1188,6 +1188,43 @@ common_init_result::common_init_result(common_params & params) : pimpl->lora.emplace_back(std::move(lora)); // copy to list of loaded adapters } + if (params.speculative.has_dft() && params.speculative.type == COMMON_SPECULATIVE_TYPE_MTP) { + if (params.speculative.mparams_dft.path.empty() && params.speculative.mparams_dft.hf_repo.empty()) { + LOG_ERR("%s: MTP speculative decoding requires --mtp-head or --model-draft with a local path\n", __func__); + pimpl->model.reset(); + return; + } + if (params.speculative.mparams_dft.path.empty()) { + LOG_ERR("%s: MTP assistant must be loaded from a local GGUF path (HF repo download not wired here)\n", __func__); + pimpl->model.reset(); + return; + } + + common_params p_mtp = params; + p_mtp.n_parallel = 1; + p_mtp.n_ctx = params.speculative.n_ctx > 0 ? params.speculative.n_ctx : params.n_ctx; + p_mtp.n_batch = std::max(p_mtp.n_ctx, params.n_batch); + p_mtp.devices = params.speculative.devices; + p_mtp.model = params.speculative.mparams_dft; + p_mtp.n_gpu_layers = params.speculative.n_gpu_layers; + p_mtp.cache_type_k = params.speculative.cache_type_k; + p_mtp.cache_type_v = params.speculative.cache_type_v; + if (params.speculative.cpuparams.n_threads > 0) { + p_mtp.cpuparams = params.speculative.cpuparams; + p_mtp.cpuparams_batch = params.speculative.cpuparams_batch; + } + p_mtp.tensor_buft_overrides = params.speculative.tensor_buft_overrides; + + llama_model_params mparams_mtp = common_model_params_to_llama(p_mtp); + const char * path_mtp = params.speculative.mparams_dft.path.c_str(); + if (llama_model_load_mtp_from_file(model, path_mtp, mparams_mtp) != 0) { + LOG_ERR("%s: failed to load MTP assistant from '%s'\n", __func__, path_mtp); + pimpl->model.reset(); + return; + } + params.speculative.model_dft = nullptr; + } + // updates params.sampling // TODO: fix naming common_init_sampler_from_model(model, params.sampling); diff --git a/common/common.h b/common/common.h index 020b6a721ff9..d32d78e8fb11 100644 --- a/common/common.h +++ b/common/common.h @@ -177,6 +177,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_MTP, // Gemma 4 MTP assistant drafter COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type }; @@ -316,6 +317,9 @@ struct common_params_speculative { int32_t n_max = 16; // maximum number of tokens to draft during speculative decoding int32_t n_min = 0; // minimum number of draft tokens to use for speculative decoding + + // MTP (Gemma 4 assistant): draft block size B produces B-1 draft tokens per round (default 4) + int32_t draft_block_size = 4; float p_split = 0.1f; // speculative decoding split probability float p_min = 0.75f; // minimum speculative decoding probability (greedy) diff --git a/common/speculative.cpp b/common/speculative.cpp index 3e68c38e49cc..644b9551e582 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -10,13 +10,17 @@ #include "sampling.h" #include +#include #include #include #include +#include +#include #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 128 #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5 + const std::vector common_speculative_types = { COMMON_SPECULATIVE_TYPE_NONE, COMMON_SPECULATIVE_TYPE_DRAFT, @@ -25,7 +29,8 @@ const std::vector common_speculative_types = { COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K, COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, COMMON_SPECULATIVE_TYPE_NGRAM_MOD, - COMMON_SPECULATIVE_TYPE_NGRAM_CACHE + COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, + COMMON_SPECULATIVE_TYPE_MTP }; const std::map common_speculative_type_from_name_map = { @@ -36,7 +41,8 @@ const std::map common_speculative_typ {"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}, + {"mtp", COMMON_SPECULATIVE_TYPE_MTP} }; struct common_speculative_config { @@ -47,6 +53,48 @@ struct common_speculative_config { const common_params_speculative & p = common_params_speculative{}) : type(t), params(p) {} }; +static bool common_speculative_mtp_arch_ok(const llama_model * model_tgt, const llama_model * model_dft) { + return std::strcmp(llama_model_arch_str(model_tgt), "gemma4") == 0 + && std::strcmp(llama_model_arch_str(model_dft), "gemma4_assistant") == 0; +} + +// MTP-specific vocab compatibility: +// the assistant (draft) only predicts the next token id from the same SentencePiece +// vocabulary; stop-condition / chat-template special tokens are owned by the target. +// Therefore we only require identical vocab_type, vocab size (within tolerance) and +// per-token text equality, and intentionally skip bos/eos id and add_bos/add_eos +// checks (target may be chat-tuned with eos==106, draft with eos==1). +static bool common_speculative_are_compatible_mtp( + const llama_model * model_tgt, + const llama_model * model_dft) { + const llama_vocab * vocab_tgt = llama_model_get_vocab(model_tgt); + const llama_vocab * vocab_dft = llama_model_get_vocab(model_dft); + + if (llama_vocab_type(vocab_tgt) != llama_vocab_type(vocab_dft)) { + return false; + } + + const int n_vocab_tgt = llama_vocab_n_tokens(vocab_tgt); + const int n_vocab_dft = llama_vocab_n_tokens(vocab_dft); + const int vocab_diff = n_vocab_tgt > n_vocab_dft + ? n_vocab_tgt - n_vocab_dft + : n_vocab_dft - n_vocab_tgt; + + if (vocab_diff > SPEC_VOCAB_MAX_SIZE_DIFFERENCE) { + return false; + } + + for (int i = SPEC_VOCAB_CHECK_START_TOKEN_ID; i < std::min(n_vocab_tgt, n_vocab_dft); ++i) { + const char * t_tgt = llama_vocab_get_text(vocab_tgt, i); + const char * t_dft = llama_vocab_get_text(vocab_dft, i); + if (std::strcmp(t_tgt, t_dft) != 0) { + return false; + } + } + + return true; +} + static bool common_speculative_are_compatible( const llama_model * model_tgt, const llama_model * model_dft) { @@ -462,6 +510,119 @@ struct common_speculative_state_eagle3 : public common_speculative_state { } }; +struct common_speculative_state_mtp : public common_speculative_state { + llama_context * ctx_tgt; + llama_seq_id seq_id = 0; // target-side sequence id (set by host, e.g. server slot.id) + int h_idx = -1; // output index in target's last decode for h_prev (-1 = last) + // Adaptive skip after consecutive zero-accept batches: when MTP head consistently + // mispredicts (e.g. on numbers/code/rare tokens during long generation), drafting + // costs ~10ms but yields no accepted tokens. Detect this and fall back to plain + // verify-only for one batch; reset skip on next non-empty accept. + size_t prev_n_acc_drafts = 0; + int zero_accept_streak = 0; + int skip_streak_threshold = 2; + + explicit common_speculative_state_mtp(enum common_speculative_type type, llama_context * ctx_tgt) + : common_speculative_state(type), ctx_tgt(ctx_tgt) { + // MTP reads last backbone hidden from the target; keep embeddings on across decodes. + llama_set_embeddings(ctx_tgt, true); + } + + void begin(const llama_tokens & prompt) override { + GGML_UNUSED(prompt); + llama_set_embeddings(ctx_tgt, true); + } + + void draft( + const common_params_speculative & params, + const llama_tokens & prompt_tgt, + llama_token id_last, + llama_tokens & draft_tokens) override { + + draft_tokens.clear(); + + const llama_model * model_tgt = llama_get_model(ctx_tgt); + const uint32_t n_bb_u = llama_model_mtp_n_embd_backbone(model_tgt); + if (n_bb_u == 0) { + LOG_ERR("%s: no MTP assistant on target model\n", __func__); + return; + } + const int32_t n_bb = (int32_t) n_bb_u; + + // Detect zero-accept of previous draft batch: n_acc_drafts only increments when + // common_speculative_accept is called with n_accepted>0. So if it didn't move + // since our previous draft() return, the previous batch produced 0 accepted drafts. + if (n_call_draft > 0) { + if (n_acc_drafts == prev_n_acc_drafts) { + ++zero_accept_streak; + } else { + zero_accept_streak = 0; + } + } + // After threshold consecutive misses, skip MTP draft for one batch — drafting + // would cost ~10ms with no benefit; better to let server do a single-token + // verify (baseline path). + if (zero_accept_streak >= skip_streak_threshold) { + // Reset streak after one skip; if next batch still misses (streak resumes), we'll skip again. + zero_accept_streak = 0; + prev_n_acc_drafts = n_acc_drafts; + return; // empty draft_tokens — server falls back to single-token verify + } + + int32_t n_steps_raw = params.draft_block_size > 1 ? params.draft_block_size - 1 : 0; + int32_t n_steps = std::min(n_steps_raw, params.n_max); + + if (n_steps <= 0) { + return; + } + + llama_set_embeddings(ctx_tgt, true); + + std::vector h_prev((size_t) n_bb, 0.0f); + bool h_tgt_used = false; + // Use the explicit h_idx pointing at the last accepted output (set by the host after + // sample_and_accept_n). If unset, fall back to -1 (last output) which is correct only + // when the previous decode was prefill or when ALL drafts of the previous batch were + // accepted (otherwise -1 points at a rejected draft's hidden state). + if (float * h_tgt = llama_get_embeddings_ith(ctx_tgt, h_idx)) { + const int32_t n_out_tgt = llama_model_n_embd_out(model_tgt); + const int32_t n_copy = std::min(n_bb, n_out_tgt); + std::memcpy(h_prev.data(), h_tgt, (size_t) n_copy * sizeof(float)); + h_tgt_used = true; + } + + llama_memory_t mem = llama_get_memory(ctx_tgt); + llama_pos attn_pos = mem ? llama_memory_seq_pos_max(mem, seq_id) : (llama_pos) 0; + if (attn_pos < 0) { + attn_pos = 0; + } + + draft_tokens.resize((size_t) n_steps); + const int32_t rc = llama_decode_mtp( + ctx_tgt, + seq_id, + attn_pos, + id_last, + h_prev.data(), + n_steps, + draft_tokens.data(), + /*out_logits*/ nullptr, + /*out_h_prev_last*/ nullptr); + + if (rc != 0) { + LOG_ERR("%s: llama_decode_mtp failed (%d)\n", __func__, (int) rc); + draft_tokens.clear(); + } + + // Snapshot accepted-draft counter for next call's zero-accept detection. + prev_n_acc_drafts = n_acc_drafts; + } + + void accept(uint16_t n_accepted) override { + GGML_UNUSED(n_accepted); + } +}; + // state of self-speculation (simple implementation, not ngram-map) struct common_speculative_state_ngram_simple : public common_speculative_state { common_ngram_simple_config config; @@ -786,6 +947,7 @@ std::string common_speculative_type_to_str(enum 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_MTP: return "mtp"; default: return "unknown"; } } @@ -840,7 +1002,8 @@ common_speculative * common_speculative_init( common_params_speculative & params, llama_context * ctx_tgt) { llama_context * ctx_dft = nullptr; - if (params.model_dft) { + // Gemma4 MTP loads the assistant into the target model (llama_model_load_mtp_from_file); no second context. + if (params.model_dft && params.type != COMMON_SPECULATIVE_TYPE_MTP) { ctx_dft = llama_init_from_model(params.model_dft, params.cparams_dft); if (ctx_dft == nullptr) { LOG_ERR("%s", "failed to create draft context\n"); @@ -848,6 +1011,24 @@ common_speculative * common_speculative_init( } } + if (params.type == COMMON_SPECULATIVE_TYPE_MTP) { + const llama_model * model_tgt = llama_get_model(ctx_tgt); + const llama_model * model_mtp = llama_model_get_mtp_assistant(model_tgt); + + if (!model_mtp) { + LOG_ERR("%s: MTP requires the assistant GGUF loaded into the target (CLI: --spec-type mtp with --mtp-head or --model-draft)\n", __func__); + return nullptr; + } + if (!common_speculative_mtp_arch_ok(model_tgt, model_mtp)) { + LOG_ERR("%s: MTP requires target arch gemma4 and assistant arch gemma4_assistant\n", __func__); + return nullptr; + } + if (!common_speculative_are_compatible_mtp(model_tgt, model_mtp)) { + LOG_ERR("%s: MTP assistant failed vocab compatibility check\n", __func__); + return nullptr; + } + } + // Compute the implementations to use based on the config and their order of preference std::vector configs = {}; // list of speculative configs to try { @@ -859,6 +1040,7 @@ common_speculative * common_speculative_init( bool has_ngram_map_k = (params.type == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K); bool has_ngram_map_k4v = (params.type == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V); bool has_ngram_mod = (params.type == COMMON_SPECULATIVE_TYPE_NGRAM_MOD); + bool has_mtp = (params.type == COMMON_SPECULATIVE_TYPE_MTP); // In a more complex implementation we could use the same implementation but with different parameters. // This was initially used in PR-18471 but removed to simplify the code. @@ -893,7 +1075,11 @@ common_speculative * common_speculative_init( configs.push_back(common_speculative_config(COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, params)); } if (has_draft) { - configs.push_back(common_speculative_config(COMMON_SPECULATIVE_TYPE_DRAFT, params)); + if (has_mtp) { + configs.push_back(common_speculative_config(COMMON_SPECULATIVE_TYPE_MTP, params)); + } else { + configs.push_back(common_speculative_config(COMMON_SPECULATIVE_TYPE_DRAFT, params)); + } } if (has_draft_eagle3) { configs.push_back(common_speculative_config(COMMON_SPECULATIVE_TYPE_EAGLE3, params)); @@ -919,6 +1105,10 @@ common_speculative * common_speculative_init( impls.push_back(std::make_unique(config.type)); break; } + case COMMON_SPECULATIVE_TYPE_MTP: { + impls.push_back(std::make_unique(config.type, ctx_tgt)); + break; + } case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: { common_ngram_map ngram_map = get_common_ngram_map(config); @@ -980,6 +1170,28 @@ void common_speculative_free(common_speculative * spec) { delete spec; } +void common_speculative_set_seq_id(common_speculative * spec, llama_seq_id seq_id) { + if (spec == nullptr) { + return; + } + for (auto & impl : spec->impls) { + if (impl->type == COMMON_SPECULATIVE_TYPE_MTP) { + static_cast(impl.get())->seq_id = seq_id; + } + } +} + +void common_speculative_set_h_idx(common_speculative * spec, int batch_idx) { + if (spec == nullptr) { + return; + } + for (auto & impl : spec->impls) { + if (impl->type == COMMON_SPECULATIVE_TYPE_MTP) { + static_cast(impl.get())->h_idx = batch_idx; + } + } +} + void common_speculative_begin(common_speculative * spec, const llama_tokens & prompt) { if (spec == nullptr) { return; diff --git a/common/speculative.h b/common/speculative.h index 876cde3d1801..e61fa6edb473 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -27,6 +27,17 @@ void common_speculative_free(common_speculative * spec); // optionally call once at the beginning of a new generation void common_speculative_begin(common_speculative * spec, const llama_tokens & prompt); +// set target-side sequence id used by implementations that read from the target's KV memory +// (currently only used by the MTP implementation; safe no-op for others) +void common_speculative_set_seq_id(common_speculative * spec, llama_seq_id seq_id); + +// Set the output index in the target's most recent decode whose embeddings should be read +// as h_prev for the next MTP draft. -1 means "last output" (default). +// In speculative verification, after partial draft acceptance the last batch output corresponds +// to a rejected draft; the correct h_prev is at the last *accepted* batch index. +// Safe no-op for non-MTP implementations. +void common_speculative_set_h_idx(common_speculative * spec, int batch_idx); + // sample up to n_draft tokens and add them to the batch using the draft model llama_tokens common_speculative_draft( common_speculative * spec, diff --git a/convert_hf_to_gguf.py b/convert_hf_to_gguf.py index f6441b8d2662..078a92a1e8d2 100755 --- a/convert_hf_to_gguf.py +++ b/convert_hf_to_gguf.py @@ -1019,11 +1019,20 @@ def __init__(self, *args, **kwargs): else: self.hf_arch = "" + root_model_type = None if "text_config" in self.hparams: - # move the text_config to the root level + # HF nested text_config often sets architectures=null and model_type=gemma4_text, which would + # wipe the wrapper's Gemma4AssistantForCausalLM / gemma4_assistant metadata if merged naively. + root_arch = self.hparams.get("architectures") + root_model_type = self.hparams.get("model_type") self.hparams = {**self.hparams, **self.hparams["text_config"]} + if root_arch is not None and self.hparams.get("architectures") is None: + self.hparams["architectures"] = root_arch - self.block_count = self.find_hparam(["n_layers", "num_hidden_layers", "n_layer", "num_layers"]) + if root_model_type == "gemma4_assistant" and "num_hidden_layers" in self.hparams: + self.block_count = int(self.hparams["num_hidden_layers"]) + else: + self.block_count = self.find_hparam(["n_layers", "num_hidden_layers", "n_layer", "num_layers"]) self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count) self.rope_parameters = self.hparams.get("rope_parameters", self.hparams.get("rope_scaling")) or {} @@ -7788,6 +7797,67 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield from super().modify_tensors(data_torch, name, bid) +@ModelBase.register("Gemma4AssistantForCausalLM") +class Gemma4AssistantModel(Gemma4Model): + model_arch = gguf.MODEL_ARCH.GEMMA4_ASSISTANT + + def set_gguf_parameters(self): + super().set_gguf_parameters() + hp = self.hparams + self.gguf_writer.add_n_centroids(hp.get("num_centroids", 0)) + self.gguf_writer.add_centroid_top_k(hp.get("centroid_intermediate_top_k", 0)) + self.gguf_writer.add_n_embd_backbone(hp.get("backbone_hidden_size", 0)) + self.gguf_writer.add_use_ordered_embeddings(hp.get("use_ordered_embeddings", False)) + self.gguf_writer.add_attention_k_eq_v(hp.get("attention_k_eq_v", False)) + # MTP head must be paired with this target architecture in llama.cpp + self.gguf_writer.add_requires_target_arch("gemma4") + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name.endswith("per_dim_scale") or name.endswith("layer_scalar"): + name = name + ".weight" + + # Tied lm_head shares embed; skip standalone lm_head if present in checkpoint + if bid is None and name.endswith("lm_head.weight"): + return + + # HF layout is [vocab, hidden_size]. Some checkpoints widen hidden to backbone_hidden_size; llama.cpp expects hidden_size (= text_config.hidden_size). + if bid is None and name == "model.embed_tokens.weight" and data_torch.ndim == 2: + hs = int(self.hparams["hidden_size"]) + n_bb = int(self.hparams.get("backbone_hidden_size") or 0) + n_rows, n_cols = data_torch.shape + if n_rows > n_cols: + # [vocab, n_embd] + if n_cols > hs: + logger.warning(f"gemma4_assistant: trimming embed_tokens weight columns {n_cols} -> {hs}") + data_torch = data_torch[:, :hs].contiguous() + elif n_bb > 0 and n_cols > n_rows and n_rows >= n_bb and n_rows > hs: + # Mistaken GGML-ish [n_embd_padded, vocab] + logger.warning(f"gemma4_assistant: trimming embed_tokens weight rows {n_rows} -> {hs}") + data_torch = data_torch[:hs, :].contiguous() + + if name == "pre_projection.weight": + # HF Linear (out, in) = (n_embd, 2*n_bb); GGUF / ggml mul_mat expects w ne [2*n_bb, n_embd] + yield (self.format_tensor_name(gguf.MODEL_TENSOR.MTP_PRE_PROJECTION), data_torch) + return + if name == "post_projection.weight": + # HF (n_bb, n_embd); GGUF ne [n_embd, n_bb] for mul_mat(h, w) with h [n_embd, ...] + yield (self.format_tensor_name(gguf.MODEL_TENSOR.MTP_POST_PROJECTION), data_torch) + return + if name.endswith("masked_embedding.centroids.weight"): + yield (self.format_tensor_name(gguf.MODEL_TENSOR.MTP_CENTROIDS), data_torch) + return + if "masked_embedding.token_ordering" in name: + yield (self.format_tensor_name(gguf.MODEL_TENSOR.MTP_TOKEN_ORDERING), data_torch.to(torch.int32)) + return + + # Gemma4Model.modify_tensors expects a language_model.* prefix on HF names + lm_name = name + if name.startswith("model.") and not name.startswith("language_model."): + lm_name = "language_model." + name + + yield from super().modify_tensors(data_torch, lm_name, bid) + + @ModelBase.register("Gemma4ForConditionalGeneration") class Gemma4VisionAudioModel(MmprojModel): has_audio_encoder = True diff --git a/docs/development/gemma4-assistant-tensor-inventory.md b/docs/development/gemma4-assistant-tensor-inventory.md new file mode 100644 index 000000000000..6a844b33cea3 --- /dev/null +++ b/docs/development/gemma4-assistant-tensor-inventory.md @@ -0,0 +1,38 @@ +# Gemma 4 Assistant (MTP drafter) — tensor inventory (Stage 0) + +This document records the expected tensor layout for `Gemma4AssistantForCausalLM` / `model_type: gemma4_assistant`, cross-referenced with the MLX-VLM reference implementation (PR #1112). + +## HF config highlights (`google/gemma-4-26B-A4B-it-assistant`) + +- `architectures`: `["Gemma4AssistantForCausalLM"]` +- `model_type`: `gemma4_assistant` +- `backbone_hidden_size`: 2816 (must match paired target Gemma 4 backbone) +- `use_ordered_embeddings`: typically `false` for 26B-A4B / 31B (dense tied LM head); `true` for E2B/E4B (centroid `MaskedEmbedder`) +- `num_centroids`: 2048 (when ordered embeddings) +- `centroid_intermediate_top_k`: 32 +- Nested `text_config`: 4 layers, `layer_types` e.g. three `sliding_attention` + one `full_attention`, `attention_k_eq_v: true`, `vocab_size: 262144`, `hidden_size: 1024`, etc. + +## Expected safetensors names (HF / MLX) + +| Logical component | Typical HF / checkpoint name | GGUF name (this fork) | +|-------------------|------------------------------|------------------------| +| Pre-projection | `pre_projection.weight` | `mtp.pre_projection.weight` | +| Post-projection | `post_projection.weight` | `mtp.post_projection.weight` | +| Token embeddings (inner) | `model.embed_tokens.weight` | `token_embd.weight` | +| Final norm | `model.norm.weight` | `output_norm.weight` | +| Per-layer | `model.layers.{i}.*` | `blk.{i}.*` (via `tensor_mapping.py`) | +| Centroid head (E2B/E4B) | `masked_embedding.centroids.weight` | `mtp.centroids.weight` | +| Token ordering | `masked_embedding.token_ordering` | `mtp.token_ordering` (I32) | +| LM head (if untied) | `lm_head.weight` | `output.weight` | + +## MLX reference files + +- `mlx_vlm/speculative/drafters/gemma4_assistant/gemma4_assistant.py` — forward, `draft_block`, `sanitize` +- `mlx_vlm/speculative/drafters/gemma4_assistant/masked_embedder.py` — sparse centroid LM head +- `mlx_vlm/speculative/drafters/gemma4_assistant/masks.py` — SWA / full masks + +## Notes for llama.cpp port + +1. MTP consumes **target K/V** for the last sliding-attention and last full-attention layers; the assistant has **no independent KV** in the reference design. The initial C++ integration uses the assistant as a loadable arch with standard KV for bring-up; full KV sharing is wired through `--spec-type mtp` and remains dependent on target/draft pairing and cache layout. +2. `attention_k_eq_v: true` maps to missing `blk.*.attn_v.weight` (V taken from K), matching Gemma 4 handling in `gemma4-iswa.cpp`. +3. Greedy parity with the target requires byte-identical drafting; validate with `tests/test-speculative-mtp` when model paths are available. diff --git a/docs/speculative.md b/docs/speculative.md index 29da332875f0..13016c33e860 100644 --- a/docs/speculative.md +++ b/docs/speculative.md @@ -13,6 +13,43 @@ The `llama-server` application supports several implementations of speculative d A much smaller model (called the _draft model_) generates drafts. A draft model is the most used approach in speculative decoding. +### Gemma 4 MTP assistant (`mtp`) + +For **Gemma 4** targets with the **gemma4_assistant** (MTP head) GGUF, use `--spec-type mtp`. The assistant is **not** a second `llama_context`: weights are loaded into the target model via `llama_model_load_mtp_from_file` (done automatically when using the server/CLI init path). Cross-attention in the MTP graph reads **K/V from the target KV cache** (shared full/sliding layers). + +- Prefer **`--mtp-head /path/to/assistant.gguf`** for clarity; **`--model-draft` (`-md`)** is accepted as a backward-compatible alias (same path field). +- The draft block size \(B\) is **`--draft-block-size`** (the head proposes `B - 1` tokens per round; default 4). +- **`--gpu-layers-draft` / `-ngld`** and **`-ctkd` / `-ctvd`** still apply to how the **assistant tensors** are placed and typed when the assistant GGUF is loaded; the target uses `-ngl` and `-ctk`/`-ctv`. + +Example (paths illustrative). **TurboQuant** KV on the target: `-ctk`/`-ctv`. Assistant-side cache types follow the draft flags if you use them for offload/quant selection. + +```sh +llama-server \ + -m /path/to/gemma-4-target.gguf \ + --mtp-head /path/to/gemma-4-assistant.gguf \ + --spec-type mtp \ + --draft-block-size 4 \ + -c 16384 \ + -ngl 99 -ngld 99 \ + -ctk turbo3 -ctv turbo3 \ + -ctkd turbo3 -ctvd turbo3 \ + -fa on \ + --host 127.0.0.1 --port 8080 +``` + +Repo helper (defaults under `.scratch/`): `scripts/run-gemma4-mtp-server.sh`. + +#### Reconverting `gemma4_assistant` from Hugging Face + +Example (paths relative to repo root): + +```sh +python convert_hf_to_gguf.py .scratch/gemma-4-26B-A4B-it-assistant \ + --outfile .scratch/gemma-assistant-mtp.gguf --outtype f16 +``` + +Use the resulting GGUF as `--mtp-head` (or `-md`) with `--spec-type mtp`. Older assistant GGUFs with `token_embd.weight` first axis 2816 (backbone width) instead of 1024 will fail load; run `scripts/verify-gemma4-assistant-gguf.py` on the file to check. + ### n-gram Cache (`ngram-cache`) An n-gram is a sequence of n tokens. The n-gram cache implementation maintains statistics about short n-gram sequences. diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 997744f34c34..678a0060ed83 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -153,6 +153,12 @@ class LLM: DENSE_FEAT_IN_SIZE = "{arch}.{dense}_feat_in" DENSE_FEAT_OUT_SIZE = "{arch}.{dense}_feat_out" + N_CENTROIDS = "{arch}.n_centroids" + CENTROID_TOP_K = "{arch}.centroid_top_k" + N_EMBD_BACKBONE = "{arch}.n_embd_backbone" + USE_ORDERED_EMBEDDINGS = "{arch}.use_ordered_embeddings" + REQUIRES_TARGET_ARCH = "{arch}.requires_target_arch" + class Attention: HEAD_COUNT = "{arch}.attention.head_count" HEAD_COUNT_KV = "{arch}.attention.head_count_kv" @@ -181,6 +187,7 @@ class Attention: KEY_LENGTH_SWA = "{arch}.attention.key_length_swa" VALUE_LENGTH_SWA = "{arch}.attention.value_length_swa" SHARED_KV_LAYERS = "{arch}.attention.shared_kv_layers" + K_EQ_V = "{arch}.attention.k_eq_v" SLIDING_WINDOW_PATTERN = "{arch}.attention.sliding_window_pattern" TEMPERATURE_SCALE = "{arch}.attention.temperature_scale" @@ -420,6 +427,7 @@ class MODEL_ARCH(IntEnum): GEMMA3 = auto() GEMMA3N = auto() GEMMA4 = auto() + GEMMA4_ASSISTANT = auto() GEMMA_EMBEDDING = auto() STARCODER2 = auto() RWKV6 = auto() @@ -842,6 +850,11 @@ class MODEL_TENSOR(IntEnum): NEXTN_HNORM = auto() NEXTN_SHARED_HEAD_HEAD = auto() NEXTN_SHARED_HEAD_NORM = auto() + # Gemma 4 MTP assistant (GGUF names: mtp.*) + MTP_PRE_PROJECTION = auto() + MTP_POST_PROJECTION = auto() + MTP_CENTROIDS = auto() + MTP_TOKEN_ORDERING = auto() # lfm2 audio A_ENC_NORM_CONV = auto() A_ENC_LINEAR_POS = auto() @@ -905,6 +918,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.GEMMA3: "gemma3", MODEL_ARCH.GEMMA3N: "gemma3n", MODEL_ARCH.GEMMA4: "gemma4", + MODEL_ARCH.GEMMA4_ASSISTANT: "gemma4_assistant", MODEL_ARCH.GEMMA_EMBEDDING: "gemma-embedding", MODEL_ARCH.STARCODER2: "starcoder2", MODEL_ARCH.RWKV6: "rwkv6", @@ -1337,6 +1351,10 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.NEXTN_HNORM: "blk.{bid}.nextn.hnorm", MODEL_TENSOR.NEXTN_SHARED_HEAD_HEAD: "blk.{bid}.nextn.shared_head_head", MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM: "blk.{bid}.nextn.shared_head_norm", + MODEL_TENSOR.MTP_PRE_PROJECTION: "mtp.pre_projection", + MODEL_TENSOR.MTP_POST_PROJECTION: "mtp.post_projection", + MODEL_TENSOR.MTP_CENTROIDS: "mtp.centroids", + MODEL_TENSOR.MTP_TOKEN_ORDERING: "mtp.token_ordering", } MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = { @@ -2366,6 +2384,26 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.PER_LAYER_PROJ_NORM, MODEL_TENSOR.PER_LAYER_POST_NORM, ], + MODEL_ARCH.GEMMA4_ASSISTANT: [ + MODEL_TENSOR.ROPE_FREQS, + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.MTP_PRE_PROJECTION, + MODEL_TENSOR.MTP_POST_PROJECTION, + MODEL_TENSOR.MTP_CENTROIDS, + MODEL_TENSOR.MTP_TOKEN_ORDERING, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_Q_NORM, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_PRE_NORM, + MODEL_TENSOR.FFN_POST_NORM, + MODEL_TENSOR.LAYER_OUT_SCALE, + ], MODEL_ARCH.GEMMA_EMBEDDING: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT, diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index 90d500dc7719..d166db415352 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -799,6 +799,24 @@ def add_clamp_kqv(self, value: float) -> None: def add_shared_kv_layers(self, value: int) -> None: self.add_uint32(Keys.Attention.SHARED_KV_LAYERS.format(arch=self.arch), value) + def add_n_centroids(self, value: int) -> None: + self.add_uint32(Keys.LLM.N_CENTROIDS.format(arch=self.arch), value) + + def add_centroid_top_k(self, value: int) -> None: + self.add_uint32(Keys.LLM.CENTROID_TOP_K.format(arch=self.arch), value) + + def add_n_embd_backbone(self, value: int) -> None: + self.add_uint32(Keys.LLM.N_EMBD_BACKBONE.format(arch=self.arch), value) + + def add_use_ordered_embeddings(self, value: bool) -> None: + self.add_bool(Keys.LLM.USE_ORDERED_EMBEDDINGS.format(arch=self.arch), value) + + def add_attention_k_eq_v(self, value: bool) -> None: + self.add_bool(Keys.Attention.K_EQ_V.format(arch=self.arch), value) + + def add_requires_target_arch(self, value: str) -> None: + self.add_string(Keys.LLM.REQUIRES_TARGET_ARCH.format(arch=self.arch), value) + # if input is array, true means SWA and false means full_attention for each layer def add_sliding_window_pattern(self, value: int | Sequence[bool]) -> None: key = Keys.Attention.SLIDING_WINDOW_PATTERN.format(arch=self.arch) diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index 01a9b236000b..68e6c7d32551 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -2138,6 +2138,19 @@ class TensorNameMap: MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM: ( "model.layers.{bid}.shared_head.norm", ), + + MODEL_TENSOR.MTP_PRE_PROJECTION: ( + "pre_projection", + ), + MODEL_TENSOR.MTP_POST_PROJECTION: ( + "post_projection", + ), + MODEL_TENSOR.MTP_CENTROIDS: ( + "masked_embedding.centroids", + ), + MODEL_TENSOR.MTP_TOKEN_ORDERING: ( + "masked_embedding.token_ordering", + ), } # architecture-specific block mappings diff --git a/include/llama.h b/include/llama.h index d4211d3c47b1..c817c1654f0d 100644 --- a/include/llama.h +++ b/include/llama.h @@ -492,6 +492,20 @@ extern "C" { size_t n_paths, struct llama_model_params params); + // Gemma 4 MTP: load gemma4_assistant GGUF into a gemma4 target (call after llama_model_load_from_file, before llama_init_from_model). + // Returns 0 on success. + LLAMA_API int llama_model_load_mtp_from_file( + struct llama_model * model, + const char * path_mtp, + struct llama_model_params params); + + LLAMA_API const struct llama_model * llama_model_get_mtp_assistant(const struct llama_model * model); + + LLAMA_API bool llama_model_has_mtp_assistant(const struct llama_model * model); + + // Backbone hidden size for MTP input (0 if no MTP assistant is loaded). + LLAMA_API uint32_t llama_model_mtp_n_embd_backbone(const struct llama_model * model); + LLAMA_API void llama_model_save_to_file( const struct llama_model * model, const char * path_model); @@ -587,6 +601,16 @@ extern "C" { // Returns label of classifier output by index (