Coverage Report

Created: 2026-08-22 07:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/src/models/glm4-moe.cpp
Line
Count
Source
1
#include "models.h"
2
3
0
void llama_model_glm4_moe::load_arch_hparams(llama_model_loader & ml) {
4
0
    ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH,     hparams.n_ff_exp);
5
0
    ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,    hparams.f_norm_rms_eps);
6
0
    ml.get_key_or_arr(LLM_KV_ROPE_DIMENSION_SECTIONS, hparams.rope_sections, 4, false);
7
8
    // MoE parameters
9
0
    ml.get_key(LLM_KV_EXPERT_SHARED_COUNT,         hparams.n_expert_shared);
10
0
    ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT,   hparams.n_layer_dense_lead, false);
11
0
    ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE,        hparams.expert_weights_scale, false);
12
0
    ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM,         hparams.expert_weights_norm, false);
13
14
    // Expert gating function (GLM-4.5 uses sigmoid)
15
0
    ml.get_key(LLM_KV_EXPERT_GATING_FUNC,          hparams.expert_gating_func, false);
16
0
    if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) {
17
0
        hparams.expert_gating_func =  LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID;
18
0
    }
19
20
    // NextN/MTP parameters
21
0
    ml.get_key(LLM_KV_NEXTN_PREDICT_LAYERS, hparams.n_layer_nextn, false);
22
0
    GGML_ASSERT(hparams.n_layer_nextn < hparams.n_layer_all && "n_layer_nextn must be < n_layer_impl");
23
24
0
    switch (hparams.n_layer()) {
25
0
        case 46: type = LLM_TYPE_106B_A12B; break; // GLM-4.5-Air
26
0
        case 48: type = LLM_TYPE_102B_A12B; break; // Solar Open
27
0
        case 92: type = LLM_TYPE_355B_A32B; break; // GLM-4.5
28
0
        default: type = LLM_TYPE_UNKNOWN;
29
0
    }
30
0
}
31
32
0
void llama_model_glm4_moe::load_arch_tensors(llama_model_loader &) {
33
0
    LLAMA_LOAD_LOCALS;
34
0
    const int64_t n_expert_shared = hparams.n_expert_shared;
35
36
37
0
    GGML_ASSERT(hparams.n_expert > 0 && "n_expert must be > 0 for GLM4_MOE MoE layers");
38
0
    GGML_ASSERT(hparams.n_expert_used > 0 && "n_expert_used must be > 0 for GLM4_MOE MoE layers");
39
40
0
    tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, 0);
41
42
    // output
43
0
    output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
44
0
    output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED);
45
    // if output is NULL, init from the input tok embed
46
0
    if (output == NULL) {
47
0
        output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, TENSOR_DUPLICATED);
48
0
    }
49
50
    // Load ALL tensors including NextN layer to satisfy total tensor count
51
    // but only PROCESS up to last layer (skipping final NextN layer) in forward pass
52
0
    for (int i = 0; i < n_layer_all; ++i) {
53
0
        int flags = 0;
54
0
        if (i >= n_layer) {
55
            // skip all tensors in the NextN layers
56
0
            flags |= TENSOR_SKIP;
57
0
        }
58
59
0
        auto & layer = layers[i];
60
61
0
        layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd }, flags);
62
63
        // GLM-style attention with bias terms
64
0
        create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head, n_embd_k_gqa, n_embd_v_gqa, flags);
65
66
0
        layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd_head_k * n_head, n_embd }, flags);
67
68
        // K/Q norm tensors (optional for GLM-4.5 355B variant)
69
0
        layer.attn_q_norm = create_tensor(
70
0
            tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), { n_embd_head_k }, TENSOR_NOT_REQUIRED | flags);
71
0
        layer.attn_k_norm = create_tensor(
72
0
            tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), { n_embd_head_k }, TENSOR_NOT_REQUIRED | flags);
73
74
0
        layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), { n_embd }, flags);
75
76
        // Check if this layer uses MoE or dense FFN based on n_layer_dense_lead
77
        // GLM 4.5 uses hybrid architecture: layer 0 is dense, layers 1+ are MoE
78
0
        const bool use_moe = (static_cast<uint32_t>(i) >= hparams.n_layer_dense_lead);
79
80
0
        if (use_moe) {
81
            // MoE layers
82
0
            layer.ffn_gate_inp =
83
0
                create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), { n_embd, n_expert }, flags);
84
0
            layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), { n_expert }, flags);
85
86
            // MoE branch
87
0
            const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
