forked from ggml-org/whisper.cpp
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy patht3_mtl.cpp
More file actions
2233 lines (2000 loc) · 105 KB
/
Copy patht3_mtl.cpp
File metadata and controls
2233 lines (2000 loc) · 105 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 multilingual T3 (Llama-520M) variant: loader + forward pass.
//
// Structural differences from the GPT-2 Medium Turbo variant in src/main.cpp:
// - 30 layers vs 24, head_dim=64, n_kv_head=16 (MHA, not GQA).
// - Pre-norm with RMSNorm (no bias) instead of LayerNorm.
// - Rotary position embedding with llama3 scaling: freq_factors precomputed
// at load time and applied through ggml_rope_ext's `c` param.
// - SwiGLU MLP: SiLU(gate(x)) * up(x) -> down(x); three Linears per layer.
// - Separate Q/K/V projections (no fused c_attn).
// - Classifier-Free Guidance: each T3 graph runs twice per call, once for
// the conditional (full text embeddings) batch element and once for the
// unconditional one (text embeddings zeroed). Two independent KV caches
// live inside the model struct for this. Logits are combined in the
// sampler as `cond + cfg_weight * (cond - uncond)`.
// - Conditioning tokens:
// spkr_enc(speaker_emb) -> 1 token
// perceiver(cond_prompt_speech_emb) -> 32 tokens (shared AttentionBlock2
// used cross-attn then self-attn)
// emotion_adv_fc(exaggeration) -> 1 token
// These concatenate into `cond_emb` (34 tokens). Conditional and
// unconditional passes share the cond_emb; text/speech embeddings differ
// between them (uncond zeroes text embeds but keeps the speech BOS).
#include "chatterbox_t3_internal.h"
#include "t3_mtl.h"
#include "t3_alignment_analyzer.h"
#include "backend_util.h"
#include "gguf_stream.h"
#include "ggml.h"
#include "ggml-alloc.h"
#include "ggml-backend.h"
#include "ggml-cpu.h"
#include "gguf.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <list>
#include <mutex>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
namespace tts_cpp::chatterbox::detail {
namespace {
// ---------------------------------------------------------------------------
// Phase 2: alignment-probe state (thread-local, one generation per
// thread). Set via t3_align_configure(); read back via t3_align_last_row().
// See t3_mtl.h for the rationale.
// ---------------------------------------------------------------------------
struct t3_align_state {
bool enabled = false;
int text_i = 0;
int text_j = 0;
std::vector<std::pair<int, int>> layer_heads; // (layer_idx, head_idx)
std::vector<float> last_row; // averaged softmax row (len text_j-text_i)
};
thread_local t3_align_state g_t3_align;
// Average the "align_L<layer>" probe outputs (newest query column) of the
// cond pass into g_t3_align.last_row.
void t3_align_capture_from_graph(ggml_cgraph * gf) {
const int nt = g_t3_align.text_j - g_t3_align.text_i;
if (nt <= 0) { g_t3_align.last_row.clear(); return; }
std::vector<double> acc((size_t) nt, 0.0);
int cnt = 0;
for (const auto & lh : g_t3_align.layer_heads) {
char nm[24];
std::snprintf(nm, sizeof(nm), "align_L%d", lh.first);
ggml_tensor * t = ggml_graph_get_tensor(gf, nm);
if (!t) continue;
const int rows = (int) t->ne[0]; // n_text
const int cols = (int) t->ne[1]; // N queries
if (rows != nt || cols < 1) continue;
std::vector<float> buf((size_t) rows * (size_t) cols);
ggml_backend_tensor_get(t, buf.data(), 0, ggml_nbytes(t));
const float * last_col = buf.data() + (size_t)(cols - 1) * (size_t) rows;
for (int r = 0; r < nt; ++r) acc[(size_t) r] += last_col[r];
++cnt;
}
// Leave the row empty (not all-zeros) when no probe output was found so the
// analyzer takes its empty-row fast path and falls back to Phase 1.
if (cnt == 0) { g_t3_align.last_row.clear(); return; }
g_t3_align.last_row.assign((size_t) nt, 0.0f);
for (int r = 0; r < nt; ++r)
g_t3_align.last_row[(size_t) r] = (float) (acc[(size_t) r] / cnt);
}
// Process-wide registry of the Phase-15 stacked-weight buffers, with an
// atexit hook that frees them before Metal's static device destructors
// run. Without this Metal asserts on `[rsets->data count] == 0` because
// `buffer_stack` is still live when the ggml-metal dylib tears down.
// Mirrors `s3gen_model_cache_release` in chatterbox_tts.cpp; the
// existing buffer_w / buffer_kv get cleaned up by other paths
// (explicit free_t3() in error returns, dylib finaliser via the
// model_ctx cache for s3gen, etc.) — only the new buffer_stack needs
// to be added to the atexit chain.
struct t3_stack_entry {
ggml_backend_buffer_t buffer = nullptr;
ggml_context * ctx = nullptr;
};
std::mutex t3_stack_mu;
std::vector<t3_stack_entry> t3_stack_registry;
bool t3_stack_atexit_registered = false;
void t3_stack_release_atexit() {
std::lock_guard<std::mutex> lk(t3_stack_mu);
for (auto & e : t3_stack_registry) {
if (e.buffer) {
ggml_backend_buffer_free(e.buffer);
e.buffer = nullptr;
}
if (e.ctx) {
ggml_free(e.ctx);
e.ctx = nullptr;
}
}
t3_stack_registry.clear();
}
} // anonymous namespace
void t3_stack_register(ggml_backend_buffer_t buf, ggml_context * ctx) {
std::lock_guard<std::mutex> lk(t3_stack_mu);
t3_stack_registry.push_back({buf, ctx});
if (!t3_stack_atexit_registered) {
std::atexit(t3_stack_release_atexit);
t3_stack_atexit_registered = true;
}
}
// Drop a (buffer, ctx) pair from the atexit registry without freeing.
// Used by free_t3() in main on error-path early-returns: free_t3 itself
// frees buffer_stack + ctx_stack so the backend can shut down cleanly in
// the same scope; the atexit hook would otherwise double-free dangling
// pointers if we didn't pull them out of the registry first.
void t3_stack_unregister(ggml_backend_buffer_t buf, ggml_context * ctx) {
std::lock_guard<std::mutex> lk(t3_stack_mu);
for (auto it = t3_stack_registry.begin(); it != t3_stack_registry.end(); ) {
if (it->buffer == buf && it->ctx == ctx) {
it = t3_stack_registry.erase(it);
} else {
++it;
}
}
}
// Forward declaration for the step-graph builder used by the
// cache below. Body lives in the second anonymous namespace further
// down (alongside the legacy build_step_graph_mtl wrapper).
namespace {
ggml_cgraph * build_step_graph_mtl_in_ctx(const chatterbox_model & model,
ggml_context * ctx,
int n_past,
bool is_uncond);
}
// ============================================================================
// T3 step-graph cache (multilingual CFG token decode)
// ============================================================================
//
// `build_step_graph_mtl(n_past, is_uncond)` constructs a 30-layer Llama-block
// graph from scratch on every token decode call. Multilingual CFG fires
// this 2× per token (cond + uncond on CPU); a 136-token Spanish synth
// previously rebuilt 272 graphs at ~3 ms each — roughly 800 ms / synth of
// pure host-CPU graph construction work.
//
// The cache stores per-(n_past, is_uncond) entries with their own
// ggml_context, gallocator, and metadata buf. ggml_view's offset is a
// graph-build-time constant in `build_llama_block` (KV write/read offsets
// scale with `n_past`), so each distinct n_past needs its own cached
// graph — there is no shape-independent path here.
//
// Memory cap: a hard FIFO bound of `T3_STEP_CACHE_CAP` entries (default
// 256, covering 128 tokens × 2 modes). When the cap is hit, new
// (n_past, is_uncond) keys fall back to the legacy thread_local-buf path
// (correct, just no caching benefit). Tested: cache invariants stay
// correct under cap pressure; bit-exact preserved.
//
// Lifecycle: cleared by detail::t3_release_caches() — called from the
// CLI's free_t3 lambda + Engine::Impl::free_model BEFORE the model
// backend is freed (gallocators carry backend references; freeing them
// against a dead backend would assert). Plus a fallback atexit hook
// for the unsurprising case where neither path runs.
namespace {
// Cache entry holds just the graph metadata — NOT a per-entry
// gallocator. The caller's existing shared allocator (passed into
// run_step_pass) is used for both cached and legacy-fallback graphs;
// alloc_graph re-lays-out per call but reuses one backend buffer
// across every (n_past, is_uncond) variant. This is what keeps the
// single-utterance regression at zero — per-entry gallocator would
// allocate ~1 MB device memory PER cached graph (272 misses × 1 MB =
// ~270 MB allocator churn on the first multilingual synth, observed
// as ~10 % T3 wall-time regression). Share the allocator instead.
struct t3_step_cache_entry {
int64_t key = -1; // pack(n_past, is_uncond)
ggml_context * ctx = nullptr;
ggml_cgraph * gf = nullptr;
std::vector<uint8_t> buf;
t3_step_cache_entry() = default;
t3_step_cache_entry(const t3_step_cache_entry &) = delete;
t3_step_cache_entry & operator=(const t3_step_cache_entry &) = delete;
t3_step_cache_entry(t3_step_cache_entry && other) noexcept
: key(other.key), ctx(other.ctx), gf(other.gf),
buf(std::move(other.buf)) {
other.key = -1;
other.ctx = nullptr;
other.gf = nullptr;
}
t3_step_cache_entry & operator=(t3_step_cache_entry && other) noexcept {
if (this != &other) {
destroy();
key = other.key;
ctx = other.ctx;
gf = other.gf;
buf = std::move(other.buf);
other.key = -1;
other.ctx = nullptr;
other.gf = nullptr;
}
return *this;
}
~t3_step_cache_entry() { destroy(); }
void destroy() {
if (ctx) { ggml_free(ctx); ctx = nullptr; }
gf = nullptr;
key = -1;
}
};
constexpr size_t T3_STEP_CACHE_CAP = 256;
// Caching is opt-in to avoid a small (~10 %) T3 regression on
// single-utterance workloads where every step call is a cache miss.
// In a single multilingual synth, n_past goes 0, 1, 2, ..., N-1 once
// each, so the cache fills up but nothing is re-used — every miss
// pays the bookkeeping cost (vector::resize, list insert, mutex
// acquire) without any compensating hit savings.
//
// Server-mode and other multi-synth callers — where synth #2 starts
// at n_past=0 again and re-decodes the same prompt prefix as
// synth #1 — get a real win (~3 ms × hits per call ≈ 1 s / synth
// on multilingual), so the env var unlocks caching for those
// workloads:
//
// CHATTERBOX_T3_STEP_CACHE=1 ./tts-cli ...
//
// Reads once at first use, cached as a static const bool. Tests
// set the env var via `setenv()` before any eval_step_mtl call.
bool t3_step_cache_enabled() {
static const bool enabled = []() {
const char * e = std::getenv("CHATTERBOX_T3_STEP_CACHE");
if (!e || !e[0]) return false;
return e[0] == '1' || e[0] == 't' || e[0] == 'T' ||
e[0] == 'y' || e[0] == 'Y';
}();
return enabled;
}
// Mutex protects the entire cache state below. Held only across cache
// state mutations, not across the underlying backend compute itself.
std::mutex t3_step_cache_mu;
std::list<t3_step_cache_entry> t3_step_cache_lru; // front = most recent
std::unordered_map<int64_t, std::list<t3_step_cache_entry>::iterator> t3_step_cache_idx;
size_t t3_step_cache_hits = 0;
size_t t3_step_cache_misses = 0;
bool t3_step_cache_atexit_registered = false;
inline int64_t pack_step_key(int n_past, bool is_uncond) {
return ((int64_t) n_past << 1) | (is_uncond ? 1 : 0);
}
void t3_step_cache_release_locked() {
// Caller holds t3_step_cache_mu.
t3_step_cache_idx.clear();
t3_step_cache_lru.clear(); // entries' destructors free ctx + allocr
t3_step_cache_hits = 0;
t3_step_cache_misses = 0;
}
void t3_step_cache_release_atexit() {
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
t3_step_cache_release_locked();
}
// Look up a cached entry; on hit, splice it to the front (LRU "touch").
// Returns nullptr on miss. Mutex must NOT be held by caller.
t3_step_cache_entry * t3_step_cache_lookup(int n_past, bool is_uncond) {
const int64_t key = pack_step_key(n_past, is_uncond);
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
auto it = t3_step_cache_idx.find(key);
if (it == t3_step_cache_idx.end()) {
++t3_step_cache_misses;
return nullptr;
}
// Move to front (LRU touch). splice within the same list keeps
// iterators valid; this is the canonical std::list LRU pattern.
t3_step_cache_lru.splice(t3_step_cache_lru.begin(),
t3_step_cache_lru, it->second);
++t3_step_cache_hits;
return &(*it->second);
}
// Build a new cached entry and insert at the front. If the cache is
// at capacity, evicts the oldest (back-of-list) entry first. Returns
// the inserted entry, or nullptr on failure (e.g., backend init).
//
// Caller must NOT hold the mutex; this function takes it internally
// because the build itself is heavy (~3 ms) and we don't want to
// block other reader threads on it. Two threads racing on the same
// (n_past, is_uncond) miss are serialised here so only one builds.
t3_step_cache_entry * t3_step_cache_insert_or_get(const chatterbox_model & model,
int n_past, bool is_uncond) {
const int64_t key = pack_step_key(n_past, is_uncond);
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
// Re-check after locking — another thread may have inserted while
// we were waiting.
auto existing = t3_step_cache_idx.find(key);
if (existing != t3_step_cache_idx.end()) {
t3_step_cache_lru.splice(t3_step_cache_lru.begin(),
t3_step_cache_lru, existing->second);
++t3_step_cache_hits;
return &(*existing->second);
}
// Evict back-of-list if at capacity.
if (t3_step_cache_lru.size() >= T3_STEP_CACHE_CAP) {
const int64_t old_key = t3_step_cache_lru.back().key;
t3_step_cache_idx.erase(old_key);
t3_step_cache_lru.pop_back(); // dtor frees ctx + allocr
}
// Build the new entry at the front.
t3_step_cache_lru.emplace_front();
t3_step_cache_entry & e = t3_step_cache_lru.front();
const size_t buf_size = ggml_tensor_overhead() * CHBX_MAX_NODES +
ggml_graph_overhead_custom(CHBX_MAX_NODES, false);
e.buf.resize(buf_size);
e.key = key;
ggml_init_params p = { buf_size, e.buf.data(), /*no_alloc=*/true };
e.ctx = ggml_init(p);
if (!e.ctx) {
t3_step_cache_lru.pop_front();
return nullptr;
}
e.gf = build_step_graph_mtl_in_ctx(model, e.ctx, n_past, is_uncond);
if (!e.gf) {
t3_step_cache_lru.pop_front();
return nullptr;
}
t3_step_cache_idx[key] = t3_step_cache_lru.begin();
if (!t3_step_cache_atexit_registered) {
std::atexit(t3_step_cache_release_atexit);
t3_step_cache_atexit_registered = true;
}
return &t3_step_cache_lru.front();
}
} // namespace
// Public release entry-point. Called from chatterbox_cli.cpp's
// free_t3 lambda and chatterbox_engine.cpp's Impl::free_model BEFORE
// ggml_backend_free. Idempotent.
void t3_release_caches() {
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
t3_step_cache_release_locked();
}
// detail-scope bridges so the test_hooks namespace (defined further
// down, outside detail::) can reach the step-graph cache state without
// each individual symbol leaking into the public surface. These
// helpers are NOT for production callers; the only consumers are
// test_hooks::t3_* in the same TU.
size_t _t3_step_cache_size_for_tests() {
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
return t3_step_cache_lru.size();
}
size_t _t3_step_cache_capacity_for_tests() {
return T3_STEP_CACHE_CAP;
}
bool _t3_step_cache_contains_for_tests(int n_past, bool is_uncond) {
const int64_t key = pack_step_key(n_past, is_uncond);
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
return t3_step_cache_idx.count(key) > 0;
}
size_t _t3_step_cache_hits_for_tests() {
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
return t3_step_cache_hits;
}
size_t _t3_step_cache_misses_for_tests() {
std::lock_guard<std::mutex> lk(t3_step_cache_mu);
return t3_step_cache_misses;
}
namespace {
int64_t require_key(const gguf_context * ctx, const char * key) {
int64_t id = gguf_find_key(ctx, key);
if (id < 0) throw std::runtime_error(std::string("missing GGUF key: ") + key);
return id;
}
ggml_tensor * require_tensor(const chatterbox_model & m, const char * name) {
auto it = m.tensors.find(name);
if (it == m.tensors.end() || !it->second) {
throw std::runtime_error(std::string("missing tensor: ") + name);
}
return it->second;
}
uint32_t get_u32(const gguf_context * ctx, const char * key) {
return gguf_get_val_u32(ctx, require_key(ctx, key));
}
float get_f32(const gguf_context * ctx, const char * key) {
return gguf_get_val_f32(ctx, require_key(ctx, key));
}
bool get_bool(const gguf_context * ctx, const char * key) {
return gguf_get_val_bool(ctx, require_key(ctx, key));
}
// Llama-3 style RoPE frequency scaling (transformers `_compute_llama3_parameters`).
// Produces a per-frequency-bin correction factor that ggml_rope_ext will
// apply as its `c` (freq_factors) parameter. Length is head_dim/2.
//
// base_inv_freq[i] = 1 / theta^(2i / head_dim)
// wavelen[i] = 2*pi / base_inv_freq[i]
// if wavelen > low_wavelen: inv_freq = base / factor
// if wavelen < high_wavelen: inv_freq = base
// else: smooth transition
// freq_factor[i] = base_inv_freq[i] / effective_inv_freq[i]
// (ggml multiplies the position by 1/freq_factor[i] when
// rotating each band, so storing base/effective here is
// equivalent to dividing the base frequency by the
// same ratio Python's `inv_freq_llama / inv_freq_extrapolation`
// produces). Parity test green against PyTorch.
std::vector<float> compute_llama3_freq_factors(int head_dim, float theta,
float factor, float low_freq,
float high_freq, int orig_max_pos) {
const int half = head_dim / 2;
std::vector<float> ff(half, 1.0f);
const float low_wavelen = (float) orig_max_pos / low_freq;
const float high_wavelen = (float) orig_max_pos / high_freq;
for (int i = 0; i < half; ++i) {
const float base = 1.0f / std::pow(theta, (float)(2 * i) / (float) head_dim);
const float wavelen = 2.0f * (float) M_PI / base;
float effective;
if (wavelen > low_wavelen) {
effective = base / factor;
} else if (wavelen < high_wavelen) {
effective = base;
} else {
const float smooth = ((float) orig_max_pos / wavelen - low_freq) /
(high_freq - low_freq);
const float scaled = base / factor;
effective = (1.0f - smooth) * scaled + smooth * base;
}
ff[i] = base / effective;
}
return ff;
}
// Perceiver cross/self attention block (Perceiver.attn): a single
// AttentionBlock2 with LayerNorm + 4-head scaled-dot-product attention +
// proj_out + residual to the query side.
//
// In the perceiver forward we call this twice with the same weights:
// pre_att = attn(query_tokens, h_in) // cross-attn
// out = attn(pre_att, pre_att) // self-attn
//
// perc_q shape: (n_embd, T_q) query input (added to the output as residual)
// perc_kv shape: (n_embd, T_kv) key/value input
// Returns: (n_embd, T_q)
ggml_tensor * build_perceiver_attn(ggml_context * ctx,
const perceiver_weights & w,
const chatterbox_hparams & hp,
ggml_tensor * perc_q,
ggml_tensor * perc_kv) {
const int n_embd = hp.n_embd;
const int n_heads = hp.perceiver_heads;
const int head_dim = n_embd / n_heads;
const int T_q = perc_q->ne[1];
const int T_kv = perc_kv->ne[1];
// LayerNorm on both inputs (same affine weights as Python's self.norm).
// eps fixed at 1e-5 to match nn.LayerNorm's PyTorch default; this is
// intentionally NOT hp.eps (which is the Llama backbone's RMSNorm eps
// and only applies to the 30 transformer blocks).
auto ln = [&](ggml_tensor * x) {
ggml_tensor * n = ggml_norm(ctx, x, /*eps=*/1e-5f);
return ggml_add(ctx, ggml_mul(ctx, n, w.norm_g), w.norm_b);
};
ggml_tensor * q_norm = ln(perc_q);
ggml_tensor * kv_norm = ln(perc_kv);
ggml_tensor * q_lin = ggml_add(ctx, ggml_mul_mat(ctx, w.to_q_w, q_norm), w.to_q_b);
ggml_tensor * k_lin = ggml_add(ctx, ggml_mul_mat(ctx, w.to_k_w, kv_norm), w.to_k_b);
ggml_tensor * v_lin = ggml_add(ctx, ggml_mul_mat(ctx, w.to_v_w, kv_norm), w.to_v_b);
// Reshape to (head_dim, T, n_heads) for flash_attn_ext.
ggml_tensor * Q = ggml_reshape_3d(ctx, q_lin, head_dim, n_heads, T_q);
Q = ggml_cont(ctx, ggml_permute(ctx, Q, 0, 2, 1, 3)); // (head_dim, T_q, n_heads)
ggml_tensor * K = ggml_reshape_3d(ctx, k_lin, head_dim, n_heads, T_kv);
K = ggml_cont(ctx, ggml_permute(ctx, K, 0, 2, 1, 3));
ggml_tensor * V = ggml_reshape_3d(ctx, v_lin, head_dim, n_heads, T_kv);
V = ggml_cont(ctx, ggml_permute(ctx, V, 0, 2, 1, 3));
const float scale = 1.0f / std::sqrt((float) head_dim);
ggml_tensor * attn = ggml_flash_attn_ext(ctx, Q, K, V, /*mask=*/nullptr,
scale, /*max_bias=*/0.0f, /*logit_softcap=*/0.0f);
// attn output layout: (head_dim, n_heads, T_q, 1)
attn = ggml_reshape_2d(ctx, attn, n_embd, T_q);
ggml_tensor * proj = ggml_add(ctx, ggml_mul_mat(ctx, w.proj_out_w, attn), w.proj_out_b);
return ggml_add(ctx, perc_q, proj);
}
// Perceiver forward: pre_att = attn(pre_attention_query, h); return attn(pre_att, pre_att)
// pre_attention_query shape in the GGUF: (1024, 32, 1) after transpose convention
// h shape (cond_prompt_speech_emb): (1024, cond_prompt_len)
ggml_tensor * build_perceiver(ggml_context * ctx,
const chatterbox_model & m,
ggml_tensor * h) {
// pre_attention_query stored as (1, 32, 1024) → ggml storage (1024, 32, 1).
// Take it as a (1024, 32) 2D tensor.
ggml_tensor * query = ggml_reshape_2d(ctx, m.perceiver.pre_attention_query, m.hparams.n_embd, m.hparams.perceiver_queries);
ggml_tensor * pre_att = build_perceiver_attn(ctx, m.perceiver, m.hparams, query, h);
ggml_tensor * out = build_perceiver_attn(ctx, m.perceiver, m.hparams, pre_att, pre_att);
return out;
}
// One Llama transformer block. Writes K/V into the selected KV cache
// tensors at positions [n_past, n_past + N).
//
// inpL: (n_embd, N) for B=1
// (n_embd, N, 2) for B=2 (cond + uncond packed as ne[2])
// memory_k/v: 1D buffer (dtype = hparams.kv_type) holding the
// **cond+uncond pair** for MTL:
// size = 2 * head_dim * n_kv_head * n_ctx * n_layer elements.
// Per-layer slab is two batch slabs; cond at offset 0,
// uncond one batch slab later.
//
// Layout within a batch slab is TOKEN-MAJOR: one
// ggml_row_size(kv_type, HD * NKV) row per cached position, heads
// packed [HD-head0 ‖ HD-head1 ‖ ...] inside the row. The per-step
// append at position n_past is therefore a CONTIGUOUS span, which is
// what allows a quantised kv_type (ggml-cpu's dup→quantized path
// aborts on a non-contiguous dst) — and it lets the append consume
// the pre-permute K (rope output) / V (projection output) directly,
// dropping the two per-layer ggml_cont(permute(...)) calls the old
// head-major [HD, n_ctx, NKV] slab needed. flash_attn_ext reads the
// [HD, L, NKV] slice with plain strides (pos stride = one token row,
// head stride = one HD-row inside it; same shape llama.cpp uses).
//
// b_offset_elems selects which half is touched in the B=1 path:
// 0 → cond pass writes/reads the cond slab
// non-zero → uncond pass writes/reads the uncond slab
// In the B=2 path b_offset_elems is ignored: ne[3]=2 spans both halves
// and the per-batch stride is one batch slab.
ggml_tensor * build_llama_block(ggml_context * ctx, ggml_cgraph * gf,
const chatterbox_model & m,
int il,
ggml_tensor * inpL,
int n_past, int N, int B,
size_t b_offset_elems,
ggml_tensor * memory_k,
ggml_tensor * memory_v,
ggml_tensor * pos_ids,
ggml_tensor * kq_mask) {
const auto & hp = m.hparams;
const auto & l = m.layers_mtl[il];
const int HD = hp.head_dim;
const int NH = hp.n_head;
const int NKV = hp.n_kv_head;
const int n_ctx = hp.n_ctx;
const int64_t L = n_past + N;
// KV strides are sized off the cache dtype via ggml_row_size so the
// same builder works for f32 / f16 / q8_0 without re-deriving
// offsets per-call. Every offset lands on whole HD-rows (HD = 64 =
// two q8_0 blocks), so quantised views stay block-aligned.
const ggml_type kvt = memory_k->type;
const size_t kv_tok_row = ggml_row_size(kvt, (size_t) HD * NKV); // bytes per cached position
const size_t kv_head_row = ggml_row_size(kvt, HD); // bytes per head inside a row
const size_t kv_batch_stride = (size_t) n_ctx * kv_tok_row; // step from cond to uncond
const size_t kv_layer_stride = (size_t) 2 * kv_batch_stride; // per-layer slab is 2x
const size_t layer_off = (size_t) il * kv_layer_stride
+ (b_offset_elems != 0 ? kv_batch_stride : 0);
// Pre-attention RMSNorm (no bias).
ggml_tensor * cur = ggml_rms_norm(ctx, inpL, hp.eps);
cur = ggml_mul(ctx, cur, l.ln_attn_g);
// Q/K/V mat-muls. When the Phase-15 stacked W_qkv is available
// (Metal hot path) we run ONE Q4_0 mat-mul producing
// (3 * n_embd, N, B), then slice Q/K/V via strided views straight
// into the (HD, NH, N[, B]) shape that RoPE expects — no
// ggml_reshape (would require a contiguous source) and no
// ggml_cont (would defeat the saving). RoPE's metal kernel walks
// src via per-element nb00/nb01/nb02/nb03 strides so it handles
// the non-contiguous N stride on the slice transparently.
const int n_embd_t = hp.n_embd;
ggml_tensor * Qlin;
ggml_tensor * Klin;
ggml_tensor * Vlin;
bool used_stacked_qkv = false;
if (l.wqkv) {
ggml_tensor * QKV = ggml_mul_mat(ctx, l.wqkv, cur); // (3*n_embd, N) or (3*n_embd, N, B)
used_stacked_qkv = true;
const size_t f = sizeof(float);
const size_t row_stride = (size_t) 3 * n_embd_t * f;
const size_t batch_stride = row_stride * (size_t) N;
const size_t off_q = 0 * (size_t) n_embd_t * f;
const size_t off_k = 1 * (size_t) n_embd_t * f;
const size_t off_v = 2 * (size_t) n_embd_t * f;
if (B == 1) {
Qlin = ggml_view_2d(ctx, QKV, n_embd_t, N, row_stride, off_q);
Klin = ggml_view_2d(ctx, QKV, n_embd_t, N, row_stride, off_k);
Vlin = ggml_view_2d(ctx, QKV, n_embd_t, N, row_stride, off_v);
} else {
Qlin = ggml_view_3d(ctx, QKV, n_embd_t, N, B, row_stride, batch_stride, off_q);
Klin = ggml_view_3d(ctx, QKV, n_embd_t, N, B, row_stride, batch_stride, off_k);
Vlin = ggml_view_3d(ctx, QKV, n_embd_t, N, B, row_stride, batch_stride, off_v);
}
} else {
Qlin = ggml_mul_mat(ctx, l.wq, cur);
Klin = ggml_mul_mat(ctx, l.wk, cur);
Vlin = ggml_mul_mat(ctx, l.wv, cur);
}
// Reshape to (HD, n_head, N) [B=1] or (HD, n_head, N, B) [B=2].
// ggml_rope_ext requires ne[2] == len(pos_ids), so sequence stays on
// ne[2] at the rope call; the optional batch dim sits at ne[3].
//
// Use ggml_view_3d/4d (not ggml_reshape) so the same code path
// works whether Q/K/V came from contiguous per-head mul_mats
// (un-stacked path) or from strided slices of the W_qkv mul_mat
// (Phase-15 stacked path). RoPE's metal kernel walks src via
// per-element nb01/nb02/nb03 strides so the strided N step is
// transparent.
ggml_tensor * Q;
ggml_tensor * K;
{
const size_t f = sizeof(float);
if (B == 1) {
Q = ggml_view_3d(ctx, Qlin, HD, NH, N, HD * f, Qlin->nb[1], 0);
K = ggml_view_3d(ctx, Klin, HD, NKV, N, HD * f, Klin->nb[1], 0);
} else {
Q = ggml_view_4d(ctx, Qlin, HD, NH, N, B, HD * f, Qlin->nb[1], Qlin->nb[2], 0);
K = ggml_view_4d(ctx, Klin, HD, NKV, N, B, HD * f, Klin->nb[1], Klin->nb[2], 0);
}
}
(void) used_stacked_qkv;
// RoPE on Q and K (NEOX-style half-split convention used by Llama).
// ggml_rope_ext broadcasts cleanly over an optional batch dim at ne[3].
const int rope_mode = GGML_ROPE_TYPE_NEOX;
Q = ggml_rope_ext(ctx, Q, pos_ids, m.rope_freq_factors,
HD, rope_mode, hp.rope_orig_max_pos,
hp.rope_theta, 1.0f, 0.0f, 1.0f, 32.0f, 1.0f);
K = ggml_rope_ext(ctx, K, pos_ids, m.rope_freq_factors,
HD, rope_mode, hp.rope_orig_max_pos,
hp.rope_theta, 1.0f, 0.0f, 1.0f, 32.0f, 1.0f);
// Phase 2: alignment probe (cond pass, B==1 only). Recompute
// softmax(scale * q . K_text^T) over the text-token key columns for the
// configured (layer, head) and export it as "align_L<il>". Uses the
// post-RoPE Q/K (pre-permute) so it matches what flash-attention consumes.
// Cheap: one head, (text_j - text_i) keys. Restricted to the decode step
// (N == 1) and the cond pass / cond batch (b_offset_elems == 0; batch 0 for
// the B==2 GPU path). No-op (and graph byte-identical) when disabled.
if (N == 1 && b_offset_elems == 0 && g_t3_align.enabled) {
const int probe_head = t3_align_head_for_layer(il);
const int n_text = g_t3_align.text_j - g_t3_align.text_i;
if (probe_head >= 0 && probe_head < NH && n_text > 0) {
const int ti = g_t3_align.text_i;
// q for this head, all N queries: (HD, N).
ggml_tensor * q_h = ggml_cont(ctx,
ggml_view_2d(ctx, Q, HD, N, Q->nb[2], (size_t) probe_head * Q->nb[1]));
// K_text for this head: (HD, n_text). Text keys are in the current
// pass for the prompt (n_past covers them) and in the KV cache for
// a decode step.
ggml_tensor * k_text;
const bool text_in_pass = (ti >= n_past && g_t3_align.text_j <= n_past + N);
if (text_in_pass) {
k_text = ggml_view_2d(ctx, K, HD, n_text, K->nb[2],
(size_t) probe_head * K->nb[1] + (size_t) (ti - n_past) * K->nb[2]);
} else {
// Token-major cache: a head's HD elements are contiguous within
// a position row (kv_head_row apart between heads), and rows are
// kv_tok_row apart between positions.
k_text = ggml_view_2d(ctx, memory_k, HD, n_text, kv_tok_row,
layer_off + (size_t) probe_head * kv_head_row
+ (size_t) ti * kv_tok_row);
}
k_text = ggml_cont(ctx, k_text);
ggml_tensor * scores = ggml_mul_mat(ctx, k_text, q_h); // (n_text, N)
scores = ggml_scale(ctx, scores, 1.0f / std::sqrt((float) HD));
ggml_tensor * aprobs = ggml_soft_max(ctx, scores); // softmax over n_text
char nm[24];
std::snprintf(nm, sizeof(nm), "align_L%d", il);
ggml_set_name(aprobs, nm);
ggml_set_output(aprobs);
ggml_build_forward_expand(gf, aprobs);
}
}
// Flash attention expects Q as (HD, N, NH[, B]). Permute lifts N to
// ne[1]. K and V are NOT permuted: the rope output K (HD, NKV, N[, B])
// and the projection output V (n_embd, N[, B]) already match the
// token-major cache row layout, so the appends below consume them
// directly (saving the two per-layer ggml_cont(permute(...)) the old
// head-major slab needed).
Q = ggml_cont(ctx, ggml_permute(ctx, Q, 0, 2, 1, 3));
// Write K/V into the cache at [n_past : n_past+N) for this layer.
// Positions are consecutive token rows, so each (batch) destination
// view is contiguous and ggml_cpy converts/quantises f32 → kv_type
// on write. One cpy per batch: a single ne[3]=2 view would have a
// batch gap and stop being contiguous, which the quantising dup
// path rejects.
for (int b = 0; b < B; ++b) {
const size_t dst_off = layer_off + (size_t) b * kv_batch_stride
+ (size_t) n_past * kv_tok_row;
// K rope output is contiguous: slice batch b, flatten heads into
// the token row. V projection output rows are contiguous but
// batch/sequence strides depend on the producing path (stacked
// QKV view vs plain mul_mat), so slice via its own nb[].
ggml_tensor * k_src = ggml_view_2d(ctx, K,
(size_t) HD * NKV, N,
K->nb[2],
(size_t) b * K->nb[3]);
ggml_tensor * v_src = ggml_view_2d(ctx, Vlin,
(size_t) HD * NKV, N,
Vlin->nb[1],
(size_t) b * Vlin->nb[2]);
ggml_tensor * k_dst = ggml_view_2d(ctx, memory_k,
(size_t) HD * NKV, N,
kv_tok_row,
dst_off);
ggml_tensor * v_dst = ggml_view_2d(ctx, memory_v,
(size_t) HD * NKV, N,
kv_tok_row,
dst_off);
ggml_build_forward_expand(gf, ggml_cpy(ctx, k_src, k_dst));
ggml_build_forward_expand(gf, ggml_cpy(ctx, v_src, v_dst));
}
// Attention: read the full [0, L) slice from the cache.
ggml_tensor * Kfull;
ggml_tensor * Vfull;
if (B == 1) {
Kfull = ggml_view_3d(ctx, memory_k,
HD, L, NKV,
kv_tok_row, kv_head_row,
layer_off);
Vfull = ggml_view_3d(ctx, memory_v,
HD, L, NKV,
kv_tok_row, kv_head_row,
layer_off);
} else {
Kfull = ggml_view_4d(ctx, memory_k,
HD, L, NKV, B,
kv_tok_row, kv_head_row, kv_batch_stride,
layer_off);
Vfull = ggml_view_4d(ctx, memory_v,
HD, L, NKV, B,
kv_tok_row, kv_head_row, kv_batch_stride,
layer_off);
}
const float scale = 1.0f / std::sqrt((float) HD);
ggml_tensor * attn = ggml_flash_attn_ext(ctx, Q, Kfull, Vfull, kq_mask,
scale, 0.0f, 0.0f);
// attn ne=[HD, NH, N, B]. Reshape back to (n_embd, N[, B]).
if (B == 1) {
cur = ggml_reshape_2d(ctx, attn, hp.n_embd, N);
} else {
cur = ggml_reshape_3d(ctx, attn, hp.n_embd, N, B);
}
// O-proj + residual.
cur = ggml_mul_mat(ctx, l.wo, cur);
cur = ggml_add(ctx, cur, inpL);
// MLP (SwiGLU) with pre-norm + residual.
//
// Phase 15 stacks `[W_gate ‖ W_up]` along the M dim so a single
// Q4_0 mat-mul produces (2 * n_ff, N, B); ggml_swiglu (the
// single-arg variant, GGML_GLU_OP_SWIGLU on the stacked tensor)
// splits the result internally and fuses
// `silu(first_half) * second_half` into one Metal kernel
// (kernel_swiglu_f32). Net effect per layer per step: 2 mat-muls
// + 1 swiglu instead of 2 mat-muls + 1 swiglu_split, **plus**
// one fewer mul_mat dispatch.
//
// Pre-norm `mul(rms_norm(x), g)` is already auto-fused upstream
// by ggml-metal's `can_fuse(RMS_NORM, MUL)` path
// (kernel_rms_norm_mul_f32) — leave it written as the obvious
// two ops so CPU + non-Metal backends get the same shape.
ggml_tensor * inpFF = cur;
ggml_tensor * norm2 = ggml_mul(ctx, ggml_rms_norm(ctx, cur, hp.eps), l.ln_mlp_g);
ggml_tensor * gate = ggml_mul_mat(ctx, l.mlp_gate, norm2);
ggml_tensor * up = ggml_mul_mat(ctx, l.mlp_up, norm2);
ggml_tensor * mlp = ggml_swiglu_split(ctx, gate, up);
ggml_tensor * down = ggml_mul_mat(ctx, l.mlp_down, mlp);
return ggml_add(ctx, inpFF, down);
}
// Build the shared cond_emb fragment: (n_embd, 34).
// exaggeration_tensor is a 1-D F32 tensor of length 1 with the emotion
// scalar (we multiply with emotion_adv_w to get the 1024-d emotion token).
ggml_tensor * build_cond_emb(ggml_context * ctx,
const chatterbox_model & m,
ggml_tensor * exaggeration) {
const auto & hp = m.hparams;
// 1. spkr_enc(speaker_emb): (n_embd, 1).
// cond_spkr_w ggml ne=(256, 1024) [from nn.Linear (out=1024, in=256) -> no
// explicit transpose, numpy <-> ggml axis reversal gives us (in, out)].
// builtin_speaker_emb ggml ne=(256, 1). Result ne=(1024, 1). Bias
// (1024,) broadcasts along the N=1 column.
ggml_tensor * spkr_raw = ggml_mul_mat(ctx, m.cond_spkr_w, m.builtin_speaker_emb);
ggml_tensor * spkr = ggml_add(ctx, spkr_raw,
ggml_reshape_2d(ctx, m.cond_spkr_b, hp.n_embd, 1));
// 2. cond_prompt_speech_emb = speech_emb[tokens] + speech_pos_emb[0..len).
// T3.prepare_conditioning adds positional embeddings to the speech
// tokens before handing them to the perceiver (not-is_gpt branch).
ggml_tensor * cond_tok_emb = ggml_get_rows(ctx, m.speech_emb, m.builtin_cond_prompt_tokens);
const int cond_prompt_len = m.builtin_cond_prompt_tokens->ne[0];
ggml_tensor * cond_pos_ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, cond_prompt_len);
ggml_set_name(cond_pos_ids, "cond_prompt_pos_ids");
ggml_set_input(cond_pos_ids);
ggml_tensor * cond_pos = ggml_get_rows(ctx, m.speech_pos_emb, cond_pos_ids);
ggml_tensor * cond_prompt_emb = ggml_add(ctx, cond_tok_emb, cond_pos);
// 3. perceiver output: (n_embd, 32)
ggml_tensor * perc = build_perceiver(ctx, m, cond_prompt_emb);
// 4. emotion_adv: emotion_adv_w is (1, n_embd) after transpose; exaggeration
// is a (1,1) input scalar. mul_mat((n_embd, 1), (1, 1)) → (n_embd, 1).
// Wait, emotion_adv_fc.weight in PyTorch is shape (1024, 1) (out, in).
// After transpose in the converter: (1, 1024) stored as ggml shape (1, 1024).
// mul_mat(w[K=1, M=1024], x[K=1, N=1]) → (M=1024, N=1). Good.
ggml_tensor * emot = ggml_mul_mat(ctx, m.emotion_adv_w, exaggeration);
// 5. Concat along seq dim (ne[1]). spkr(1024,1), perc(1024,32), emot(1024,1)
// → (1024, 34).
ggml_tensor * cond_emb = ggml_concat(ctx, spkr, perc, /*dim=*/1);
cond_emb = ggml_concat(ctx, cond_emb, emot, /*dim=*/1);
return cond_emb;
}
// Build the prompt graph for either the conditional or unconditional pass.
//
// tokens: the T_text text token IDs (same for both passes)
// is_uncond: if true, zero out the text token embeddings (but keep text_pos_emb
// and the BOS speech tokens unchanged).
ggml_cgraph * build_prompt_graph_mtl(const chatterbox_model & model,
int n_text_tokens,
bool is_uncond) {
const auto & hp = model.hparams;
const int len_cond = 1 + hp.perceiver_queries + (hp.emotion_adv ? 1 : 0);
const int N = len_cond + n_text_tokens + 2; // +1 initial_speech, +1 bos
static size_t buf_size = ggml_tensor_overhead() * CHBX_MAX_NODES +
ggml_graph_overhead_custom(CHBX_MAX_NODES, false);
thread_local std::vector<uint8_t> buf(buf_size);
ggml_init_params p = { buf_size, buf.data(), true };
ggml_context * ctx = ggml_init(p);
ggml_cgraph * gf = ggml_new_graph_custom(ctx, CHBX_MAX_NODES, false);
// Dynamic inputs.
ggml_tensor * text_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_text_tokens);
ggml_set_name(text_tokens, "text_tokens"); ggml_set_input(text_tokens);
ggml_tensor * speech_bos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
ggml_set_name(speech_bos, "speech_bos"); ggml_set_input(speech_bos);
ggml_tensor * pos_ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N);
ggml_set_name(pos_ids, "pos_ids"); ggml_set_input(pos_ids);
ggml_tensor * text_pos_ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_text_tokens);
ggml_set_name(text_pos_ids, "text_pos_ids"); ggml_set_input(text_pos_ids);
ggml_tensor * speech_pos0 = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
ggml_set_name(speech_pos0, "speech_pos0"); ggml_set_input(speech_pos0);
ggml_tensor * exaggeration = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, 1);
ggml_set_name(exaggeration, "exaggeration"); ggml_set_input(exaggeration);
// Causal attention mask for prompt path (N > 1). F16 as required by Metal FA.
ggml_tensor * kq_mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, N, N);
ggml_set_name(kq_mask, "kq_mask"); ggml_set_input(kq_mask);
// 1. cond_emb (34 tokens).
ggml_tensor * cond_emb = build_cond_emb(ctx, model, exaggeration);
// 2. text_emb with learned pos (zeroed token part if uncond).
ggml_tensor * text_pos_emb_seq = ggml_get_rows(ctx, model.text_pos_emb, text_pos_ids);
ggml_tensor * text_emb_out;
if (is_uncond) {
text_emb_out = text_pos_emb_seq;
} else {
ggml_tensor * text_tok_emb = ggml_get_rows(ctx, model.text_emb, text_tokens);
text_emb_out = ggml_add(ctx, text_tok_emb, text_pos_emb_seq);
}
// 3. Speech embeddings: initial_speech = bos (both are speech_emb(6561) + spos[0]).
ggml_tensor * speech_tok_emb = ggml_get_rows(ctx, model.speech_emb, speech_bos);
ggml_tensor * speech_pos_emb_0 = ggml_get_rows(ctx, model.speech_pos_emb, speech_pos0);
ggml_tensor * speech_emb_out = ggml_add(ctx, speech_tok_emb, speech_pos_emb_0);
// 4. Concat: cond_emb | text_emb | initial_speech | bos.
ggml_tensor * inp = ggml_concat(ctx, cond_emb, text_emb_out, /*dim=*/1);
inp = ggml_concat(ctx, inp, speech_emb_out, /*dim=*/1);
inp = ggml_concat(ctx, inp, speech_emb_out, /*dim=*/1);
// 5. Run 30 Llama layers. Cond/uncond share one memory_k/memory_v
// buffer (size 2 * kv_layer_elems per layer); pick the right half via
// b_offset_elems.
const size_t kv_layer_elems = (size_t) hp.head_dim * hp.n_kv_head * hp.n_ctx;
const size_t b_off = is_uncond ? kv_layer_elems : 0;
ggml_tensor * cur = inp;
for (int il = 0; il < hp.n_layer; ++il) {
cur = build_llama_block(ctx, gf, model, il, cur, /*n_past=*/0, N,
/*B=*/1, b_off,
model.memory_k, model.memory_v,
pos_ids, kq_mask);
}
// Final RMSNorm + speech_head (take logits at last position only — seq index N-1).
cur = ggml_mul(ctx, ggml_rms_norm(ctx, cur, hp.eps), model.norm_g);
// cur: (n_embd, N) -> take last column.
ggml_tensor * last = ggml_view_2d(ctx, cur, hp.n_embd, 1,
cur->nb[1],
(size_t)(N - 1) * cur->nb[1]);
ggml_tensor * logits = ggml_mul_mat(ctx, model.speech_head, last); // (n_speech_vocab, 1)
ggml_set_name(logits, "logits"); ggml_set_output(logits);
ggml_build_forward_expand(gf, logits);
ggml_free(ctx);
return gf;
}
// B=2 prompt graph: pack cond + uncond into a single forward over the
// batch dim (ne[2]). cond_emb (spkr+perceiver+emotion) is identical
// between the two passes, so we just duplicate it; the text-token
// embedding differs (uncond zeroes the token part but keeps the learned
// positional embedding). Output: (n_speech_vocab, 1, 2) with cond at
// b=0 and uncond at b=1. Mirrors the use_b2 pattern from
// src/chatterbox_tts.cpp:1994 (S3Gen CFM CFG).
ggml_cgraph * build_prompt_graph_mtl_b2(const chatterbox_model & model,
int n_text_tokens) {
const auto & hp = model.hparams;
const int len_cond = 1 + hp.perceiver_queries + (hp.emotion_adv ? 1 : 0);
const int N = len_cond + n_text_tokens + 2;
static size_t buf_size = ggml_tensor_overhead() * CHBX_MAX_NODES +
ggml_graph_overhead_custom(CHBX_MAX_NODES, false);
thread_local std::vector<uint8_t> buf(buf_size);
ggml_init_params p = { buf_size, buf.data(), true };
ggml_context * ctx = ggml_init(p);
ggml_cgraph * gf = ggml_new_graph_custom(ctx, CHBX_MAX_NODES, false);
ggml_tensor * text_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_text_tokens);
ggml_set_name(text_tokens, "text_tokens"); ggml_set_input(text_tokens);
ggml_tensor * speech_bos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
ggml_set_name(speech_bos, "speech_bos"); ggml_set_input(speech_bos);
ggml_tensor * pos_ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N);
ggml_set_name(pos_ids, "pos_ids"); ggml_set_input(pos_ids);
ggml_tensor * text_pos_ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_text_tokens);
ggml_set_name(text_pos_ids, "text_pos_ids"); ggml_set_input(text_pos_ids);
ggml_tensor * speech_pos0 = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);