diff --git a/common/sampling.cpp b/common/sampling.cpp index 9c04d35fd00a2..a5824ebeedbaa 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -348,6 +348,11 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co llama_sampler_apply(chain, &cur_p); + /*for (int k = 0; k < (int)cur_p.size; ++k) { + LOG_INF(" - draft candidate %3d, pos %3d: %6d (%8.3f)\n", + k, 0, cur_p.data[k].id, cur_p.data[k].p); + }*/ + GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration"); const llama_token id = cur_p.data[cur_p.selected].id; diff --git a/common/speculative.cpp b/common/speculative.cpp index 262b2c23e720f..9f8384abb1325 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -5,6 +5,8 @@ #include "log.h" #include "common.h" #include "sampling.h" +#include "../src/llama-graph.h" +#include "../src/llama-context.h" #include #include @@ -359,3 +361,72 @@ llama_tokens common_speculative_gen_draft( } return result; } + + +llama_token mtp_speculative_gen_draft( + struct common_sampler* smpl, + struct llama_context* ctx, + llama_token id_last, + int32_t n_past, + int32_t last_tok_idx) { + + llama_token token_data[] = { id_last }; + llama_pos pos_data[] = { n_past }; + int32_t n_seq_id_data[] = { 1 }; + llama_seq_id seq_id_data_internal[] = { 0 }; + llama_seq_id* seq_id_data[] = {seq_id_data_internal}; + int8_t logits_data[] = { (int8_t) (smpl != nullptr) }; + + llama_batch batch = { + /*.n_tokens = */ 1, + /*.token = */ token_data, + /*.embd = */ nullptr, + /*.pos = */ pos_data, + /*.n_seq_id = */ n_seq_id_data, + /*.seq_id = */ seq_id_data, + /*.logits = */ logits_data + }; + + llama_build_and_execute_mtp_graph(ctx, batch, id_last, n_past, last_tok_idx); + //LOG_INF("updating kv cache for n_past: %d\n", n_past); + + if (!smpl) { + return -1; + } + else { + common_sampler_sample(smpl, ctx, last_tok_idx, true); + const auto* cur_p = common_sampler_get_candidates(smpl); + + //for (int k = 0; k < std::min(3, (int)cur_p->size); ++k) { + // LOG_INF(" - draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", + // k, 0, cur_p->data[k].id, cur_p->data[k].p, common_token_to_piece(ctx, cur_p->data[k].id).c_str()); + //} + + const llama_token id = cur_p->data[0].id; + return id; + } + // LOG_INF("cur_p->size: %d\n", cur_p->size); + + + // add drafted token for each sequence + + // skip accepting draft token -- since we're only drafting one token this can't affect future outputs + // smpl will accept the token if it doesn't get rejected by main model later + // common_sampler_accept(smpl, id, true); + + //llama_tokens result; + //result.reserve(1); + //result.push_back(id); + //return result; +} + + +void mtp_update_kv_cache(struct llama_context * ctx, std::vector& tokens) { + mtp_kv_update_data token; + for (int i = 0; i < tokens.size(); ++i) { + token = tokens[i]; + mtp_speculative_gen_draft(nullptr, ctx, token.id, token.n_past, token.tok_idx); + } + + tokens.clear(); +} diff --git a/common/speculative.h b/common/speculative.h index e69d7aaa1eb00..786f3ad1e8d6d 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -12,6 +12,12 @@ struct common_speculative_params { float p_min = 0.75f; // min probability required to accept a token in the draft }; +struct mtp_kv_update_data { + llama_token id; + int32_t n_past; + int32_t tok_idx; +}; + struct common_speculative * common_speculative_init( struct llama_context * ctx_tgt, struct llama_context * ctx_dft @@ -27,9 +33,20 @@ void common_speculative_add_replacement_tgt_dft( struct common_speculative * spec, const char *source, const char *dest); + +// sample up to n_draft tokens and add them to the batch using the draft model +llama_token mtp_speculative_gen_draft( + struct common_sampler* smpl, + struct llama_context* ctx, + llama_token id_last, + int32_t n_past, + int32_t last_tok_idx); + // sample up to n_draft tokens and add them to the batch using the draft model llama_tokens common_speculative_gen_draft( struct common_speculative * spec, struct common_speculative_params params, const llama_tokens & prompt, llama_token id_last); + +void mtp_update_kv_cache(struct llama_context * ctx, std::vector& tokens); diff --git a/include/llama.h b/include/llama.h index 545e957e5f52b..1de8a963cc034 100644 --- a/include/llama.h +++ b/include/llama.h @@ -495,6 +495,8 @@ extern "C" { LLAMA_API int32_t llama_vocab_n_tokens(const struct llama_vocab * vocab); + LLAMA_API int32_t llama_model_n_nextn_layer(const struct llama_model * model); + // Functions to access the model's GGUF metadata scalar values // - The functions return the length of the string on success, or -1 on failure // - The output string is always null-terminated and cleared on failure @@ -548,6 +550,8 @@ extern "C" { const char * fname_out, const llama_model_quantize_params * params); + + // // Adapters // @@ -1450,6 +1454,9 @@ extern "C" { ggml_opt_epoch_callback callback_train, ggml_opt_epoch_callback callback_eval); + LLAMA_API void llama_build_and_execute_mtp_graph(struct llama_context * ctx, + const llama_batch batch_inp, llama_token last_token_id, int32_t n_past, int32_t last_tok_idx); + #ifdef __cplusplus } #endif diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 18dcc6ddfe567..4b6fa3e6059a2 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -2240,12 +2240,13 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_SHORTCONV_OUTPROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, // NextN/MTP tensors are currently ignored (reserved for future MTP support) // These tensors only exist in the last layer(s) and are treated as output tensors - {LLM_TENSOR_NEXTN_EH_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, - {LLM_TENSOR_NEXTN_EMBED_TOKENS, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}}, - {LLM_TENSOR_NEXTN_ENORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}}, - {LLM_TENSOR_NEXTN_HNORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, - {LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, - {LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, + // Changed to LLM_TENSOR_LAYER_REPEATING because we saved these under a blk with a non-negative id + {LLM_TENSOR_NEXTN_EH_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_NEXTN_EMBED_TOKENS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}}, + {LLM_TENSOR_NEXTN_ENORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}}, + {LLM_TENSOR_NEXTN_HNORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, }; LLM_KV::LLM_KV(llm_arch arch, const char * suffix) : arch(arch), suffix(suffix) {} diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 8698d89acecb2..ff73429301d68 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -275,7 +275,9 @@ bool llama_batch_allocr::init( } } - if (!ok) { + // TEMPORARILY DISABLING THIS SANITY CHECK + // TODO: UNDO THIS IF IT WORKS + /*if (!ok) { LLAMA_LOG_ERROR( "%s: the tokens of sequence %d in the input batch have inconsistent sequence positions:\n" " - the last position stored in the memory module of the context (i.e. the KV cache) for sequence %d is X = %d\n" @@ -284,7 +286,7 @@ bool llama_batch_allocr::init( __func__, s, s, p0, s, seq_pos_min(s)); return false; - } + }*/ } if (seq_pos_max(s) - seq_pos_min(s) + 1 > (int) seq_pos[s].size()) { diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 26a5cf9c3f8db..62d7898b5fe1c 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -6,6 +6,8 @@ #include "llama-memory.h" #include "llama-mmap.h" #include "llama-model.h" +#include "llama-graph.h" +#include "llama-kv-cache-unified.h" #include #include @@ -522,6 +524,18 @@ float * llama_context::get_logits() { return logits; } +void llama_context::set_logits_ith(struct ggml_tensor * logit_override, ggml_backend_sched_t sched_override, int32_t i) { + output_reorder(); + + ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched_override, logit_override); + GGML_ASSERT(backend_res != nullptr); + GGML_ASSERT(logits != nullptr); + + int64_t j = output_ids[i]; + + ggml_backend_tensor_get_async(backend_res, logit_override, logits + j*model.vocab.n_tokens(), 0, model.vocab.n_tokens() * sizeof(float)); +} + float * llama_context::get_logits_ith(int32_t i) { int64_t j = -1; @@ -617,6 +631,10 @@ float * llama_context::get_embeddings_seq(llama_seq_id seq_id) { return it->second.data(); } +ggml_tensor * llama_context::get_embeddings_tensor() { + return embd_tensor; +} + void llama_context::attach_threadpool( ggml_threadpool_t threadpool, ggml_threadpool_t threadpool_batch) { @@ -1113,6 +1131,7 @@ int llama_context::decode(const llama_batch & batch_inp) { auto * t_logits = res->get_logits(); auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr; + embd_tensor = res->get_embd(); if (t_embd && res->get_embd_pooled()) { t_embd = res->get_embd_pooled(); @@ -1429,6 +1448,45 @@ llm_graph_params llama_context::graph_params( }; } +llm_graph_params llama_context::mtp_graph_params( + llm_graph_result * res, + const llama_ubatch& ubatch, + const llama_memory_context_i * mctx) { + size_t n_nodes = std::max(1024u, 8u * 8u * (((model.hparams.nextn_predict_layers + 1) * model.n_tensors()) / model.hparams.n_layer)); + ggml_backend_sched_t temp_sched = create_temp_scheduler(n_nodes); + return { + /*.arch =*/ model.arch, + /*.hparams =*/ model.hparams, + /*.cparams =*/ cparams, + /*.ubatch =*/ ubatch, + /*.gtype =*/ LLM_GRAPH_TYPE_DECODER, + /*.sched =*/ temp_sched, + /*.backend_cpu =*/ backend_cpu, + /*.cvec =*/ &cvec, + /*.loras =*/ &loras, + /*.mctx =*/ mctx, + /*.cross =*/ &cross, + /*.n_outputs =*/ 1, + /*.cb =*/ graph_get_cb(temp_sched), + /*.res =*/ res, + }; +} + +std::unique_ptr llama_context::mtp_memory_batch(const llama_batch& batch_inp) { + const auto& vocab = model.vocab; + const auto& hparams = model.hparams; + + const int64_t n_vocab = vocab.n_tokens(); + const int64_t n_embd = hparams.n_embd; + + if (!balloc->init(batch_inp, vocab, memory.get(), n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, false)) { + LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__); + return nullptr; + } + + return memory->init_batch(*balloc, 1, false); +} + ggml_status llama_context::graph_compute( ggml_cgraph * gf, bool batched) { @@ -1456,8 +1514,10 @@ ggml_status llama_context::graph_compute( return status; } -llm_graph_cb llama_context::graph_get_cb() const { - return [&](const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il) { +llm_graph_cb llama_context::graph_get_cb(ggml_backend_sched * sched_override) const { + ggml_backend_sched * cb_sched = sched_override ? sched_override : sched.get(); + + return [=](const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il) { if (il >= 0) { ggml_format_name(cur, "%s-%d", name, il); } else { @@ -1467,7 +1527,7 @@ llm_graph_cb llama_context::graph_get_cb() const { if (!cparams.offload_kqv) { if (strcmp(name, "kqv_merged_cont") == 0) { // all nodes between the KV store and the attention output are run on the CPU - ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend_cpu); + ggml_backend_sched_set_tensor_backend(cb_sched, cur, backend_cpu); } } @@ -1480,7 +1540,7 @@ llm_graph_cb llama_context::graph_get_cb() const { for (const auto & backend : backends) { if (ggml_backend_get_device(backend.get()) == dev_layer) { if (ggml_backend_supports_op(backend.get(), cur)) { - ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend.get()); + ggml_backend_sched_set_tensor_backend(cb_sched, cur, backend.get()); } } } @@ -1489,6 +1549,10 @@ llm_graph_cb llama_context::graph_get_cb() const { }; } +ggml_backend_sched_t llama_context::create_temp_scheduler(size_t n_nodes) { + return ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), n_nodes, false, cparams.op_offload); +} + // // state save/load // @@ -2233,6 +2297,7 @@ void llama_context::opt_epoch( llama_batch_free(batch); } + // // interface implementation // @@ -2274,6 +2339,8 @@ llama_context_params llama_context_default_params() { return result; } + + llama_context * llama_init_from_model( llama_model * model, llama_context_params params) { @@ -2412,6 +2479,7 @@ float * llama_get_logits_ith(llama_context * ctx, int32_t i) { return ctx->get_logits_ith(i); } + float * llama_get_embeddings(llama_context * ctx) { ctx->synchronize(); @@ -2926,3 +2994,63 @@ void llama_opt_epoch( callback_train, callback_eval); } + +void llama_build_and_execute_mtp_graph(struct llama_context * ctx, + const llama_batch batch_inp, llama_token last_token_id, int32_t n_past, int32_t last_tok_idx) { + + const auto * model = llama_get_model(ctx); + + auto res_mtp = std::make_unique(ctx->graph_max_nodes()); + std::unique_ptr mctx = ctx->mtp_memory_batch(batch_inp); + + std::vector idxs; + idxs.push_back(n_past); + llama_kv_cache_unified::slot_info sinfo = { + /*.s0 =*/ 0, + /*.s1 =*/ 0, + /*.strm =*/ { 0 }, + /*.idxs =*/ { idxs }, + }; + llama_kv_cache_unified::slot_info_vec_t sinfos; + sinfos.push_back(sinfo); + + static_cast(mctx.get())->set_sinfos(sinfos); + const auto& ubatch_mtp = mctx->get_ubatch(); + + //llama_ubatch ubatch_mtp; + //ubatch_mtp.n_tokens = 1; + //ubatch_mtp.pos = &n_past; + + auto params_mtp = std::make_unique(ctx->mtp_graph_params(res_mtp.get(), ubatch_mtp, mctx.get())); + ggml_backend_sched_t sched = params_mtp->sched; + + auto * last_embd = ctx->get_embeddings_ith(last_tok_idx); + + //if (mctx && !mctx->set_n_kv()) { + // LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__); + //} + static_cast(mctx.get())->set_n_kv(); + + auto * gf = model->build_mtp_graph(*params_mtp, last_token_id, n_past); + + ggml_backend_sched_reset(sched); // clear the allocation of the previous graph + ggml_backend_sched_alloc_graph(sched, gf); // explicitly allocate the new graph but do not execute it + + ggml_tensor * mtp_token_id_input = ggml_get_tensor(res_mtp->get_ctx(), "mtp_token_id_input"); + ggml_backend_tensor_set(mtp_token_id_input, &last_token_id, 0, sizeof(last_token_id)); // copy data to the newly allocated graph tensors + + ggml_tensor * mtp_prev_embedding_input = ggml_get_tensor(res_mtp->get_ctx(), "mtp_prev_embedding_input"); + ggml_backend_tensor_set(mtp_prev_embedding_input, last_embd, 0, ggml_nbytes(mtp_prev_embedding_input)); // copy data to the newly allocated graph tensors + + ggml_backend_sched_graph_compute(sched, gf); // execute the graph + + struct ggml_tensor * logits_mtp = res_mtp->get_logits();; + //LLAMA_LOG_INFO("logits_mtp pointer address: %p\n", (void*)logits_mtp); + + if (logits_mtp) { + ctx->set_logits_ith(logits_mtp, sched, last_tok_idx); + } + + ggml_backend_sched_free(sched); +} + diff --git a/src/llama-context.h b/src/llama-context.h index 25c143d56dfb2..e8ea3a4c9be39 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -59,6 +59,7 @@ struct llama_context { float * get_embeddings(); float * get_embeddings_ith(int32_t i); float * get_embeddings_seq(llama_seq_id seq_id); + ggml_tensor * get_embeddings_tensor(); void attach_threadpool( ggml_threadpool_t threadpool, @@ -199,6 +200,14 @@ struct llama_context { // reserve a graph with a dummy ubatch of the specified size ggml_cgraph * graph_reserve(uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx); + llm_graph_params mtp_graph_params(llm_graph_result * res, const llama_ubatch & ubatch, const llama_memory_context_i * mctx); + + void set_logits_ith(struct ggml_tensor * logit_override, ggml_backend_sched_t sched_override, int32_t i); + + ggml_backend_sched_t create_temp_scheduler(size_t n_nodes); + + std::unique_ptr mtp_memory_batch(const llama_batch& batch_inp); + private: llm_graph_params graph_params( llm_graph_result * res, @@ -206,7 +215,7 @@ struct llama_context { const llama_memory_context_i * mctx, llm_graph_type gtype) const; - llm_graph_cb graph_get_cb() const; + llm_graph_cb graph_get_cb(ggml_backend_sched * sched_override = nullptr) const; // TODO: read/write lora adapters and cvec size_t state_write_data(llama_io_write_i & io); @@ -240,6 +249,7 @@ struct llama_context { // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE size_t embd_size = 0; // capacity (of floats) for embeddings float * embd = nullptr; + ggml_tensor * embd_tensor = nullptr; // sequence embeddings output (map of [n_embd] vectors) // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE @@ -308,3 +318,4 @@ struct llama_context { mutable int32_t n_reused = 0; // number of times the previous graph was reused }; + diff --git a/src/llama-graph.h b/src/llama-graph.h index 6ff49de3a1ce8..10702ed219c01 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -818,3 +818,4 @@ struct llm_graph_context { // TODO: better name int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional); + diff --git a/src/llama-kv-cache-unified.cpp b/src/llama-kv-cache-unified.cpp index e539142e6b8cd..53466264cd9a7 100644 --- a/src/llama-kv-cache-unified.cpp +++ b/src/llama-kv-cache-unified.cpp @@ -41,7 +41,7 @@ llama_kv_cache_unified::llama_kv_cache_unified( } if (model.arch == LLM_ARCH_GLM4_MOE) { // GLM-4.5: Only process up to last layer, skip final NextN layer - n_layer_cache = hparams.n_layer - hparams.nextn_predict_layers; + n_layer_cache = hparams.n_layer;// - hparams.nextn_predict_layers; } // create a context for each buffer type @@ -2322,6 +2322,11 @@ bool llama_kv_cache_unified_context::apply() { return true; } +void llama_kv_cache_unified_context::set_n_kv() { + n_kv = kv->get_n_kv(); +} + + llama_memory_status llama_kv_cache_unified_context::get_status() const { return status; } @@ -2384,6 +2389,10 @@ void llama_kv_cache_unified_context::set_input_pos_bucket(ggml_tensor * dst, con kv->set_input_pos_bucket(dst, ubatch); } +void llama_kv_cache_unified_context::set_sinfos(llama_kv_cache_unified::slot_info_vec_t new_sinfos) { + sinfos = new_sinfos; +} + uint32_t llama_kv_cache_unified::get_padding(const llama_cparams & cparams) { // the FA kernels require padding to avoid extra runtime boundary checks return cparams.flash_attn ? 256u : 32u; diff --git a/src/llama-kv-cache-unified.h b/src/llama-kv-cache-unified.h index 342a675962e2a..c02607c2d0f38 100644 --- a/src/llama-kv-cache-unified.h +++ b/src/llama-kv-cache-unified.h @@ -340,6 +340,7 @@ class llama_kv_cache_unified_context : public llama_memory_context_i { // uint32_t get_n_kv() const; + void set_n_kv(); // TODO: temporary bool get_supports_set_rows() const; @@ -362,6 +363,8 @@ class llama_kv_cache_unified_context : public llama_memory_context_i { void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + void set_sinfos(slot_info_vec_t new_sinfos); + private: llama_memory_status status; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 58ca7df707ef3..04743e01f37a2 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -4507,9 +4507,10 @@ bool llama_model::load_tensors(llama_model_loader & ml) { // but only PROCESS up to last layer (skipping final NextN layer) in forward pass for (int i = 0; i < n_layer; ++i) { int flags = 0; + if (hparams.nextn_predict_layers > 0 && static_cast(i) >= n_layer - hparams.nextn_predict_layers) { // skip all tensors in the NextN layers - flags |= TENSOR_SKIP; + // flags |= TENSOR_SKIP; } auto & layer = layers[i]; @@ -4573,12 +4574,37 @@ bool llama_model::load_tensors(llama_model_loader & ml) { // NextN/MTP tensors (preserved but unused) - conditionally load for last nextn_predict_layers if (hparams.nextn_predict_layers > 0 && static_cast(i) >= n_layer - hparams.nextn_predict_layers) { + + // our input/output layer sanity check prevents us from loading the eh_proj layer! + // this is because eh_proj is labelled with a layer number in existing GGUFs, + // so we need to set bid == to successfully load the tensors, but our io layer sanity check requires bid == -1. + // this function is a hack that creates the nextn layers as LLM_TENSOR_LAYER_REPEATING instead. + /* auto create_tensor_override_io_sanity_check = + [&](llm_tensor type_enum, const char * suffix, int bid, const std::initializer_list& ne, int flags) -> ggml_tensor * { + + auto tn_orig = tn(type_enum, suffix, bid); + llm_tensor_info info_override = *tn_orig.info; + info_override.layer = LLM_TENSOR_LAYER_REPEATING; + + auto tn_override = tn_orig; + tn_override.info = &info_override; + + return create_tensor(tn_override, ne, flags); + };*/ + layer.nextn.eh_proj = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), { 2 * n_embd, n_embd }, flags); layer.nextn.embed_tokens = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS, "weight", i), { n_embd, n_vocab }, flags); layer.nextn.enorm = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), { n_embd }, flags); layer.nextn.hnorm = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), { n_embd }, flags); layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, flags); layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, flags); + + // layer.nextn.eh_proj = create_tensor_override_io_sanity_check(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i, { 2 * n_embd, n_embd }, flags); + // layer.nextn.embed_tokens = create_tensor_override_io_sanity_check(LLM_TENSOR_NEXTN_EMBED_TOKENS, "weight", i, { n_embd, n_vocab }, flags); + // layer.nextn.enorm = create_tensor_override_io_sanity_check(LLM_TENSOR_NEXTN_ENORM, "weight", i, { n_embd }, flags); + // layer.nextn.hnorm = create_tensor_override_io_sanity_check(LLM_TENSOR_NEXTN_HNORM, "weight", i, { n_embd }, flags); + // layer.nextn.shared_head_head = create_tensor_override_io_sanity_check(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i, { n_embd, n_vocab }, flags); + // layer.nextn.shared_head_norm = create_tensor_override_io_sanity_check(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i, { n_embd }, flags); } } } @@ -13919,6 +13945,164 @@ struct llm_build_glm4_moe : public llm_graph_context { } }; +struct llm_build_glm4_moe_mtp : public llm_graph_context { + llm_build_glm4_moe_mtp(const llama_model & model, const llm_graph_params & params, + // For v0, let's rebuild the computational graph for every step + this mimics the vLLM impl parameterization + llama_token last_token_id, int n_past + ) : llm_graph_context(params) { + const int64_t n_embd_head = hparams.n_embd_head_v; + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k); + + // Assuming a single MTP layer at the end + const int il = hparams.n_layer - 1; + const auto & mtp_layer = model.layers[il]; + + // ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1); + // ggml_set_i32(inp_pos, n_past); + ggml_tensor * inp_pos = build_inp_pos(); + + //llm_graph_input_attn_no_cache * inp_attn = build_attn_inp_no_cache();//nullptr; + auto * inp_attn = build_attn_inp_kv_unified(); + + ggml_tensor * cur; + + // get MTP embedding for last (conventionally sampled) token + // ggml_tensor * inp_token_id = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1); + // LLAMA_LOG_INFO("step: '%d'\n", 5641); + // ggml_set_i32(inp_token_id, last_token_id); + //ggml_set_no_alloc(ctx0, false); + //LLAMA_LOG_INFO("last token id: '%d'\n", last_token_id); + + ggml_tensor * inp_token_id = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1); + ggml_set_name(inp_token_id, "mtp_token_id_input"); + ggml_set_input(inp_token_id); + + //ggml_tensor * inp_token_id = ggml_new_i32(ctx0, last_token_id); + //ggml_set_no_alloc(ctx0, true); + + ggml_tensor * token_emb = ggml_get_rows(ctx0, mtp_layer.nextn.embed_tokens, inp_token_id); + ggml_tensor * token_emb_norm = build_norm(token_emb, mtp_layer.nextn.enorm, NULL, LLM_NORM_RMS, il); + + ggml_tensor* prev_embedding_leaf = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, model.hparams.n_embd); + ggml_set_name(prev_embedding_leaf, "mtp_prev_embedding_input"); + ggml_set_input(prev_embedding_leaf); + + // vLLM l99 previous_hidden_states = self.hnorm(previous_hidden_states) + ggml_tensor * hidden_state_norm = build_norm(prev_embedding_leaf, mtp_layer.nextn.hnorm, NULL, LLM_NORM_RMS, il); + //token_emb_norm = ggml_cont(ctx0, token_emb_norm); + //hidden_state_norm = ggml_cont(ctx0, hidden_state_norm); + + ggml_tensor * combined = ggml_concat(ctx0, token_emb_norm, hidden_state_norm, 0); // torch.cat + + + cur = build_lora_mm(mtp_layer.nextn.eh_proj, combined); // eh_proj + + + // now proceed through last layer (skipped in main model) + ggml_tensor * inpSA = cur; + + // Pre-attention norm for the MTP block + ggml_tensor* attn_inp = build_norm(cur, mtp_layer.attn_norm, NULL, LLM_NORM_RMS, il); + + // self-attention + { + ggml_tensor * Qcur = build_lora_mm(mtp_layer.wq, cur); + if (mtp_layer.bq) { + Qcur = ggml_add(ctx0, Qcur, mtp_layer.bq); + } + cb(Qcur, "Qcur", il); + + ggml_tensor * Kcur = build_lora_mm(mtp_layer.wk, cur); + if (mtp_layer.bk) { + Kcur = ggml_add(ctx0, Kcur, mtp_layer.bk); + } + cb(Kcur, "Kcur", il); + + ggml_tensor * Vcur = build_lora_mm(mtp_layer.wv, cur); + if (mtp_layer.bv) { + Vcur = ggml_add(ctx0, Vcur, mtp_layer.bv); + } + cb(Vcur, "Vcur", il); + + Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens); + Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens); + Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens); + + // Apply Q/K norm if available (GLM-4.5 355B variant) + if (mtp_layer.attn_q_norm) { + Qcur = build_norm(Qcur, mtp_layer.attn_q_norm, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + } + if (mtp_layer.attn_k_norm) { + Kcur = build_norm(Kcur, mtp_layer.attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Kcur, "Kcur_normed", il); + } + + Qcur = ggml_rope_ext( + ctx0, Qcur, inp_pos, nullptr, + n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, + ext_factor, attn_factor, beta_fast, beta_slow + ); + + Kcur = ggml_rope_ext( + ctx0, Kcur, inp_pos, nullptr, + n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, + ext_factor, attn_factor, beta_fast, beta_slow + ); + + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + + cur = build_attn(inp_attn, + mtp_layer.wo, NULL, + Qcur, Kcur, Vcur, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); + + cur = build_norm(ffn_inp, mtp_layer.attn_post_norm, NULL, LLM_NORM_RMS, il); + + // moe ffn for nextn block + { + // Process routed experts using existing MoE infrastructure + ggml_tensor * routed_out = build_moe_ffn(cur, + mtp_layer.ffn_gate_inp, + mtp_layer.ffn_up_exps, + mtp_layer.ffn_gate_exps, + mtp_layer.ffn_down_exps, + mtp_layer.ffn_exp_probs_b, + n_expert, n_expert_used, + LLM_FFN_SILU, hparams.expert_weights_norm, + true, hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il); + cb(routed_out, "ffn_moe_out", il); + + // Process shared expert on original input + ggml_tensor * shared_out = build_ffn(cur, + mtp_layer.ffn_up_shexp, NULL, NULL, + mtp_layer.ffn_gate_shexp, NULL, NULL, + mtp_layer.ffn_down_shexp, NULL, NULL, + NULL, + LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(shared_out, "ffn_shexp_out", il); + + // Final output: routed_output + shared_output + cur = ggml_add(ctx0, routed_out, shared_out); + cb(cur, "ffn_out", il); + } + cur = ggml_add(ctx0, cur, ffn_inp); + + cur = build_norm(cur, mtp_layer.nextn.shared_head_norm, NULL, LLM_NORM_RMS, il); + cur = build_lora_mm(mtp_layer.nextn.shared_head_head, cur); + + res->t_logits = cur; + + ggml_build_forward_expand(gf, res->t_logits); + } +}; + struct llm_build_nemotron : public llm_graph_context { llm_build_nemotron(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) { const int64_t n_embd_head = hparams.n_embd_head_v; @@ -18509,6 +18693,22 @@ ggml_cgraph * llama_model::build_graph(const llm_graph_params & params) const { return llm->res->get_gf(); } +ggml_cgraph * llama_model::build_mtp_graph(const llm_graph_params& params, + llama_token last_token_id, int n_past) const { + std::unique_ptr llm; + + switch (arch) { + case LLM_ARCH_GLM4_MOE: + { + llm = std::make_unique(*this, params, last_token_id, n_past); + } break; + default: + GGML_ABORT("fatal error"); + } + + return llm->res->get_gf(); +} + // // interface implementation // @@ -18587,6 +18787,10 @@ const char * llama_model_cls_label(const struct llama_model * model, uint32_t i) return nullptr; } +int32_t llama_model_n_nextn_layer(const llama_model * model) { + return model->hparams.nextn_predict_layers; +} + // deprecated int32_t llama_n_ctx_train(const llama_model * model) { return llama_model_n_ctx_train(model); @@ -18820,3 +19024,4 @@ bool llama_model_is_diffusion(const llama_model * model) { const std::vector> & llama_internal_get_tensor_map(const llama_model * model) { return model->tensors_by_name; } + diff --git a/src/llama-model.h b/src/llama-model.h index 6fcd74d57fdca..b28a37488f78a 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -475,6 +475,8 @@ struct llama_model { // TODO: move this to new llm_arch_model_i interface ggml_cgraph * build_graph(const llm_graph_params & params) const; + ggml_cgraph * build_mtp_graph(const llm_graph_params & params, + llama_token last_token_id, int n_past) const; private: struct impl; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index a255d481a4d1c..1191564dd2ba3 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -1278,6 +1278,7 @@ struct server_task_result_apply_lora : server_task_result { } }; + struct server_slot { int id; int id_task = -1; @@ -1294,6 +1295,9 @@ struct server_slot { mtmd_context * mctx = nullptr; common_speculative * spec = nullptr; + bool has_mtp = false; + std::vector mtp_kv_update_batch; + int32_t last_tok_idx = -1; std::vector lora; @@ -1391,7 +1395,7 @@ struct server_slot { } bool need_embd() const { - return server_task_type_need_embd(task_type); + return server_task_type_need_embd(task_type) || has_mtp; } bool need_logits() const { @@ -1431,7 +1435,8 @@ struct server_slot { } bool can_speculate() const { - return ctx_dft && params.speculative.n_max > 0 && params.cache_prompt; + return (ctx_dft || has_mtp) && params.speculative.n_max > 0 && params.cache_prompt; + // return (ctx_dft) && params.speculative.n_max > 0 && params.cache_prompt; } void add_token(const completion_token_output & token) { @@ -1566,6 +1571,7 @@ struct server_slot { } }; + struct server_metrics { int64_t t_start = 0; @@ -2122,6 +2128,22 @@ struct server_context { } } + // if model has MTP and no draft model is specified... + else if (llama_model_n_nextn_layer(model) > 0) { + SRV_INF("model has nextn layers = %d\n", llama_model_n_nextn_layer(model)); + slot.has_mtp = true; + + // assume one speculative token (true of all well-known MTP models so far) + slot.batch_spec = llama_batch_init(2, 0, 1); + SLT_DBG(slot, "batch_spec contains %d tokens\n", slot.batch_spec.n_tokens); + + params_base.speculative.n_min = 0; + params_base.speculative.n_max = 1; + + SRV_INF("%s\n", "MTP needs embeddings on decode, enabling"); + llama_set_embeddings(ctx, true); + } + SLT_INF(slot, "new slot n_ctx_slot = %d\n", slot.n_ctx); slot.params.sampling = params_base.sampling; @@ -3367,7 +3389,11 @@ struct server_context { // embedding requires all tokens in the batch to be output const bool need_embd = server_task_type_need_embd(slot.task_type); + if (slot.has_mtp) { + slot.mtp_kv_update_batch.push_back({ cur_tok, slot.n_past, batch.n_tokens }); + } common_batch_add(batch, cur_tok, slot.n_past, { slot.id }, need_embd); + slot.cache_tokens.push_back(cur_tok); slot.n_prompt_tokens_processed++; @@ -3518,11 +3544,18 @@ struct server_context { const int tok_idx = slot.i_batch - i; llama_token id = common_sampler_sample(slot.smpl, ctx, tok_idx); + slot.last_tok_idx = tok_idx; + //SRV_INF("main loop sampled token: '%s'\n", common_token_to_piece(ctx, id, true).c_str()); slot.i_batch = -1; common_sampler_accept(slot.smpl, id, true); + // This should only trigger on a non-empty update batch once, after prompt processing but not during token generation + if (slot.has_mtp) { + mtp_update_kv_cache(ctx, slot.mtp_kv_update_batch); + } + slot.n_decoded += 1; const int64_t t_current = ggml_time_us(); @@ -3590,23 +3623,38 @@ struct server_context { llama_token id = slot.sampled; - struct common_speculative_params params_spec; - params_spec.n_draft = n_draft_max; - params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.params.speculative.n_max; - params_spec.p_min = slot.params.speculative.p_min; + llama_tokens draft; + if (slot.has_mtp) { + llama_token draft_id = mtp_speculative_gen_draft(slot.smpl, ctx, id, slot.n_past, slot.last_tok_idx); + draft.reserve(1); + draft.push_back(draft_id); + } + else { + struct common_speculative_params params_spec; + params_spec.n_draft = n_draft_max; + params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.params.speculative.n_max; + params_spec.p_min = slot.params.speculative.p_min; - const llama_tokens & cached_text_tokens = slot.cache_tokens.get_text_tokens(); - llama_tokens draft = common_speculative_gen_draft(slot.spec, params_spec, cached_text_tokens, id); + const llama_tokens& cached_text_tokens = slot.cache_tokens.get_text_tokens(); + + draft = common_speculative_gen_draft(slot.spec, params_spec, cached_text_tokens, id); + } + + //llama_token draft_id = mtp_speculative_gen_draft(slot.smpl, ctx, id, slot.n_past, slot.last_tok_idx); + //llama_tokens draft; + //draft.reserve(1); + //draft.push_back(draft_id); // ignore small drafts - if (slot.params.speculative.n_min > (int) draft.size()) { - SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int) draft.size(), slot.params.speculative.n_min); + if (slot.params.speculative.n_min > (int)draft.size()) { + SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int)draft.size(), slot.params.speculative.n_min); continue; } // keep track of total number of drafted tokens tested slot.n_draft_total += draft.size(); + SLT_DBG(slot, "draft size = %d\n", draft.size()); // construct the speculation batch common_batch_clear(slot.batch_spec); @@ -3623,6 +3671,13 @@ struct server_context { // the accepted tokens from the speculation const auto ids = common_sampler_sample_and_accept_n(slot.smpl, ctx, draft); + if (slot.has_mtp) { + for (int32_t i = 0; i < ids.size(); ++i) { + slot.mtp_kv_update_batch.push_back({ ids[i], slot.n_past + 1 + i, i }); + } + mtp_update_kv_cache(ctx, slot.mtp_kv_update_batch); + } + slot.n_past += ids.size(); slot.n_decoded += ids.size();