okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

main
11.0 KiB272 linesraw
1#include "models.h"
2
3void llama_model_llama4::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_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all);
6    ml.get_key(LLM_KV_INTERLEAVE_MOE_LAYER_STEP,   hparams.n_moe_layer_step);
7
8    const bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
9    if (found_swa && hparams.n_swa == 0) {
10        hparams.swa_type             = LLAMA_SWA_TYPE_NONE;
11        hparams.n_no_rope_layer_step = hparams.n_layer(); // always use rope
12    } else {
13        hparams.swa_type                = LLAMA_SWA_TYPE_CHUNKED;
14        hparams.n_swa                   = 8192;
15        hparams.n_attn_temp_floor_scale = 8192;
16        hparams.f_attn_temp_scale       = 0.1f;
17        hparams.f_attn_temp_offset      = 1.0f;
18
19        load_swa_pattern(ml, 4); // pattern: 3 chunked - 1 full
20
21        hparams.rope_freq_base_train_swa  = hparams.rope_freq_base_train;
22        hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train;
23        ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa, false);
24    }
25
26    switch (hparams.n_expert) {
27        case 0: {
28            // MobileLLM (no MoE)
29            switch (hparams.n_embd) {
30                case 2048: type = LLM_TYPE_140M; break;
31                case 4096: type = LLM_TYPE_360M; break;
32                case 6144: type = LLM_TYPE_950M; break;
33                default:   type = LLM_TYPE_UNKNOWN;
34            }
35        } break;
36        case 16:  type = LLM_TYPE_17B_16E; break;
37        case 128: type = LLM_TYPE_17B_128E; break;
38        default:  type = LLM_TYPE_UNKNOWN;
39    }
40
41    hparams.use_kq_norm = type != LLM_TYPE_17B_128E;
42}
43
44void llama_model_llama4::load_arch_tensors(llama_model_loader &) {
45    LLAMA_LOAD_LOCALS;
46
47    if (n_expert == 0) {
48        throw std::runtime_error(arch_name() + " model cannot have zero experts");
49    }
50    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
51
52    // output
53    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
54    output      = create_tensor(tn(LLM_TENSOR_OUTPUT,      "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
55
56    // if output is NULL, init from the input tok embed
57    if (output == NULL) {
58        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
59    }
60
61    for (int i = 0; i < n_layer; ++i) {
62        const bool is_moe_layer = hparams.n_moe_layer_step > 0 && (i + 1) % hparams.n_moe_layer_step == 0;
63
64        auto & layer = layers[i];
65
66        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
67
68        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head, n_embd_k_gqa, n_embd_v_gqa, 0);
69        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
70
71        layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
72
73        layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot/2}, TENSOR_NOT_REQUIRED | (i != 0 ? TENSOR_DUPLICATED : 0));
74
75        if (is_moe_layer) {
76            const int64_t n_ff_exp = hparams.n_ff_exp();
77
78            layer.ffn_gate_inp  = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP,  "weight", i), {n_embd, n_expert}, 0);
79            layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd,   n_ff_exp, n_expert}, 0);
80            layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {  n_ff_exp, n_embd, n_expert}, 0);
81            layer.ffn_up_exps   = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS,   "weight", i), {n_embd,   n_ff_exp, n_expert}, 0);
82
83            // Shared expert
84            const int64_t n_ff_shexp = n_ff_exp;
85            layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {    n_embd, n_ff_shexp}, 0);
86            layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd    }, 0);
87            layer.ffn_up_shexp   = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP,   "weight", i), {    n_embd, n_ff_shexp}, 0);
88        } else {
89            layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd,   n_ff}, 0);
90            layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {  n_ff, n_embd}, 0);
91            layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), {n_embd,   n_ff}, 0);
92        }
93    }
94}
95
96std::unique_ptr<llm_graph_context> llama_model_llama4::build_arch_graph(const llm_graph_params & params) const {
97    if (hparams.swa_type == LLAMA_SWA_TYPE_NONE) {
98        return std::make_unique<graph<false>>(*this, params);
99    } else {
100        return std::make_unique<graph<true>>(*this, params);
101    }
102}
103
104template <bool iswa>
105llama_model_llama4::graph<iswa>::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) {
106    const int64_t n_embd_head = hparams.n_embd_head_v();
107
108    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
109    GGML_ASSERT(n_embd_head == n_rot);
110
111    ggml_tensor * cur;
112    ggml_tensor * inpL;
113
114    inpL = build_inp_embd(model.tok_embd);
115
116    // inp_pos - contains the positions
117    ggml_tensor * inp_pos = build_inp_pos();
118
119    // temperature tuning
120    ggml_tensor * inp_attn_scale = nullptr;
121    inp_attn_scale = build_inp_attn_scale();
122
123    using inp_attn_type = std::conditional_t<iswa, llm_graph_input_attn_kv_iswa, llm_graph_input_attn_kv>;
124    inp_attn_type * inp_attn = nullptr;
125
126    if constexpr (iswa) {
127        inp_attn = build_attn_inp_kv_iswa();
128    } else {
129        inp_attn = build_attn_inp_kv();
130    }
131
132    const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
133
134    ggml_tensor * inp_out_ids = build_inp_out_ids();
135
136    for (int il = 0; il < n_layer; ++il) {
137        const float freq_base_l  = model.get_rope_freq_base (cparams, il);
138        const float freq_scale_l = model.get_rope_freq_scale(cparams, il);
139
140        ggml_tensor * inpSA = inpL;
141
142        // This overlaps with SWA layers in current models, so get_rope_freq_base/scale may be superfluous
143        const bool use_rope = hparams.n_no_rope_layer_step > 0 &&
144                              (il + 1) % hparams.n_no_rope_layer_step != 0;
145
146        // norm
147        cur = build_norm(inpL,
148                model.layers[il].attn_norm, NULL,
149                LLM_NORM_RMS, il);
150        cb(cur, "attn_norm", il);
151
152        // self-attention
153        {
154            // rope freq factors for llama3; may return nullptr for llama2 and other models
155            ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
156
157            // compute Q and K and RoPE them
158            auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur,
159                    n_embd_head, n_head, n_head_kv, il);
160
161            if (use_rope) {
162                Qcur = ggml_rope_ext(
163                        ctx0, Qcur, inp_pos, rope_factors,
164                        n_rot, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,
165                        ext_factor, attn_factor, beta_fast, beta_slow
166                        );
167
168                Kcur = ggml_rope_ext(
169                        ctx0, Kcur, inp_pos, rope_factors,
170                        n_rot, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,
171                        ext_factor, attn_factor, beta_fast, beta_slow
172                        );
173            } else if (inp_attn_scale) {
174                Qcur = ggml_mul(ctx0, Qcur, inp_attn_scale);
175            }
176            cb(Qcur, "Qcur", il);
177            cb(Kcur, "Kcur", il);
178            cb(Vcur, "Vcur", il);
179
180            if (use_rope && hparams.use_kq_norm) {
181                // Llama4TextL2Norm
182                Qcur = ggml_rms_norm(ctx0, Qcur, hparams.f_norm_rms_eps);
183                Kcur = ggml_rms_norm(ctx0, Kcur, hparams.f_norm_rms_eps);
184                cb(Qcur, "Qcur_normed", il);
185                cb(Kcur, "Kcur_normed", il);
186            }
187            cur = build_attn(inp_attn,
188                    model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
189                    Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
190            cb(cur, "attn_out", il);
191        }
192        if (il == n_layer - 1 && inp_out_ids) {
193            cur   = ggml_get_rows(ctx0,   cur, inp_out_ids);
194            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
195        }
196        ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
197        cb(ffn_inp, "ffn_inp", il);
198
199        // feed-forward network (non-MoE)
200        if (model.layers[il].ffn_gate_inp == nullptr) {
201            cur = build_norm(ffn_inp,
202                    model.layers[il].ffn_norm, NULL,
203                    LLM_NORM_RMS, il);
204            cb(cur, "ffn_norm", il);
205
206            cur = build_ffn(cur,
207                    model.layers[il].ffn_up,   model.layers[il].ffn_up_b,   NULL,
208                    model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
209                    model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
210                    NULL,
211                    LLM_FFN_SILU, LLM_FFN_PAR, il);
212            cb(cur, "ffn_out", il);
213        } else {
214            ggml_tensor * ffn_inp_normed = build_norm(ffn_inp,
215                    model.layers[il].ffn_norm, NULL,
216                    LLM_NORM_RMS, il);
217            cb(cur, "ffn_norm", il);
218
219            ggml_tensor * moe_out = build_moe_ffn(ffn_inp_normed,
220                    model.layers[il].ffn_gate_inp,
221                    model.layers[il].ffn_up_exps,
222                    model.layers[il].ffn_gate_exps,
223                    model.layers[il].ffn_down_exps,
224                    nullptr,
225                    n_expert, n_expert_used,
226                    LLM_FFN_SILU, false,
227                    hparams.expert_weights_scale,
228                    LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID,
229                    il);
230
231            // Shared experts
232            ggml_tensor * shexp_out = build_ffn(ffn_inp_normed,
233                model.layers[il].ffn_up_shexp,   NULL, NULL,
234                model.layers[il].ffn_gate_shexp, NULL, NULL,
235                model.layers[il].ffn_down_shexp, NULL, NULL,
236                NULL,
237                LLM_FFN_SILU, LLM_FFN_PAR, il);
238            cb(shexp_out, "ffn_moe_shexp", il);
239
240            cur = ggml_add(ctx0, moe_out, shexp_out);
241            cb(cur, "ffn_moe_out_merged", il);
242        }
243        cur = ggml_add(ctx0, cur, ffn_inp);
244        cb(cur, "ffn_out", il);
245
246        cur = build_cvec(cur, il);
247        cb(cur, "l_out", il);
248
249        // input for next layer
250        inpL = cur;
251    }
252    cur = inpL;
253
254    cur = build_norm(cur,
255            model.output_norm, NULL,
256            LLM_NORM_RMS, -1);
257
258    cb(cur, "result_norm", -1);
259    res->t_embd = cur;
260
261    // lm_head
262    cur = build_lora_mm(model.output, cur, model.output_s);
263
264    cb(cur, "result_output", -1);
265    res->t_logits = cur;
266
267    ggml_build_forward_expand(gf, cur);
268}
269
270// Explicit template instantiations
271template struct llama_model_llama4::graph<false>;
272template struct llama_model_llama4::graph<true>;