88
89
0
            layer.ffn_gate_exps = create_tensor(
90
0
                tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert }, flags);
91
0
            layer.ffn_down_exps = create_tensor(
92
0
                tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff_exp, n_embd, n_expert }, flags);
93
0
            layer.ffn_up_exps = create_tensor(
94
0
                tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert }, flags);
95
96
            // Shared expert
97
0
            if (n_expert_shared > 0) {
98
0
                const int64_t n_ff_shexp = n_ff_exp * n_expert_shared;
99
0
                layer.ffn_gate_shexp = create_tensor(
100
0
                    tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp }, flags);
101
0
                layer.ffn_down_shexp = create_tensor(
102
0
                    tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff_shexp, n_embd }, flags);
103
0
                layer.ffn_up_shexp = create_tensor(
104
0
                    tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp }, flags);
105
0
            }
106
0
        } else {
107
            // Dense layers (first k layers) - GLM uses separate gate/up projections
108
0
            layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), { n_embd, n_ff }, flags);
109
0
            layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd }, flags);
110
0
            layer.ffn_up   = create_tensor(tn(LLM_TENSOR_FFN_UP,   "weight", i), { n_embd, n_ff }, flags);
111
0
        }
112
113
        // NextN/MTP tensors (preserved but unused) - conditionally load for last nextn_predict_layers
114
0
        if (i >= n_layer) {
115
0
            layer.nextn.eh_proj          = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), { 2 * n_embd, n_embd }, flags);
116
0
            layer.nextn.enorm            = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), { n_embd }, flags);
117
0
            layer.nextn.hnorm            = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), { n_embd }, flags);
118
119
            // Optional tensors
120
0
            layer.nextn.embed_tokens     = create_tensor(tn(LLM_TENSOR_NEXTN_EMBED_TOKENS, "weight", i), { n_embd, n_vocab }, flags | TENSOR_NOT_REQUIRED);
121
0
            layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, flags | TENSOR_NOT_REQUIRED);
122
0
            layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, flags | TENSOR_NOT_REQUIRED);
123
0
        }
124
0
    }
125
0
}
126
127
0
std::unique_ptr<llm_graph_context> llama_model_glm4_moe::build_arch_graph(const llm_graph_params & params) const {
128
0
    return std::make_unique<graph>(*this, params);
129
0
}
130
131
0
llama_model_glm4_moe::graph::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) {
132
0
    const int64_t n_embd_head = hparams.n_embd_head_v();
133
134
0
    GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
135
136
0
    int sections[4];
137
0
    std::copy(std::begin(hparams.rope_sections), std::begin(hparams.rope_sections) + 4, sections);
138
139
0
    ggml_tensor * cur;
140
0
    ggml_tensor * inpL;
141
142
0
    inpL = build_inp_embd(model.tok_embd);
143
144
0
    bool use_mrope = hparams.use_mrope();
145
0
    if (ubatch.embd && !use_mrope) {
146
        // unfortunately, we need to forcefully stop here, to avoid users complaining about wrong results
147
0
        GGML_ABORT("This GGUF does not support multimodal. Please reconvert it.");
148
0
    }
149
150
    // inp_pos - contains the positions
151
0
    ggml_tensor * inp_pos = build_inp_pos();
152
153
0
    auto * inp_attn = build_attn_inp_kv();
154
155
0
    ggml_tensor * inp_out_ids = build_inp_out_ids();
156
157
    // Only process up to last layer (skip final NextN layer)
158
    // Final layer tensors are loaded but not processed in forward pass
159
0
    for (int il = 0; il < n_layer; ++il) {
160
0
        ggml_tensor * inpSA = inpL;
161
162
        // Pre-attention norm
163
0
        cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
164
0
        cb(cur, "attn_norm", il);
165
166
        // self-attention
167
0
        {
168
0
            auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur,
169
0
                    n_embd_head, n_head, n_head_kv, il);
170
171
            // Apply Q/K norm if available (GLM-4.5 355B variant)
172
0
            if (model.layers[il].attn_q_norm) {
173
0
                Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il);
174
0
                cb(Qcur, "Qcur_normed", il);
175
0
            }
176
0
            if (model.layers[il].attn_k_norm) {
177
0
                Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il);
178
0
                cb(Kcur, "Kcur_normed", il);
179
0
            }
