Team Ai
Datasetpublic

Brunobkr/llama.cpp_AlgMor24_github

ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes3.1kdownloads
step35.cpp561 linesDownload Raw Back to models
1#include "models.h"2 3void llama_model_step35::load_arch_hparams(llama_model_loader & ml) {4    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);5 6    hparams.swa_type = LLAMA_SWA_TYPE_STANDARD;7 8    // full_attention layer only use half of the RoPE dimensions9    hparams.n_rot_full = hparams.n_rot_full / 2;10 11    // MoE + SWA parameters12    ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH,        hparams.n_ff_exp);13    ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);14    ml.get_key(LLM_KV_EXPERT_GATING_FUNC,                hparams.expert_gating_func, false);15    ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE,              hparams.expert_weights_scale, false);16    ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM,               hparams.expert_weights_norm, false);17 18    // Step35 uses sigmoid gating by default (if not set in GGUF)19    if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) {20        hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID;21    }22 23    ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW,  hparams.n_swa);24    ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA,        hparams.rope_freq_base_train_swa, false);25 26    ml.get_key_or_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl, hparams.n_layer());27 28    ml.get_key_or_arr(LLM_KV_SWIGLU_CLAMP_EXP,   hparams.swiglu_clamp_exp,   hparams.n_layer(), false);29    ml.get_key_or_arr(LLM_KV_SWIGLU_CLAMP_SHEXP, hparams.swiglu_clamp_shexp, hparams.n_layer(), false);30 31    // NextN/MTP (Step3p5): extra decoder block appended beyond the main stack.32    ml.get_key(LLM_KV_NEXTN_PREDICT_LAYERS, hparams.n_layer_nextn, false);33    GGML_ASSERT(hparams.n_layer_nextn < hparams.n_layer_all && "n_layer_nextn must be < n_layer_impl");34 35    switch (hparams.n_layer()) {36        case 45: type = LLM_TYPE_196B_A11B; break;37        default: type = LLM_TYPE_UNKNOWN;38    }39}40 41void llama_model_step35::load_arch_tensors(llama_model_loader & ml) {42    LLAMA_LOAD_LOCALS;43 44    const bool mtp_only = (hparams.n_layer_nextn > 0) && (ml.get_weight("blk.0.attn_norm.weight") == nullptr);45    // Trunk-only: the GGUF declares MTP layers in metadata but the actual MTP46    // tensors live in a separate file (e.g. user split target/draft). Mark47    // MTP tensors NOT_REQUIRED so the trunk loads cleanly.48    const std::string mtp_probe = "blk." + std::to_string(n_layer) + ".nextn.eh_proj.weight";49    const bool trunk_only = (hparams.n_layer_nextn > 0) && (ml.get_weight(mtp_probe.c_str()) == nullptr);50    const int trunk_flags = mtp_only  ? TENSOR_NOT_REQUIRED : 0;51    int mtp_flags         = trunk_only ? TENSOR_NOT_REQUIRED : 0;52 53    if (!ml.load_mtp) {54        mtp_flags |= TENSOR_SKIP;55    }56 57    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);58 59    // output60    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);61    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), {n_embd, n_vocab}, trunk_flags);62 63    // STEP35 supports per-layer partial RoPE dims; rope factors are stored as a single shared tensor64    // ("rope_freqs.weight") and ggml uses only the first (n_rot_l/2) entries per layer.65    uint32_t n_rot_max = 0;66    for (int i = 0; i < n_layer; ++i) {67        n_rot_max = std::max(n_rot_max, hparams.n_rot(i));68    }69    if (n_rot_max == 0) {70        n_rot_max = n_rot;71    }72 73    auto load_block_trunk = [&](int i, int flags) {74        auto & layer = layers[i];75 76        const uint32_t n_head_l      = hparams.n_head(i);77        const uint32_t n_embd_k_gqa  = hparams.n_embd_k_gqa(i);78        const uint32_t n_embd_v_gqa  = hparams.n_embd_v_gqa(i);79 80        layer.attn_norm   = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, flags);81        layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, TENSOR_NOT_REQUIRED);82        layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, TENSOR_NOT_REQUIRED);83 84        // optional rope factors (llama3) / longrope tensors85        if (hparams.rope_scaling_type_train == LLAMA_ROPE_SCALING_TYPE_LONGROPE) {86            layer.rope_long  = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_LONG,  "weight", i), {n_rot_max/2}, TENSOR_NOT_REQUIRED | (i != 0 ? TENSOR_DUPLICATED : 0));87            layer.rope_short = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight", i), {n_rot_max/2}, TENSOR_NOT_REQUIRED | (i != 0 ? TENSOR_DUPLICATED : 0));88        } else {89            layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot_max/2}, TENSOR_NOT_REQUIRED | (i != 0 ? TENSOR_DUPLICATED : 0));90        }91 92        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head_l, n_embd_k_gqa, n_embd_v_gqa, flags);93        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_v * n_head_l, n_embd}, flags);94 95        // head-wise attention gate (Step35 self_attn.g_proj)96        layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head_l}, TENSOR_NOT_REQUIRED);97 98        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, flags);99 100        // dense MLP (leading dense blocks)101        layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd,   n_ff}, TENSOR_NOT_REQUIRED);102        layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {  n_ff, n_embd}, TENSOR_NOT_REQUIRED);103        layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd,   n_ff}, TENSOR_NOT_REQUIRED);104 105        // MoE routed experts + selection bias (router_bias)106        const int64_t n_ff_exp = hparams.n_ff_exp;107        layer.ffn_gate_inp      = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,  "weight", i), {n_embd, n_expert}, TENSOR_NOT_REQUIRED);108        layer.ffn_gate_exps     = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp,   n_expert}, TENSOR_NOT_REQUIRED);109        layer.ffn_down_exps     = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp,   n_embd, n_expert}, TENSOR_NOT_REQUIRED);110        layer.ffn_up_exps       = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS,   "weight", i), {n_embd, n_ff_exp,   n_expert}, TENSOR_NOT_REQUIRED);111        layer.ffn_exp_probs_b   = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED);112 113        // shared expert MLP114        layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, hparams.n_ff_shexp}, TENSOR_NOT_REQUIRED);115        layer.ffn_up_shexp   = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {n_embd, hparams.n_ff_shexp}, TENSOR_NOT_REQUIRED);116        layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {hparams.n_ff_shexp, n_embd}, TENSOR_NOT_REQUIRED);117    };118 119    auto load_block_mtp = [&](int i) {120        auto & layer = layers[i];121 122        const uint32_t n_head_l      = hparams.n_head(i);123        const uint32_t n_embd_k_gqa  = hparams.n_embd_k_gqa(i);124        const uint32_t n_embd_v_gqa  = hparams.n_embd_v_gqa(i);125 126        // The MTP block is a full Step3p5 decoder layer (mtp_block) plus the127        // NextN-specific wiring (enorm/hnorm/eh_proj + optional shared head).128        // Multi-block MTP: every declared MTP block is required (the draft chain129        // runs all n_layer_nextn heads), so each block uses the captured130        // `mtp_flags` directly — already NOT_REQUIRED for a trunk-only GGUF,131        // which keeps that path correct.132 133        layer.attn_norm   = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, mtp_flags);134        layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, TENSOR_NOT_REQUIRED);135        layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, TENSOR_NOT_REQUIRED);136 137        if (hparams.rope_scaling_type_train == LLAMA_ROPE_SCALING_TYPE_LONGROPE) {138            layer.rope_long  = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_LONG,  "weight", i), {n_rot_max/2}, TENSOR_NOT_REQUIRED | TENSOR_DUPLICATED);139            layer.rope_short = create_tensor(tn(LLM_TENSOR_ROPE_FACTORS_SHORT, "weight", i), {n_rot_max/2}, TENSOR_NOT_REQUIRED | TENSOR_DUPLICATED);140        } else {141            layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot_max/2}, TENSOR_NOT_REQUIRED | TENSOR_DUPLICATED);142        }143 144        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head_l, n_embd_k_gqa, n_embd_v_gqa, mtp_flags);145        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_v * n_head_l, n_embd}, mtp_flags);146 147        layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head_l}, TENSOR_NOT_REQUIRED);148 149        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, mtp_flags);150 151        // dense MLP (leading dense blocks) — present if the MTP block isn't MoE152        layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd,   n_ff}, TENSOR_NOT_REQUIRED);153        layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {  n_ff, n_embd}, TENSOR_NOT_REQUIRED);154        layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd,   n_ff}, TENSOR_NOT_REQUIRED);155 156        // MoE routed experts + selection bias (router_bias)157        const int64_t n_ff_exp = hparams.n_ff_exp;158        layer.ffn_gate_inp      = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,  "weight", i), {n_embd, n_expert}, TENSOR_NOT_REQUIRED);159        layer.ffn_gate_exps     = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp,   n_expert}, TENSOR_NOT_REQUIRED);160        layer.ffn_down_exps     = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp,   n_embd, n_expert}, TENSOR_NOT_REQUIRED);161        layer.ffn_up_exps       = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS,   "weight", i), {n_embd, n_ff_exp,   n_expert}, TENSOR_NOT_REQUIRED);162        layer.ffn_exp_probs_b   = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED);163 164        layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, hparams.n_ff_shexp}, TENSOR_NOT_REQUIRED);165        layer.ffn_up_shexp   = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {n_embd, hparams.n_ff_shexp}, TENSOR_NOT_REQUIRED);166        layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {hparams.n_ff_shexp, n_embd}, TENSOR_NOT_REQUIRED);167 168        // NextN-specific tensors that define the MTP block.169        layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ,          "weight", i), { 2 * n_embd, n_embd }, mtp_flags);170        layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM,            "weight", i), { n_embd },              mtp_flags);171        layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM,            "weight", i), { n_embd },              mtp_flags);172        layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS,     "weight", i), { n_embd, n_vocab },     TENSOR_NOT_REQUIRED);173        layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab },     TENSOR_NOT_REQUIRED);174        layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd },              TENSOR_NOT_REQUIRED);175    };176 177    for (int i = 0; i < n_layer; ++i) {178        load_block_trunk(i, trunk_flags);179    }180    // All n_layer_nextn MTP blocks are required — the multi-block draft chain181    // runs every head (head k at offset k). The GGUF declares the count via182    // step35.nextn_predict_layers.183    for (int i = n_layer; i < n_layer_all; ++i) {184        load_block_mtp(i);185    }186}187 188std::unique_ptr<llm_graph_context> llama_model_step35::build_arch_graph(const llm_graph_params & params) const {189    if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) {190        return std::make_unique<graph_mtp>(*this, params);191    }192    return std::make_unique<graph>(*this, params);193}194 195llama_model_step35::graph::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) {196    ggml_tensor * cur;197    ggml_tensor * inpL;198 199    inpL = build_inp_embd(model.tok_embd);200    ggml_tensor * inp_pos     = build_inp_pos();201    auto        * inp_attn    = build_attn_inp_kv_iswa();202    ggml_tensor * inp_out_ids = build_inp_out_ids();203 204    // MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass.205    for (int il = 0; il < n_layer; ++il) {206        ggml_tensor * inpSA = inpL;207 208        const uint32_t n_head_l    = hparams.n_head(il);209        const uint32_t n_head_kv_l = hparams.n_head_kv(il);210 211        const float freq_base_l  = model.get_rope_freq_base(cparams, il);212        const float freq_scale_l = model.get_rope_freq_scale(cparams, il);213 214        cur = inpL;215 216        // dump pre-attn RMSNorm input to pinpoint layer boundary issues217        cb(cur, "attn_norm_in", il);218 219        // self-attention220        {221            cur = build_norm(cur, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);222            cb(cur, "attn_norm", il);223            ggml_tensor * Qcur = build_lora_mm(model.layers[il].wq, cur);224            ggml_tensor * Kcur = build_lora_mm(model.layers[il].wk, cur);225            ggml_tensor * Vcur = build_lora_mm(model.layers[il].wv, cur);226 227            cb(Qcur, "Qcur", il);228            cb(Kcur, "Kcur", il);229            cb(Vcur, "Vcur", il);230 231            Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head_l,    n_tokens);232            Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv_l, n_tokens);233            Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head_v, n_head_kv_l, n_tokens);234 235            // Q/K per-head RMSNorm (Step35 q_norm / k_norm)236            if (model.layers[il].attn_q_norm) {237                Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, nullptr, LLM_NORM_RMS, il);238                cb(Qcur, "Qcur_normed", il);239            }240            if (model.layers[il].attn_k_norm) {241                Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, nullptr, LLM_NORM_RMS, il);242                cb(Kcur, "Kcur_normed", il);243            }244 245            // RoPE (partial rotary factors per layer)246            const bool is_swa = hparams.is_swa(il);247            ggml_tensor * rope_factors = is_swa ? nullptr : model.get_rope_factors(cparams, il);248            const int64_t n_rot_l = hparams.n_rot(il);249            Qcur = ggml_rope_ext(250                ctx0, Qcur, inp_pos, rope_factors,251                n_rot_l, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,252                ext_factor, attn_factor, beta_fast, beta_slow253            );254            Kcur = ggml_rope_ext(255                ctx0, Kcur, inp_pos, rope_factors,256                n_rot_l, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,257                ext_factor, attn_factor, beta_fast, beta_slow258            );259            cb(Qcur, "Qcur_pos", il);260            cb(Kcur, "Kcur_pos", il);261 262            const float kq_scale = 1.0f / sqrtf(float(n_embd_head_k));263            ggml_tensor * attn_out = build_attn(inp_attn,264                    nullptr, nullptr, nullptr,265                    Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);266            cb(attn_out, "attn_out", il);267            // head-wise attention gate: sigmoid(g_proj(x)) in torch268            if (model.layers[il].wqkv_gate) {269                ggml_tensor * gate = build_lora_mm(model.layers[il].wqkv_gate, cur); // [n_head_l, n_tokens]270                cb(gate, "attn_gate", il);271 272                gate = ggml_sigmoid(ctx0, gate);273                cb(gate, "attn_gate_sigmoid", il);274 275                // reshape + broadcast to [n_embd_head_v, n_head_l, n_tokens]276                ggml_tensor * attn_3d = ggml_reshape_3d(ctx0, attn_out, n_embd_head_v, n_head_l, n_tokens);277                ggml_tensor * gate_3d = ggml_reshape_3d(ctx0, gate,       1,          n_head_l, n_tokens);278                cb(gate_3d, "attn_gate_3d", il);279 280                attn_3d = ggml_mul(ctx0, attn_3d, gate_3d);281                cb(attn_3d, "attn_gated_3d", il);282 283                attn_out = ggml_reshape_2d(ctx0, attn_3d, n_embd_head_v * n_head_l, n_tokens);284                cb(attn_out, "attn_gated", il);285            }286 287            // output projection288            cur = build_lora_mm(model.layers[il].wo, attn_out, model.layers[il].wo_s);289            cb(cur, "attn_proj", il);290        }291 292        if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked) {293            cur   = ggml_get_rows(ctx0, cur, inp_out_ids);294            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);295        }296 297        ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);298        cb(ffn_inp, "ffn_inp", il);299 300        cur = build_norm(ffn_inp, model.layers[il].ffn_norm, nullptr, LLM_NORM_RMS, il);301        cb(cur, "ffn_norm", il);302 303        // feed-forward304        if (model.layers[il].ffn_gate_inp == nullptr) {305            // dense MLP306            cur = build_ffn(cur,307                    model.layers[il].ffn_up,   model.layers[il].ffn_up_b,   nullptr,308                    model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, nullptr,309                    model.layers[il].ffn_down, model.layers[il].ffn_down_b, nullptr,310                    nullptr,311                    LLM_FFN_SILU, LLM_FFN_PAR, il);312            cb(cur, "ffn_out", il);313        } else {314            // MoE routed experts315            ggml_tensor * moe_out = build_moe_ffn(cur,316                    model.layers[il].ffn_gate_inp,317                    model.layers[il].ffn_up_exps,318                    model.layers[il].ffn_gate_exps,319                    model.layers[il].ffn_down_exps,320                    model.layers[il].ffn_exp_probs_b,321                    n_expert, n_expert_used,322                    LLM_FFN_SILU, hparams.expert_weights_norm,323                    hparams.expert_weights_scale,324                    (llama_expert_gating_func_type) hparams.expert_gating_func,325                    il);326            cb(moe_out, "ffn_moe_out", il);327 328            // shared expert MLP (always added on MoE layers in Step35)329            ggml_tensor * sh_out = build_ffn(cur,330                    model.layers[il].ffn_up_shexp,   nullptr, nullptr,331                    model.layers[il].ffn_gate_shexp, nullptr, nullptr,332                    model.layers[il].ffn_down_shexp, nullptr, nullptr,333                    nullptr,334                    LLM_FFN_SILU, LLM_FFN_PAR, il);335            cb(sh_out, "ffn_shared_out", il);336 337            cur = ggml_add(ctx0, moe_out, sh_out);338            cb(cur, "ffn_out", il);339        }340        cur = ggml_add(ctx0, cur, ffn_inp);341 342        cur = build_cvec(cur, il);343        cb(cur, "l_out", il);344 345        // input for next layer346        inpL = cur;347    }348 349    cur = inpL;350 351    cb(cur, "h_nextn", -1);352    res->t_h_nextn = cur;353 354    if (!cparams.embeddings_nextn_masked && inp_out_ids) {355        cur = ggml_get_rows(ctx0, cur, inp_out_ids);356    }357 358    cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1);359    cb(cur, "result_norm", -1);360    res->t_embd = cur;361 362    cur = build_lora_mm(model.output, cur, model.output_s);363    cb(cur, "result_output", -1);364    res->t_logits = cur;365 366    ggml_build_forward_expand(gf, cur);367}368 369// LLM_GRAPH_TYPE_DECODER_MTP draft head for Step3p5 (MoE)370llama_model_step35::graph_mtp::graph_mtp(const llama_model & model, const llm_graph_params & params)371    : llm_graph_context(params) {372    GGML_ASSERT(hparams.n_layer_nextn > 0 && "STEP35 MTP requires n_layer_nextn > 0");373 374    // Multi-block MTP: the DECODER_MTP graph runs the MTP head selected by375    // cparams.nextn_layer_offset (0 = first trained head). The speculative driver376    // bumps the offset per draft step to chain heads 45->46->47. offset 0 keeps377    // single-block behavior identical to before.378    const int il = hparams.n_layer() + cparams.nextn_layer_offset;379    GGML_ASSERT(cparams.nextn_layer_offset >= 0 &&380                cparams.nextn_layer_offset < (int) hparams.n_layer_nextn &&381                "nextn_layer_offset out of range [0, n_layer_nextn)");382    const auto & layer = model.layers[il];383 384    GGML_ASSERT(layer.nextn.eh_proj && "MTP block missing nextn.eh_proj");385    GGML_ASSERT(layer.nextn.enorm   && "MTP block missing nextn.enorm");386    GGML_ASSERT(layer.nextn.hnorm   && "MTP block missing nextn.hnorm");387 388    const uint32_t n_head_l    = hparams.n_head(il);389    const uint32_t n_head_kv_l = hparams.n_head_kv(il);390 391    const float freq_base_l  = model.get_rope_freq_base(cparams, il);392    const float freq_scale_l = model.get_rope_freq_scale(cparams, il);393 394    auto inp = std::make_unique<llm_graph_input_embd>(hparams.n_embd);395 396    inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);397    ggml_set_input(inp->tokens);398 399    inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd, n_tokens);400    ggml_set_input(inp->embd);401    ggml_set_name(inp->embd, "mtp_h_input");402 403    ggml_tensor * tok_embd_w = layer.nextn.embed_tokens ? layer.nextn.embed_tokens : model.tok_embd;404 405    ggml_tensor * h_input  = inp->embd;406    ggml_tensor * tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens);407    cb(tok_embd, "mtp_tok_embd", il);408 409    res->add_input(std::move(inp));410 411    ggml_tensor * inp_pos  = build_inp_pos();412    auto        * inp_attn = build_attn_inp_kv_iswa();413 414    ggml_tensor * h_norm = build_norm(h_input, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il);415    cb(h_norm, "mtp_hnorm", il);416 417    ggml_tensor * e_norm = build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il);418    cb(e_norm, "mtp_enorm", il);419 420    ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, /*dim=*/ 0);421    cb(concat, "mtp_concat", il);422 423    ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat);424    cb(cur, "mtp_eh_proj", il);425 426    ggml_tensor * inpSA = cur;427 428    // mtp_block: full Step3p5 decoder layer (attention with optional head-wise gate, then MoE/dense FFN)429    cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);430    cb(cur, "mtp_attn_norm", il);431 432    ggml_tensor * Qcur = build_lora_mm(layer.wq, cur, layer.wq_s);433    ggml_tensor * Kcur = build_lora_mm(layer.wk, cur, layer.wk_s);434    ggml_tensor * Vcur = build_lora_mm(layer.wv, cur, layer.wv_s);435    cb(Qcur, "mtp_Qcur", il);436    cb(Kcur, "mtp_Kcur", il);437    cb(Vcur, "mtp_Vcur", il);438 439    Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head_l,    n_tokens);440    Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv_l, n_tokens);441    Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head_v, n_head_kv_l, n_tokens);442 443    if (layer.attn_q_norm) {444        Qcur = build_norm(Qcur, layer.attn_q_norm, nullptr, LLM_NORM_RMS, il);445        cb(Qcur, "mtp_Qcur_normed", il);446    }447    if (layer.attn_k_norm) {448        Kcur = build_norm(Kcur, layer.attn_k_norm, nullptr, LLM_NORM_RMS, il);449        cb(Kcur, "mtp_Kcur_normed", il);450    }451 452    const bool    is_swa       = hparams.is_swa(il);453    ggml_tensor * rope_factors = is_swa ? nullptr : model.get_rope_factors(cparams, il);454    const int64_t n_rot_l      = hparams.n_rot(il);455 456    Qcur = ggml_rope_ext(457        ctx0, Qcur, inp_pos, rope_factors,458        n_rot_l, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,459        ext_factor, attn_factor, beta_fast, beta_slow);460    Kcur = ggml_rope_ext(461        ctx0, Kcur, inp_pos, rope_factors,462        n_rot_l, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,463        ext_factor, attn_factor, beta_fast, beta_slow);464    cb(Qcur, "mtp_Qcur_pos", il);465    cb(Kcur, "mtp_Kcur_pos", il);466 467    const float kq_scale = 1.0f / sqrtf(float(n_embd_head_k));468    ggml_tensor * attn_out = build_attn(inp_attn,469            nullptr, nullptr, nullptr,470            Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);471    cb(attn_out, "mtp_attn_out", il);472 473    // head-wise attention gate: sigmoid(g_proj(x))474    if (layer.wqkv_gate) {475        ggml_tensor * gate = build_lora_mm(layer.wqkv_gate, cur); // [n_head_l, n_tokens]476        cb(gate, "mtp_attn_gate", il);477 478        gate = ggml_sigmoid(ctx0, gate);479        cb(gate, "mtp_attn_gate_sigmoid", il);480 481        ggml_tensor * attn_3d = ggml_reshape_3d(ctx0, attn_out, n_embd_head_v, n_head_l, n_tokens);482        ggml_tensor * gate_3d = ggml_reshape_3d(ctx0, gate,       1,           n_head_l, n_tokens);483        cb(gate_3d, "mtp_attn_gate_3d", il);484 485        attn_3d = ggml_mul(ctx0, attn_3d, gate_3d);486        cb(attn_3d, "mtp_attn_gated_3d", il);487 488        attn_out = ggml_reshape_2d(ctx0, attn_3d, n_embd_head_v * n_head_l, n_tokens);489        cb(attn_out, "mtp_attn_gated", il);490    }491 492    cur = build_lora_mm(layer.wo, attn_out, layer.wo_s);493    cb(cur, "mtp_attn_proj", il);494 495    cur = ggml_add(ctx0, cur, inpSA);496    cb(cur, "mtp_attn_residual", il);497 498    ggml_tensor * ffn_inp = cur;499    cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);500    cb(cur, "mtp_ffn_norm", il);501 502    // FFN: dense MLP or MoE (mirrors trunk path)503    if (layer.ffn_gate_inp == nullptr) {504        cur = build_ffn(cur,505                layer.ffn_up,   layer.ffn_up_b,   nullptr,506                layer.ffn_gate, layer.ffn_gate_b, nullptr,507                layer.ffn_down, layer.ffn_down_b, nullptr,508                nullptr,509                LLM_FFN_SILU, LLM_FFN_PAR, il);510        cb(cur, "mtp_ffn_out", il);511    } else {512        ggml_tensor * moe_out = build_moe_ffn(cur,513                layer.ffn_gate_inp,514                layer.ffn_up_exps,515                layer.ffn_gate_exps,516                layer.ffn_down_exps,517                layer.ffn_exp_probs_b,518                n_expert, n_expert_used,519                LLM_FFN_SILU, hparams.expert_weights_norm,520                hparams.expert_weights_scale,521                (llama_expert_gating_func_type) hparams.expert_gating_func,522                il);523        cb(moe_out, "mtp_ffn_moe_out", il);524 525        ggml_tensor * sh_out = build_ffn(cur,526                layer.ffn_up_shexp,   nullptr, nullptr,527                layer.ffn_gate_shexp, nullptr, nullptr,528                layer.ffn_down_shexp, nullptr, nullptr,529                nullptr,530                LLM_FFN_SILU, LLM_FFN_PAR, il);531        cb(sh_out, "mtp_ffn_shared_out", il);532 533        cur = ggml_add(ctx0, moe_out, sh_out);534        cb(cur, "mtp_ffn_out", il);535    }536    cur = ggml_add(ctx0, cur, ffn_inp);537    cb(cur, "mtp_post_ffn", il);538 539    ggml_tensor * inp_out_ids = build_inp_out_ids();540    cur = ggml_get_rows(ctx0, cur, inp_out_ids);541 542    // Pre-norm hidden state: used by the AR draft loop to seed the next MTP step.543    cb(cur, "h_nextn", -1);544    res->t_h_nextn = cur;545 546    ggml_tensor * head_norm_w = layer.nextn.shared_head_norm547            ? layer.nextn.shared_head_norm548            : model.output_norm;549    GGML_ASSERT(head_norm_w && "STEP35 MTP: missing both nextn.shared_head_norm and output_norm");550    cur = build_norm(cur, head_norm_w, nullptr, LLM_NORM_RMS, -1);551    cb(cur, "mtp_shared_head_norm", -1);552 553    ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;554    GGML_ASSERT(head_w && "STEP35 MTP: missing LM head (nextn.shared_head_head or model.output)");555    cur = build_lora_mm(head_w, cur);556    cb(cur, "result_output", -1);557 558    res->t_logits = cur;559    ggml_build_forward_expand(gf, cur);560}561 
Brunobkr/llama.cpp_AlgMor24_github · Team Ai