CoolFace
Modelpublic

Felipe97/llama-cpp-compiled

sourceHugging Faceupdated 2d agoView on Hugging Face
0likes1.1kdownloads
granite-switch.cpp428 linesDownload Raw Back to models
1#include "models.h"2 3#include <cmath>4 5void llama_model_granite_switch::load_arch_hparams(llama_model_loader & ml) {6    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);7    ml.get_key(LLM_KV_LOGIT_SCALE,                 hparams.f_logit_scale);8    ml.get_key(LLM_KV_RESIDUAL_SCALE,              hparams.f_residual_scale, false);9    ml.get_key(LLM_KV_EMBEDDING_SCALE,             hparams.f_embedding_scale, false);10    ml.get_key(LLM_KV_ATTENTION_SCALE,             hparams.f_attention_scale, false);11 12    bool rope_finetuned = true;13    ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);14    hparams.rope_finetuned = rope_finetuned; // needed for round trip save15    std::fill(hparams.rope_pattern.begin(), hparams.rope_pattern.end(), rope_finetuned);16 17    switch (hparams.n_layer()) {18        case 40: type = hparams.n_embd == 4096 ? LLM_TYPE_8B : LLM_TYPE_3B; break;19        case 64: type = LLM_TYPE_30B; break;20        default: type = LLM_TYPE_UNKNOWN;21    }22 23    ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, /* required */ false);24 25    ml.get_key(LLM_KV_ADAPTER_COUNT,     n_adapters);26    ml.get_key(LLM_KV_ADAPTER_LORA_RANK, max_lora_rank);27    ml.get_key(LLM_KV_ADAPTER_ROUTER_GAIN, router_gain, /* required */ false);28 29    // bound counts that size tensors30    if (n_adapters > 4096) {31        throw std::runtime_error(format("graniteswitch: invalid adapter count %u", n_adapters));32    }33    if (max_lora_rank > 4096) {34        throw std::runtime_error(format("graniteswitch: invalid lora rank %u", max_lora_rank));35    }36 37    std::vector<llama_token> token_ids;38    std::vector<llama_token> substitute_ids;39    ml.get_arr(LLM_KV_ADAPTER_TOKEN_IDS_ACTIVATE,   token_ids);40    ml.get_arr(LLM_KV_ADAPTER_TOKEN_IDS_SUBSTITUTE, substitute_ids);41 42    if (token_ids.size() != n_adapters || substitute_ids.size() != n_adapters) {43        throw std::runtime_error(format(44            "graniteswitch: adapter token id arrays (%zu activate, %zu substitute) do not match adapter count %u",45            token_ids.size(), substitute_ids.size(), n_adapters));46    }47 48    adapter_token_to_slot.clear();49    adapter_token_to_substitute.clear();50    for (uint32_t i = 0; i < n_adapters; ++i) {51        // adapter i -> stacked slot i+1 (slot 0 is the base/zero delta)52        adapter_token_to_slot[token_ids[i]]       = (int32_t) (i + 1);53        adapter_token_to_substitute[token_ids[i]] = substitute_ids[i];54    }55 56    // extra single-head attention layer at the END (index n_real) holds the router57    // K/V. reusing n_layer_nextn keeps n_layer() == n_real, so the regular layers58    // keep their indices and the KV cache shift/defrag skips the router layer.59    // n_layer_nextn is repurposed here (no MTP): it leaks as 1 into the60    // llama_model_n_layer_nextn() getter and a re-saved nextn_predict_layers61    const uint32_t n_real = hparams.n_layer();62    if (n_real >= LLAMA_MAX_LAYERS) {63        throw std::runtime_error(format("graniteswitch: block count %u exceeds LLAMA_MAX_LAYERS", n_real));64    }65    hparams.router_layer  = (int32_t) n_real;66    hparams.n_layer_all   = n_real + 1;67    hparams.n_layer_nextn = 1;68 69    hparams.n_head_arr[n_real]    = 1;70    hparams.n_head_kv_arr[n_real] = 1;71    hparams.n_ff_arr[n_real]      = 0;72}73 74void llama_model_granite_switch::load_arch_tensors(llama_model_loader &) {75    LLAMA_LOAD_LOCALS;76 77    const int64_t n_slots     = (int64_t) n_adapters + 1; // slot 0 = base/zero delta78    const int64_t n_rank      = (int64_t) max_lora_rank;79    const int64_t n_embd_q    = n_embd_head_k * n_head;80    const int64_t n_embd_kv   = n_embd_k_gqa;81 82    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);83 84    // substitute ids index tok_embd rows directly; range-check against n_vocab85    for (const auto & kv : adapter_token_to_substitute) {86        const llama_token sub = kv.second;87        if (sub < 0 || (int64_t) sub >= n_vocab) {88            throw std::runtime_error(format(89                "graniteswitch: substitute token id %d out of range [0, %d)", sub, (int) n_vocab));90        }91    }92 93    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);94    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);95    if (output == NULL) {96        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);97    }98 99    for (int i = 0; i < n_layer; ++i) {100        auto & layer = layers[i];101 102        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);103 104        layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd_q + 2*n_embd_kv}, 0);105        layer.wo   = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_q, n_embd}, 0);106 107        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);108 109        layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd,   n_ff}, 0);110        layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {  n_ff, n_embd}, 0);111        layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd,   n_ff}, 0);112 113        auto & sl = layer.switch_lora;114 115        sl.a_q = create_tensor(tn(LLM_TENSOR_ATTN_Q, "lora_a", i), {n_embd,  n_rank, n_slots}, 0);116        sl.b_q = create_tensor(tn(LLM_TENSOR_ATTN_Q, "lora_b", i), {n_rank, n_embd_q, n_slots}, 0);117        sl.a_k = create_tensor(tn(LLM_TENSOR_ATTN_K, "lora_a", i), {n_embd,  n_rank, n_slots}, 0);118        sl.b_k = create_tensor(tn(LLM_TENSOR_ATTN_K, "lora_b", i), {n_rank, n_embd_kv, n_slots}, 0);119        sl.a_v = create_tensor(tn(LLM_TENSOR_ATTN_V, "lora_a", i), {n_embd,  n_rank, n_slots}, 0);120        sl.b_v = create_tensor(tn(LLM_TENSOR_ATTN_V, "lora_b", i), {n_rank, n_embd_kv, n_slots}, 0);121 122        sl.a_o = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "lora_a", i), {n_embd_q, n_rank, n_slots}, 0);123        sl.b_o = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "lora_b", i), {n_rank,   n_embd, n_slots}, 0);124 125        sl.a_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "lora_a", i), {n_embd, n_rank, n_slots}, 0);126        sl.b_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "lora_b", i), {n_rank,  n_ff,  n_slots}, 0);127        sl.a_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "lora_a", i), {n_embd, n_rank, n_slots}, 0);128        sl.b_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "lora_b", i), {n_rank,  n_ff,  n_slots}, 0);129        sl.a_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "lora_a", i), {  n_ff, n_rank, n_slots}, 0);130        sl.b_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "lora_b", i), {n_rank, n_embd, n_slots}, 0);131    }132}133 134class llm_graph_input_switch : public llm_graph_input_i {135public:136    llm_graph_input_switch(const llama_model_granite_switch & smodel) : smodel(smodel) {}137    virtual ~llm_graph_input_switch() = default;138 139    void set_input(const llama_ubatch * ubatch) override;140 141    ggml_tensor * sub_tokens  = nullptr; // I32 [n_tokens] adapter-substituted token ids142    ggml_tensor * router_ksig = nullptr; // F32 [n_tokens] router K signal (+/-gain)143    ggml_tensor * router_vval = nullptr; // F32 [n_tokens] router V value (adapter slot / 0)144    ggml_tensor * router_q    = nullptr; // F32 [n_tokens] router Q value (constant 1.0)145 146    const llama_model_granite_switch & smodel;147};148 149// K dim-0 is +gain for an adapter token, -gain otherwise; the causal softmax then150// lets a single visible adapter token dominate so the readback recovers its slot.151void llm_graph_input_switch::set_input(const llama_ubatch * ubatch) {152    if (!ubatch->token) {153        return;154    }155 156    const int64_t n_tokens = ubatch->n_tokens;157 158    std::vector<int32_t> sub (n_tokens);159    std::vector<float>   ksig(n_tokens);160    std::vector<float>   vval(n_tokens);161    std::vector<float>   q   (n_tokens, 1.0f);162 163    for (int64_t i = 0; i < n_tokens; ++i) {164        const llama_token tok = ubatch->token[i];165 166        const auto it = smodel.adapter_token_to_slot.find(tok);167        if (it != smodel.adapter_token_to_slot.end()) {168            ksig[i] = +smodel.router_gain;169            vval[i] = (float) it->second;170        } else {171            ksig[i] = -smodel.router_gain;172            vval[i] = 0.0f;173        }174 175        const auto sit = smodel.adapter_token_to_substitute.find(tok);176        sub[i] = (sit != smodel.adapter_token_to_substitute.end())177            ? (int32_t) sit->second178            : (int32_t) tok;179    }180 181    ggml_backend_tensor_set(sub_tokens,  sub.data(),  0, n_tokens*ggml_element_size(sub_tokens));182    ggml_backend_tensor_set(router_ksig, ksig.data(), 0, n_tokens*ggml_element_size(router_ksig));183    ggml_backend_tensor_set(router_vval, vval.data(), 0, n_tokens*ggml_element_size(router_vval));184    ggml_backend_tensor_set(router_q,    q.data(),    0, n_tokens*ggml_element_size(router_q));185}186 187std::unique_ptr<llm_graph_context> llama_model_granite_switch::build_arch_graph(const llm_graph_params & params) const {188    return std::make_unique<graph>(*this, params);189}190 191// per-token switched LoRA delta: B_a*(A_a*x), adapter selected per token via ids.192// cur: {n_in, n_tokens}, ids: {n_tokens} -> {n_out, n_tokens}193ggml_tensor * llama_model_granite_switch::graph::build_switched_lora_delta(194          ggml_tensor * lora_a,195          ggml_tensor * lora_b,196          ggml_tensor * cur,197          ggml_tensor * ids) {198    const int64_t n_in     = cur->ne[0];199    const int64_t n_tokens = cur->ne[1];200 201    ggml_tensor * x    = ggml_reshape_3d(ctx0, cur, n_in, 1, n_tokens);202    ggml_tensor * ids2 = ggml_reshape_2d(ctx0, ids, 1, n_tokens);203 204    ggml_tensor * a = ggml_mul_mat_id(ctx0, lora_a, x, ids2); // {max_rank, 1, n_tokens}205    ggml_tensor * d = ggml_mul_mat_id(ctx0, lora_b, a, ids2); // {n_out,    1, n_tokens}206 207    return ggml_reshape_2d(ctx0, d, d->ne[0], n_tokens);208}209 210ggml_tensor * llama_model_granite_switch::graph::build_switched_lora_mm(211          ggml_tensor * w,212          ggml_tensor * lora_a,213          ggml_tensor * lora_b,214          ggml_tensor * cur,215          ggml_tensor * ids) {216    ggml_tensor * base  = ggml_mul_mat(ctx0, w, cur);217    ggml_tensor * delta = build_switched_lora_delta(lora_a, lora_b, cur, ids);218    return ggml_add(ctx0, base, delta);219}220 221llama_model_granite_switch::graph::graph(222    const llama_model & model,223    const llm_graph_params & params)224    : llm_graph_context(params) {225 226    const auto & smodel = static_cast<const llama_model_granite_switch &>(model);227 228    // TODO: support raw embedding input (multimodal / pre-embedded tokens) when needed229    GGML_ASSERT(ubatch.token && "granite-switch requires token input");230 231    const int64_t n_embd_head = hparams.n_embd_head_v();232    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());233    GGML_ASSERT(n_embd_head == n_rot);234 235    auto inp_switch = std::make_unique<llm_graph_input_switch>(smodel);236    inp_switch->sub_tokens  = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);237    inp_switch->router_ksig = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_tokens);238    inp_switch->router_vval = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_tokens);239    inp_switch->router_q    = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_tokens);240    ggml_set_input(inp_switch->sub_tokens);241    ggml_set_input(inp_switch->router_ksig);242    ggml_set_input(inp_switch->router_vval);243    ggml_set_input(inp_switch->router_q);244    ggml_tensor * sub_tokens  = inp_switch->sub_tokens;245    ggml_tensor * router_ksig = inp_switch->router_ksig;246    ggml_tensor * router_vval = inp_switch->router_vval;247    ggml_tensor * router_q    = inp_switch->router_q;248    res->add_input(std::move(inp_switch));249 250    // embed the substituted ids directly; build_inp_embd would embed the raw tokens251    ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embd, sub_tokens);252    if (hparams.f_embedding_scale != 0.0f) {253        inpL = ggml_scale(ctx0, inpL, hparams.f_embedding_scale);254    }255    cb(inpL, "inp_embd", -1);256 257    ggml_tensor * inp_pos = nullptr;258    if (hparams.has_rope(0)) {259        inp_pos = build_inp_pos();260    }261    auto * inp_attn = build_attn_inp_kv();262 263    // single causal head at layer R recovers the adapter index in-graph: only dim 0264    // carries signal (Q[0]=1, K[0]=+/-gain, V[0]=slot/0), the rest is zero-padded.265    const int R = hparams.router_layer;266    GGML_ASSERT(R >= 0);267    auto router_lane = [&](ggml_tensor * sig1d) {268        ggml_tensor * t = ggml_reshape_3d(ctx0, sig1d, 1, 1, n_tokens);269        return ggml_pad(ctx0, t, (int) n_embd_head - 1, 0, 0, 0);270    };271    ggml_tensor * Qr = router_lane(router_q);272    ggml_tensor * Kr = router_lane(router_ksig);273    ggml_tensor * Vr = router_lane(router_vval);274 275    ggml_tensor * router_out = build_attn(inp_attn,276            nullptr, nullptr, nullptr,277            Qr, Kr, Vr, nullptr, nullptr, nullptr, /*kq_scale=*/1.0f, /*il=*/R);278    cb(router_out, "router_out", R);279 280    // row 0 of router_out is the attended slot; clamp+round to an I32 index281    ggml_tensor * slot_f = ggml_cont(ctx0,282        ggml_view_2d(ctx0, router_out, 1, n_tokens, router_out->nb[1], 0));283    slot_f = ggml_reshape_1d(ctx0, slot_f, n_tokens);284    slot_f = ggml_clamp(ctx0, slot_f, 0.0f, (float) smodel.n_adapters);285    slot_f = ggml_round(ctx0, slot_f);286    ggml_tensor * adapter_ids = ggml_cast(ctx0, slot_f, GGML_TYPE_I32);287    cb(adapter_ids, "adapter_ids", -1);288 289    ggml_tensor * inp_out_ids = build_inp_out_ids();290 291    ggml_tensor * cur;292 293    for (int il = 0; il < n_layer; ++il) {294        ggml_tensor * inpSA = inpL;295 296        cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);297        cb(cur, "attn_norm", il);298 299        cur = build_attention_layer(cur, inp_pos, adapter_ids, inp_attn, model, n_embd_head, il);300 301        if (il == n_layer - 1 && inp_out_ids) {302            cur   = ggml_get_rows(ctx0, cur,   inp_out_ids);303            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);304            // keep adapter_ids aligned to the kept rows (2D round-trip for get_rows)305            const int64_t n_out = inp_out_ids->ne[0];306            adapter_ids = ggml_get_rows(ctx0,307                ggml_reshape_2d(ctx0, adapter_ids, 1, adapter_ids->ne[0]), inp_out_ids);308            adapter_ids = ggml_reshape_1d(ctx0, adapter_ids, n_out);309        }310 311        cur = build_layer_ffn(cur, inpSA, adapter_ids, model, il);312 313        inpL = cur;314    }315 316    cur = inpL;317 318    cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1);319    cb(cur, "result_norm", -1);320    res->t_embd = cur;321 322    cur = build_lora_mm(model.output, cur, model.output_s);323 324    cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);325    cb(cur, "result_output", -1);326    res->t_logits = cur;327 328    ggml_build_forward_expand(gf, cur);329}330 331ggml_tensor * llama_model_granite_switch::graph::build_attention_layer(332          ggml_tensor             * cur,333          ggml_tensor             * inp_pos,334          ggml_tensor             * adapter_ids,335          llm_graph_input_attn_kv * inp_attn,336    const llama_model             & model,337    const int64_t                 n_embd_head,338    const int                     il) {339 340    const auto & layer = model.layers[il];341    const auto & sl    = layer.switch_lora;342 343    const int64_t n_head    = hparams.n_head(il);344    const int64_t n_head_kv = hparams.n_head_kv(il);345 346    ggml_tensor * qkv = ggml_mul_mat(ctx0, layer.wqkv, cur);347    cb(qkv, "wqkv", il);348 349    const int64_t n_embd_q  = n_embd_head * n_head;350    const int64_t n_embd_kv = n_embd_head * n_head_kv;351 352    // slice fused qkv into Q/K/V, made contiguous so LoRA deltas can be added353    ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, qkv, n_embd_q,  qkv->ne[1], qkv->nb[1], 0));354    ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, qkv, n_embd_kv, qkv->ne[1], qkv->nb[1], n_embd_q*ggml_element_size(qkv)));355    ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, qkv, n_embd_kv, qkv->ne[1], qkv->nb[1], (n_embd_q + n_embd_kv)*ggml_element_size(qkv)));356 357    Qcur = ggml_add(ctx0, Qcur, build_switched_lora_delta(sl.a_q, sl.b_q, cur, adapter_ids));358    Kcur = ggml_add(ctx0, Kcur, build_switched_lora_delta(sl.a_k, sl.b_k, cur, adapter_ids));359    Vcur = ggml_add(ctx0, Vcur, build_switched_lora_delta(sl.a_v, sl.b_v, cur, adapter_ids));360 361    Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head,    n_tokens);362    Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);363    Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens);364 365    if (hparams.has_rope(il)) {366        ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);367        Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, rope_factors,368                n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,369                ext_factor, attn_factor, beta_fast, beta_slow);370        Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, rope_factors,371                n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,372                ext_factor, attn_factor, beta_fast, beta_slow);373    }374    cb(Qcur, "Qcur", il);375    cb(Kcur, "Kcur", il);376    cb(Vcur, "Vcur", il);377 378    const float kq_scale = hparams.f_attention_scale == 0.0f379        ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;380 381    // wo = nullptr so build_attn returns concatenated heads; o-proj is switched below382    ggml_tensor * attn = build_attn(inp_attn,383            nullptr, nullptr, nullptr,384            Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);385    cb(attn, "attn_pre_o", il);386 387    cur = build_switched_lora_mm(layer.wo, sl.a_o, sl.b_o, attn, adapter_ids);388    cb(cur, "attn_out", il);389    return cur;390}391 392ggml_tensor * llama_model_granite_switch::graph::build_layer_ffn(393          ggml_tensor       * cur,394          ggml_tensor       * inpSA,395          ggml_tensor       * adapter_ids,396    const llama_model       & model,397    const int                 il) {398 399    const auto & layer = model.layers[il];400    const auto & sl    = layer.switch_lora;401 402    if (hparams.f_residual_scale) {403        cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);404    }405    ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);406    cb(ffn_inp, "ffn_inp", il);407 408    cur = build_norm(ffn_inp, layer.ffn_norm, NULL, LLM_NORM_RMS, il);409    cb(cur, "ffn_norm", il);410 411    ggml_tensor * g = build_switched_lora_mm(layer.ffn_gate, sl.a_gate, sl.b_gate, cur, adapter_ids);412    ggml_tensor * u = build_switched_lora_mm(layer.ffn_up,   sl.a_up,   sl.b_up,   cur, adapter_ids);413    g = ggml_silu(ctx0, g);414    ggml_tensor * gu = ggml_mul(ctx0, g, u);415    cur = build_switched_lora_mm(layer.ffn_down, sl.a_down, sl.b_down, gu, adapter_ids);416    cb(cur, "ffn_out", il);417 418    if (hparams.f_residual_scale) {419        cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);420    }421    cur = ggml_add(ctx0, cur, ffn_inp);422 423    cur = build_cvec(cur, il);424    cb(cur, "l_out", il);425 426    return cur;427}428