char-fork/llama.cpp

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

Xuan-Son Nguyenmtmd: support pocket-tts (#26871)6e62ba538

char/aliceai-t5-moe
13.2 KiB291 linesraw
1#include "models.h"
2
3#include <cmath>
4
5// pocket-tts generation stages
6//
7// GEN_CODE: backbone hidden state -> next 32-d latent (flow matching) + end-of-speech score
8// GEN_WAV : a window of latents -> PCM, through the mimi decoder
9//
10// there is no codebook anywhere, "codes" in the mtmd API are continuous features here
11
12ggml_tensor * clip_graph_pockettts_gen::modulate(ggml_tensor * x, ggml_tensor * shift, ggml_tensor * scale) const {
13    ggml_tensor * cur = ggml_mul(ctx0, x, ggml_scale_bias(ctx0, scale, 1.0f, 1.0f));
14    return ggml_add(ctx0, cur, shift);
15}
16
17// see TimestepEmbedder in the reference
18ggml_tensor * clip_graph_pockettts_gen::time_embed(const clip_flow_net::time_embd & te, float t) const {
19    // t is a graph-build constant, so the cos/sin table can be folded into a scaled copy
20    ggml_tensor * args = ggml_scale(ctx0, te.freqs, t);
21    ggml_tensor * emb  = ggml_concat(ctx0, ggml_cos(ctx0, args), ggml_sin(ctx0, args), 0);
22
23    ggml_tensor * cur = build_mm(te.up_w, emb);
24    cur = ggml_add(ctx0, cur, te.up_b);
25    cur = ggml_silu(ctx0, cur);
26    cur = build_mm(te.down_w, cur);
27    cur = ggml_add(ctx0, cur, te.down_b);
28
29    // this "RMSNorm" divides by the unbiased variance, not the mean square
30    // it also rescales the input, not the centered value, see _rms_norm() in mlp.py
31    {
32        const int64_t n = cur->ne[0];
33        ggml_tensor * mean = ggml_mean(ctx0, cur);
34        ggml_tensor * dev  = ggml_sub(ctx0, cur, mean);
35        ggml_tensor * var  = ggml_mean(ctx0, ggml_sqr(ctx0, dev));
36        var = ggml_scale_bias(ctx0, var, (float) n / (float) (n - 1), 1e-5f);
37        cur = ggml_div(ctx0, cur, ggml_sqrt(ctx0, var));
38        cur = ggml_mul(ctx0, cur, te.norm);
39    }
40
41    return cur;
42}
43
44// one velocity evaluation: v(cond, s, t, x)
45ggml_tensor * clip_graph_pockettts_gen::flow_forward(ggml_tensor * cond, ggml_tensor * x, float s, float t) const {
46    const auto & flow = model.flow;
47
48    ggml_tensor * cur = build_mm(flow.input_proj_w, x);
49    cur = ggml_add(ctx0, cur, flow.input_proj_b);
50
51    // the two time conditions are averaged, then added to the projected backbone state
52    ggml_tensor * ts = ggml_add(ctx0, time_embed(flow.time[0], s), time_embed(flow.time[1], t));
53    ts = ggml_scale(ctx0, ts, 1.0f / (float) flow.time.size());
54
55    ggml_tensor * c = build_mm(flow.cond_embd_w, cond);
56    c = ggml_add(ctx0, c, flow.cond_embd_b);
57
58    ggml_tensor * y = ggml_add(ctx0, ts, c);
59    cb(y, "flow_cond", -1);
60
61    const int64_t n_ch = flow.blocks.empty() ? 0 : flow.blocks[0].norm_w->ne[0];
62
63    for (size_t il = 0; il < flow.blocks.size(); il++) {
64        const auto & blk = flow.blocks[il];
65
66        ggml_tensor * mod = build_mm(blk.ada_w, ggml_silu(ctx0, y));
67        mod = ggml_add(ctx0, mod, blk.ada_b);
68
69        ggml_tensor * shift = ggml_view_1d(ctx0, mod, n_ch, 0);
70        ggml_tensor * scale = ggml_view_1d(ctx0, mod, n_ch, (size_t) n_ch * mod->nb[0]);
71        ggml_tensor * gate  = ggml_view_1d(ctx0, mod, n_ch, (size_t) 2 * n_ch * mod->nb[0]);
72
73        ggml_tensor * h = build_norm(cur, blk.norm_w, blk.norm_b, NORM_TYPE_NORMAL, 1e-6f, (int) il);
74        h = modulate(h, shift, scale);
75        h = build_mm(blk.up_w, h);
76        h = ggml_add(ctx0, h, blk.up_b);
77        h = ggml_silu(ctx0, h);
78        h = build_mm(blk.down_w, h);
79        h = ggml_add(ctx0, h, blk.down_b);
80
81        cur = ggml_add(ctx0, cur, ggml_mul(ctx0, gate, h));
82        cb(cur, "flow_blk", (int) il);
83    }
84
85    // final layer: the norm has no weights, only the AdaLN modulation
86    ggml_tensor * mod = build_mm(flow.final_ada_w, ggml_silu(ctx0, y));
87    mod = ggml_add(ctx0, mod, flow.final_ada_b);
88
89    ggml_tensor * shift = ggml_view_1d(ctx0, mod, n_ch, 0);
90    ggml_tensor * scale = ggml_view_1d(ctx0, mod, n_ch, (size_t) n_ch * mod->nb[0]);
91
92    cur = build_norm(cur, nullptr, nullptr, NORM_TYPE_NORMAL, 1e-6f, -1);
93    cur = modulate(cur, shift, scale);
94    cur = build_mm(flow.final_proj_w, cur);
95    cur = ggml_add(ctx0, cur, flow.final_proj_b);
96
97    return cur;
98}
99
100// state carried between GEN_WAV calls: rope offset, per-layer KV window, conv left context
101// and the transposed-conv overlap tails
102std::vector<c2w_state_slot> list_pockettts_state_slots(const clip_hparams & hparams, const clip_model & model) {
103    std::vector<c2w_state_slot> slots;
104    if (model.gen_upsample_w == nullptr) {
105        return slots; // not a pocket-tts decoder
106    }
107    const auto & seanet = model.seanet;
108
109    // the slots below are sized from these
110    GGML_ASSERT(!model.gen_tfm_layers.empty());
111    GGML_ASSERT((int) seanet.stages.size() >= hparams.seanet_n_stage);
112    GGML_ASSERT((int) hparams.seanet_ratios.size() >= hparams.seanet_n_stage);
113    GGML_ASSERT(hparams.mimi_tfm_context > 1 && hparams.mimi_downsample > 0);
114
115    slots.push_back({"tfm_pos", 1, 1});
116
117    const int64_t n_embd_a = model.gen_tfm_layers[0].q_w->ne[1];
118    const int64_t prefix   = hparams.mimi_tfm_context - 1;
119    for (size_t il = 0; il < model.gen_tfm_layers.size(); il++) {
120        slots.push_back({"tfm_k_" + std::to_string(il), n_embd_a, prefix});
121        slots.push_back({"tfm_v_" + std::to_string(il), n_embd_a, prefix});
122    }
123
124    // upsample is depthwise, its output channel count is the input one
125    slots.push_back({"up", model.gen_upsample_w->ne[0] - hparams.mimi_downsample, model.gen_upsample_w->ne[2]});
126
127    slots.push_back({"dec_in", seanet.conv_in_w->ne[0] - 1, seanet.conv_in_w->ne[1]});
128    for (int i = 0; i < hparams.seanet_n_stage; i++) {
129        const auto & stage  = seanet.stages[i];
130        const int    stride = hparams.seanet_ratios[hparams.seanet_n_stage - 1 - i];
131        slots.push_back({"dec_up_" + std::to_string(i), stage.scale_conv_w->ne[0] - stride, stage.scale_conv_w->ne[1]});
132        slots.push_back({"dec_res_" + std::to_string(i), stage.res_conv1_w->ne[0] - 1, stage.res_conv1_w->ne[1]});
133    }
134    slots.push_back({"dec_out", seanet.conv_out_w->ne[0] - 1, seanet.conv_out_w->ne[1]});
135
136    return slots;
137}
138
139ggml_cgraph * clip_graph_pockettts_gen::build() {
140    if (gen_process == CLIP_GEN_PROCESS_GEN_CODE) {
141        // the backbone hidden state arrives as the single batch entry
142        ggml_tensor * h_state = build_inp_raw(1);
143        h_state = ggml_reshape_2d(ctx0, h_state, n_mmproj_embd, 1);
144
145        // end-of-speech probe, thresholded on the host side
146        ggml_tensor * eos = build_mm(model.gen_out_eos_w, h_state);
147        eos = ggml_add(ctx0, eos, model.gen_out_eos_b);
148        ggml_set_name(eos, "out_eos_score");
149        ggml_set_output(eos);
150        ggml_build_forward_expand(gf, eos);
151
152        const int64_t n_latent = model.gen_input_lin_w->ne[0];
153
154        ggml_tensor * noise = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_latent, 1);
155        ggml_set_name(noise, "inp_noise");
156        ggml_set_input(noise);
157
158        // lsd_decode: integrate the velocity field from the noise sample
159        ggml_tensor * cur = noise;
160        for (int i = 0; i < n_step; i++) {
161            const float s = (float) i / (float) n_step;
162            const float t = (float) (i + 1) / (float) n_step;
163            ggml_tensor * v = flow_forward(h_state, cur, s, t);
164            cur = ggml_add(ctx0, cur, ggml_scale(ctx0, v, 1.0f / (float) n_step));
165        }
166        cb(cur, "flow_latent", -1);
167
168        ggml_set_name(cur, "out_feats");
169        ggml_set_output(cur);
170        ggml_build_forward_expand(gf, cur);
171
172        // the same latent, projected into the backbone's input space for the next step
173        ggml_tensor * embd = build_mm(model.gen_input_lin_w, cur);
174        cb(embd, "gen_embd", -1);
175        ggml_build_forward_expand(gf, embd);
176
177        return gf;
178    }
179
180    // GEN_WAV: [32, n_frames] latents -> PCM
181    ggml_tensor * feats = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32,
182                                             model.gen_input_lin_w->ne[0], n_frames);
183    ggml_set_name(feats, "inp_feats");
184    ggml_set_input(feats);
185
186    // denormalize, then the DummyQuantizer up-projection
187    ggml_tensor * cur = ggml_add(ctx0, ggml_mul(ctx0, feats, model.gen_emb_std), model.gen_emb_mean);
188    cur = build_mm(model.gen_quant_out_w, cur);
189    cb(cur, "quant_out", -1);
190
191    clip_graph_pockettts_seanet seanet(*this);
192    for (const auto & slot : list_pockettts_state_slots(hparams, model)) {
193        ggml_tensor * t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1);
194        ggml_set_name(t, ("state_in_" + slot.name).c_str());
195        ggml_set_input(t);
196        seanet.state_in[slot.name] = t;
197    }
198
199    // model frame rate -> encoder frame rate, depthwise transposed conv
200    cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
201    cur = seanet.conv_transpose1d(cur, model.gen_upsample_w, nullptr, hparams.mimi_downsample, "up");
202    cb(cur, "mimi_upsample", -1);
203
204    cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
205
206    // positions continue across calls, the counter lives in the state
207    const int64_t n_pos  = cur->ne[1];
208    const int64_t prefix = hparams.mimi_tfm_context - 1;
209    const int64_t n_kv   = prefix + n_pos;
210
211    ggml_tensor * base    = ggml_reshape_1d(ctx0, seanet.state_in.at("tfm_pos"), 1);
212    ggml_tensor * inp_pos = ggml_cast(ctx0, ggml_add(ctx0, ggml_arange(ctx0, 0.0f, (float) n_pos, 1.0f), base),
213                                      GGML_TYPE_I32);
214    seanet.state_out.push_back({"tfm_pos", ggml_scale_bias(ctx0, seanet.state_in.at("tfm_pos"), 1.0f, (float) n_pos)});
215
216    // banded causal mask over [cached prefix | this chunk]
217    // the last factor masks out cache rows that hold no real frame yet
218    ggml_tensor * pos_k = ggml_reshape_2d(ctx0, ggml_arange(ctx0, 0.0f, (float) n_kv, 1.0f), n_kv, 1);
219    ggml_tensor * pos_q = ggml_reshape_2d(ctx0, ggml_arange(ctx0, (float) prefix, (float) (prefix + n_pos), 1.0f), 1, n_pos);
220    ggml_tensor * diff  = ggml_sub(ctx0, ggml_repeat_4d(ctx0, pos_q, n_kv, n_pos, 1, 1), pos_k);
221
222    ggml_tensor * keep = ggml_mul(ctx0,
223        ggml_step(ctx0, ggml_scale_bias(ctx0, diff, 1.0f, 0.5f)),                                     // delta >= 0
224        ggml_step(ctx0, ggml_scale_bias(ctx0, diff, -1.0f, (float) hparams.mimi_tfm_context - 0.5f))); // delta < context
225    keep = ggml_mul(ctx0, keep,
226        ggml_step(ctx0, ggml_scale_bias(ctx0, ggml_add(ctx0, pos_k, base), 1.0f, 0.5f - (float) prefix)));
227    ggml_tensor * kq_mask = ggml_reshape_4d(ctx0, ggml_log(ctx0, keep), n_kv, n_pos, 1, 1);
228
229    for (int il = 0; il < n_layer; il++) {
230        const auto & layer = model.gen_tfm_layers[il];
231        ggml_tensor * inp = cur;
232
233        cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, NORM_TYPE_NORMAL, eps, il);
234
235        ggml_tensor * Qcur = build_mm(layer.q_w, cur);
236        ggml_tensor * Kcur = build_mm(layer.k_w, cur);
237        ggml_tensor * Vcur = build_mm(layer.v_w, cur);
238
239        Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos);
240        Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos);
241
242        Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0,
243                             hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
244        Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0,
245                             hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
246
247        // prepend the cached window, then keep this chunk's tail for the next call
248        const std::string k_name = "tfm_k_" + std::to_string(il);
249        const std::string v_name = "tfm_v_" + std::to_string(il);
250        ggml_tensor * k_full = ggml_concat(ctx0, seanet.state_in.at(k_name),
251                                           ggml_reshape_2d(ctx0, Kcur, d_head * n_head, n_pos), 1);
252        ggml_tensor * v_full = ggml_concat(ctx0, seanet.state_in.at(v_name), Vcur, 1);
253        seanet.state_out.push_back({k_name, ggml_cont(ctx0, ggml_view_2d(ctx0, k_full, k_full->ne[0], prefix,
254                                                                         k_full->nb[1], (size_t) n_pos * k_full->nb[1]))});
255        seanet.state_out.push_back({v_name, ggml_cont(ctx0, ggml_view_2d(ctx0, v_full, v_full->ne[0], prefix,
256                                                                         v_full->nb[1], (size_t) n_pos * v_full->nb[1]))});
257
258        ggml_tensor * q_cur = ggml_reshape_4d(ctx0, Qcur,   d_head, n_head, n_pos, 1);
259        ggml_tensor * k_cur = ggml_reshape_4d(ctx0, k_full, d_head, n_head, n_kv,  1);
260        ggml_tensor * v_cur = ggml_reshape_4d(ctx0, v_full, d_head, n_head, n_kv,  1);
261
262        cur = build_attn(layer.o_w, nullptr, q_cur, k_cur, v_cur, kq_mask, kq_scale, il);
263        cur = ggml_mul(ctx0, cur, layer.ls_1_w);
264        cur = ggml_add(ctx0, cur, inp);
265
266        inp = cur;
267        cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, NORM_TYPE_NORMAL, eps, il);
268        cur = build_ffn(cur, layer.ff_up_w, nullptr, nullptr, nullptr, layer.ff_down_w, nullptr, FFN_GELU, il);
269        cur = ggml_mul(ctx0, cur, layer.ls_2_w);
270        cur = ggml_add(ctx0, cur, inp);
271    }
272    cb(cur, "mimi_dec_tfm", -1);
273
274    cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
275    cur = seanet.decode(cur);
276
277    for (const auto & s : seanet.state_out) {
278        ggml_set_name(s.second, ("state_out_" + s.first).c_str());
279        ggml_set_output(s.second);
280        ggml_build_forward_expand(gf, s.second);
281    }
282
283    // [n_samples, 1] -> [n_samples], clamped like the reference output
284    cur = ggml_reshape_1d(ctx0, cur, cur->ne[0]);
285    cur = ggml_clamp(ctx0, cur, -1.0f, 1.0f);
286    ggml_set_name(cur, "out_audio");
287    ggml_set_output(cur);
288    ggml_build_forward_expand(gf, cur);
289
290    return gf;
291}