char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Georgi Gerganovggml : update ggml_prec specification (#26675)5a6caa05f

char/aliceai-t5-moe
9.2 KiB209 linesraw
1#include "models.h"
2
3ggml_tensor * clip_graph_mimovl::build_mm(ggml_tensor * w, ggml_tensor * x) const {
4    ggml_tensor * cur = ggml_mul_mat(ctx0, w, x);
5    ggml_prec_set_acc(cur, GGML_PREC_F32);
6    return cur;
7}
8
9// MiMoVL vision tower for MiMo-V2.5 (non-Pro). Qwen2.5-VL-shaped ViT, except:
10//   1. GQA in attention (32 Q / 8 KV heads, head_dim 64).
11//   2. Per-head attention sinks on every windowed layer. The sinks adjust
12//      the softmax denominator (equivalently, a virtual extra K column with V=0),
13//      so they decay attention weight without contributing to the output.
14//   3. Per-layer window-attention mode in hparams.wa_pattern_mode:
15//        -1 -> full,  0 -> row-window+sinks,  1 -> col-window+sinks.
16//      Col mode transposes the merge-unit grid on entry and restores
17//      it on exit. Both patch and rotary orderings are pre-computed
18//      host-side.
19//   4. 1D banded sliding window (|q-k| > window_size -> -inf) as a
20//      single 2D mask broadcast across heads.
21//   5. Per-block MLP biases.
22ggml_cgraph * clip_graph_mimovl::build() {
23    GGML_ASSERT(model.patch_embeddings_0 != nullptr);
24    GGML_ASSERT(model.patch_embeddings_1 != nullptr);
25    GGML_ASSERT(model.class_embedding == nullptr);
26    GGML_ASSERT(hparams.n_head_kv > 0);
27    GGML_ASSERT(n_head % hparams.n_head_kv == 0);
28    GGML_ASSERT((int) hparams.wa_pattern_mode.size() == n_layer);
29
30    const int batch_size = 1;
31    const int n_pos      = n_patches;
32    const int n_head_kv  = hparams.n_head_kv;
33    const int merge      = hparams.n_merge > 0 ? hparams.n_merge : 2;
34    const int merge_unit = merge * merge;
35    const int n_units    = n_pos / merge_unit;
36    GGML_ASSERT(n_units * merge_unit == n_pos);
37
38    // MiMoVL has head_dim=64 with n_embd=1280, so n_embd is NOT n_head*head_dim
39    // (the base class's d_head = n_embd/n_head = 40 is wrong here). Derive
40    // head_dim from the fused QKV projection: rows = (n_head + 2*n_head_kv)*head_dim.
41    GGML_ASSERT(model.layers[0].qkv_w != nullptr);
42    const int qkv_rows     = model.layers[0].qkv_w->ne[1];
43    const int head_dim     = qkv_rows / (n_head + 2 * n_head_kv);
44    GGML_ASSERT(head_dim * (n_head + 2 * n_head_kv) == qkv_rows);
45    const float attn_scale = 1.0f / std::sqrt((float) head_dim);
46    const int rope_n_dims = head_dim / 2;
47    int mrope_sections[4] = {rope_n_dims/2, rope_n_dims/2, 0, 0};
48
49    // Patch embed: Conv3D(kt=2) split into two Conv2D, then interleave-merge
50    // along the height axis to match the merge-tile token order.
51    ggml_tensor * inp_raw = build_inp_raw();
52    ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw,
53                                     patch_size, patch_size, 0, 0, 1, 1);
54    {
55        ggml_tensor * inp_1 = ggml_conv_2d(ctx0, model.patch_embeddings_1, inp_raw,
56                                           patch_size, patch_size, 0, 0, 1, 1);
57        inp = ggml_add(ctx0, inp, inp_1);
58
59        GGML_ASSERT(img.nx() % (patch_size * 2) == 0);
60        GGML_ASSERT(img.ny() % (patch_size * 2) == 0);
61
62        inp = ggml_permute(ctx0, inp, 1, 2, 0, 3);  // [w,h,c,b] -> [c,w,h,b]
63        inp = ggml_cont_4d(ctx0, inp, n_embd * 2, n_patches_x / 2, n_patches_y, batch_size);
64        inp = ggml_reshape_4d(ctx0, inp, n_embd * 2, n_patches_x / 2, 2, batch_size * (n_patches_y / 2));
65        inp = ggml_permute(ctx0, inp, 0, 2, 1, 3);
66        inp = ggml_cont_3d(ctx0, inp, n_embd, n_patches_x * n_patches_y, batch_size);
67    }
68    cb(inp, "patch_embed", -1);
69
70    ggml_tensor * positions_row = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pos * 4);
71    ggml_set_name(positions_row, "mimovl_positions_row");
72    ggml_set_input(positions_row);
73
74    ggml_tensor * positions_col = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pos * 4);
75    ggml_set_name(positions_col, "mimovl_positions_col");
76    ggml_set_input(positions_col);
77
78    // idx_col is the col-major merge-unit permutation. Take it as F32 so we can
79    // derive the inverse permutation in-graph via ggml_argsort;
80    // ggml_get_rows requires its index tensor to be I32, so cast back as well.
81    ggml_tensor * idx_col_f = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_units);
82    ggml_set_name(idx_col_f, "mimovl_idx_col");
83    ggml_set_input(idx_col_f);
84    ggml_tensor * idx_col     = ggml_cast(ctx0, idx_col_f, GGML_TYPE_I32);
85    ggml_tensor * idx_col_inv = ggml_argsort(ctx0, idx_col_f, GGML_SORT_ORDER_ASC);
86
87    ggml_tensor * window_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_pos, n_pos);
88    ggml_set_name(window_mask, "mimovl_window_mask");
89    ggml_set_input(window_mask);
90
91    ggml_tensor * window_mask_attn = (flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED)
92        ? ggml_cast(ctx0, window_mask, GGML_TYPE_F16)
93        : window_mask;
94
95    // Reorder helper: permute patches at merge-unit granularity. The patch
96    // sequence is laid out as n_units groups of merge_unit (=4) consecutive
97    // patches; the row<->col transpose only permutes whole groups. We keep
98    // the per-group (h,w) ordering intact by reshaping to
99    // [n_embd*merge_unit, n_units] before ggml_get_rows.
100    auto reorder = [&](ggml_tensor * x, ggml_tensor * idx) {
101        ggml_tensor * y = ggml_reshape_2d(ctx0, x, n_embd * merge_unit, n_units);
102        y = ggml_get_rows(ctx0, y, idx);
103        return ggml_reshape_3d(ctx0, y, n_embd, n_pos, batch_size);
104    };
105
106    ggml_tensor * inpL = inp;
107    int prev_mode = -1;
108
109    for (int il = 0; il < n_layer; il++) {
110        const auto & layer = model.layers[il];
111        const int  mode    = hparams.wa_pattern_mode[il];
112        const bool is_full = (mode == -1);
113        const bool is_col  = (mode == 1);
114
115        // Reorder transitions on entry/exit of a col-mode run.
116        if (is_col && prev_mode != 1) {
117            inpL = reorder(inpL, idx_col);
118            cb(inpL, "reorder_to_col", il);
119        } else if (!is_col && prev_mode == 1) {
120            inpL = reorder(inpL, idx_col_inv);
121            cb(inpL, "reorder_to_row", il);
122        }
123
124        ggml_tensor * cur = inpL;
125
126        // Pre-attention RMSNorm.
127        cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, NORM_TYPE_RMS, eps, il);
128        cb(cur, "ln1", il);
129
130        // Fused QKV with GQA.
131        ggml_tensor * qkv = build_mm(layer.qkv_w, cur);
132        qkv = ggml_add(ctx0, qkv, layer.qkv_b);
133
134        const size_t row    = ggml_row_size(qkv->type, head_dim);
135        const size_t off_k  = ggml_row_size(qkv->type, n_head    * head_dim);
136        const size_t off_v  = ggml_row_size(qkv->type, (n_head + n_head_kv) * head_dim);
137
138        ggml_tensor * Qcur = ggml_view_3d(ctx0, qkv, head_dim, n_head,    n_pos, row, qkv->nb[1], 0);
139        ggml_tensor * Kcur = ggml_view_3d(ctx0, qkv, head_dim, n_head_kv, n_pos, row, qkv->nb[1], off_k);
140        ggml_tensor * Vcur = ggml_view_3d(ctx0, qkv, head_dim, n_head_kv, n_pos, row, qkv->nb[1], off_v);
141
142        cb(Qcur, "Qcur", il);
143        cb(Kcur, "Kcur", il);
144        cb(Vcur, "Vcur", il);
145
146        // 2D RoPE
147        ggml_tensor * pos = is_col ? positions_col : positions_row;
148        Qcur = ggml_rope_multi(ctx0, Qcur, pos, nullptr, rope_n_dims, mrope_sections, GGML_ROPE_TYPE_VISION, 32768, 10000.0f, 1.0f, 0.0f, 1.0f, 32.0f, 1.0f);
149        Kcur = ggml_rope_multi(ctx0, Kcur, pos, nullptr, rope_n_dims, mrope_sections, GGML_ROPE_TYPE_VISION, 32768, 10000.0f, 1.0f, 0.0f, 1.0f, 32.0f, 1.0f);
150        cb(Qcur, "Qcur_rope", il);
151        cb(Kcur, "Kcur_rope", il);
152
153        // Full layers: plain attention. Windowed layers: banded mask and per-head sinks.
154        ggml_tensor * mask  = is_full ? nullptr : window_mask_attn;
155        ggml_tensor * sinks = is_full ? nullptr : layer.attn_sinks;
156        if (!is_full) {
157            GGML_ASSERT(layer.attn_sinks != nullptr);
158        }
159        ggml_tensor * attn_out = build_attn(layer.o_w, layer.o_b, Qcur, Kcur, Vcur, mask, attn_scale, il, sinks);
160        cb(attn_out, "attn_out", il);
161
162        // Residual 1.
163        cur = ggml_add(ctx0, attn_out, inpL);
164        inpL = cur;
165        cb(cur, "ffn_inp", il);
166
167        // Pre-FFN RMSNorm.
168        cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, NORM_TYPE_RMS, eps, il);
169        cb(cur, "ffn_inp_normed", il);
170
171        // SwiGLU MLP with biases
172        cur = build_ffn(cur,
173            layer.ff_up_w,   layer.ff_up_b,
174            layer.ff_gate_w, layer.ff_gate_b,
175            layer.ff_down_w, layer.ff_down_b,
176            hparams.ffn_op, il);
177        cb(cur, "ffn_out", il);
178
179        // Residual 2.
180        cur = ggml_add(ctx0, inpL, cur);
181        cb(cur, "layer_out", il);
182
183        inpL = cur;
184        prev_mode = mode;
185    }
186
187    // If the last block was col-mode, undo the transpose so the merger sees patches in row order.
188    if (prev_mode == 1) {
189        inpL = reorder(inpL, idx_col_inv);
190        cb(inpL, "reorder_to_row_final", -1);
191    }
192
193    // Merger: post-LayerNorm
194    inpL = build_norm(inpL, model.post_ln_w, model.post_ln_b, NORM_TYPE_NORMAL, 1e-6f, n_layer);
195    cb(inpL, "post_ln", -1);
196
197    // Spatial merge: pack each merge_unit (=4) of patches into a single
198    // (n_embd*merge_unit)-wide row, then run the 2-layer MLP.
199    ggml_tensor * embeddings = ggml_reshape_3d(ctx0, inpL, n_embd * merge_unit, n_units, batch_size);
200    embeddings = build_ffn(embeddings,
201        model.mm_0_w, nullptr,
202        nullptr,      nullptr,
203        model.mm_1_w, nullptr,
204        FFN_GELU, -1);
205    cb(embeddings, "vit_out", -1);
206
207    ggml_build_forward_expand(gf, embeddings);
208    return gf;
209}