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
0likes3kdownloads
hy-v3.cpp395 linesDownload Raw Back to models
1#include "models.h"2 3void llama_model_hy_v3::load_arch_hparams(llama_model_loader & ml) {4    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,       hparams.f_norm_rms_eps);5    ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH,        hparams.n_ff_exp);6    ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);7    ml.get_key(LLM_KV_EXPERT_GATING_FUNC,                hparams.expert_gating_func, false);8    ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE,              hparams.expert_weights_scale, false);9    ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM,               hparams.expert_weights_norm, false);10 11    // HY V3 uses a sigmoid router with expert selection bias by default12    if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) {13        hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID;14    }15 16    // NextN/MTP (HY V3): extra decoder block(s) appended beyond the main stack17    ml.get_key(LLM_KV_NEXTN_PREDICT_LAYERS, hparams.n_layer_nextn, false);18    GGML_ASSERT(hparams.n_layer_nextn < hparams.n_layer_all && "n_layer_nextn must be < n_layer_all");19 20    switch (hparams.n_layer()) {21        case 48: type = LLM_TYPE_30B_A3B; break;22        default: type = LLM_TYPE_UNKNOWN;23    }24}25 26void llama_model_hy_v3::load_arch_tensors(llama_model_loader & ml) {27    LLAMA_LOAD_LOCALS;28 29    const bool mtp_only = (hparams.n_layer_nextn > 0) && (ml.get_weight("blk.0.attn_norm.weight") == nullptr);30    // Trunk-only: the GGUF declares MTP layers in metadata but the actual MTP31    // tensors live in a separate file (e.g. user split target/draft). Mark32    // MTP tensors NOT_REQUIRED so the trunk loads cleanly.33    const std::string mtp_probe = "blk." + std::to_string(n_layer) + ".nextn.eh_proj.weight";34    const bool trunk_only = (hparams.n_layer_nextn > 0) && (ml.get_weight(mtp_probe.c_str()) == nullptr);35    const int trunk_flags = mtp_only   ? TENSOR_NOT_REQUIRED : 0;36    int mtp_flags         = trunk_only ? TENSOR_NOT_REQUIRED : 0;37 38    if (!ml.load_mtp) {39        mtp_flags |= TENSOR_SKIP;40    }41 42    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);43 44    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);45    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);46    if (output == NULL) {47        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);48    }49 50    auto load_block = [&](int i, int flags) {51        auto & layer = layers[i];52        const int64_t n_ff_exp   = hparams.n_ff_exp   ? hparams.n_ff_exp   : n_ff / (n_expert_used > 0 ? n_expert_used : 1);53        const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff_exp;54 55        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, flags);56 57        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head, n_embd_k_gqa, n_embd_v_gqa, flags);58        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, flags);59 60        layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, flags);61        layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, flags);62 63        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, flags);64 65        // dense FFN (leading dense blocks, first_k_dense_replace)66        layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, TENSOR_NOT_REQUIRED);67        layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, TENSOR_NOT_REQUIRED);68        layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd, n_ff}, TENSOR_NOT_REQUIRED);69 70        // MoE routed experts (sigmoid router + expert selection bias)71        layer.ffn_gate_inp    = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,    "weight", i), {n_embd, n_expert}, TENSOR_NOT_REQUIRED);72        layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B,           i), {n_expert}, TENSOR_NOT_REQUIRED);73        layer.ffn_down_exps   = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS,   "weight", i), {n_ff_exp, n_embd, n_expert}, TENSOR_NOT_REQUIRED);74        create_tensor_gate_up_exps(layer, i, n_embd, n_ff_exp, n_expert, TENSOR_NOT_REQUIRED);75 76        // shared expert (always active, no gate)77        layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, TENSOR_NOT_REQUIRED);78        layer.ffn_up_shexp   = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {n_embd, n_ff_shexp}, TENSOR_NOT_REQUIRED);79        layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, TENSOR_NOT_REQUIRED);80    };81 82    for (int i = 0; i < n_layer; ++i) {83        load_block(i, trunk_flags);84    }85 86    // NextN/MTP block(s): a full hy_v3 decoder block plus the NextN projections.87    for (int i = n_layer; i < n_layer_all; ++i) {88        auto & layer = layers[i];89 90        load_block(i, mtp_flags);91 92        layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ,          "weight", i), { 2 * n_embd, n_embd }, mtp_flags);93        layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM,            "weight", i), { n_embd },             mtp_flags);94        layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM,            "weight", i), { n_embd },             mtp_flags);95        layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS,     "weight", i), { n_embd, n_vocab },    TENSOR_NOT_REQUIRED);96        layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab },    TENSOR_NOT_REQUIRED);97        // hy_v3 stores the MTP block's trailing final_layernorm here (applied98        // after the decoder block, before the shared LM head).99        layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd },             TENSOR_NOT_REQUIRED);100    }101}102 103std::unique_ptr<llm_graph_context> llama_model_hy_v3::build_arch_graph(const llm_graph_params & params) const {104    if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) {105        return std::make_unique<graph_mtp>(*this, params);106    }107    return std::make_unique<graph>(*this, params);108}109 110llama_model_hy_v3::graph::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) {111    const int64_t n_embd_head = hparams.n_embd_head_v();112 113    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());114    GGML_ASSERT(n_embd_head == n_rot);115 116    ggml_tensor * cur;117    ggml_tensor * inpL;118 119    inpL = build_inp_embd(model.tok_embd);120    ggml_tensor * inp_pos = build_inp_pos();121    auto * inp_attn = build_attn_inp_kv();122    ggml_tensor * inp_out_ids = build_inp_out_ids();123 124    const float kq_scale = 1.0f / sqrtf(float(n_embd_head));125 126    // MTP/NextN layers are loaded as extra decoder blocks but not executed in the main pass.127    for (int il = 0; il < n_layer; ++il) {128        ggml_tensor * inpSA = inpL;129 130        cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);131        cb(cur, "attn_norm", il);132 133        // self-attention134        {135            ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);136 137            auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il);138 139            Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, nullptr, LLM_NORM_RMS, il);140            Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, nullptr, LLM_NORM_RMS, il);141 142            Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, rope_factors,143                    n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,144                    ext_factor, attn_factor, beta_fast, beta_slow);145            Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, rope_factors,146                    n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,147                    ext_factor, attn_factor, beta_fast, beta_slow);148 149            cur = build_attn(inp_attn,150                    model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,151                    Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);152            cb(cur, "attn_out", il);153        }154 155        if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked) {156            cur   = ggml_get_rows(ctx0,   cur, inp_out_ids);157            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);158        }159 160        ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);161        cb(ffn_inp, "ffn_inp", il);162 163        cur = build_norm(ffn_inp, model.layers[il].ffn_norm, nullptr, LLM_NORM_RMS, il);164        cb(cur, "ffn_norm", il);165 166        if (model.layers[il].ffn_gate_inp == nullptr) {167            // dense FFN (leading dense blocks)168            cur = build_ffn(cur,169                    model.layers[il].ffn_up,   model.layers[il].ffn_up_b,   model.layers[il].ffn_up_s,170                    model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, model.layers[il].ffn_gate_s,171                    model.layers[il].ffn_down, model.layers[il].ffn_down_b, model.layers[il].ffn_down_s,172                    nullptr,173                    LLM_FFN_SILU, LLM_FFN_PAR, il);174            cb(cur, "ffn_dense_out", il);175        } else {176            // MoE routed experts (sigmoid gating + expert selection bias)177            ggml_tensor * moe_out = build_moe_ffn(cur,178                    model.layers[il].ffn_gate_inp,179                    model.layers[il].ffn_up_exps,180                    model.layers[il].ffn_gate_exps,181                    model.layers[il].ffn_down_exps,182                    model.layers[il].ffn_exp_probs_b,183                    n_expert, n_expert_used,184                    LLM_FFN_SILU,185                    hparams.expert_weights_norm,186                    hparams.expert_weights_scale,187                    (llama_expert_gating_func_type) hparams.expert_gating_func,188                    il,189                    nullptr, model.layers[il].ffn_gate_up_exps,190                    model.layers[il].ffn_up_exps_s,191                    model.layers[il].ffn_gate_exps_s,192                    model.layers[il].ffn_down_exps_s);193            cb(moe_out, "ffn_moe_out", il);194 195            // shared expert (always active, no gate)196            ggml_tensor * sh_out = build_ffn(cur,197                    model.layers[il].ffn_up_shexp,   nullptr, model.layers[il].ffn_up_shexp_s,198                    model.layers[il].ffn_gate_shexp, nullptr, model.layers[il].ffn_gate_shexp_s,199                    model.layers[il].ffn_down_shexp, nullptr, model.layers[il].ffn_down_shexp_s,200                    nullptr,201                    LLM_FFN_SILU, LLM_FFN_PAR, il);202            cb(sh_out, "ffn_shared_out", il);203 204            cur = ggml_add(ctx0, moe_out, sh_out);205            cb(cur, "ffn_out", il);206        }207 208        cur = ggml_add(ctx0, cur, ffn_inp);209        cur = build_cvec(cur, il);210        cb(cur, "l_out", il);211 212        inpL = cur;213    }214 215    cur = build_norm(inpL, model.output_norm, nullptr, LLM_NORM_RMS, -1);216 217    // Post-final-norm hidden state: what the MTP draft head's hnorm consumes.218    // vLLM feeds the target model's normed output states, and the MTP layer219    // itself returns final_layernorm(h), so the chained state is post-norm.220    cb(cur, "h_nextn", -1);221    res->t_h_nextn = cur;222 223    if (!cparams.embeddings_nextn_masked && inp_out_ids) {224        cur = ggml_get_rows(ctx0, cur, inp_out_ids);225    }226 227    cb(cur, "result_norm", -1);228    res->t_embd = cur;229 230    cur = build_lora_mm(model.output, cur, model.output_s);231    cb(cur, "result_output", -1);232    res->t_logits = cur;233 234    ggml_build_forward_expand(gf, cur);235}236 237// LLM_GRAPH_TYPE_DECODER_MTP draft head for HY V3 (MoE).238// Semantics mirror vLLM's HYV3MultiTokenPredictorLayer (hy_v3_mtp.py):239//   enorm(embed) + hnorm(prev_hidden) -> concat(e, h) -> eh_proj ->240//   hy_v3 decoder block -> final_layernorm (stored as nextn.shared_head_norm) ->241//   shared LM head (the main model's lm_head; the checkpoint has no separate242//   MTP head or MTP embeddings).243llama_model_hy_v3::graph_mtp::graph_mtp(const llama_model & model, const llm_graph_params & params)244    : llm_graph_context(params) {245    GGML_ASSERT(hparams.n_layer_nextn > 0 && "HY_V3 MTP requires n_layer_nextn > 0");246 247    const int64_t n_embd_head = hparams.n_embd_head_v();248    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());249    GGML_ASSERT(n_embd_head == n_rot);250 251    const int il = hparams.n_layer() + cparams.nextn_layer_offset;252    GGML_ASSERT(cparams.nextn_layer_offset >= 0 &&253                cparams.nextn_layer_offset < (int) hparams.n_layer_nextn &&254                "nextn_layer_offset out of range [0, n_layer_nextn)");255    const auto & layer = model.layers[il];256 257    GGML_ASSERT(layer.nextn.eh_proj && "MTP block missing nextn.eh_proj");258    GGML_ASSERT(layer.nextn.enorm   && "MTP block missing nextn.enorm");259    GGML_ASSERT(layer.nextn.hnorm   && "MTP block missing nextn.hnorm");260 261    auto inp = std::make_unique<llm_graph_input_embd>(hparams.n_embd);262 263    inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);264    ggml_set_input(inp->tokens);265 266    inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd, n_tokens);267    ggml_set_input(inp->embd);268    ggml_set_name(inp->embd, "mtp_h_input");269 270    ggml_tensor * tok_embd_w = layer.nextn.embed_tokens ? layer.nextn.embed_tokens : model.tok_embd;271 272    ggml_tensor * h_input  = inp->embd;273    ggml_tensor * tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens);274    cb(tok_embd, "mtp_tok_embd", il);275 276    res->add_input(std::move(inp));277 278    ggml_tensor * inp_pos     = build_inp_pos();279    ggml_tensor * inp_out_ids = build_inp_out_ids();280    auto * inp_attn           = build_attn_inp_kv();281 282    ggml_tensor * h_norm = build_norm(h_input, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il);283    cb(h_norm, "mtp_hnorm", il);284 285    ggml_tensor * e_norm = build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il);286    cb(e_norm, "mtp_enorm", il);287 288    ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, /*dim=*/ 0);289    cb(concat, "mtp_concat", il);290 291    ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat);292    cb(cur, "mtp_eh_proj", il);293 294    ggml_tensor * inpSA = cur;295 296    // mtp_block: a full hy_v3 decoder layer (mirrors the trunk graph)297    cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);298    cb(cur, "mtp_attn_norm", il);299 300    {301        ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);302 303        auto [Qcur, Kcur, Vcur] = build_qkv(layer, cur, n_embd_head, n_head, n_head_kv, il);304 305        Qcur = build_norm(Qcur, layer.attn_q_norm, nullptr, LLM_NORM_RMS, il);306        Kcur = build_norm(Kcur, layer.attn_k_norm, nullptr, LLM_NORM_RMS, il);307 308        Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, rope_factors,309                n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,310                ext_factor, attn_factor, beta_fast, beta_slow);311        Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, rope_factors,312                n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,313                ext_factor, attn_factor, beta_fast, beta_slow);314 315        const float kq_scale = 1.0f / sqrtf(float(n_embd_head));316 317        cur = build_attn(inp_attn,318                layer.wo, layer.wo_b, layer.wo_s,319                Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);320        cb(cur, "mtp_attn_out", il);321    }322 323    ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);324    cb(ffn_inp, "mtp_ffn_inp", il);325 326    cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);327    cb(cur, "mtp_ffn_norm", il);328 329    if (layer.ffn_gate_inp == nullptr) {330        cur = build_ffn(cur,331                layer.ffn_up,   layer.ffn_up_b,   layer.ffn_up_s,332                layer.ffn_gate, layer.ffn_gate_b, layer.ffn_gate_s,333                layer.ffn_down, layer.ffn_down_b, layer.ffn_down_s,334                nullptr,335                LLM_FFN_SILU, LLM_FFN_PAR, il);336        cb(cur, "mtp_ffn_dense_out", il);337    } else {338        ggml_tensor * moe_out = build_moe_ffn(cur,339                layer.ffn_gate_inp,340                layer.ffn_up_exps,341                layer.ffn_gate_exps,342                layer.ffn_down_exps,343                layer.ffn_exp_probs_b,344                n_expert, n_expert_used,345                LLM_FFN_SILU,346                hparams.expert_weights_norm,347                hparams.expert_weights_scale,348                (llama_expert_gating_func_type) hparams.expert_gating_func,349                il,350                nullptr, layer.ffn_gate_up_exps,351                layer.ffn_up_exps_s,352                layer.ffn_gate_exps_s,353                layer.ffn_down_exps_s);354        cb(moe_out, "mtp_ffn_moe_out", il);355 356        ggml_tensor * sh_out = build_ffn(cur,357                layer.ffn_up_shexp,   nullptr, layer.ffn_up_shexp_s,358                layer.ffn_gate_shexp, nullptr, layer.ffn_gate_shexp_s,359                layer.ffn_down_shexp, nullptr, layer.ffn_down_shexp_s,360                nullptr,361                LLM_FFN_SILU, LLM_FFN_PAR, il);362        cb(sh_out, "mtp_ffn_shared_out", il);363 364        cur = ggml_add(ctx0, moe_out, sh_out);365        cb(cur, "mtp_ffn_out", il);366    }367 368    cur = ggml_add(ctx0, cur, ffn_inp);369    cb(cur, "mtp_post_ffn", il);370 371    // final_layernorm applied after the decoder block, before the shared head.372    // The post-norm hidden state seeds the next MTP step (matches vLLM, where373    // HYV3MultiTokenPredictorLayer returns final_layernorm(h)).374    ggml_tensor * head_norm_w = layer.nextn.shared_head_norm375            ? layer.nextn.shared_head_norm376            : model.output_norm;377    GGML_ASSERT(head_norm_w && "HY_V3 MTP: missing both nextn.shared_head_norm and output_norm");378    cur = build_norm(cur, head_norm_w, nullptr, LLM_NORM_RMS, -1);379 380    cb(cur, "h_nextn", -1);381    res->t_h_nextn = cur;382 383    cur = ggml_get_rows(ctx0, cur, inp_out_ids);384    cb(cur, "mtp_shared_head_norm", -1);385 386    ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;387    ggml_tensor * head_s = layer.nextn.shared_head_head ? layer.nextn.shared_head_head_s : model.output_s;388    GGML_ASSERT(head_w && "HY_V3 MTP: missing LM head (nextn.shared_head_head or model.output)");389    cur = build_lora_mm(head_w, cur, head_s);390    cb(cur, "result_output", -1);391 392    res->t_logits = cur;393    ggml_build_forward_expand(gf, cur);394}395 
Brunobkr/llama.cpp_AlgMor24_github · Team Ai