forked from ggml-org/whisper.cpp
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathparakeet_engine.cpp
More file actions
1719 lines (1515 loc) · 72.3 KB
/
Copy pathparakeet_engine.cpp
File metadata and controls
1719 lines (1515 loc) · 72.3 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
// Engine: GGUF load, transcribe, streaming sessions, diarization, timing and options.
#include "parakeet/engine.h"
#include "parakeet/streaming.h"
#include "parakeet/diarization.h"
#include "parakeet/attributed.h"
#include "parakeet_ctc.h"
#include "parakeet_tdt.h"
#include "parakeet_eou.h"
#include "parakeet_sortformer.h"
#include "mel_preprocess.h"
#include "sentencepiece_bpe.h"
#include "energy_vad.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace parakeet {
namespace {
// Encoder frame stride in milliseconds, derived from the GGUF's mel hop
// length, encoder subsampling factor and sample rate. All shipped models
// happen to land at 80 ms (16 kHz x hop=160 x sub=8) but new GGUFs may
// differ -- e.g. a 24 kHz checkpoint or a 4x subsampling variant.
inline double encoder_frame_stride_ms(const ParakeetCtcModel & model) {
const int hop = model.mel_cfg.hop_length;
const int sub = model.encoder_cfg.subsampling_factor > 0
? model.encoder_cfg.subsampling_factor : 8;
const int sr = model.mel_cfg.sample_rate > 0 ? model.mel_cfg.sample_rate : 16000;
return 1000.0 * (double) (hop * sub) / (double) sr;
}
double ms_since(std::chrono::steady_clock::time_point a) {
using namespace std::chrono;
return duration_cast<microseconds>(steady_clock::now() - a).count() / 1000.0;
}
}
struct Engine::Impl {
EngineOptions opts;
ParakeetCtcModel model;
std::atomic<bool> cancel_flag{false};
TdtRuntimeWeights tdt_rt;
bool tdt_ready = false;
EouRuntimeWeights eou_rt;
bool eou_ready = false;
bool sortformer_ready = false;
// Reusable mel preprocess scratch buffers. Engine APIs are
// documented as single-threaded per-instance (see engine.h
// `Engine::transcribe_*` notes), so a single state member is
// sufficient. StreamSession holds its own MelState (see below)
// because the encoder + decoder pipelines run independently.
MelState mel_state;
Impl() = default;
};
// Opt-in encoder prewarm. Runs one synthetic
// forward pass through the encoder so the cold-graph-build cost is
// amortised into Engine construction instead of warmup_1.
//
// What this catches across backends:
// * Metal: triggers MSL → MTLPipelineState compile.
// * OpenCL: triggers clBuildProgram for every kernel variant the
// encoder graph touches; binaries get cached via the
// program-binary-cache patch when GGML_OPENCL_CACHE_DIR
// is set, so subsequent processes skip even this prewarm cost.
// * Vulkan: triggers vkCreateGraphicsPipelines.
// * CUDA: triggers cuGraphInstantiate.
// * CPU: pre-builds the ggml graph nodes + scratch + caches them
// via the same encoder_graphs LRU as a real call.
//
// Mel input is all-zero (filterbank output for a silent buffer is
// the model's mel_floor / log_zero_guard, but for warmup we just
// need any valid-shape input that flows through every node — zeros
// are fine; log-mel of true zeros is effectively `log(eps)`, no NaN
// risk because compute_log_mel + run_encoder both apply the model's
// log_zero_guard from the GGUF metadata).
//
// Shape: `prewarm_audio_seconds * sample_rate` samples mapped to
// `(prewarm_audio_seconds * sr / hop)` mel frames. Encoder cache
// is shape-keyed on `(T_mel, layers, all_valid)`, so a real call
// with a different T_mel will trigger a fresh graph build — but on
// Metal/OpenCL/Vulkan the *kernel pipeline cache* is keyed on
// kernel signature, not graph shape, so prewarm with any shape
// still warms the relevant compile cost.
//
// Cost: typically 50-300 ms on the first construction; subsequent
// constructions in the same process land near zero (encoder cache
// + GPU pipeline cache hit).
static void prewarm_encoder(ParakeetCtcModel & model, float audio_seconds) {
if (audio_seconds <= 0.0f) audio_seconds = 1.0f;
const int sr = model.mel_cfg.sample_rate > 0 ? model.mel_cfg.sample_rate : 16000;
const int hop = model.mel_cfg.hop_length > 0 ? model.mel_cfg.hop_length : 160;
// Frame count derived directly from the audio-seconds knob; we
// skip compute_log_mel entirely (the host-side mel pipeline
// doesn't have any cold-build state worth amortising) and feed
// the encoder zeros at the correct shape.
const int n_frames = std::max(8,
(int) std::lround((double) audio_seconds * (double) sr / (double) hop));
const int n_mels = model.mel_cfg.n_mels > 0 ? model.mel_cfg.n_mels : 80;
std::vector<float> zeros((size_t) n_frames * (size_t) n_mels, 0.0f);
EncoderOutputs out;
// capture_intermediates=false: production-shape call (no
// per-stage host roundtrips); same `false` the audit
// wired into Engine::transcribe_*. capture=false keeps the
// graph topology identical to a real call so the kernel
// pipeline cache hit is real.
if (int rc = run_encoder(model, zeros.data(), n_frames, n_mels, out,
/*max_layers=*/-1,
/*capture_intermediates=*/false); rc != 0) {
// Don't fail construction — the user's first transcribe
// call will surface the same error with full context.
// Just log so the field is observable.
std::fprintf(stderr,
"[parakeet] prewarm_encoder: run_encoder rc=%d (T_mel=%d, n_mels=%d) -- "
"first transcribe will pay the cold cost the prewarm was meant to cover\n",
rc, n_frames, n_mels);
}
}
Engine::Engine(const EngineOptions & opts) : pimpl_(std::make_unique<Impl>()) {
pimpl_->opts = opts;
// Apply backend-init knobs before the first ggml call. Both are
// process-singleton-scoped (the ggml-backend registry only ever
// gets populated once per process; `$GGML_OPENCL_CACHE_DIR` is
// read once by ggml-opencl at first init), so this is effectively
// a "first Engine wins" race -- a second Engine with a different
// backends_dir is logged + ignored by set_backends_directory().
// Hosts that need per-Engine isolation should run each Engine in
// its own subprocess.
if (!opts.backends_dir.empty()) {
set_backends_directory(opts.backends_dir);
}
if (!opts.opencl_cache_dir.empty()) {
set_opencl_cache_dir(opts.opencl_cache_dir);
}
const int rc = load_from_gguf(opts.model_gguf_path,
pimpl_->model,
opts.n_threads,
opts.n_gpu_layers,
opts.verbose);
if (rc != 0) {
throw std::runtime_error("parakeet::Engine: failed to load GGUF '" +
opts.model_gguf_path +
"' (rc=" + std::to_string(rc) + ")");
}
if (pimpl_->model.model_type == ParakeetModelType::TDT) {
if (tdt_prepare_runtime(pimpl_->model, pimpl_->tdt_rt) != 0) {
throw std::runtime_error("Engine: tdt_prepare_runtime failed");
}
pimpl_->tdt_ready = true;
}
if (pimpl_->model.model_type == ParakeetModelType::EOU) {
if (eou_prepare_runtime(pimpl_->model, pimpl_->eou_rt) != 0) {
throw std::runtime_error("Engine: eou_prepare_runtime failed");
}
pimpl_->eou_ready = true;
}
if (pimpl_->model.model_type == ParakeetModelType::SORTFORMER) {
pimpl_->sortformer_ready = true;
}
if (opts.prewarm) {
prewarm_encoder(pimpl_->model, opts.prewarm_audio_seconds);
}
}
Engine::~Engine() = default;
Engine::Engine(Engine &&) noexcept = default;
Engine & Engine::operator=(Engine &&) noexcept = default;
const EngineOptions & Engine::options() const {
return pimpl_->opts;
}
std::string Engine::model_type() const {
switch (pimpl_->model.model_type) {
case ParakeetModelType::TDT: return "tdt";
case ParakeetModelType::EOU: return "eou";
case ParakeetModelType::SORTFORMER: return "sortformer";
case ParakeetModelType::CTC:
default: return "ctc";
}
}
bool Engine::is_diarization_model() const {
return pimpl_->model.model_type == ParakeetModelType::SORTFORMER;
}
bool Engine::is_transcription_model() const {
return pimpl_->model.model_type == ParakeetModelType::CTC ||
pimpl_->model.model_type == ParakeetModelType::TDT ||
pimpl_->model.model_type == ParakeetModelType::EOU;
}
BackendDevice Engine::backend_device() const {
return model_has_gpu_backend(pimpl_->model) ? BackendDevice::GPU
: BackendDevice::CPU;
}
std::string Engine::backend_name() const {
return model_active_backend_name(pimpl_->model);
}
bool Engine::gpu_unsupported() const {
return model_gpu_unsupported(pimpl_->model);
}
void Engine::cancel() {
pimpl_->cancel_flag.store(true);
}
EngineResult Engine::transcribe(const std::string & wav_path) {
std::vector<float> samples;
int sr = 0;
if (int rc = load_wav_mono_f32(wav_path, samples, sr); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe: failed to load wav '" +
wav_path + "' (rc=" + std::to_string(rc) + ")");
}
return transcribe_samples(samples.data(), (int) samples.size(), sr);
}
EngineResult Engine::transcribe_samples(const float * samples, int n_samples, int sample_rate) {
if (!samples || n_samples <= 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples: empty input");
}
if (sample_rate != pimpl_->model.mel_cfg.sample_rate) {
throw std::runtime_error("parakeet::Engine::transcribe_samples: input is " +
std::to_string(sample_rate) + " Hz but model expects " +
std::to_string(pimpl_->model.mel_cfg.sample_rate) + " Hz");
}
if (pimpl_->model.model_type == ParakeetModelType::SORTFORMER) {
throw std::runtime_error(
"parakeet::Engine::transcribe_samples: loaded GGUF is a Sortformer "
"diarization model; call Engine::diarize() (or transcribe_with_speakers "
"with a separate ASR engine) instead.");
}
pimpl_->cancel_flag.store(false);
using clock = std::chrono::steady_clock;
const auto t_total = clock::now();
const auto t_mel = clock::now();
std::vector<float> mel;
int n_mel_frames = 0;
if (int rc = compute_log_mel(samples, n_samples, pimpl_->model.mel_cfg,
pimpl_->mel_state, mel, n_mel_frames); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples: compute_log_mel failed (rc=" +
std::to_string(rc) + ")");
}
const double preprocess_ms = ms_since(t_mel);
const auto t_enc = clock::now();
EncoderOutputs enc_out;
if (int rc = run_encoder(pimpl_->model, mel.data(), n_mel_frames,
pimpl_->model.mel_cfg.n_mels, enc_out,
/*max_layers=*/-1,
/*capture_intermediates=*/false); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples: run_encoder failed (rc=" +
std::to_string(rc) + ")");
}
const double encoder_ms = ms_since(t_enc);
const auto t_dec = clock::now();
std::vector<int32_t> ids;
std::string text;
if (pimpl_->model.model_type == ParakeetModelType::TDT) {
TdtDecodeOptions dopts;
TdtDecodeResult dres;
if (int rc = tdt_greedy_decode(pimpl_->model, pimpl_->tdt_rt,
enc_out.encoder_out.data(),
enc_out.n_enc_frames, enc_out.d_model,
dopts, dres); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples: tdt_greedy_decode failed (rc=" +
std::to_string(rc) + ")");
}
ids = std::move(dres.token_ids);
text = std::move(dres.text);
} else if (pimpl_->model.model_type == ParakeetModelType::EOU) {
EouDecodeOptions dopts;
dopts.max_symbols_per_step = pimpl_->model.encoder_cfg.eou_max_symbols_per_step;
EouDecodeResult dres;
if (int rc = eou_greedy_decode(pimpl_->model, pimpl_->eou_rt,
enc_out.encoder_out.data(),
enc_out.n_enc_frames, enc_out.d_model,
dopts, dres); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples: eou_greedy_decode failed (rc=" +
std::to_string(rc) + ")");
}
ids = std::move(dres.token_ids);
text = std::move(dres.text);
} else {
ids = ctc_greedy_decode(enc_out.logits.data(), enc_out.n_enc_frames,
pimpl_->model.vocab_size, pimpl_->model.blank_id);
text = detokenize(pimpl_->model.vocab, ids);
}
const double decode_ms = ms_since(t_dec);
EngineResult result;
result.text = std::move(text);
result.token_ids = std::move(ids);
result.preprocess_ms = preprocess_ms;
result.encoder_ms = encoder_ms;
result.decode_ms = decode_ms;
result.total_ms = ms_since(t_total);
result.audio_samples = n_samples;
result.sample_rate = sample_rate;
result.mel_frames = n_mel_frames;
result.encoder_frames = enc_out.n_enc_frames;
return result;
}
EngineResult Engine::transcribe_stream(const std::string & wav_path,
const StreamingOptions & opts,
StreamingCallback on_segment) {
std::vector<float> samples;
int sr = 0;
if (int rc = load_wav_mono_f32(wav_path, samples, sr); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_stream: failed to load wav '" +
wav_path + "' (rc=" + std::to_string(rc) + ")");
}
return transcribe_samples_stream(samples.data(), (int) samples.size(), sr,
opts, std::move(on_segment));
}
EngineResult Engine::transcribe_samples_stream(const float * samples,
int n_samples,
int sample_rate,
const StreamingOptions & opts,
StreamingCallback on_segment) {
if (!samples || n_samples <= 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: empty input");
}
if (sample_rate != pimpl_->model.mel_cfg.sample_rate) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: input is " +
std::to_string(sample_rate) + " Hz but model expects " +
std::to_string(pimpl_->model.mel_cfg.sample_rate) + " Hz");
}
if (opts.sample_rate != 0 && opts.sample_rate != sample_rate) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: "
"StreamingOptions.sample_rate must match the input sample_rate");
}
if (opts.chunk_ms <= 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: "
"StreamingOptions.chunk_ms must be > 0");
}
if (pimpl_->model.model_type == ParakeetModelType::SORTFORMER) {
throw std::runtime_error(
"transcribe_samples_stream: streaming is for transcription models only; "
"Sortformer is a diarization model. Use Engine::diarize().");
}
pimpl_->cancel_flag.store(false);
using clock = std::chrono::steady_clock;
const auto t_total = clock::now();
const auto t_mel = clock::now();
std::vector<float> mel;
int n_mel_frames = 0;
if (int rc = compute_log_mel(samples, n_samples, pimpl_->model.mel_cfg,
pimpl_->mel_state, mel, n_mel_frames); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: compute_log_mel failed (rc=" +
std::to_string(rc) + ")");
}
const double preprocess_ms = ms_since(t_mel);
const auto t_enc = clock::now();
EncoderOutputs enc_out;
if (int rc = run_encoder(pimpl_->model, mel.data(), n_mel_frames,
pimpl_->model.mel_cfg.n_mels, enc_out,
/*max_layers=*/-1,
/*capture_intermediates=*/false); rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: run_encoder failed (rc=" +
std::to_string(rc) + ")");
}
const double encoder_ms = ms_since(t_enc);
const int T_enc = enc_out.n_enc_frames;
const int vocab = pimpl_->model.vocab_size;
const int blank = pimpl_->model.blank_id;
const double frame_stride_ms = encoder_frame_stride_ms(pimpl_->model);
int frames_per_window = (int) std::floor(opts.chunk_ms / frame_stride_ms);
if (frames_per_window < 1) frames_per_window = 1;
EngineResult result;
result.preprocess_ms = preprocess_ms;
result.encoder_ms = encoder_ms;
result.audio_samples = n_samples;
result.sample_rate = sample_rate;
result.mel_frames = n_mel_frames;
result.encoder_frames = T_enc;
const auto t_dec = clock::now();
const bool is_tdt = (pimpl_->model.model_type == ParakeetModelType::TDT);
const bool is_eou = (pimpl_->model.model_type == ParakeetModelType::EOU);
int32_t prev_token = -1;
TdtDecodeState tdt_state;
EouDecodeState eou_state;
if (is_tdt) tdt_init_state(pimpl_->tdt_rt, (int) pimpl_->model.blank_id, tdt_state);
if (is_eou) eou_init_state(pimpl_->eou_rt, eou_state);
int chunk_index = 0;
bool first_segment = true;
for (int start = 0; start < T_enc; start += frames_per_window) {
if (pimpl_->cancel_flag.load()) break;
int end = start + frames_per_window;
if (end > T_enc) end = T_enc;
const auto t_win = clock::now();
std::vector<int32_t> win_tokens;
int eou_boundaries_in_chunk = 0;
if (is_tdt) {
TdtDecodeOptions dopts;
int steps = 0;
const float * win_enc = enc_out.encoder_out.data()
+ static_cast<size_t>(start) * enc_out.d_model;
if (int rc = tdt_decode_window(pimpl_->model, pimpl_->tdt_rt,
win_enc, end - start, enc_out.d_model,
dopts, tdt_state, win_tokens, steps);
rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: "
"tdt_decode_window failed (rc=" + std::to_string(rc) + ")");
}
} else if (is_eou) {
EouDecodeOptions dopts;
dopts.max_symbols_per_step = pimpl_->model.encoder_cfg.eou_max_symbols_per_step;
std::vector<EouSegmentBoundary> win_segments;
int steps = 0;
const float * win_enc = enc_out.encoder_out.data()
+ static_cast<size_t>(start) * enc_out.d_model;
if (int rc = eou_decode_window(pimpl_->model, pimpl_->eou_rt,
win_enc, end - start, enc_out.d_model,
dopts, eou_state,
win_tokens, win_segments, steps);
rc != 0) {
throw std::runtime_error("parakeet::Engine::transcribe_samples_stream: "
"eou_decode_window failed (rc=" + std::to_string(rc) + ")");
}
eou_boundaries_in_chunk = static_cast<int>(win_segments.size());
} else {
ctc_greedy_decode_window(enc_out.logits.data(),
start, end, vocab, blank,
prev_token, win_tokens, nullptr);
}
const size_t prev_cumulative_len = result.text.size();
result.token_ids.insert(result.token_ids.end(),
win_tokens.begin(), win_tokens.end());
result.text = detokenize(pimpl_->model.vocab, result.token_ids);
const std::string win_text = result.text.substr(prev_cumulative_len);
const double win_decode_ms = ms_since(t_win);
const double seg_end_s = static_cast<double>(end) * frame_stride_ms / 1000.0;
if (on_segment) {
StreamingSegment seg;
seg.text = win_text;
seg.token_ids = win_tokens;
seg.start_s = static_cast<double>(start) * frame_stride_ms / 1000.0;
seg.end_s = seg_end_s;
seg.chunk_index = chunk_index;
seg.is_final = true;
seg.starts_word = win_tokens.empty()
? true
: token_is_word_start(pimpl_->model.vocab, win_tokens.front());
seg.is_eou_boundary = eou_boundaries_in_chunk > 0;
seg.encoder_ms = first_segment ? encoder_ms : 0.0;
seg.decode_ms = win_decode_ms;
on_segment(seg);
}
// EOU Mode 2: emit EndOfTurn when EOU boundaries appear in this chunk (same idea as Mode 3).
if (opts.on_event && eou_boundaries_in_chunk > 0) {
StreamEvent ev;
ev.type = StreamEventType::EndOfTurn;
ev.timestamp_s = seg_end_s;
ev.chunk_index = chunk_index;
ev.eot_confidence = 1.0f;
for (int i = 0; i < eou_boundaries_in_chunk; ++i) {
opts.on_event(ev);
}
}
++chunk_index;
first_segment = false;
}
result.decode_ms = ms_since(t_dec);
result.total_ms = ms_since(t_total);
return result;
}
DiarizationResult Engine::diarize(const std::string & wav_path,
const DiarizationOptions & opts) {
std::vector<float> samples;
int sr = 0;
if (int rc = load_wav_mono_f32(wav_path, samples, sr); rc != 0) {
throw std::runtime_error("Engine::diarize: failed to load wav '" + wav_path +
"' (rc=" + std::to_string(rc) + ")");
}
return diarize_samples(samples.data(), (int) samples.size(), sr, opts);
}
static DiarizationResult engine_impl_diarize_helper(Engine::Impl & impl,
const float * samples,
int n_samples,
int sample_rate,
const DiarizationOptions & opts) {
if (!samples || n_samples <= 0) {
throw std::runtime_error("diarize: empty input");
}
if (sample_rate != impl.model.mel_cfg.sample_rate) {
throw std::runtime_error("diarize: input is " +
std::to_string(sample_rate) + " Hz but model expects " +
std::to_string(impl.model.mel_cfg.sample_rate) + " Hz");
}
if (impl.model.model_type != ParakeetModelType::SORTFORMER || !impl.sortformer_ready) {
throw std::runtime_error("diarize: loaded GGUF is not a Sortformer model");
}
impl.cancel_flag.store(false);
using clock = std::chrono::steady_clock;
const auto t_total = clock::now();
std::vector<float> work(samples, samples + n_samples);
float peak = 0.0f;
for (float v : work) {
const float a = std::fabs(v);
if (a > peak) peak = a;
}
constexpr float NORM_FLOOR = 1e-3f;
if (peak > NORM_FLOOR) {
const float inv = 1.0f / peak;
for (float & v : work) v *= inv;
}
const auto t_mel = clock::now();
std::vector<float> mel;
int n_mel_frames = 0;
if (int rc = compute_log_mel(work.data(), n_samples, impl.model.mel_cfg,
impl.mel_state, mel, n_mel_frames); rc != 0) {
throw std::runtime_error("diarize: compute_log_mel failed (rc=" +
std::to_string(rc) + ")");
}
const double preprocess_ms = ms_since(t_mel);
const auto t_enc = clock::now();
EncoderOutputs enc_out;
if (int rc = run_encoder(impl.model, mel.data(), n_mel_frames,
impl.model.mel_cfg.n_mels, enc_out,
/*max_layers=*/-1,
/*capture_intermediates=*/false); rc != 0) {
throw std::runtime_error("diarize: run_encoder failed (rc=" +
std::to_string(rc) + ")");
}
const double encoder_ms = ms_since(t_enc);
SortformerDiarizationOptions sopts;
sopts.threshold = opts.threshold;
SortformerDiarizationResult dres;
ggml_backend_t head_backend = model_sortformer_backend(impl.model);
if (!head_backend) {
throw std::runtime_error("diarize: no ggml backend for the diarization head");
}
int diarize_rc = sortformer_diarize_ggml(impl.model,
enc_out.encoder_out.data(),
enc_out.n_enc_frames, enc_out.d_model,
head_backend, sopts, dres);
if (diarize_rc != 0) {
throw std::runtime_error("diarize: sortformer_diarize failed (rc=" +
std::to_string(diarize_rc) + ")");
}
DiarizationResult result;
result.n_frames = dres.n_frames;
result.num_spks = dres.num_spks;
result.frame_stride_s = dres.frame_stride_s;
result.speaker_probs = std::move(dres.speaker_probs);
result.audio_samples = n_samples;
result.sample_rate = sample_rate;
result.preprocess_ms = preprocess_ms;
result.encoder_ms = encoder_ms;
result.decode_ms = dres.decode_ms;
result.total_ms = ms_since(t_total);
const double min_dur = opts.min_segment_ms / 1000.0;
for (const auto & s : dres.segments) {
if ((s.end_s - s.start_s) < min_dur) continue;
DiarizationSegment d;
d.speaker_id = s.speaker_id;
d.start_s = s.start_s;
d.end_s = s.end_s;
result.segments.push_back(d);
}
return result;
}
// AOSC streaming variant of engine_impl_diarize_helper. NeMo-faithful port of
// `forward_streaming_step` + `streaming_update`:
// 1. compute_log_mel on the chunk audio (which already includes lc/rc context)
// 2. run_subsampling -> chunk_pre_encode_embs (post-subsampling, 512-d)
// 3. sortformer_aosc_step assembles [spkcache | fifo | chunk_pre_encode],
// runs the conformer layers via run_encoder_bypass_pre_encode, then the
// diariser head, then streaming_update on the resulting preds + new chunk
//
// Returned segments are chunk-relative (start_s == 0 at the START OF THE
// committed chunk -- the lc_enc frames at the head of the encoder output are
// dropped before thresholding).
static DiarizationResult engine_impl_diarize_streaming_helper(
Engine::Impl & impl,
const float * samples, int n_samples,
int sample_rate,
const DiarizationOptions & opts,
SortformerSpeakerCache & cache,
const SortformerStreamingConfig & cfg,
int lc_enc_frames_expected, int rc_enc_frames_expected) {
if (!samples || n_samples <= 0) {
throw std::runtime_error("diarize_streaming: empty input");
}
if (sample_rate != impl.model.mel_cfg.sample_rate) {
throw std::runtime_error("diarize_streaming: input is " +
std::to_string(sample_rate) + " Hz but model expects " +
std::to_string(impl.model.mel_cfg.sample_rate) + " Hz");
}
if (impl.model.model_type != ParakeetModelType::SORTFORMER || !impl.sortformer_ready) {
throw std::runtime_error("diarize_streaming: loaded GGUF is not a Sortformer model");
}
impl.cancel_flag.store(false);
using clock = std::chrono::steady_clock;
const auto t_total = clock::now();
// No per-chunk peak normalisation: amplitude consistency across chunks
// matters for the cache embeddings to remain in-distribution.
std::vector<float> work(samples, samples + n_samples);
const auto t_mel = clock::now();
std::vector<float> mel;
int n_mel_frames = 0;
if (int rc = compute_log_mel(work.data(), n_samples, impl.model.mel_cfg,
impl.mel_state, mel, n_mel_frames); rc != 0) {
throw std::runtime_error("diarize_streaming: compute_log_mel failed (rc=" +
std::to_string(rc) + ")");
}
const double preprocess_ms = ms_since(t_mel);
// Subsampling only -- the cache concat happens BEFORE the conformer layers.
const auto t_enc = clock::now();
std::vector<float> pre_encode;
int n_pre_encode_frames = 0;
if (int rc = run_subsampling(impl.model, mel.data(), n_mel_frames,
impl.model.mel_cfg.n_mels,
pre_encode, n_pre_encode_frames); rc != 0) {
throw std::runtime_error("diarize_streaming: run_subsampling failed (rc=" +
std::to_string(rc) + ")");
}
const int D = impl.model.encoder_cfg.d_model;
// Reconcile expected lc/rc encoder frames with what subsampling actually
// produced. If subsampling returned fewer frames than expected (tail-chunk
// with insufficient right context), shrink rc to what fits and let
// chunk_len_eff absorb the leftover.
int lc = lc_enc_frames_expected;
int rc = rc_enc_frames_expected;
if (lc + rc > n_pre_encode_frames) {
rc = std::max(0, n_pre_encode_frames - lc);
if (lc + rc > n_pre_encode_frames) {
lc = std::max(0, n_pre_encode_frames - rc);
}
}
int chunk_len_eff = n_pre_encode_frames - lc - rc;
if (chunk_len_eff <= 0) {
DiarizationResult result;
result.n_frames = 0;
result.num_spks = impl.model.encoder_cfg.sortformer_num_spks;
result.frame_stride_s = (double)(impl.model.mel_cfg.hop_length *
impl.model.encoder_cfg.subsampling_factor) /
(double)impl.model.mel_cfg.sample_rate;
result.audio_samples = n_samples;
result.sample_rate = sample_rate;
result.preprocess_ms = preprocess_ms;
result.encoder_ms = ms_since(t_enc);
result.total_ms = ms_since(t_total);
return result;
}
SortformerDiarizationOptions s_opts;
s_opts.threshold = opts.threshold;
SortformerDiarizationResult dres;
ggml_backend_t head_backend = model_sortformer_backend(impl.model);
if (!head_backend) {
throw std::runtime_error("diarize_streaming: no ggml backend for the diarization head");
}
if (int rc_ = sortformer_aosc_step(impl.model,
pre_encode.data(),
n_pre_encode_frames, D,
lc, rc, chunk_len_eff,
cache, cfg, head_backend, s_opts, dres);
rc_ != 0) {
throw std::runtime_error("diarize_streaming: sortformer_aosc_step failed (rc=" +
std::to_string(rc_) + ")");
}
const double encoder_ms = ms_since(t_enc) - dres.decode_ms;
DiarizationResult result;
result.n_frames = dres.n_frames;
result.num_spks = dres.num_spks;
result.frame_stride_s = dres.frame_stride_s;
result.speaker_probs = std::move(dres.speaker_probs);
result.audio_samples = n_samples;
result.sample_rate = sample_rate;
result.preprocess_ms = preprocess_ms;
result.encoder_ms = encoder_ms;
result.decode_ms = dres.decode_ms;
result.total_ms = ms_since(t_total);
const double min_dur = opts.min_segment_ms / 1000.0;
for (const auto & s : dres.segments) {
if ((s.end_s - s.start_s) < min_dur) continue;
DiarizationSegment d;
d.speaker_id = s.speaker_id;
d.start_s = s.start_s;
d.end_s = s.end_s;
result.segments.push_back(d);
}
return result;
}
DiarizationResult Engine::diarize_samples(const float * samples,
int n_samples,
int sample_rate,
const DiarizationOptions & opts) {
return engine_impl_diarize_helper(*pimpl_, samples, n_samples, sample_rate, opts);
}
AttributedTranscriptionResult transcribe_with_speakers(
Engine & sortformer_engine,
Engine & asr_engine,
const std::string & wav_path,
const AttributedTranscriptionOptions & opts) {
std::vector<float> samples;
int sr = 0;
if (int rc = load_wav_mono_f32(wav_path, samples, sr); rc != 0) {
throw std::runtime_error("transcribe_with_speakers: failed to load wav '" +
wav_path + "' (rc=" + std::to_string(rc) + ")");
}
return transcribe_samples_with_speakers(sortformer_engine, asr_engine,
samples.data(), (int) samples.size(),
sr, opts);
}
AttributedTranscriptionResult transcribe_samples_with_speakers(
Engine & sortformer_engine,
Engine & asr_engine,
const float * samples,
int n_samples,
int sample_rate,
const AttributedTranscriptionOptions & opts) {
if (!samples || n_samples <= 0) {
throw std::runtime_error("transcribe_samples_with_speakers: empty input");
}
if (!sortformer_engine.is_diarization_model()) {
throw std::runtime_error("transcribe_samples_with_speakers: first engine "
"is not a Sortformer diarization model");
}
if (!asr_engine.is_transcription_model()) {
throw std::runtime_error("transcribe_samples_with_speakers: second engine "
"is not an ASR transcription model");
}
using clock = std::chrono::steady_clock;
const auto t_total = clock::now();
AttributedTranscriptionResult out;
out.audio_samples = n_samples;
out.sample_rate = sample_rate;
out.diarization = sortformer_engine.diarize_samples(samples, n_samples, sample_rate, opts.diarization);
const double pad_s = opts.pad_segment_ms / 1000.0;
const double min_s = opts.min_segment_ms / 1000.0;
std::vector<AttributedSegment> raw;
raw.reserve(out.diarization.segments.size());
for (const auto & seg : out.diarization.segments) {
const double slice_start = std::max(0.0, seg.start_s - pad_s);
const double slice_end = std::min((double) n_samples / sample_rate, seg.end_s + pad_s);
if ((slice_end - slice_start) < min_s) continue;
const int start_sample = (int) std::floor(slice_start * sample_rate);
const int end_sample = std::min((int) std::ceil(slice_end * sample_rate), n_samples);
const int n_slice = end_sample - start_sample;
if (n_slice <= 0) continue;
EngineResult er = asr_engine.transcribe_samples(
samples + start_sample, n_slice, sample_rate);
++out.asr_calls;
AttributedSegment a;
a.speaker_id = seg.speaker_id;
a.text = std::move(er.text);
a.start_s = seg.start_s;
a.end_s = seg.end_s;
raw.push_back(std::move(a));
}
if (!opts.merge_same_speaker) {
out.segments = std::move(raw);
} else {
for (auto & s : raw) {
if (!out.segments.empty() &&
out.segments.back().speaker_id == s.speaker_id) {
if (!out.segments.back().text.empty() && !s.text.empty()) {
out.segments.back().text += ' ';
}
out.segments.back().text += s.text;
out.segments.back().end_s = s.end_s;
} else {
out.segments.push_back(std::move(s));
}
}
}
out.total_ms = ms_since(t_total);
return out;
}
struct StreamSession::Impl {
Engine::Impl * engine_impl = nullptr;
StreamingOptions opts;
StreamingCallback on_segment;
int chunk_samples = 0;
int left_context_samples = 0;
int right_lookahead_samples = 0;
std::vector<float> left_history;
std::vector<float> pending;
int chunk_index = 0;
int64_t emitted_samples = 0;
int32_t prev_token = -1;
TdtDecodeState tdt_state;
EouDecodeState eou_state;
std::string cumulative_text;
std::vector<int32_t> cumulative_token_ids;
bool finalized = false;
bool cancelled = false;
// Optional EnergyVad for CTC/TDT when enable_energy_vad and no native VAD exists.
std::unique_ptr<EnergyVad> energy_vad;
int64_t total_pcm_seen = 0;
// Reusable mel preprocess scratch. Carrying it on the session
// means every Mode 2 / Mode 3 chunk skips the 6-vector allocation
// in `compute_log_mel` after the first call -- the dominant
// per-chunk allocator pressure on streaming workloads.
MelState mel_state;
void process_window(const float * window_samples, int window_n,
int center_start_sample,
int center_end_sample,
bool is_final_chunk);
void try_emit_chunks();
void flush_remainder();
};
void StreamSession::Impl::process_window(const float * window_samples, int window_n,
int center_start_sample,
int center_end_sample,
bool is_final_chunk) {
if (cancelled) return;
if (window_n <= 0) return;
using clock = std::chrono::steady_clock;
const auto t_chunk = clock::now();
std::vector<float> mel;
int n_mel_frames = 0;
if (int rc = compute_log_mel(window_samples, window_n,
engine_impl->model.mel_cfg,
mel_state, mel, n_mel_frames); rc != 0) {
throw std::runtime_error("StreamSession: compute_log_mel failed (rc=" +
std::to_string(rc) + ")");
}
EncoderOutputs enc_out;
if (int rc = run_encoder(engine_impl->model, mel.data(), n_mel_frames,
engine_impl->model.mel_cfg.n_mels, enc_out,
/*max_layers=*/-1,
/*capture_intermediates=*/false); rc != 0) {
throw std::runtime_error("StreamSession: run_encoder failed (rc=" +
std::to_string(rc) + ")");
}
const double encoder_ms = ms_since(t_chunk);
const int T_enc = enc_out.n_enc_frames;
const int sr = opts.sample_rate;
const double frame_stride_ms = encoder_frame_stride_ms(engine_impl->model);
const int frame_samples = (int) std::round(sr * frame_stride_ms / 1000.0);
int left_drop_frames = center_start_sample / frame_samples;
int center_frame_count = (center_end_sample - center_start_sample) / frame_samples;
int right_drop_frames = T_enc - left_drop_frames - center_frame_count;
if (is_final_chunk) {
right_drop_frames = 0;
center_frame_count = T_enc - left_drop_frames;
}
if (left_drop_frames < 0) left_drop_frames = 0;
if (left_drop_frames > T_enc) left_drop_frames = T_enc;
if (right_drop_frames < 0) right_drop_frames = 0;
if (right_drop_frames > T_enc - left_drop_frames) {
right_drop_frames = T_enc - left_drop_frames;
}
const int center_end_frame = T_enc - right_drop_frames;
const auto t_dec = clock::now();
std::vector<int32_t> win_tokens;
int eou_boundaries_in_chunk = 0;
if (engine_impl->model.model_type == ParakeetModelType::TDT) {
TdtDecodeOptions dopts;
int steps = 0;
const int n_frames = std::max(0, center_end_frame - left_drop_frames);
const float * win_enc = enc_out.encoder_out.data()
+ static_cast<size_t>(left_drop_frames) * enc_out.d_model;
if (int rc = tdt_decode_window(engine_impl->model, engine_impl->tdt_rt,
win_enc, n_frames, enc_out.d_model,
dopts, tdt_state, win_tokens, steps);
rc != 0) {
throw std::runtime_error("StreamSession: tdt_decode_window failed (rc=" +
std::to_string(rc) + ")");
}
} else if (engine_impl->model.model_type == ParakeetModelType::EOU) {
EouDecodeOptions dopts;
dopts.max_symbols_per_step =
engine_impl->model.encoder_cfg.eou_max_symbols_per_step;
std::vector<EouSegmentBoundary> win_segments;
int steps = 0;
const int n_frames = std::max(0, center_end_frame - left_drop_frames);
const float * win_enc = enc_out.encoder_out.data()
+ static_cast<size_t>(left_drop_frames) * enc_out.d_model;
if (int rc = eou_decode_window(engine_impl->model, engine_impl->eou_rt,
win_enc, n_frames, enc_out.d_model,
dopts, eou_state,
win_tokens, win_segments, steps);
rc != 0) {
throw std::runtime_error("StreamSession: eou_decode_window failed (rc=" +
std::to_string(rc) + ")");
}
eou_boundaries_in_chunk = static_cast<int>(win_segments.size());
} else {
ctc_greedy_decode_window(enc_out.logits.data(),
left_drop_frames, center_end_frame,