-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathchatterbox_tts.cpp
More file actions
2309 lines (2102 loc) · 110 KB
/
chatterbox_tts.cpp
File metadata and controls
2309 lines (2102 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// chatterbox_tts: end-to-end text -> wav synthesis using T3-generated speech
// tokens and a pre-computed speaker/prompt reference dump.
//
// Pipeline (all in C++/ggml):
// flow_input_tokens = concat(prompt_token, speech_tokens_padded)
// x = input_embedding(flow_input_tokens) (T, D=512)
// mu = encoder(x) + upsample2x + encoder_proj (2T, 80)
// spks = affine(F.normalize(embedding)) (80,)
// conds[:mel_len1] = prompt_feat, rest = 0 (2T, 80)
// z = randn(80, 2T)
// for t,r in [(0, 0.5), (0.5, 1.0)]:
// dxdt = estimator(z, mu, t_emb, spks, conds)
// z = z + (r-t) * dxdt
// mel = z[:, mel_len1:] (80, 2T - mel_len1)
// f0 = f0_predictor(mel)
// source = sinegen(upsample(f0)) -> tanh(linear) (T_wav,)
// s_stft = stft(source)
// wav = hift_decode(mel, s_stft) + istft
//
// Usage:
// chatterbox_tts --s3gen-gguf MODEL.gguf --ref-dir DIR \
// --tokens-file TOKENS.txt --out OUT.wav
#include "ggml.h"
#include "ggml-alloc.h"
#include "ggml-backend.h"
#include "ggml-cpu.h"
#include "gguf.h"
#include "npy.h"
#ifdef GGML_USE_CUDA
#include "ggml-cuda.h"
#endif
#ifdef GGML_USE_METAL
#include "ggml-metal.h"
#endif
#ifdef GGML_USE_VULKAN
#include "ggml-vulkan.h"
#endif
#ifdef GGML_USE_OPENCL
#include "ggml-opencl.h"
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
// Global thread count (set in main; used to configure CPU backend in each graph run)
static int g_n_threads = 1;
static double now_ms() {
using clock = std::chrono::steady_clock;
return std::chrono::duration<double, std::milli>(clock::now().time_since_epoch()).count();
}
static void compute(ggml_backend_t backend, ggml_cgraph * gf) {
if (ggml_backend_is_cpu(backend)) ggml_backend_cpu_set_n_threads(backend, g_n_threads);
ggml_backend_graph_compute(backend, gf);
}
struct scoped_timer {
const char * label;
double t0;
scoped_timer(const char * l) : label(l), t0(now_ms()) {}
~scoped_timer() { fprintf(stderr, " [%-16s] %.1f ms\n", label, now_ms() - t0); }
};
#define TIMED(label) scoped_timer _st_##__LINE__(label)
// ============================================================================
// GGUF loader + helpers
// ============================================================================
struct model_ctx {
ggml_backend_t backend = nullptr;
ggml_context * ctx_w = nullptr;
ggml_backend_buffer_t buffer_w = nullptr;
std::map<std::string, ggml_tensor*> tensors;
// Variant metadata read from GGUF once at load time.
// meanflow=true : Turbo (2-step Euler, time_embed_mixer, noised_mels overlay,
// no CFG on the CFM side)
// meanflow=false : Multilingual (10-step Euler with cosine t_schedule,
// classifier-free-guidance via cfg_rate)
bool meanflow = true;
int n_timesteps = 2;
float cfg_rate = 0.0f;
};
static ggml_backend_t s3gen_init_backend(int n_gpu_layers, bool verbose) {
#ifdef GGML_USE_CUDA
if (n_gpu_layers > 0) {
auto * b = ggml_backend_cuda_init(0);
if (b) { if (verbose) fprintf(stderr, "s3gen: using CUDA backend\n"); return b; }
}
#endif
#ifdef GGML_USE_METAL
if (n_gpu_layers > 0) {
auto * b = ggml_backend_metal_init();
if (b) { if (verbose) fprintf(stderr, "s3gen: using Metal backend\n"); return b; }
}
#endif
#ifdef GGML_USE_VULKAN
if (n_gpu_layers > 0) {
auto * b = ggml_backend_vk_init(0);
if (b) {
if (verbose) {
char desc[256] = {0};
ggml_backend_vk_get_device_description(0, desc, sizeof(desc));
fprintf(stderr, "s3gen: using Vulkan backend (device 0: %s)\n", desc);
}
return b;
}
}
#endif
#if defined(GGML_USE_OPENCL)
if (n_gpu_layers > 0) {
ggml_backend_reg_t ocl_reg = ggml_backend_opencl_reg();
if (ocl_reg && ggml_backend_reg_dev_count(ocl_reg) > 0) {
auto * b = ggml_backend_opencl_init();
if (b) {
if (verbose) {
fprintf(stderr, "s3gen: using OpenCL backend\n");
}
return b;
}
} else if (verbose && ocl_reg) {
if (ggml_backend_reg_dev_count(ocl_reg) == 0) {
fprintf(stderr, "s3gen: no OpenCL device; using CPU\n");
} else {
fprintf(stderr, "s3gen: OpenCL init failed; using CPU\n");
}
}
}
#endif
auto * b = ggml_backend_cpu_init();
if (!b) throw std::runtime_error("ggml_backend_cpu_init() failed");
if (verbose) fprintf(stderr, "s3gen: using CPU backend\n");
return b;
}
// Process-wide cache of the loaded S3Gen GGUF so repeated calls (streaming
// or server mode) pay the ~700 ms tensor-load cost only once. Keyed on
// (path, n_gpu_layers) — switching backend invalidates the cache.
//
// Thread-safety: simple mutex around load/lookup. The returned pointer
// stays alive for the lifetime of the process (we never evict), which
// matches the streaming CLI's single-voice use case. A proper LRU would
// belong in a server front-end.
static model_ctx load_s3gen_gguf(const std::string & path, int n_gpu_layers, bool verbose);
namespace {
struct s3gen_cache_entry { std::string path; int gpu = 0; std::unique_ptr<model_ctx> m; };
static std::mutex g_s3gen_cache_mu;
static std::unique_ptr<s3gen_cache_entry> g_s3gen_cache_entry;
static double g_s3gen_cache_last_load_ms = 0.0;
} // namespace
// Release any cached model_ctx (frees its backend buffer, ggml context and
// backend). Must run before the ggml-metal / ggml-cuda / ggml-vulkan dylib
// tears down its static device list; otherwise their static destructors hit
// a "rsets->data count != 0" assert (residency sets still referenced by an
// orphan backend buffer). We register it with atexit() on first cache
// insertion so it runs before process-exit dylib finalisers.
static void s3gen_model_cache_release() {
std::lock_guard<std::mutex> lk(g_s3gen_cache_mu);
if (!g_s3gen_cache_entry) return;
model_ctx * m = g_s3gen_cache_entry->m.get();
if (m) {
if (m->buffer_w) { ggml_backend_buffer_free(m->buffer_w); m->buffer_w = nullptr; }
if (m->ctx_w) { ggml_free(m->ctx_w); m->ctx_w = nullptr; }
if (m->backend) { ggml_backend_free(m->backend); m->backend = nullptr; }
m->tensors.clear();
}
g_s3gen_cache_entry.reset();
}
static model_ctx * s3gen_model_cache_get(const std::string & path, int n_gpu_layers, bool verbose) {
std::lock_guard<std::mutex> lk(g_s3gen_cache_mu);
if (g_s3gen_cache_entry &&
g_s3gen_cache_entry->path == path &&
g_s3gen_cache_entry->gpu == n_gpu_layers) {
if (verbose) {
fprintf(stderr, " %zu tensors (cached — skip GGUF load)\n",
g_s3gen_cache_entry->m->tensors.size());
}
g_s3gen_cache_last_load_ms = 0.0;
return g_s3gen_cache_entry->m.get();
}
if (verbose) fprintf(stderr, "Loading %s\n", path.c_str());
double t0 = now_ms();
auto m = std::make_unique<model_ctx>(load_s3gen_gguf(path, n_gpu_layers, verbose));
g_s3gen_cache_last_load_ms = now_ms() - t0;
if (verbose) fprintf(stderr, " %zu tensors loaded (%.1f ms)\n", m->tensors.size(), g_s3gen_cache_last_load_ms);
g_s3gen_cache_entry = std::make_unique<s3gen_cache_entry>(
s3gen_cache_entry{path, n_gpu_layers, std::move(m)});
// Register the release on first insertion. atexit() handlers run in
// LIFO and execute before any static destructors in DSOs loaded *after*
// this point — which on macOS / Linux is how we avoid Metal's device
// teardown assert on process exit.
static bool registered = false;
if (!registered) {
std::atexit(s3gen_model_cache_release);
registered = true;
}
return g_s3gen_cache_entry->m.get();
}
static double s3gen_model_cache_last_load_ms() { return g_s3gen_cache_last_load_ms; }
static model_ctx load_s3gen_gguf(const std::string & path, int n_gpu_layers, bool verbose) {
model_ctx m;
ggml_context * tmp_ctx = nullptr;
gguf_init_params gp = { /*.no_alloc=*/ false, /*.ctx=*/ &tmp_ctx };
gguf_context * g = gguf_init_from_file(path.c_str(), gp);
if (!g) throw std::runtime_error("gguf_init_from_file failed: " + path);
m.backend = s3gen_init_backend(n_gpu_layers, verbose);
int64_t n_tensors = gguf_get_n_tensors(g);
ggml_init_params p = { ggml_tensor_overhead() * (size_t)n_tensors, nullptr, true };
m.ctx_w = ggml_init(p);
for (int64_t i = 0; i < n_tensors; ++i) {
const char * name = gguf_get_tensor_name(g, i);
ggml_tensor * src = ggml_get_tensor(tmp_ctx, name);
ggml_tensor * dst = ggml_dup_tensor(m.ctx_w, src);
ggml_set_name(dst, name);
m.tensors[name] = dst;
}
m.buffer_w = ggml_backend_alloc_ctx_tensors(m.ctx_w, m.backend);
for (ggml_tensor * cur = ggml_get_first_tensor(m.ctx_w); cur; cur = ggml_get_next_tensor(m.ctx_w, cur)) {
ggml_tensor * src = ggml_get_tensor(tmp_ctx, ggml_get_name(cur));
ggml_backend_tensor_set(cur, ggml_get_data(src), 0, ggml_nbytes(src));
}
{
int64_t k_mf = gguf_find_key(g, "s3gen.meanflow");
int64_t k_ts = gguf_find_key(g, "s3gen.n_timesteps");
int64_t k_cf = gguf_find_key(g, "s3gen.cfg_rate");
m.meanflow = (k_mf >= 0) ? gguf_get_val_bool(g, k_mf) : true;
m.n_timesteps = (k_ts >= 0) ? (int) gguf_get_val_u32(g, k_ts) : (m.meanflow ? 2 : 10);
m.cfg_rate = (k_cf >= 0) ? gguf_get_val_f32(g, k_cf) : (m.meanflow ? 0.0f : 0.7f);
if (k_mf < 0 && k_ts < 0 && k_cf < 0) {
// Pre-§3.19 GGUFs lack the variant keys. Defaults match the
// historical Turbo behaviour, so legacy chatterbox-s3gen.gguf
// files continue to work unchanged. Print a one-time warning
// because the same defaults applied to a *multilingual* S3Gen
// GGUF produced by an older converter would silently run the
// wrong CFM solver and emit garbage. Re-converting picks up
// the proper keys.
fprintf(stderr, "warning: s3gen GGUF lacks variant keys "
"(s3gen.meanflow / n_timesteps / cfg_rate); "
"assuming Turbo (meanflow, 2 steps). If this is "
"an MTL S3Gen, re-run "
"scripts/convert-s3gen-to-gguf.py --variant mtl.\n");
}
if (verbose) {
fprintf(stderr, " s3gen variant: %s (n_timesteps=%d, cfg_rate=%.2f)\n",
m.meanflow ? "meanflow" : "standard CFM + CFG",
m.n_timesteps, m.cfg_rate);
}
}
gguf_free(g);
ggml_free(tmp_ctx);
return m;
}
static ggml_tensor * find_tensor(const model_ctx & m, const std::string & name) {
auto it = m.tensors.find(name);
if (it == m.tensors.end()) throw std::runtime_error("tensor not found: " + name);
return it->second;
}
// F32 conv1d via im2col + mul_mat. kernel ne=[K, IC, OC]
static ggml_tensor * conv1d_f32(ggml_context * ctx, ggml_tensor * kernel, ggml_tensor * input,
int stride, int padding, int dilation) {
ggml_tensor * im2col = ggml_im2col(ctx, kernel, input, stride, 0, padding, 0, dilation, 0, false, GGML_TYPE_F32);
ggml_tensor * result = ggml_mul_mat(ctx,
ggml_reshape_2d(ctx, im2col, im2col->ne[0], im2col->ne[2] * im2col->ne[1]),
ggml_reshape_2d(ctx, kernel, kernel->ne[0] * kernel->ne[1], kernel->ne[2]));
return ggml_reshape_3d(ctx, result, im2col->ne[1], kernel->ne[2], im2col->ne[2]);
}
// Batch-aware F32 conv1d. Input: (L, IC, B) or (L, IC). Kernel: (K, IC, OC).
// Output: (L_out, OC, B). B=1 degenerates to the old (L_out, OC, 1) layout.
//
// ggml_mul_mat broadcasts its FIRST operand over the SECOND's ne[2..3]
// (the docs state: "A: [ne03, ne02, n, k]", "B: [ne03*x, ne02*y, m, k]"),
// and ggml_can_mul_mat rejects the opposite broadcast direction. When the
// im2col output carries a batch dim and the kernel does not, we therefore
// put the kernel first and permute the result back to (L_out, OC, B) so
// downstream bias-add + LayerNorm layouts stay the same as the batch=1
// path.
static ggml_tensor * conv1d_f32_b(ggml_context * ctx, ggml_tensor * kernel, ggml_tensor * input,
int stride, int padding, int dilation) {
ggml_tensor * im2col = ggml_im2col(ctx, kernel, input, stride, 0, padding, 0, dilation, 0, false, GGML_TYPE_F32);
// im2col ne=[K*IC, L_out, B]
ggml_tensor * k_flat = ggml_reshape_2d(ctx, kernel, kernel->ne[0] * kernel->ne[1], kernel->ne[2]);
// mul_mat(A=k_flat[k=K*IC, n=OC], B=im2col[k=K*IC, m=L_out, ne02=B])
// → result ne=[OC, L_out, B]
ggml_tensor * prod = ggml_mul_mat(ctx, k_flat, im2col);
// Permute (OC, L_out, B) → (L_out, OC, B).
return ggml_cont(ctx, ggml_permute(ctx, prod, 1, 0, 2, 3));
}
static ggml_tensor * conv_transpose_1d_f32(ggml_context * ctx, ggml_tensor * kernel,
ggml_tensor * input, int stride, int padding) {
ggml_tensor * out = ggml_conv_transpose_1d(ctx, kernel, input, stride, 0, 1);
if (padding == 0) return out;
int64_t L_new = out->ne[0] - 2 * padding;
ggml_tensor * v = ggml_view_3d(ctx, out, L_new, out->ne[1], out->ne[2],
out->nb[1], out->nb[2], (size_t)padding * out->nb[0]);
return ggml_cont(ctx, v);
}
// Metal backend currently has no PAD / PAD_EXT dispatcher entry, so emulate
// front/back zero padding on dim 0 via concat(scale(view, 0), x) /
// concat(x, scale(view, 0)). The scale(..., 0) trick produces a defined
// zero tensor (as opposed to allocating an uninitialised one and hoping).
static ggml_tensor * zero_pad_dim0(ggml_context * ctx, ggml_tensor * x, int p_front, int p_back) {
if (p_front <= 0 && p_back <= 0) return x;
ggml_tensor * y = x;
if (p_front > 0) {
GGML_ASSERT(p_front <= (int)x->ne[0]);
ggml_tensor * head = ggml_view_4d(ctx, x, p_front, x->ne[1], x->ne[2], x->ne[3],
x->nb[1], x->nb[2], x->nb[3], 0);
ggml_tensor * z = ggml_scale(ctx, ggml_cont(ctx, head), 0.0f);
y = ggml_concat(ctx, z, y, 0);
}
if (p_back > 0) {
GGML_ASSERT(p_back <= (int)x->ne[0]);
ggml_tensor * tail = ggml_view_4d(ctx, x, p_back, x->ne[1], x->ne[2], x->ne[3],
x->nb[1], x->nb[2], x->nb[3],
(size_t)(x->ne[0] - p_back) * x->nb[0]);
ggml_tensor * z = ggml_scale(ctx, ggml_cont(ctx, tail), 0.0f);
y = ggml_concat(ctx, y, z, 0);
}
return y;
}
static ggml_tensor * ggml_mish_fn(ggml_context * ctx, ggml_tensor * x) {
ggml_tensor * sp = ggml_unary(ctx, x, GGML_UNARY_OP_SOFTPLUS);
ggml_tensor * th = ggml_unary(ctx, sp, GGML_UNARY_OP_TANH);
return ggml_mul(ctx, x, th);
}
static ggml_tensor * layer_norm(ggml_context * ctx, ggml_tensor * x,
ggml_tensor * w, ggml_tensor * b, float eps = 1e-5f) {
ggml_tensor * y = ggml_norm(ctx, x, eps);
y = ggml_mul(ctx, y, w);
return ggml_add(ctx, y, b);
}
// LayerNorm on channel axis where x ne=[T, C].
static ggml_tensor * layer_norm_on_channel(ggml_context * ctx, ggml_tensor * x,
ggml_tensor * w, ggml_tensor * b, float eps = 1e-5f) {
ggml_tensor * xt = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3));
xt = ggml_norm(ctx, xt, eps);
xt = ggml_mul(ctx, xt, w);
xt = ggml_add(ctx, xt, b);
return ggml_cont(ctx, ggml_permute(ctx, xt, 1, 0, 2, 3));
}
static ggml_tensor * reflect_pad_1d(ggml_context * ctx, ggml_tensor * x, int p_left, int p_right) {
ggml_tensor * y = x;
for (int i = 0; i < p_left; ++i) {
int src_idx = p_left - i;
ggml_tensor * s = ggml_view_3d(ctx, x, 1, x->ne[1], x->ne[2], x->nb[1], x->nb[2], (size_t)src_idx * x->nb[0]);
s = ggml_cont(ctx, s);
y = ggml_concat(ctx, s, y, 0);
}
int L_orig = (int)x->ne[0];
for (int i = 0; i < p_right; ++i) {
int src_idx = L_orig - 2 - i;
ggml_tensor * s = ggml_view_3d(ctx, x, 1, x->ne[1], x->ne[2], x->nb[1], x->nb[2], (size_t)src_idx * x->nb[0]);
s = ggml_cont(ctx, s);
y = ggml_concat(ctx, y, s, 0);
}
return y;
}
// ============================================================================
// Encoder (Conformer) — produces mu for CFM
// ============================================================================
struct conformer_w {
ggml_tensor *norm_mha_w, *norm_mha_b, *norm_ff_w, *norm_ff_b;
ggml_tensor *q_w, *q_b, *k_w, *k_b, *v_w, *v_b, *o_w, *o_b;
ggml_tensor *pos_w, *pos_bias_u, *pos_bias_v;
ggml_tensor *ff1_w, *ff1_b, *ff2_w, *ff2_b;
};
static conformer_w load_conformer(const model_ctx & m, const std::string & pfx) {
conformer_w w;
w.norm_mha_w = find_tensor(m, pfx + "/norm_mha/w");
w.norm_mha_b = find_tensor(m, pfx + "/norm_mha/b");
w.norm_ff_w = find_tensor(m, pfx + "/norm_ff/w");
w.norm_ff_b = find_tensor(m, pfx + "/norm_ff/b");
w.q_w = find_tensor(m, pfx + "/attn/q/w"); w.q_b = find_tensor(m, pfx + "/attn/q/b");
w.k_w = find_tensor(m, pfx + "/attn/k/w"); w.k_b = find_tensor(m, pfx + "/attn/k/b");
w.v_w = find_tensor(m, pfx + "/attn/v/w"); w.v_b = find_tensor(m, pfx + "/attn/v/b");
w.o_w = find_tensor(m, pfx + "/attn/o/w"); w.o_b = find_tensor(m, pfx + "/attn/o/b");
w.pos_w = find_tensor(m, pfx + "/attn/pos/w");
w.pos_bias_u = find_tensor(m, pfx + "/attn/pos_bias_u");
w.pos_bias_v = find_tensor(m, pfx + "/attn/pos_bias_v");
w.ff1_w = find_tensor(m, pfx + "/ff/w1/w"); w.ff1_b = find_tensor(m, pfx + "/ff/w1/b");
w.ff2_w = find_tensor(m, pfx + "/ff/w2/w"); w.ff2_b = find_tensor(m, pfx + "/ff/w2/b");
return w;
}
static ggml_tensor * conformer_block(ggml_context * ctx, const conformer_w & w,
ggml_tensor * x, ggml_tensor * pos_emb,
int D, int T, int H, int HD, float eps = 1e-12f) {
ggml_tensor * residual = x;
ggml_tensor * xn = ggml_norm(ctx, x, eps);
xn = ggml_add(ctx, ggml_mul(ctx, xn, w.norm_mha_w), w.norm_mha_b);
ggml_tensor * q = ggml_add(ctx, ggml_mul_mat(ctx, w.q_w, xn), w.q_b);
ggml_tensor * k = ggml_add(ctx, ggml_mul_mat(ctx, w.k_w, xn), w.k_b);
ggml_tensor * v = ggml_add(ctx, ggml_mul_mat(ctx, w.v_w, xn), w.v_b);
ggml_tensor * p = ggml_mul_mat(ctx, w.pos_w, pos_emb);
q = ggml_reshape_3d(ctx, q, HD, H, T);
k = ggml_reshape_3d(ctx, k, HD, H, T);
v = ggml_reshape_3d(ctx, v, HD, H, T);
p = ggml_reshape_3d(ctx, p, HD, H, pos_emb->ne[1]);
ggml_tensor * q_perm = ggml_cont(ctx, ggml_permute(ctx, q, 0, 2, 1, 3));
ggml_tensor * k_perm = ggml_cont(ctx, ggml_permute(ctx, k, 0, 2, 1, 3));
ggml_tensor * v_perm = ggml_cont(ctx, ggml_permute(ctx, v, 0, 2, 1, 3));
ggml_tensor * p_perm = ggml_cont(ctx, ggml_permute(ctx, p, 0, 2, 1, 3));
ggml_tensor * u_bias = ggml_reshape_3d(ctx, w.pos_bias_u, HD, 1, H);
ggml_tensor * v_bias = ggml_reshape_3d(ctx, w.pos_bias_v, HD, 1, H);
ggml_tensor * q_plus_u = ggml_add(ctx, q_perm, u_bias);
ggml_tensor * q_plus_v = ggml_add(ctx, q_perm, v_bias);
ggml_tensor * ac = ggml_mul_mat(ctx, k_perm, q_plus_u);
ggml_tensor * bd = ggml_mul_mat(ctx, p_perm, q_plus_v);
ggml_tensor * bd_padded = zero_pad_dim0(ctx, bd, 1, 0);
ggml_tensor * bd_viewed = ggml_reshape_3d(ctx, bd_padded, T, 2*T, H);
ggml_tensor * bd_sliced = ggml_view_3d(ctx, bd_viewed, T, 2*T - 1, H,
bd_viewed->nb[1], bd_viewed->nb[2], bd_viewed->nb[1]);
ggml_tensor * bd_reshaped = ggml_reshape_3d(ctx, ggml_cont(ctx, bd_sliced), 2*T - 1, T, H);
ggml_tensor * bd_final = ggml_view_3d(ctx, bd_reshaped, T, T, H,
bd_reshaped->nb[1], bd_reshaped->nb[2], 0);
bd_final = ggml_cont(ctx, bd_final);
// Rel-pos Conformer MHA is kept on the classic ggml_soft_max +
// separate V mat-mul path rather than ggml_flash_attn_ext because
// the f16 cast of the relative-position bias `bd_final` (which
// flash_attn_ext requires for its mask argument — ggml.c:5320
// GGML_ASSERT(mask->type == GGML_TYPE_F16)) drifts the softmax
// output by ~1e-4 per block, which compounds through the
// 10-step CFM estimator downstream and fails the WAV quality
// gate (cos 0.998647 vs required > 0.9998, md5 differs vs the
// §3.22 reference 79002f09bc48dda95ec0c2cfc2b895bd). Measured
// speed upside was −13 ms S3Gen / −1.8 % total on M3 Ultra with
// Metal, Q4_0, Spanish prompt, seed 42 — real but not worth
// trading against the audio quality threshold. See PROGRESS
// §3.25 for the full negative-finding writeup. Same pattern
// works on parakeet.cpp (see §15.8 there) because parakeet's
// downstream is a joint argmax over tokens, which is invariant
// to sub-bit-15 precision drift in attention scores.
ggml_tensor * scores = ggml_add(ctx, ac, bd_final);
scores = ggml_scale(ctx, scores, 1.0f / std::sqrt((float)HD));
ggml_tensor * attn = ggml_soft_max(ctx, scores);
ggml_tensor * v_for_mm = ggml_cont(ctx, ggml_permute(ctx, v_perm, 1, 0, 2, 3));
ggml_tensor * attn_v = ggml_mul_mat(ctx, v_for_mm, attn);
ggml_tensor * merged = ggml_cont(ctx, ggml_permute(ctx, attn_v, 0, 2, 1, 3));
ggml_tensor * flat = ggml_reshape_2d(ctx, merged, HD * H, T);
ggml_tensor * attn_out = ggml_add(ctx, ggml_mul_mat(ctx, w.o_w, flat), w.o_b);
x = ggml_add(ctx, residual, attn_out);
residual = x;
xn = ggml_norm(ctx, x, eps);
xn = ggml_add(ctx, ggml_mul(ctx, xn, w.norm_ff_w), w.norm_ff_b);
ggml_tensor * ff = ggml_add(ctx, ggml_mul_mat(ctx, w.ff1_w, xn), w.ff1_b);
ff = ggml_silu(ctx, ff);
ff = ggml_add(ctx, ggml_mul_mat(ctx, w.ff2_w, ff), w.ff2_b);
return ggml_add(ctx, residual, ff);
}
static void compute_pos_emb(std::vector<float> & pe, int T, int D) {
int L = 2 * T - 1;
pe.assign(L * D, 0.0f);
const float log10000 = std::log(10000.0f);
std::vector<float> div_term(D / 2);
for (int i = 0; i < D / 2; ++i) div_term[i] = std::exp(-((float)(2*i) * log10000 / (float)D));
std::vector<std::vector<float>> pos_pe(T, std::vector<float>(D, 0.0f));
std::vector<std::vector<float>> neg_pe(T, std::vector<float>(D, 0.0f));
for (int i = 0; i < T; ++i) {
for (int k = 0; k < D / 2; ++k) {
pos_pe[i][2*k] = std::sin((float)i * div_term[k]);
pos_pe[i][2*k + 1] = std::cos((float)i * div_term[k]);
neg_pe[i][2*k] = std::sin(-(float)i * div_term[k]);
neg_pe[i][2*k + 1] = std::cos(-(float)i * div_term[k]);
}
}
for (int t = 0; t < T; ++t) {
int src = T - 1 - t;
for (int d = 0; d < D; ++d) pe[t*D + d] = pos_pe[src][d];
}
for (int t = 1; t < T; ++t) {
for (int d = 0; d < D; ++d) pe[(T - 1 + t)*D + d] = neg_pe[t][d];
}
}
// Run the full S3Gen encoder: input (T, D=512) -> mu (2T, 80)
static std::vector<float> run_encoder(const model_ctx & m, const std::vector<float> & input_embed, int T, int D = 512) {
const int H = 8, HEAD_DIM = 64;
const int T2 = 2 * T;
static size_t buf_size = 64 * 1024 * 1024; // plenty
std::vector<uint8_t> buf(buf_size);
ggml_init_params gp = { buf_size, buf.data(), true };
ggml_context * ctx = ggml_init(gp);
ggml_cgraph * gf = ggml_new_graph_custom(ctx, 32768, false);
ggml_tensor * x_in = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, D, T);
ggml_set_name(x_in, "x_in"); ggml_set_input(x_in);
ggml_tensor * pos1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, D, 2*T - 1);
ggml_set_name(pos1, "pos1"); ggml_set_input(pos1);
ggml_tensor * pos2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, D, 2*T2 - 1);
ggml_set_name(pos2, "pos2"); ggml_set_input(pos2);
// encoder_embed: Linear + LayerNorm + scale
ggml_tensor * elw = find_tensor(m, "flow/encoder/embed/linear/w");
ggml_tensor * elb = find_tensor(m, "flow/encoder/embed/linear/b");
ggml_tensor * enw = find_tensor(m, "flow/encoder/embed/norm/w");
ggml_tensor * enb = find_tensor(m, "flow/encoder/embed/norm/b");
ggml_tensor * x = ggml_add(ctx, ggml_mul_mat(ctx, elw, x_in), elb);
x = ggml_norm(ctx, x, 1e-5f);
x = ggml_add(ctx, ggml_mul(ctx, x, enw), enb);
x = ggml_scale(ctx, x, std::sqrt((float)D));
// pre_lookahead: 2 convs + LeakyReLU + residual
ggml_tensor * residual = x;
ggml_tensor * xt = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3));
ggml_tensor * pw1 = find_tensor(m, "flow/encoder/pre_lookahead/conv1/w");
ggml_tensor * pb1 = find_tensor(m, "flow/encoder/pre_lookahead/conv1/b");
ggml_tensor * pw2 = find_tensor(m, "flow/encoder/pre_lookahead/conv2/w");
ggml_tensor * pb2 = find_tensor(m, "flow/encoder/pre_lookahead/conv2/b");
xt = zero_pad_dim0(ctx, xt, 0, 3);
xt = conv1d_f32(ctx, pw1, xt, 1, 0, 1);
xt = ggml_add(ctx, xt, ggml_reshape_2d(ctx, pb1, 1, D));
xt = ggml_leaky_relu(ctx, xt, 0.01f, false);
xt = zero_pad_dim0(ctx, xt, 2, 0);
xt = conv1d_f32(ctx, pw2, xt, 1, 0, 1);
xt = ggml_add(ctx, xt, ggml_reshape_2d(ctx, pb2, 1, D));
xt = ggml_cont(ctx, ggml_permute(ctx, xt, 1, 0, 2, 3));
x = ggml_add(ctx, xt, residual);
// 6 conformer blocks at length T
for (int i = 0; i < 6; ++i) {
auto w = load_conformer(m, "flow/encoder/block" + std::to_string(i));
x = conformer_block(ctx, w, x, pos1, D, T, H, HEAD_DIM);
}
// Upsample1D 2x
ggml_tensor * up_w = find_tensor(m, "flow/encoder/up_layer/conv/w");
ggml_tensor * up_b = find_tensor(m, "flow/encoder/up_layer/conv/b");
ggml_tensor * xu = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3));
ggml_tensor * xu_3d = ggml_reshape_3d(ctx, xu, 1, xu->ne[0], xu->ne[1]);
ggml_tensor * xu_2x = ggml_concat(ctx, xu_3d, xu_3d, 0);
xu = ggml_cont(ctx, ggml_reshape_2d(ctx, xu_2x, xu_3d->ne[1]*2, xu_3d->ne[2]));
xu = zero_pad_dim0(ctx, xu, 4, 0);
xu = conv1d_f32(ctx, up_w, xu, 1, 0, 1);
xu = ggml_add(ctx, xu, ggml_reshape_2d(ctx, up_b, 1, D));
x = ggml_cont(ctx, ggml_permute(ctx, xu, 1, 0, 2, 3));
// up_embed
ggml_tensor * ulw = find_tensor(m, "flow/encoder/up_embed/linear/w");
ggml_tensor * ulb = find_tensor(m, "flow/encoder/up_embed/linear/b");
ggml_tensor * unw = find_tensor(m, "flow/encoder/up_embed/norm/w");
ggml_tensor * unb = find_tensor(m, "flow/encoder/up_embed/norm/b");
x = ggml_add(ctx, ggml_mul_mat(ctx, ulw, x), ulb);
x = ggml_norm(ctx, x, 1e-5f);
x = ggml_add(ctx, ggml_mul(ctx, x, unw), unb);
x = ggml_scale(ctx, x, std::sqrt((float)D));
// 4 up_conformer blocks at length 2T
for (int i = 0; i < 4; ++i) {
auto w = load_conformer(m, "flow/encoder/up_block" + std::to_string(i));
x = conformer_block(ctx, w, x, pos2, D, T2, H, HEAD_DIM);
}
// after_norm
ggml_tensor * anw = find_tensor(m, "flow/encoder/after_norm/w");
ggml_tensor * anb = find_tensor(m, "flow/encoder/after_norm/b");
x = ggml_norm(ctx, x, 1e-5f);
x = ggml_add(ctx, ggml_mul(ctx, x, anw), anb);
// encoder_proj: Linear(D -> 80)
ggml_tensor * epw = find_tensor(m, "flow/encoder_proj/w");
ggml_tensor * epb = find_tensor(m, "flow/encoder_proj/b");
ggml_tensor * mu = ggml_add(ctx, ggml_mul_mat(ctx, epw, x), epb);
ggml_set_name(mu, "mu"); ggml_set_output(mu);
ggml_build_forward_expand(gf, mu);
ggml_gallocr_t allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(m.backend));
ggml_gallocr_reserve(allocr, gf);
ggml_gallocr_alloc_graph(allocr, gf);
ggml_backend_tensor_set(ggml_graph_get_tensor(gf, "x_in"), input_embed.data(), 0, input_embed.size()*sizeof(float));
std::vector<float> pe1, pe2;
compute_pos_emb(pe1, T, D);
compute_pos_emb(pe2, T2, D);
ggml_backend_tensor_set(ggml_graph_get_tensor(gf, "pos1"), pe1.data(), 0, pe1.size()*sizeof(float));
ggml_backend_tensor_set(ggml_graph_get_tensor(gf, "pos2"), pe2.data(), 0, pe2.size()*sizeof(float));
compute(m.backend, gf);
std::vector<float> mu_data(ggml_nelements(mu));
ggml_backend_tensor_get(mu, mu_data.data(), 0, ggml_nbytes(mu));
ggml_gallocr_free(allocr);
ggml_free(ctx);
return mu_data; // shape ggml ne=[T2, 80] = numpy (80, T2)
}
// ============================================================================
// CFM estimator (single forward) — same graph as stage_G4 of test_s3gen.cpp
// ============================================================================
struct cfm_resnet_w {
ggml_tensor *b1_conv_w, *b1_conv_b, *b1_ln_w, *b1_ln_b;
ggml_tensor *b2_conv_w, *b2_conv_b, *b2_ln_w, *b2_ln_b;
ggml_tensor *mlp_w, *mlp_b, *res_w, *res_b;
};
static cfm_resnet_w load_cfm_resnet(const model_ctx & m, const std::string & pfx) {
cfm_resnet_w w;
w.b1_conv_w = find_tensor(m, pfx + "/block1/block/0/weight");
w.b1_conv_b = find_tensor(m, pfx + "/block1/block/0/bias");
w.b1_ln_w = find_tensor(m, pfx + "/block1/block/2/weight");
w.b1_ln_b = find_tensor(m, pfx + "/block1/block/2/bias");
w.b2_conv_w = find_tensor(m, pfx + "/block2/block/0/weight");
w.b2_conv_b = find_tensor(m, pfx + "/block2/block/0/bias");
w.b2_ln_w = find_tensor(m, pfx + "/block2/block/2/weight");
w.b2_ln_b = find_tensor(m, pfx + "/block2/block/2/bias");
w.mlp_w = find_tensor(m, pfx + "/mlp/1/weight");
w.mlp_b = find_tensor(m, pfx + "/mlp/1/bias");
w.res_w = find_tensor(m, pfx + "/res_conv/weight");
w.res_b = find_tensor(m, pfx + "/res_conv/bias");
return w;
}
static ggml_tensor * cfm_causal_block(ggml_context * ctx, ggml_tensor * x,
ggml_tensor * conv_w, ggml_tensor * conv_b,
ggml_tensor * ln_w, ggml_tensor * ln_b, int64_t C_out) {
ggml_tensor * xp = zero_pad_dim0(ctx, x, 2, 0);
ggml_tensor * y = conv1d_f32(ctx, conv_w, xp, 1, 0, 1);
y = ggml_add(ctx, y, ggml_reshape_2d(ctx, conv_b, 1, C_out));
y = layer_norm_on_channel(ctx, y, ln_w, ln_b);
return ggml_mish_fn(ctx, y);
}
static ggml_tensor * cfm_resnet(ggml_context * ctx, const cfm_resnet_w & w,
ggml_tensor * x, ggml_tensor * t_emb, int64_t C_out) {
ggml_tensor * h = cfm_causal_block(ctx, x, w.b1_conv_w, w.b1_conv_b, w.b1_ln_w, w.b1_ln_b, C_out);
ggml_tensor * t_feat = ggml_mish_fn(ctx, t_emb);
ggml_tensor * t_proj = ggml_add(ctx, ggml_mul_mat(ctx, w.mlp_w, t_feat), w.mlp_b);
h = ggml_add(ctx, h, ggml_reshape_2d(ctx, t_proj, 1, C_out));
h = cfm_causal_block(ctx, h, w.b2_conv_w, w.b2_conv_b, w.b2_ln_w, w.b2_ln_b, C_out);
ggml_tensor * res = conv1d_f32(ctx, w.res_w, x, 1, 0, 1);
res = ggml_add(ctx, res, ggml_reshape_2d(ctx, w.res_b, 1, C_out));
return ggml_add(ctx, h, res);
}
struct basic_tfm_w {
ggml_tensor *norm1_w, *norm1_b;
ggml_tensor *to_q, *to_k, *to_v;
ggml_tensor *to_out_w, *to_out_b;
ggml_tensor *norm3_w, *norm3_b;
ggml_tensor *ff0_w, *ff0_b, *ff2_w, *ff2_b;
};
static basic_tfm_w load_basic_tfm(const model_ctx & m, const std::string & pfx) {
basic_tfm_w w;
w.norm1_w = find_tensor(m, pfx + "/norm1/weight");
w.norm1_b = find_tensor(m, pfx + "/norm1/bias");
w.to_q = find_tensor(m, pfx + "/attn1/to_q/weight");
w.to_k = find_tensor(m, pfx + "/attn1/to_k/weight");
w.to_v = find_tensor(m, pfx + "/attn1/to_v/weight");
w.to_out_w = find_tensor(m, pfx + "/attn1/to_out/0/weight");
w.to_out_b = find_tensor(m, pfx + "/attn1/to_out/0/bias");
w.norm3_w = find_tensor(m, pfx + "/norm3/weight");
w.norm3_b = find_tensor(m, pfx + "/norm3/bias");
w.ff0_w = find_tensor(m, pfx + "/ff/net/0/proj/weight");
w.ff0_b = find_tensor(m, pfx + "/ff/net/0/proj/bias");
w.ff2_w = find_tensor(m, pfx + "/ff/net/2/weight");
w.ff2_b = find_tensor(m, pfx + "/ff/net/2/bias");
return w;
}
static ggml_tensor * basic_tfm(ggml_context * ctx, const basic_tfm_w & w,
ggml_tensor * x, int T, int C, bool f16_kv_attn, int H = 8, int HD = 64) {
int INNER = H * HD;
ggml_tensor * nx = layer_norm(ctx, x, w.norm1_w, w.norm1_b);
ggml_tensor * q = ggml_mul_mat(ctx, w.to_q, nx);
ggml_tensor * k = ggml_mul_mat(ctx, w.to_k, nx);
ggml_tensor * v = ggml_mul_mat(ctx, w.to_v, nx);
// Zero-cont Q/K/V for flash-attn (see PROGRESS.md 3.14). After
// mul_mat the result is (INNER, T) contiguous; INNER = H * HD.
// Metal's flash_attn_ext takes strided (HD, T, H) views directly,
// so drop the reshape+permute+cont triple.
const size_t col_stride = (size_t) INNER * sizeof(float);
const size_t head_stride = (size_t) HD * sizeof(float);
q = ggml_view_3d(ctx, q, HD, T, H, col_stride, head_stride, 0);
k = ggml_view_3d(ctx, k, HD, T, H, col_stride, head_stride, 0);
v = ggml_view_3d(ctx, v, HD, T, H, col_stride, head_stride, 0);
if (f16_kv_attn) {
// Experimental OpenCL/mobile mode: keep Q in F32 but materialise K/V
// into contiguous F16 so backends with `flash_attn_f32_f16` (e.g.
// Adreno OpenCL, see PROGRESS.md "OpenCL / Adreno bring-up" §
// "OpenCL optimization log") dispatch the mixed-precision kernel
// instead of the F32-only one. ggml_cpy handles the strided-source
// → contiguous-F16-dst case across Metal / OpenCL / CPU.
ggml_tensor * k_f16 = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, HD, T, H);
ggml_tensor * v_f16 = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, HD, T, H);
k = ggml_cpy(ctx, k, k_f16);
v = ggml_cpy(ctx, v, v_f16);
}
// Fused softmax(QK^T / sqrt(HD)) @ V, streaming (no materialized T x T attn matrix).
// Output layout is (HD, H, T) internally ((D, H, N) per flash_attn_ext docs).
ggml_tensor * attn_fa = ggml_flash_attn_ext(ctx, q, k, v, /*mask=*/nullptr,
/*scale=*/1.0f / std::sqrt((float)HD),
/*max_bias=*/0.0f,
/*logit_softcap=*/0.0f);
// flash_attn_ext output: ne=[HD, H, T, 1] (contiguous). Reshape to (INNER, T).
ggml_tensor * flat = ggml_reshape_2d(ctx, attn_fa, INNER, T);
ggml_tensor * attn_out = ggml_add(ctx, ggml_mul_mat(ctx, w.to_out_w, flat), w.to_out_b);
x = ggml_add(ctx, x, attn_out);
ggml_tensor * nx2 = layer_norm(ctx, x, w.norm3_w, w.norm3_b);
ggml_tensor * ff = ggml_add(ctx, ggml_mul_mat(ctx, w.ff0_w, nx2), w.ff0_b);
ff = ggml_gelu_erf(ctx, ff);
ff = ggml_add(ctx, ggml_mul_mat(ctx, w.ff2_w, ff), w.ff2_b);
return ggml_add(ctx, x, ff);
}
struct cfm_tfm_stack { std::vector<basic_tfm_w> blocks; };
static cfm_tfm_stack load_tfm_stack(const model_ctx & m, const std::string & pfx, int n) {
cfm_tfm_stack s;
for (int i = 0; i < n; ++i) s.blocks.push_back(load_basic_tfm(m, pfx + "/" + std::to_string(i)));
return s;
}
static ggml_tensor * apply_tfm_stack(ggml_context * ctx, const cfm_tfm_stack & s,
ggml_tensor * x, int T, int C, bool f16_kv_attn) {
ggml_tensor * xt = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3));
for (const auto & b : s.blocks) xt = basic_tfm(ctx, b, xt, T, C, f16_kv_attn);
return ggml_cont(ctx, ggml_permute(ctx, xt, 1, 0, 2, 3));
}
static ggml_tensor * cfm_causal_k3(ggml_context * ctx, ggml_tensor * x,
ggml_tensor * w, ggml_tensor * b, int C_out) {
ggml_tensor * xp = zero_pad_dim0(ctx, x, 2, 0);
ggml_tensor * y = conv1d_f32(ctx, w, xp, 1, 0, 1);
return ggml_add(ctx, y, ggml_reshape_2d(ctx, b, 1, C_out));
}
// --------------------------------------------------------------------------
// Batch-aware CFM estimator helpers. These mirror the batch=1 helpers but
// preserve an outer batch dim so the non-meanflow CFG path can run cond +
// uncond through the decoder in a single forward call (batch=2), amortising
// the weight-read cost across both passes.
//
// Shape convention: x ne=[T, C, B]. t_emb is (TIME_DIM, B). Biases are
// (C,) — ggml broadcasts size-1 dims.
// --------------------------------------------------------------------------
static ggml_tensor * cfm_causal_block_b(ggml_context * ctx, ggml_tensor * x,
ggml_tensor * conv_w, ggml_tensor * conv_b,
ggml_tensor * ln_w, ggml_tensor * ln_b, int64_t C_out) {
ggml_tensor * xp = zero_pad_dim0(ctx, x, 2, 0);
ggml_tensor * y = conv1d_f32_b(ctx, conv_w, xp, 1, 0, 1);
y = ggml_add(ctx, y, ggml_reshape_2d(ctx, conv_b, 1, C_out));
y = layer_norm_on_channel(ctx, y, ln_w, ln_b);
return ggml_mish_fn(ctx, y);
}
static ggml_tensor * cfm_resnet_b(ggml_context * ctx, const cfm_resnet_w & w,
ggml_tensor * x, ggml_tensor * t_emb_b, int64_t C_out) {
ggml_tensor * h = cfm_causal_block_b(ctx, x, w.b1_conv_w, w.b1_conv_b, w.b1_ln_w, w.b1_ln_b, C_out);
ggml_tensor * t_feat = ggml_mish_fn(ctx, t_emb_b); // (TIME_DIM, B)
ggml_tensor * t_proj = ggml_add(ctx, ggml_mul_mat(ctx, w.mlp_w, t_feat),
w.mlp_b); // (C, B)
const int64_t B = t_proj->ne[1];
h = ggml_add(ctx, h, ggml_reshape_3d(ctx, t_proj, 1, C_out, B));
h = cfm_causal_block_b(ctx, h, w.b2_conv_w, w.b2_conv_b, w.b2_ln_w, w.b2_ln_b, C_out);
ggml_tensor * res = conv1d_f32_b(ctx, w.res_w, x, 1, 0, 1);
res = ggml_add(ctx, res, ggml_reshape_2d(ctx, w.res_b, 1, C_out));
return ggml_add(ctx, h, res);
}
static ggml_tensor * basic_tfm_b(ggml_context * ctx, const basic_tfm_w & w,
ggml_tensor * x, int T, int C, int B,
bool f16_kv_attn,
int H = 8, int HD = 64) {
int INNER = H * HD;
ggml_tensor * nx = layer_norm(ctx, x, w.norm1_w, w.norm1_b); // (C, T, B)
ggml_tensor * q = ggml_mul_mat(ctx, w.to_q, nx); // (INNER, T, B)
ggml_tensor * k = ggml_mul_mat(ctx, w.to_k, nx);
ggml_tensor * v = ggml_mul_mat(ctx, w.to_v, nx);
// Zero-cont Q/K/V (see PROGRESS.md 3.14): express the
// (HD, T, H, B) layout expected by flash_attn_ext as a strided view
// on the already-contiguous (INNER, T, B) mul_mat output.
const size_t col_stride = (size_t) INNER * sizeof(float);
const size_t head_stride = (size_t) HD * sizeof(float);
const size_t batch_stride = (size_t) INNER * T * sizeof(float);
q = ggml_view_4d(ctx, q, HD, T, H, B, col_stride, head_stride, batch_stride, 0);
k = ggml_view_4d(ctx, k, HD, T, H, B, col_stride, head_stride, batch_stride, 0);
v = ggml_view_4d(ctx, v, HD, T, H, B, col_stride, head_stride, batch_stride, 0);
if (f16_kv_attn) {
// Mirror the batch=1 path: optionally materialise K/V as contiguous
// F16 so backends with `flash_attn_f32_f16` (Adreno OpenCL) dispatch
// the mixed-precision kernel. See basic_tfm() for full rationale.
ggml_tensor * k_f16 = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, HD, T, H, B);
ggml_tensor * v_f16 = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, HD, T, H, B);
k = ggml_cpy(ctx, k, k_f16);
v = ggml_cpy(ctx, v, v_f16);
}
ggml_tensor * attn_fa = ggml_flash_attn_ext(ctx, q, k, v, /*mask=*/nullptr,
1.0f / std::sqrt((float)HD), 0.0f, 0.0f);
// flash_attn_ext output ne=[HD, H, T, B]. Reshape back to (INNER, T, B).
ggml_tensor * flat = ggml_reshape_3d(ctx, attn_fa, INNER, T, B);
ggml_tensor * attn_out = ggml_add(ctx, ggml_mul_mat(ctx, w.to_out_w, flat), w.to_out_b);
x = ggml_add(ctx, x, attn_out);
ggml_tensor * nx2 = layer_norm(ctx, x, w.norm3_w, w.norm3_b);
ggml_tensor * ff = ggml_add(ctx, ggml_mul_mat(ctx, w.ff0_w, nx2), w.ff0_b);
ff = ggml_gelu_erf(ctx, ff);
ff = ggml_add(ctx, ggml_mul_mat(ctx, w.ff2_w, ff), w.ff2_b);
return ggml_add(ctx, x, ff);
}
static ggml_tensor * apply_tfm_stack_b(ggml_context * ctx, const cfm_tfm_stack & s,
ggml_tensor * x, int T, int C, int B,
bool f16_kv_attn) {
ggml_tensor * xt = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3)); // (C, T, B)
for (const auto & b : s.blocks) xt = basic_tfm_b(ctx, b, xt, T, C, B, f16_kv_attn);
return ggml_cont(ctx, ggml_permute(ctx, xt, 1, 0, 2, 3)); // (T, C, B)
}
static ggml_tensor * cfm_causal_k3_b(ggml_context * ctx, ggml_tensor * x,
ggml_tensor * w, ggml_tensor * b, int C_out) {
ggml_tensor * xp = zero_pad_dim0(ctx, x, 2, 0);
ggml_tensor * y = conv1d_f32_b(ctx, w, xp, 1, 0, 1);
return ggml_add(ctx, y, ggml_reshape_2d(ctx, b, 1, C_out));
}
// Compute the time embedding for a single scalar t (or r).
// Returns (TIME_EMB_DIM=1024,) after sinusoidal + 2-layer MLP.
//
// Cached: the graph topology (inputs, weights, output shape) is constant
// across all 10 CFM steps. Previously each call rebuilt the graph,
// reserved a fresh gallocr, computed, and freed — burning ~1 ms of
// dispatch + allocator overhead per step on Metal. Per call (multilingual,
// 10 CFM steps) that's ~10 ms; for meanflow with `compute_time_mixed`
// it's slightly more. The cache is keyed on the backend pointer so a
// fresh model_ctx in another thread doesn't share scaffolding.
struct time_mlp_cache {
ggml_backend_t backend = nullptr;
std::vector<uint8_t> buf;
ggml_context * ctx = nullptr;
ggml_cgraph * gf = nullptr;
ggml_gallocr_t allocr = nullptr;
ggml_tensor * x_in = nullptr;
ggml_tensor * y_out = nullptr;
~time_mlp_cache() {
if (allocr) ggml_gallocr_free(allocr);
if (ctx) ggml_free(ctx);
}
};
static std::vector<float> compute_time_mlp(const model_ctx & m, float t_val) {
const int TDIM = 320;
std::vector<float> t_sin(TDIM);
float log_factor = std::log(10000.0f) / (float)(TDIM/2 - 1);
for (int i = 0; i < TDIM/2; ++i) {
float freq = std::exp(-(float)i * log_factor);
float arg = 1000.0f * t_val * freq;
t_sin[i] = std::sin(arg);
t_sin[i + TDIM/2] = std::cos(arg);
}
thread_local time_mlp_cache cache;
if (cache.ctx == nullptr || cache.backend != m.backend) {
if (cache.allocr) { ggml_gallocr_free(cache.allocr); cache.allocr = nullptr; }
if (cache.ctx) { ggml_free(cache.ctx); cache.ctx = nullptr; }
cache.buf.assign(4 * 1024 * 1024, 0);
ggml_init_params gp = { cache.buf.size(), cache.buf.data(), true };
cache.ctx = ggml_init(gp);
cache.gf = ggml_new_graph(cache.ctx);
cache.x_in = ggml_new_tensor_1d(cache.ctx, GGML_TYPE_F32, TDIM);
ggml_set_name(cache.x_in, "x"); ggml_set_input(cache.x_in);
ggml_tensor * l1w = find_tensor(m, "cfm/time_mlp/linear_1/weight");
ggml_tensor * l1b = find_tensor(m, "cfm/time_mlp/linear_1/bias");
ggml_tensor * l2w = find_tensor(m, "cfm/time_mlp/linear_2/weight");
ggml_tensor * l2b = find_tensor(m, "cfm/time_mlp/linear_2/bias");
ggml_tensor * y = ggml_add(cache.ctx, ggml_mul_mat(cache.ctx, l1w, cache.x_in), l1b);
y = ggml_silu(cache.ctx, y);
y = ggml_add(cache.ctx, ggml_mul_mat(cache.ctx, l2w, y), l2b);
ggml_set_name(y, "out"); ggml_set_output(y);
cache.y_out = y;
ggml_build_forward_expand(cache.gf, cache.y_out);
cache.allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(m.backend));
ggml_gallocr_reserve(cache.allocr, cache.gf);
cache.backend = m.backend;
}
ggml_gallocr_alloc_graph(cache.allocr, cache.gf);
ggml_backend_tensor_set(cache.x_in, t_sin.data(), 0, t_sin.size() * sizeof(float));
compute(m.backend, cache.gf);
std::vector<float> out(ggml_nelements(cache.y_out));
ggml_backend_tensor_get(cache.y_out, out.data(), 0, ggml_nbytes(cache.y_out));
return out;
}
// Mix t and r embeddings via time_embed_mixer (Linear(2048 -> 1024), no bias)
static std::vector<float> compute_time_mixed(const model_ctx & m,
const std::vector<float> & t_mlp,
const std::vector<float> & r_mlp) {
static size_t buf_size = 4 * 1024 * 1024;
std::vector<uint8_t> buf(buf_size);
ggml_init_params gp = { buf_size, buf.data(), true };
ggml_context * ctx = ggml_init(gp);
ggml_cgraph * gf = ggml_new_graph(ctx);
int TOT = (int)t_mlp.size();
ggml_tensor * t_in = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, TOT);
ggml_set_name(t_in, "t_in"); ggml_set_input(t_in);
ggml_tensor * r_in = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, TOT);
ggml_set_name(r_in, "r_in"); ggml_set_input(r_in);
ggml_tensor * cat = ggml_concat(ctx, t_in, r_in, 0);
ggml_tensor * mix_w = find_tensor(m, "cfm/time_embed_mixer/weight");
ggml_tensor * mixed = ggml_mul_mat(ctx, mix_w, cat);
ggml_set_name(mixed, "out"); ggml_set_output(mixed);
ggml_build_forward_expand(gf, mixed);
ggml_gallocr_t allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(m.backend));
ggml_gallocr_reserve(allocr, gf);
ggml_gallocr_alloc_graph(allocr, gf);
ggml_backend_tensor_set(ggml_graph_get_tensor(gf, "t_in"), t_mlp.data(), 0, t_mlp.size()*sizeof(float));
ggml_backend_tensor_set(ggml_graph_get_tensor(gf, "r_in"), r_mlp.data(), 0, r_mlp.size()*sizeof(float));
compute(m.backend, gf);
std::vector<float> out(ggml_nelements(mixed));
ggml_backend_tensor_get(mixed, out.data(), 0, ggml_nbytes(mixed));
ggml_gallocr_free(allocr);
ggml_free(ctx);
return out;
}
// Cached CFM estimator state — graph is built once and reused across steps.
//
// Cache key is (T, b2): a graph built for batch=1 (cfm_estimator_forward) cannot
// be reused for the batch=2 path (cfm_estimator_forward_b2) since the input
// tensor layouts differ (ne[2] = 1 vs 2). Today `use_b2` is constant per
// `s3gen_synthesize_to_wav` invocation and the cache lives on the stack of
// that one call, so a single key would be safe — but a future change that
// switches modes mid-utterance (e.g. CFG warm-up where step 0 is single-pass
// and steps 1+ are batched) would silently reuse a wrong-shape graph and
// crash inside the allocator.
struct cfm_estimator_cache {
int T = -1;
bool b2 = false;
ggml_context * ctx = nullptr;
ggml_cgraph * gf = nullptr;
ggml_gallocr_t allocr = nullptr;
std::vector<uint8_t> buf;
~cfm_estimator_cache() {
if (allocr) ggml_gallocr_free(allocr);
if (ctx) ggml_free(ctx);
}
};
// Single estimator forward: (x, mu, t_emb, spks, cond) -> dxdt
// All shapes are numpy (80, T) or (80,) as given, flattened row-major.
static std::vector<float> cfm_estimator_forward(
const model_ctx & m,
cfm_estimator_cache & cache,