180
181
0
            if (use_mrope) {
182
0
                Qcur = ggml_rope_multi(ctx0, Qcur, inp_pos, nullptr,
183
0
                            n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
184
0
                            ext_factor, attn_factor, beta_fast, beta_slow);
185
186
0
                Kcur = ggml_rope_multi(ctx0, Kcur, inp_pos, nullptr,
187
0
                            n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
188
0
                            ext_factor, attn_factor, beta_fast, beta_slow);
189
0
            } else {
190
                // Normal RoPE
191
0
                Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, n_rot,
192
0
                                    rope_type, n_ctx_orig, freq_base, freq_scale,
193
0
                                    ext_factor, attn_factor, beta_fast, beta_slow);
194
195
0
                Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, n_rot,
196
0
                                    rope_type, n_ctx_orig, freq_base, freq_scale,
197
0
                                    ext_factor, attn_factor, beta_fast, beta_slow);
198
0
            }
199
200
0
            cb(Qcur, "Qcur", il);
201
0
            cb(Kcur, "Kcur", il);
202
0
            cb(Vcur, "Vcur", il);
203
204
0
            cur = build_attn(inp_attn,
205
0
                    model.layers[il].wo, NULL, model.layers[il].wo_s,
206
0
                    Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
207
0
        }
208
0
        if (il == n_layer - 1 && inp_out_ids) {
209
0
            cur   = ggml_get_rows(ctx0, cur, inp_out_ids);
210
0
            inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
211
0
        }
212
0
        ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
213
0
        cb(ffn_inp, "ffn_inp", il);
214
215
        // Post-attention norm
216
0
        cur = build_norm(ffn_inp, model.layers[il].attn_post_norm, NULL, LLM_NORM_RMS, il);
217
0
        cb(cur, "post_attn_norm", il);
218
219
        // Check if this is a dense layer (n_layer_dense_lead=1, so layer 0 is dense)
220
0
        if (static_cast<uint32_t>(il) < hparams.n_layer_dense_lead) {
221
            // Dense FFN layer
222
0
            cur = build_ffn(cur,
223
0
                    model.layers[il].ffn_up,   NULL, NULL,
224
0
                    model.layers[il].ffn_gate, NULL, NULL,
225
0
                    model.layers[il].ffn_down, NULL, NULL,
226
0
                    NULL,
227
0
                    LLM_FFN_SILU, LLM_FFN_PAR, il);
228
0
            cb(cur, "ffn_out", il);
229
0
        } else {
230
            // Process routed experts using existing MoE infrastructure
231
0
            ggml_tensor * routed_out = build_moe_ffn(cur,
232
0
                    model.layers[il].ffn_gate_inp,
233
0
                    model.layers[il].ffn_up_exps,
234
0
                    model.layers[il].ffn_gate_exps,
235
0
                    model.layers[il].ffn_down_exps,
236
0
                    model.layers[il].ffn_exp_probs_b,
237
0
                    n_expert, n_expert_used,
238
0
                    LLM_FFN_SILU, hparams.expert_weights_norm,
239
0
                    hparams.expert_weights_scale,
240
0
                    (llama_expert_gating_func_type) hparams.expert_gating_func,
241
0
                    il);
242
0
            cb(routed_out, "ffn_moe_out", il);
243
244
            // Process shared expert on original input
245
0
            ggml_tensor * shared_out = build_ffn(cur,
246
0
                    model.layers[il].ffn_up_shexp,   NULL, NULL,
247
0
                    model.layers[il].ffn_gate_shexp, NULL, NULL,
248
0
                    model.layers[il].ffn_down_shexp, NULL, NULL,
249
0
                    NULL,
250
0
                    LLM_FFN_SILU, LLM_FFN_PAR, il);
251
0
            cb(shared_out, "ffn_shexp_out", il);
252
253
            // Final output: routed_output + shared_output
254
0
            cur = ggml_add(ctx0, routed_out, shared_out);
255
0
            cb(cur, "ffn_out", il);
256
0
        }
257
0
        cur = ggml_add(ctx0, cur, ffn_inp);
258
259
0
        cur = build_cvec(cur, il);
260
0
        cb(cur, "l_out", il);
261
262
        // input for next layer
263
0
        inpL = cur;
264
0
    }
265
0
    cur = inpL;
266
0
    cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1);
267
268
0
    cb(cur, "result_norm", -1);
269
0
    res->t_embd = cur;
270
271
    // lm_head
272
0
    cur = build_lora_mm(model.output, cur, model.output_s);
273
274
0
    cb(cur, "result_output", -1);
275
0
    res->t_logits = cur;
276
277
0
    ggml_build_forward_expand(gf, cur);
278
0
}