-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpocket_tts.cpp
More file actions
2868 lines (2463 loc) · 124 KB
/
pocket_tts.cpp
File metadata and controls
2868 lines (2463 loc) · 124 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
// PocketTTS.cpp — Single-file C++ TTS runtime using ONNX Runtime
// https://github.com/VolgaGerm/PocketTTS.cpp
//
// Build with CMake:
// cmake -B .build -DCMAKE_BUILD_TYPE=Release
// cmake --build .build -j$(nproc)
// ── Platform (must come first — winsock2.h before windows.h) ────────────────
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <direct.h>
#include <io.h>
#include <fcntl.h>
#pragma comment(lib, "ws2_32.lib")
#define ptt_mkdir(path) _mkdir(path)
#define ptt_close closesocket
typedef SOCKET ptt_socket_t;
typedef int socklen_t;
static constexpr ptt_socket_t PTT_INVALID_SOCKET = INVALID_SOCKET;
using ssize_t = ptrdiff_t;
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define ptt_mkdir(path) mkdir(path, 0755)
#define ptt_close close
typedef int ptt_socket_t;
static constexpr ptt_socket_t PTT_INVALID_SOCKET = -1;
#endif
#include <sys/stat.h>
#include <csignal>
// ── External Libraries ──────────────────────────────────────────────────────
#include <onnxruntime_cxx_api.h>
#include <sentencepiece_processor.h>
#define DR_WAV_IMPLEMENTATION
#include "dr_wav.h"
#define DR_MP3_IMPLEMENTATION
#include "dr_mp3.h"
#define DR_FLAC_IMPLEMENTATION
#include "dr_flac.h"
// ── Standard Library ────────────────────────────────────────────────────────
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <mutex>
#include <numeric>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
namespace pocket_tts {
// ════════════════════════════════════════════════════════════════════════════
// Types
// ════════════════════════════════════════════════════════════════════════════
static size_t calc_numel(const std::vector<int64_t>& shape) {
if (shape.empty()) return 0;
size_t n = 1;
for (auto d : shape) n *= (d > 0 ? d : 1);
return n;
}
struct Tensor {
std::vector<int64_t> shape;
std::vector<float> data;
Tensor() = default;
Tensor(std::vector<int64_t> s) : shape(std::move(s)), data(calc_numel(shape), 0.0f) {}
Tensor(std::vector<float> d, std::vector<int64_t> s) : shape(std::move(s)), data(std::move(d)) {}
size_t numel() const { return data.size(); }
float* ptr() { return data.data(); }
const float* ptr() const { return data.data(); }
Tensor& reshape(std::vector<int64_t> ns) {
int64_t neg = -1, known = 1;
for (size_t i = 0; i < ns.size(); ++i) {
if (ns[i] == -1) neg = i;
else known *= ns[i];
}
if (neg >= 0) ns[neg] = numel() / known;
shape = std::move(ns);
return *this;
}
Tensor squeeze(int64_t dim = -1) const {
std::vector<int64_t> ns;
for (size_t i = 0; i < shape.size(); ++i)
if (shape[i] != 1 || (dim >= 0 && (int64_t)i != dim)) ns.push_back(shape[i]);
if (ns.empty()) ns.push_back(1);
return Tensor(data, ns);
}
static Tensor concat(const std::vector<Tensor>& ts, int64_t dim) {
if (ts.empty()) throw std::runtime_error("Cannot concat empty list");
if (dim < 0) dim += ts[0].shape.size();
std::vector<int64_t> os = ts[0].shape;
int64_t total = 0;
for (const auto& t : ts) total += t.shape[dim];
os[dim] = total;
Tensor r(os);
int64_t outer = 1, inner = 1;
for (int64_t i = 0; i < dim; ++i) outer *= os[i];
for (size_t i = dim + 1; i < os.size(); ++i) inner *= os[i];
int64_t off = 0;
for (const auto& t : ts) {
int64_t td = t.shape[dim], chunk = td * inner;
for (int64_t o = 0; o < outer; ++o)
std::memcpy(r.data.data() + o * total * inner + off * inner,
t.data.data() + o * chunk, chunk * sizeof(float));
off += td;
}
return r;
}
};
struct TensorI64 {
std::vector<int64_t> shape;
std::vector<int64_t> data;
TensorI64() = default;
TensorI64(std::vector<int64_t> s) : shape(std::move(s)), data(calc_numel(shape), 0) {}
size_t numel() const { return data.size(); }
int64_t* ptr() { return data.data(); }
const int64_t* ptr() const { return data.data(); }
};
struct Config {
std::string models_dir = "models", tokenizer_path = "models/tokenizer.model";
std::string voices_dir = "voices";
std::string precision = "int8";
float temperature = 0.7f;
float eos_threshold = -4.0f;
float noise_clamp = 0.0f;
int lsd_steps = 1, num_threads = 0, first_chunk_frames = 1, max_chunk_frames = 15;
int eos_extra_frames = -1; // -1 = auto-calculate from text length
bool verbose = false;
bool voice_cache = true;
};
struct AudioData {
std::vector<float> samples;
int sample_rate = 24000;
float duration_sec() const { return float(samples.size()) / sample_rate; }
};
using StreamCallback = std::function<bool(const float*, size_t)>;
// ════════════════════════════════════════════════════════════════════════════
// Utilities
// ════════════════════════════════════════════════════════════════════════════
// ── RNG (xoshiro256**) ──────────────────────────────────────────────────────
namespace rng {
static uint64_t s[4] = {0x123456789ABCDEF0ULL, 0xFEDCBA9876543210ULL, 0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL};
static inline uint64_t rotl(uint64_t x, int k) { return (x << k) | (x >> (64 - k)); }
static uint64_t next() {
uint64_t result = rotl(s[1] * 5, 7) * 9, t = s[1] << 17;
s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3];
s[2] ^= t; s[3] = rotl(s[3], 45);
return result;
}
void seed(uint64_t v) {
for (int i = 0; i < 4; ++i) {
v += 0x9E3779B97F4A7C15ULL;
uint64_t z = (v ^ (v >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
s[i] = z ^ (z >> 31);
}
}
static float uniform() { return (next() >> 11) * (1.0f / 9007199254740992.0f); }
float normal(float mean = 0, float stddev = 1) {
float u1 = uniform(), u2 = uniform();
while (u1 <= 1e-10f) u1 = uniform();
return mean + stddev * std::sqrt(-2.0f * std::log(u1)) * std::cos(6.283185307179586f * u2);
}
void fill_normal(float* data, size_t n, float mean = 0, float stddev = 1) {
for (size_t i = 0; i < n; ++i) data[i] = normal(mean, stddev);
}
} // namespace rng
// ── Audio Resampling (Lanczos) ──────────────────────────────────────────────
static std::vector<float> resample(const std::vector<float>& in, int src, int dst) {
if (src == dst) return in;
constexpr int K = 16;
constexpr float PI = 3.14159265358979323846f;
double ratio = double(dst) / src;
std::vector<float> out(size_t(in.size() * ratio));
auto sinc = [&](float x) { return std::abs(x) < 1e-6f ? 1.0f : std::sin(PI * x) / (PI * x); };
auto lanczos = [&](float x) { return std::abs(x) >= K ? 0.0f : sinc(x) * sinc(x / K); };
for (size_t i = 0; i < out.size(); ++i) {
double sp = i / ratio;
int64_t c = int64_t(sp);
float f = float(sp - c), sample = 0, wsum = 0;
for (int k = -K + 1; k <= K; ++k) {
int64_t idx = c + k;
if (idx >= 0 && idx < int64_t(in.size())) {
float w = lanczos(k - f);
sample += in[idx] * w;
wsum += w;
}
}
out[i] = wsum > 0 ? sample / wsum : 0;
}
return out;
}
// ── Sentence Splitting ──────────────────────────────────────────────────────
// Splits on sentence-ending punctuation (. ! ?) followed by whitespace or EOF.
// Preserves punctuation with the sentence. Handles common abbreviations.
static std::vector<std::string> split_sentences(const std::string& text) {
std::vector<std::string> sentences;
std::string current;
auto is_abbreviation = [](const std::string& s, size_t dot_pos) -> bool {
if (dot_pos < 2) return false;
size_t start = dot_pos;
while (start > 0 && std::isalpha((unsigned char)s[start - 1])) start--;
std::string word = s.substr(start, dot_pos - start);
for (auto& c : word) c = std::tolower((unsigned char)c);
return word == "mr" || word == "mrs" || word == "ms" || word == "dr" ||
word == "st" || word == "jr" || word == "sr" || word == "vs" ||
word == "etc" || word == "inc" || word == "ltd" || word == "prof" ||
word == "gen" || word == "gov" || word == "sgt" || word == "cpl" ||
word == "pvt" || word == "capt" || word == "lt" || word == "col";
};
for (size_t i = 0; i < text.size(); ++i) {
current += text[i];
if ((text[i] == '.' || text[i] == '!' || text[i] == '?')) {
if (text[i] == '.' && i + 1 < text.size() && text[i + 1] == '.') continue;
if (text[i] == '.' && i > 0 && text[i - 1] == '.') continue;
if (text[i] == '.' && is_abbreviation(text, i)) continue;
if (i + 1 >= text.size() || text[i + 1] == ' ' || text[i + 1] == '"' || text[i + 1] == '\'') {
size_t start = current.find_first_not_of(" \t\n\r");
if (start != std::string::npos) {
sentences.push_back(current.substr(start));
}
current.clear();
}
}
}
if (!current.empty()) {
size_t start = current.find_first_not_of(" \t\n\r");
if (start != std::string::npos) {
sentences.push_back(current.substr(start));
}
}
return sentences;
}
// ── Text preparation (matches Python's prepare_text_prompt) ────────────────
static int count_words(const std::string& text) {
int count = 0;
bool in_word = false;
for (char c : text) {
if (std::isspace((unsigned char)c)) { in_word = false; }
else if (!in_word) { in_word = true; count++; }
}
return count;
}
// Prepare text for synthesis and compute frames_after_eos.
// Returns {prepared_text, eos_extra_frames}.
static std::pair<std::string, int> prepare_text(const std::string& raw, int cfg_eos_extra) {
std::string text = raw;
// Strip characters the model can't speak
std::string cleaned;
cleaned.reserve(text.size());
for (char c : text) {
if (c == '"' || c == '`') continue;
cleaned += c;
}
// Strip curly double quotes (UTF-8: " ")
auto stripUtf8 = [](std::string& s, const char* seq) {
size_t len = strlen(seq);
size_t pos;
while ((pos = s.find(seq)) != std::string::npos) s.erase(pos, len);
};
stripUtf8(cleaned, "\xe2\x80\x9c"); // "
stripUtf8(cleaned, "\xe2\x80\x9d"); // "
text = cleaned;
// Strip apostrophes/quotes from edges only (preserve contractions like don't, it's)
while (!text.empty() && (text.front() == '\'' || text.front() == '`')) text.erase(0, 1);
while (!text.empty() && (text.back() == '\'' || text.back() == '`')) text.pop_back();
// Curly apostrophes at edges (UTF-8: ' ')
while (text.size() >= 3 && text.substr(0, 3) == "\xe2\x80\x98") text.erase(0, 3);
while (text.size() >= 3 && text.substr(0, 3) == "\xe2\x80\x99") text.erase(0, 3);
while (text.size() >= 3 && text.substr(text.size() - 3) == "\xe2\x80\x98") text.erase(text.size() - 3);
while (text.size() >= 3 && text.substr(text.size() - 3) == "\xe2\x80\x99") text.erase(text.size() - 3);
// Strip leading/trailing whitespace
size_t start = text.find_first_not_of(" \t\n\r");
size_t end = text.find_last_not_of(" \t\n\r");
if (start == std::string::npos) return {"", cfg_eos_extra >= 0 ? cfg_eos_extra : 3};
text = text.substr(start, end - start + 1);
// Normalize whitespace
for (auto& c : text) { if (c == '\n' || c == '\r') c = ' '; }
int nwords = count_words(text);
int eos_extra = cfg_eos_extra >= 0 ? cfg_eos_extra : ((nwords <= 4) ? 5 : 3);
// Capitalize first letter
if (!text.empty() && std::islower((unsigned char)text[0]))
text[0] = std::toupper((unsigned char)text[0]);
// Ensure ends with punctuation
if (!text.empty() && std::isalnum((unsigned char)text.back()))
text += '.';
// Pad short text — model doesn't perform well with very few tokens
if (nwords < 5)
text = " " + text; // 8 spaces, matching Python
return {text, eos_extra};
}
// ════════════════════════════════════════════════════════════════════════════
// Profiler
// ════════════════════════════════════════════════════════════════════════════
struct Profiler {
struct Timer {
std::string name;
double total_ms = 0;
int count = 0;
double min_ms = 1e9, max_ms = 0;
void add(double ms) {
total_ms += ms;
count++;
min_ms = std::min(min_ms, ms);
max_ms = std::max(max_ms, ms);
}
double avg_ms() const { return count > 0 ? total_ms / count : 0; }
};
std::unordered_map<std::string, Timer> timers;
bool enabled = false;
class ScopedTimer {
Profiler& prof;
std::string name;
std::chrono::high_resolution_clock::time_point start;
public:
ScopedTimer(Profiler& p, const std::string& n) : prof(p), name(n), start(std::chrono::high_resolution_clock::now()) {}
~ScopedTimer() {
if (prof.enabled) {
auto end = std::chrono::high_resolution_clock::now();
double ms = std::chrono::duration<double, std::milli>(end - start).count();
prof.timers[name].name = name;
prof.timers[name].add(ms);
}
}
};
ScopedTimer time(const std::string& name) { return ScopedTimer(*this, name); }
void report() const {
std::cout << "\n========== PROFILING REPORT ==========\n";
std::vector<std::pair<std::string, Timer>> sorted;
for (const auto& [k, v] : timers) sorted.emplace_back(k, v);
std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { return a.second.total_ms > b.second.total_ms; });
std::cout << std::fixed << std::setprecision(3);
std::cout << std::left << std::setw(35) << "Operation"
<< std::right << std::setw(10) << "Total(ms)"
<< std::setw(10) << "Count"
<< std::setw(10) << "Avg(ms)"
<< std::setw(10) << "Min(ms)"
<< std::setw(10) << "Max(ms)" << "\n";
std::cout << std::string(85, '-') << "\n";
for (const auto& [name, t] : sorted) {
std::cout << std::left << std::setw(35) << name
<< std::right << std::setw(10) << t.total_ms
<< std::setw(10) << t.count
<< std::setw(10) << t.avg_ms()
<< std::setw(10) << t.min_ms
<< std::setw(10) << t.max_ms << "\n";
}
std::cout << "=======================================\n";
}
void reset() { timers.clear(); }
};
static Profiler g_prof;
// ════════════════════════════════════════════════════════════════════════════
// Disk Cache
//
// Two layers of on-disk caching, both stored under voices/.cache/:
//
// .emb files — Mimi encoder output (voice embedding).
// Avoids re-encoding the same WAV file on every run.
//
// .kv files — Transformer KV state after voice conditioning.
// Avoids re-running the expensive voice conditioning pass.
// On cache hit, restoring a KV snapshot takes ~4ms vs
// hundreds of ms for a full conditioning pass.
// ════════════════════════════════════════════════════════════════════════════
namespace cache {
static time_t get_mtime(const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) != 0) return 0;
return st.st_mtime;
}
static bool mkdir_p(const std::string& path) {
size_t pos = 0;
while (pos < path.size()) {
size_t slash = path.find('/', pos + 1);
size_t bslash = path.find('\\', pos + 1);
pos = std::min(slash, bslash);
if (pos == std::string::npos) break;
std::string sub = path.substr(0, pos);
if (!sub.empty()) ptt_mkdir(sub.c_str());
}
return ptt_mkdir(path.c_str()) == 0 || errno == EEXIST;
}
// Derive cache file path: voices/.cache/{stem}.{ext}
// ext = "emb" for voice embeddings, "kv" for KV state snapshots
static std::string get_cache_path(const std::string& voices_dir, const std::string& voice_path, const char* ext = "emb") {
std::string filename = voice_path;
size_t slash = voice_path.find_last_of("/\\");
if (slash != std::string::npos) filename = voice_path.substr(slash + 1);
size_t dot = filename.rfind('.');
if (dot != std::string::npos) filename = filename.substr(0, dot);
return voices_dir + "/.cache/" + filename + "." + ext;
}
static bool is_cache_valid(const std::string& voice_path, const std::string& cache_path) {
time_t voice_mtime = get_mtime(voice_path);
time_t cache_mtime = get_mtime(cache_path);
return cache_mtime > 0 && cache_mtime >= voice_mtime;
}
// ── Voice Embedding (.emb) Format ───────────────────────────────────────────
// [4B magic "EMB1"] [4B ndims] [ndims*8B shape] [numel*4B float data]
static constexpr uint32_t EMB_MAGIC = 0x31424D45; // "EMB1" little-endian
static bool save_embedding(const std::string& path, const std::vector<int64_t>& shape, const std::vector<float>& data) {
size_t slash = path.find_last_of('/');
if (slash != std::string::npos) {
mkdir_p(path.substr(0, slash));
}
std::ofstream f(path, std::ios::binary);
if (!f) return false;
uint32_t magic = EMB_MAGIC;
int32_t ndims = static_cast<int32_t>(shape.size());
f.write(reinterpret_cast<const char*>(&magic), 4);
f.write(reinterpret_cast<const char*>(&ndims), 4);
f.write(reinterpret_cast<const char*>(shape.data()), ndims * sizeof(int64_t));
f.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(float));
return f.good();
}
static bool load_embedding(const std::string& path, std::vector<int64_t>& shape, std::vector<float>& data) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
uint32_t magic;
int32_t ndims;
f.read(reinterpret_cast<char*>(&magic), 4);
if (magic != EMB_MAGIC) return false;
f.read(reinterpret_cast<char*>(&ndims), 4);
if (ndims <= 0 || ndims > 10) return false;
shape.resize(ndims);
f.read(reinterpret_cast<char*>(shape.data()), ndims * sizeof(int64_t));
size_t numel = 1;
for (int32_t i = 0; i < ndims; ++i) {
if (shape[i] <= 0) return false;
numel *= shape[i];
}
data.resize(numel);
f.read(reinterpret_cast<char*>(data.data()), numel * sizeof(float));
return f.good();
}
} // namespace cache
// ════════════════════════════════════════════════════════════════════════════
// ONNX Runtime Wrappers
// ════════════════════════════════════════════════════════════════════════════
static Ort::Env& get_ort_env() {
static Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "pocket_tts");
return env;
}
// Convert std::string path to ORTCHAR_T string (wchar_t on Windows, char elsewhere)
static std::basic_string<ORTCHAR_T> to_ort_path(const std::string& s) {
#ifdef _WIN32
int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
if (n <= 0) throw std::runtime_error("Failed to widen path: " + s);
std::wstring w(n - 1, 0);
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n);
return w;
#else
return s;
#endif
}
// ── OrtSession ──────────────────────────────────────────────────────────────
// Thin wrapper around Ort::Session that caches input/output names and shapes.
class OrtSession {
Ort::Session sess_;
std::vector<std::string> in_names_, out_names_;
std::vector<const char*> in_ptrs_, out_ptrs_;
std::vector<std::vector<int64_t>> in_shapes_;
std::vector<ONNXTensorElementDataType> in_types_;
std::string name_;
public:
OrtSession(Ort::Env& env, const std::string& path, const Ort::SessionOptions& opts, const std::string& name = "")
: sess_(env, to_ort_path(path).c_str(), opts), name_(name.empty() ? path : name) {
Ort::AllocatorWithDefaultOptions alloc;
size_t num_in = sess_.GetInputCount();
for (size_t i = 0; i < num_in; ++i) {
auto n = sess_.GetInputNameAllocated(i, alloc);
in_names_.push_back(n.get());
auto ti = sess_.GetInputTypeInfo(i);
auto tsi = ti.GetTensorTypeAndShapeInfo();
in_shapes_.push_back(tsi.GetShape());
in_types_.push_back(tsi.GetElementType());
}
size_t num_out = sess_.GetOutputCount();
for (size_t i = 0; i < num_out; ++i) {
auto n = sess_.GetOutputNameAllocated(i, alloc);
out_names_.push_back(n.get());
}
for (const auto& n : in_names_) in_ptrs_.push_back(n.c_str());
for (const auto& n : out_names_) out_ptrs_.push_back(n.c_str());
}
Ort::Session& session() { return sess_; }
std::vector<Ort::Value> run(const std::vector<Ort::Value>& in) {
auto _ = g_prof.time("run:" + name_);
return sess_.Run(Ort::RunOptions{nullptr}, in_ptrs_.data(), in.data(), in.size(), out_ptrs_.data(), out_ptrs_.size());
}
void run_with_binding(Ort::IoBinding& binding) {
auto _ = g_prof.time("run:" + name_);
sess_.Run(Ort::RunOptions{nullptr}, binding);
}
void print_info() const {
std::cout << "\n Model: " << name_ << "\n";
std::cout << " Inputs (" << in_names_.size() << "):\n";
for (size_t i = 0; i < in_names_.size(); ++i) {
std::cout << " [" << i << "] " << in_names_[i] << " : ";
std::cout << type_str(in_types_[i]) << " ";
print_shape(in_shapes_[i]);
std::cout << "\n";
}
std::cout << " Outputs (" << out_names_.size() << "):\n";
for (size_t i = 0; i < out_names_.size(); ++i) {
std::cout << " [" << i << "] " << out_names_[i] << "\n";
}
}
static std::string type_str(ONNXTensorElementDataType t) {
switch (t) {
case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: return "float32";
case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16: return "float16";
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: return "int8";
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: return "uint8";
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: return "int32";
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: return "int64";
case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL: return "bool";
default: return "type(" + std::to_string(t) + ")";
}
}
static void print_shape(const std::vector<int64_t>& shape) {
std::cout << "[";
for (size_t i = 0; i < shape.size(); ++i) {
if (i > 0) std::cout << ", ";
if (shape[i] < 0) std::cout << "?";
else std::cout << shape[i];
}
std::cout << "]";
}
const std::string& name() const { return name_; }
const std::vector<std::string>& input_names() const { return in_names_; }
const std::vector<std::string>& output_names() const { return out_names_; }
const std::vector<std::vector<int64_t>>& input_shapes() const { return in_shapes_; }
const std::vector<ONNXTensorElementDataType>& input_types() const { return in_types_; }
};
// ── StateBufferIO ───────────────────────────────────────────────────────────
// Manages the stateful inputs/outputs of the autoregressive transformer.
//
// The flow_lm_main model has ~60 state tensors (KV cache layers) that must
// be fed back as inputs on each step. This struct:
//
// 1. Double-buffers all state tensors so the output of step N becomes the
// input of step N+1 without copying (just swap the buffer index).
// 2. Handles mixed types (float32, int64, bool) across state tensors.
// 3. Supports both fixed-size and dynamic-size states.
// 4. Provides Snapshot (fast in-memory) and DiskSnapshot (serialized blob)
// for caching voice-conditioned KV state across runs.
struct StateBufferIO {
std::vector<std::vector<float>> f32[2];
std::vector<std::vector<int64_t>> i64[2];
std::vector<std::vector<uint8_t>> b8[2];
std::vector<std::vector<uint16_t>> f16[2]; // fp16 KV caches
std::vector<std::vector<int64_t>> shapes;
std::vector<std::vector<int64_t>> init_shapes;
std::vector<ONNXTensorElementDataType> types;
std::vector<std::string> names;
std::vector<bool> is_dynamic;
int current_buf = 0;
void init(OrtSession& s) {
const auto& in_names = s.input_names();
const auto& in_shapes = s.input_shapes();
const auto& in_types = s.input_types();
for (size_t i = 0; i < in_names.size(); ++i) {
if (in_names[i].find("state_") != 0) continue;
names.push_back(in_names[i]);
std::vector<int64_t> sh;
bool dynamic = false;
for (auto d : in_shapes[i]) {
if (d <= 0) dynamic = true;
sh.push_back(d > 0 ? d : 0);
}
shapes.push_back(sh);
types.push_back(in_types[i]);
is_dynamic.push_back(dynamic);
size_t sz = 1;
for (auto d : sh) sz *= (d > 0 ? d : 1);
size_t alloc = dynamic ? 0 : sz;
for (int b = 0; b < 2; ++b) {
if (in_types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) {
i64[b].push_back(std::vector<int64_t>(alloc, 0));
f32[b].push_back({}); f16[b].push_back({}); b8[b].push_back({});
} else if (in_types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) {
b8[b].push_back(std::vector<uint8_t>(alloc, 0));
f32[b].push_back({}); f16[b].push_back({}); i64[b].push_back({});
} else if (in_types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) {
// Single-buffered: only buffer 0 is allocated.
// Both input and output bind to buffer 0, enabling in-place scatter.
f16[b].push_back(b == 0 ? std::vector<uint16_t>(alloc, 0) : std::vector<uint16_t>());
f32[b].push_back({}); i64[b].push_back({}); b8[b].push_back({});
} else {
f32[b].push_back(std::vector<float>(alloc, 0.0f));
f16[b].push_back({}); i64[b].push_back({}); b8[b].push_back({});
}
}
}
init_shapes = shapes;
}
int in_buf() const { return current_buf; }
int out_buf() const { return 1 - current_buf; }
void swap() { current_buf = 1 - current_buf; }
// Reset all state buffers to zero without freeing/reallocating.
// Ideal for fixed-size state models (e.g. Mimi decoder) where the
// buffer sizes never change between runs.
void reset() {
current_buf = 0;
size_t n = names.size();
for (size_t i = 0; i < n; ++i) {
for (int b = 0; b < 2; ++b) {
if (is_dynamic[i]) {
f32[b][i].clear(); f16[0][i].clear();
i64[b][i].clear(); b8[b][i].clear();
} else {
std::fill(f32[b][i].begin(), f32[b][i].end(), 0.0f);
std::fill(f16[0][i].begin(), f16[0][i].end(), uint16_t(0));
std::fill(i64[b][i].begin(), i64[b][i].end(), int64_t(0));
std::fill(b8[b][i].begin(), b8[b][i].end(), uint8_t(0));
}
}
}
}
Ort::Value create_input_value(size_t state_idx, Ort::MemoryInfo& mem) {
auto t = types[state_idx];
// FP16 KV caches use single-buffered mode (always buffer 0) to enable
// in-place scatter — ORT skips the bulk copy when src == dst.
int b = (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) ? 0 : in_buf();
auto& sh = shapes[state_idx];
if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) {
return Ort::Value::CreateTensor<int64_t>(mem, i64[b][state_idx].data(), i64[b][state_idx].size(),
sh.data(), sh.size());
} else if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) {
return Ort::Value::CreateTensor<bool>(mem, reinterpret_cast<bool*>(b8[b][state_idx].data()),
b8[b][state_idx].size(), sh.data(), sh.size());
} else if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) {
return Ort::Value::CreateTensor<Ort::Float16_t>(mem, reinterpret_cast<Ort::Float16_t*>(f16[0][state_idx].data()),
f16[0][state_idx].size(), sh.data(), sh.size());
} else {
return Ort::Value::CreateTensor<float>(mem, f32[b][state_idx].data(), f32[b][state_idx].size(),
sh.data(), sh.size());
}
}
Ort::Value create_output_value(size_t state_idx, Ort::MemoryInfo& mem) {
auto t = types[state_idx];
int b = (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) ? 0 : out_buf();
auto& sh = shapes[state_idx];
if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) {
return Ort::Value::CreateTensor<int64_t>(mem, i64[b][state_idx].data(), i64[b][state_idx].size(),
sh.data(), sh.size());
} else if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) {
return Ort::Value::CreateTensor<bool>(mem, reinterpret_cast<bool*>(b8[b][state_idx].data()),
b8[b][state_idx].size(), sh.data(), sh.size());
} else if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) {
return Ort::Value::CreateTensor<Ort::Float16_t>(mem, reinterpret_cast<Ort::Float16_t*>(f16[0][state_idx].data()),
f16[0][state_idx].size(), sh.data(), sh.size());
} else {
return Ort::Value::CreateTensor<float>(mem, f32[b][state_idx].data(), f32[b][state_idx].size(),
sh.data(), sh.size());
}
}
void copy_from_output(size_t state_idx, Ort::Value& val) {
auto t = types[state_idx];
int b = (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) ? 0 : out_buf();
auto info = val.GetTensorTypeAndShapeInfo();
shapes[state_idx] = info.GetShape();
size_t out_size = info.GetElementCount();
if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) {
auto* src = val.GetTensorData<int64_t>();
i64[b][state_idx].assign(src, src + out_size);
} else if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) {
auto* src = reinterpret_cast<const uint8_t*>(val.GetTensorData<bool>());
b8[b][state_idx].assign(src, src + out_size);
} else if (t == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) {
auto* src = reinterpret_cast<const uint16_t*>(val.GetTensorData<Ort::Float16_t>());
f16[0][state_idx].assign(src, src + out_size);
} else {
auto* src = val.GetTensorData<float>();
f32[b][state_idx].assign(src, src + out_size);
}
}
// ── DiskSnapshot ────────────────────────────────────────────────────────
// Serialized blob for persisting KV state to disk (.kv files).
// Format: [4B current_buf] [4B num_states] then per-state:
// [4B ndims] [ndims*8B shape] [4B type] [8B data_bytes] [data]
struct DiskSnapshot {
std::vector<uint8_t> blob;
static constexpr uint32_t MAGIC = 0x3143564B; // "KVC1" little-endian
bool save_to_disk(const std::string& path) const {
size_t slash = path.find_last_of('/');
if (slash != std::string::npos) cache::mkdir_p(path.substr(0, slash));
std::ofstream f(path, std::ios::binary);
if (!f) return false;
uint32_t magic = MAGIC;
uint64_t sz = blob.size();
f.write(reinterpret_cast<const char*>(&magic), 4);
f.write(reinterpret_cast<const char*>(&sz), 8);
f.write(reinterpret_cast<const char*>(blob.data()), blob.size());
return f.good();
}
bool load_from_disk(const std::string& path) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
uint32_t magic;
uint64_t sz;
f.read(reinterpret_cast<char*>(&magic), 4);
if (magic != MAGIC) return false;
f.read(reinterpret_cast<char*>(&sz), 8);
if (sz == 0 || sz > 200 * 1024 * 1024) return false;
blob.resize(sz);
f.read(reinterpret_cast<char*>(blob.data()), sz);
return f.good();
}
};
// ── Snapshot ─────────────────────────────────────────────────────────────
// Fast in-memory snapshot: all state data packed into contiguous buffers.
// Restoring is a bulk memcpy into pre-sized buffers (~1ms for 60 states).
struct Snapshot {
std::vector<float> f32_data;
std::vector<int64_t> i64_data;
std::vector<uint8_t> b8_data;
std::vector<uint16_t> f16_data;
std::vector<size_t> f32_offsets;
std::vector<size_t> i64_offsets;
std::vector<size_t> b8_offsets;
std::vector<size_t> f16_offsets;
std::vector<std::vector<int64_t>> shapes;
int current_buf;
};
Snapshot take_snapshot() const {
Snapshot snap;
int b = in_buf();
size_t n = names.size();
snap.shapes.resize(n);
snap.current_buf = current_buf;
// Detect sliceable KV cache states: large float32 or float16 buffers
// paired with an int64 position counter at i+1 or i+2.
struct SliceInfo { int seq_dim; int64_t used; };
std::vector<SliceInfo> slices(n, {-1, -1});
for (size_t i = 0; i < n; ++i) {
bool is_f32 = types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT && f32[b][i].size() >= 10000;
bool is_f16 = types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16 && f16[0][i].size() >= 10000;
if (!is_f32 && !is_f16) continue;
int seq_dim = -1;
for (size_t d = 0; d < shapes[i].size(); ++d) {
if (shapes[i][d] == 1000) { seq_dim = (int)d; break; }
}
if (seq_dim < 0) continue;
for (size_t j = 1; j <= 2 && i + j < n; ++j) {
if (types[i + j] == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64 &&
i64[b][i + j].size() == 1 && i64[b][i + j][0] > 0 && i64[b][i + j][0] <= 1000) {
slices[i] = {seq_dim, i64[b][i + j][0]};
break;
}
}
}
// Compute total sizes with slicing
size_t total_f32 = 0, total_i64 = 0, total_b8 = 0, total_f16 = 0;
for (size_t i = 0; i < n; ++i) {
if (slices[i].seq_dim >= 0) {
auto sh = shapes[i];
sh[slices[i].seq_dim] = slices[i].used;
snap.shapes[i] = sh;
size_t numel = 1;
for (auto d : sh) numel *= (d > 0 ? d : 1);
if (types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) total_f16 += numel;
else total_f32 += numel;
} else {
snap.shapes[i] = shapes[i];
total_f32 += f32[b][i].size();
total_f16 += f16[0][i].size();
}
total_i64 += i64[b][i].size();
total_b8 += b8[b][i].size();
}
snap.f32_data.resize(total_f32);
snap.i64_data.resize(total_i64);
snap.b8_data.resize(total_b8);
snap.f16_data.resize(total_f16);
snap.f32_offsets.resize(n + 1);
snap.i64_offsets.resize(n + 1);
snap.b8_offsets.resize(n + 1);
snap.f16_offsets.resize(n + 1);
size_t fo = 0, io = 0, bo = 0, ho = 0;
for (size_t i = 0; i < n; ++i) {
snap.f32_offsets[i] = fo;
snap.i64_offsets[i] = io;
snap.b8_offsets[i] = bo;
snap.f16_offsets[i] = ho;
if (slices[i].seq_dim >= 0) {
int sd = slices[i].seq_dim;
int64_t N = slices[i].used;
int64_t outer = 1;
for (int d = 0; d < sd; ++d) outer *= shapes[i][d];
int64_t inner = 1;
for (size_t d = sd + 1; d < shapes[i].size(); ++d) inner *= shapes[i][d];
int64_t old_stride = shapes[i][sd] * inner;
int64_t new_stride = N * inner;
if (types[i] == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) {
const uint16_t* src = f16[0][i].data();
uint16_t* dst = snap.f16_data.data() + ho;
for (int64_t o = 0; o < outer; ++o)
memcpy(dst + o * new_stride, src + o * old_stride, new_stride * sizeof(uint16_t));
ho += outer * new_stride;
} else {
const float* src = f32[b][i].data();
float* dst = snap.f32_data.data() + fo;
for (int64_t o = 0; o < outer; ++o)
memcpy(dst + o * new_stride, src + o * old_stride, new_stride * sizeof(float));
fo += outer * new_stride;
}
} else {
if (!f32[b][i].empty()) { memcpy(snap.f32_data.data() + fo, f32[b][i].data(), f32[b][i].size() * sizeof(float)); fo += f32[b][i].size(); }
if (!f16[0][i].empty()) { memcpy(snap.f16_data.data() + ho, f16[0][i].data(), f16[0][i].size() * sizeof(uint16_t)); ho += f16[0][i].size(); }
}
if (!i64[b][i].empty()) { memcpy(snap.i64_data.data() + io, i64[b][i].data(), i64[b][i].size() * sizeof(int64_t)); io += i64[b][i].size(); }
if (!b8[b][i].empty()) { memcpy(snap.b8_data.data() + bo, b8[b][i].data(), b8[b][i].size()); bo += b8[b][i].size(); }
}
snap.f32_offsets[n] = fo;
snap.i64_offsets[n] = io;
snap.b8_offsets[n] = bo;
snap.f16_offsets[n] = ho;
return snap;
}
void restore_snapshot(const Snapshot& snap) {
current_buf = snap.current_buf;
int b = in_buf();
size_t n = names.size();
for (size_t i = 0; i < n; ++i) {
size_t f32_off = snap.f32_offsets[i], f32_end = snap.f32_offsets[i + 1];
size_t f16_off = snap.f16_offsets[i], f16_end = snap.f16_offsets[i + 1];
size_t i64_off = snap.i64_offsets[i], i64_end = snap.i64_offsets[i + 1];
size_t b8_off = snap.b8_offsets[i], b8_end = snap.b8_offsets[i + 1];
bool has_f32 = f32_end > f32_off;
bool has_f16 = f16_end > f16_off;
bool sliced = (snap.shapes[i] != init_shapes[i]) && (has_f32 || has_f16);
if (sliced) {
size_t full_size = 1;
for (auto d : init_shapes[i]) full_size *= (d > 0 ? d : 1);
int sd = -1;