-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathqwen_asr.c
More file actions
2181 lines (1945 loc) · 84.3 KB
/
qwen_asr.c
File metadata and controls
2181 lines (1945 loc) · 84.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
/*
* qwen_asr.c - Main API for Qwen3-ASR inference
*
* Pipeline: Load weights -> WAV -> Mel -> Encoder -> Build prompt ->
* Prefill decoder -> Autoregressive decode -> Tokenizer -> Text
*/
#include "qwen_asr.h"
#include "qwen_asr_kernels.h"
#include "qwen_asr_safetensors.h"
#include "qwen_asr_audio.h"
#include "qwen_asr_tokenizer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include <sys/time.h>
/* Global verbose flag */
int qwen_verbose = 0;
int qwen_monitor = 0;
void qwen_set_token_callback(qwen_ctx_t *ctx, qwen_token_cb cb, void *userdata) {
ctx->token_cb = cb;
ctx->token_cb_userdata = userdata;
}
static const char *QWEN_SUPPORTED_LANGUAGES[] = {
"Chinese", "English", "Cantonese", "Arabic", "German", "French",
"Spanish", "Portuguese", "Indonesian", "Italian", "Korean", "Russian",
"Thai", "Vietnamese", "Japanese", "Turkish", "Hindi", "Malay", "Dutch",
"Swedish", "Danish", "Finnish", "Polish", "Czech", "Filipino",
"Persian", "Greek", "Romanian", "Hungarian", "Macedonian"
};
static const char *QWEN_SUPPORTED_LANGUAGES_CSV =
"Chinese,English,Cantonese,Arabic,German,French,Spanish,Portuguese,"
"Indonesian,Italian,Korean,Russian,Thai,Vietnamese,Japanese,Turkish,"
"Hindi,Malay,Dutch,Swedish,Danish,Finnish,Polish,Czech,Filipino,"
"Persian,Greek,Romanian,Hungarian,Macedonian";
const char *qwen_supported_languages_csv(void) {
return QWEN_SUPPORTED_LANGUAGES_CSV;
}
static void reset_prompt_cache(qwen_ctx_t *ctx) {
free(ctx->prompt_tokens);
ctx->prompt_tokens = NULL;
ctx->n_prompt_tokens = 0;
free(ctx->force_prompt_tokens);
ctx->force_prompt_tokens = NULL;
ctx->n_force_prompt_tokens = 0;
ctx->prompt_tokens_ready = 0;
}
int qwen_set_prompt(qwen_ctx_t *ctx, const char *prompt) {
if (!ctx) return -1;
char *dup = NULL;
if (prompt && prompt[0] != '\0') {
dup = strdup(prompt);
if (!dup) return -1;
}
free(ctx->prompt);
ctx->prompt = dup;
reset_prompt_cache(ctx);
return 0;
}
static int normalize_language_name(const char *language, char *out, size_t out_cap) {
if (!language || !out || out_cap < 2) return -1;
while (*language && isspace((unsigned char)*language)) language++;
size_t len = strlen(language);
while (len > 0 && isspace((unsigned char)language[len - 1])) len--;
if (len == 0 || len + 1 > out_cap) return -1;
out[0] = (char)toupper((unsigned char)language[0]);
for (size_t i = 1; i < len; i++) {
out[i] = (char)tolower((unsigned char)language[i]);
}
out[len] = '\0';
return 0;
}
static int is_supported_language(const char *language) {
int n = (int)(sizeof(QWEN_SUPPORTED_LANGUAGES) / sizeof(QWEN_SUPPORTED_LANGUAGES[0]));
for (int i = 0; i < n; i++) {
if (strcmp(language, QWEN_SUPPORTED_LANGUAGES[i]) == 0) return 1;
}
return 0;
}
int qwen_set_force_language(qwen_ctx_t *ctx, const char *language) {
if (!ctx) return -1;
if (!language || language[0] == '\0') {
free(ctx->force_language);
ctx->force_language = NULL;
reset_prompt_cache(ctx);
return 0;
}
char normalized[64];
if (normalize_language_name(language, normalized, sizeof(normalized)) != 0) return -1;
if (!is_supported_language(normalized)) return -1;
char *dup = strdup(normalized);
if (!dup) return -1;
free(ctx->force_language);
ctx->force_language = dup;
reset_prompt_cache(ctx);
return 0;
}
/* ========================================================================
* Internal load functions (defined in encoder/decoder .c files)
* ======================================================================== */
extern int qwen_encoder_load(qwen_encoder_t *enc, multi_safetensors_t *ms,
const qwen_config_t *cfg);
extern int qwen_decoder_load(qwen_decoder_t *dec, multi_safetensors_t *ms,
const qwen_config_t *cfg);
/* ========================================================================
* Config Detection
* ======================================================================== */
/* Detect model variant from config.json or heuristics */
static int detect_config(qwen_ctx_t *ctx) {
qwen_config_t *cfg = &ctx->config;
/* Try to detect from number of shards:
* 1.7B has 2 shards, 0.6B has 1 shard
* But we can also check a specific weight shape. */
/* Check if thinker.audio_tower.layers.17 exists (0.6B has 18 layers, 1.7B has 24) */
multi_safetensors_t *ms = (multi_safetensors_t *)ctx->safetensors;
/* Check for layer 18 (0-indexed) in encoder - if it exists, it's 1.7B */
const safetensor_t *test = multi_safetensors_find(ms,
"thinker.audio_tower.layers.18.self_attn.q_proj.weight", NULL);
if (test) {
/* 1.7B model */
cfg->enc_d_model = 1024;
cfg->enc_layers = 24;
cfg->enc_heads = 16;
cfg->enc_head_dim = 64;
cfg->enc_ffn_dim = 4096;
cfg->enc_output_dim = 2048;
cfg->dec_hidden = 2048;
cfg->dec_layers = 28;
cfg->dec_heads = 16;
cfg->dec_kv_heads = 8;
cfg->dec_head_dim = 128;
cfg->dec_intermediate = 6144;
if (qwen_verbose >= 1) fprintf(stderr, "Detected: Qwen3-ASR-1.7B\n");
} else {
/* 0.6B model */
cfg->enc_d_model = 896;
cfg->enc_layers = 18;
cfg->enc_heads = 14;
cfg->enc_head_dim = 64;
cfg->enc_ffn_dim = 3584;
cfg->enc_output_dim = 1024;
cfg->dec_hidden = 1024;
cfg->dec_layers = 28;
cfg->dec_heads = 16;
cfg->dec_kv_heads = 8;
cfg->dec_head_dim = 128;
cfg->dec_intermediate = 3072;
if (qwen_verbose >= 1) fprintf(stderr, "Detected: Qwen3-ASR-0.6B\n");
}
/* Common parameters */
cfg->enc_n_window = 50;
cfg->enc_n_window_infer = 800;
cfg->enc_chunk_size = cfg->enc_n_window * 2; /* 100 */
cfg->enc_conv_proj_dim = QWEN_CONV_HIDDEN * 16; /* 7680 */
cfg->vocab_size = QWEN_VOCAB_SIZE;
cfg->dec_rms_norm_eps = 1e-6f;
cfg->dec_rope_theta = 1e6f;
return 0;
}
/* ========================================================================
* Model Loading
* ======================================================================== */
qwen_ctx_t *qwen_load(const char *model_dir) {
qwen_ctx_t *ctx = (qwen_ctx_t *)calloc(1, sizeof(qwen_ctx_t));
if (!ctx) return NULL;
snprintf(ctx->model_dir, sizeof(ctx->model_dir), "%s", model_dir);
/* Open safetensors (multi-shard) */
if (qwen_verbose >= 1)
fprintf(stderr, "Loading model from %s\n", model_dir);
multi_safetensors_t *ms = multi_safetensors_open(model_dir);
if (!ms) {
fprintf(stderr, "qwen_load: cannot open safetensors in %s\n", model_dir);
free(ctx);
return NULL;
}
ctx->safetensors = ms;
/* Detect model configuration */
detect_config(ctx);
/* Load encoder weights */
if (qwen_verbose >= 1) fprintf(stderr, "Loading encoder weights...\n");
if (qwen_encoder_load(&ctx->encoder, ms, &ctx->config) != 0) {
fprintf(stderr, "qwen_load: failed to load encoder\n");
qwen_free(ctx);
return NULL;
}
/* Load decoder weights */
if (qwen_verbose >= 1) fprintf(stderr, "Loading decoder weights...\n");
if (qwen_decoder_load(&ctx->decoder, ms, &ctx->config) != 0) {
fprintf(stderr, "qwen_load: failed to load decoder\n");
qwen_free(ctx);
return NULL;
}
/* Default transcription mode: full-audio offline decode (no splitting). */
ctx->segment_sec = 0.0f;
ctx->search_sec = 3.0f;
/* Default streaming parameters */
ctx->stream_chunk_sec = 2.0f;
ctx->stream_rollback = 5;
ctx->stream_unfixed_chunks = 2;
ctx->stream_max_new_tokens = 32;
ctx->past_text_conditioning = 0;
ctx->skip_silence = 0;
if (qwen_verbose >= 1) fprintf(stderr, "Model loaded.\n");
return ctx;
}
/* ========================================================================
* Free
* ======================================================================== */
void qwen_free(qwen_ctx_t *ctx) {
if (!ctx) return;
#define FREE0(p) do { free(p); (p) = NULL; } while (0)
/* Encoder conv stem */
FREE0(ctx->encoder.conv1_weight); FREE0(ctx->encoder.conv1_bias);
FREE0(ctx->encoder.conv2_weight); FREE0(ctx->encoder.conv2_bias);
FREE0(ctx->encoder.conv3_weight); FREE0(ctx->encoder.conv3_bias);
FREE0(ctx->encoder.conv_out_weight);
/* Encoder layers (weights are pre-converted f32, all allocated) */
for (int i = 0; i < ctx->config.enc_layers; i++) {
qwen_enc_layer_t *l = &ctx->encoder.layers[i];
FREE0(l->wq_weight); FREE0(l->wq_bias);
FREE0(l->wk_weight); FREE0(l->wk_bias);
FREE0(l->wv_weight); FREE0(l->wv_bias);
FREE0(l->wo_weight); FREE0(l->wo_bias);
FREE0(l->attn_norm_weight); FREE0(l->attn_norm_bias);
FREE0(l->fc1_weight); FREE0(l->fc1_bias);
FREE0(l->fc2_weight); FREE0(l->fc2_bias);
FREE0(l->ffn_norm_weight); FREE0(l->ffn_norm_bias);
}
FREE0(ctx->encoder.ln_post_weight); FREE0(ctx->encoder.ln_post_bias);
FREE0(ctx->encoder.proj1_weight); FREE0(ctx->encoder.proj1_bias);
FREE0(ctx->encoder.proj2_weight); FREE0(ctx->encoder.proj2_bias);
/* Decoder layers */
for (int i = 0; i < ctx->config.dec_layers; i++) {
qwen_dec_layer_t *l = &ctx->decoder.layers[i];
FREE0(l->q_norm_weight); FREE0(l->k_norm_weight);
FREE0(l->input_norm); FREE0(l->post_attn_norm);
FREE0(l->gate_up_fused_bf16);
}
FREE0(ctx->decoder.norm);
#undef FREE0
/* KV cache */
free(ctx->kv_cache_k);
free(ctx->kv_cache_v);
/* Persistent decoder buffers */
free(ctx->dec_x); free(ctx->dec_x_norm);
free(ctx->dec_q); free(ctx->dec_k); free(ctx->dec_v);
free(ctx->dec_attn_out); free(ctx->dec_proj_out);
free(ctx->dec_gate); free(ctx->dec_up); free(ctx->dec_ffn_out);
free(ctx->dec_rope_cos); free(ctx->dec_rope_sin);
/* Persistent decoder prefill buffers */
free(ctx->pref_x); free(ctx->pref_x_norm);
free(ctx->pref_q); free(ctx->pref_k); free(ctx->pref_v);
free(ctx->pref_attn_out); free(ctx->pref_proj_out); free(ctx->pref_ffn_out);
free(ctx->pref_gate); free(ctx->pref_gate_up);
/* Decoder RoPE caches */
free(ctx->rope_cache_cos); free(ctx->rope_cache_sin);
free(ctx->rope_inv_freq);
/* Prompt/language options */
free(ctx->prompt);
free(ctx->force_language);
free(ctx->prompt_tokens);
free(ctx->force_prompt_tokens);
/* Close safetensors */
if (ctx->safetensors) {
multi_safetensors_close((multi_safetensors_t *)ctx->safetensors);
}
free(ctx);
}
/* ========================================================================
* Transcription
* ======================================================================== */
/*
* Prompt format:
* PREFIX_HEAD: [<|im_start|>, "system", "\n"]
* [optional system prompt text tokens]
* PREFIX_TAIL: [<|im_end|>, "\n", <|im_start|>, "user", "\n", <|audio_start|>]
* AUDIO: [151676] × N_audio_tokens
* SUFFIX_BASE: [<|audio_end|>, <|im_end|>, "\n", <|im_start|>, "assistant", "\n"]
* [optional language tokens: "language X" + <asr_text>]
*/
static const int PROMPT_PREFIX_HEAD[] = {
151644, 8948, 198
};
static const int PROMPT_PREFIX_TAIL[] = {
151645, 198, 151644, 872, 198, 151669
};
static const int PROMPT_SUFFIX_BASE[] = {
151670, 151645, 198, 151644, 77091, 198
};
#define PREFIX_HEAD_LEN 3
#define PREFIX_TAIL_LEN 6
#define SUFFIX_BASE_LEN 6
/* Convert a single token embedding from bf16 to f32 */
static void tok_embed_bf16_to_f32(float *dst, const uint16_t *tok_emb_bf16,
int token_id, int dim) {
const uint16_t *src = tok_emb_bf16 + (size_t)token_id * dim;
for (int i = 0; i < dim; i++) {
uint32_t f32_bits = ((uint32_t)src[i]) << 16;
memcpy(&dst[i], &f32_bits, sizeof(float));
}
}
static double get_time_ms(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0;
}
static int cmp_float_asc(const void *a, const void *b) {
float fa = *(const float *)a;
float fb = *(const float *)b;
if (fa < fb) return -1;
if (fa > fb) return 1;
return 0;
}
/* Drop long silent spans while preserving short pauses for readability.
* Uses adaptive RMS gating with spike rejection for noisy backgrounds. */
static float *compact_silence(const float *samples, int n_samples, int *out_samples) {
if (!samples || n_samples <= 0 || !out_samples) return NULL;
const int win = 160; /* 10 ms at 16kHz */
const float base_thresh = 0.002f; /* ~ -54 dBFS */
const float max_thresh = 0.025f; /* avoid over-aggressive clipping */
const float smooth_alpha = 0.2f; /* smooth frame-level RMS */
const int min_voice_windows = 5; /* reject <50ms spikes as noise */
const int pad_voice_windows = 3; /* keep 30ms around speech edges */
const int pass_windows = 60; /* keep first 600ms of silence */
int n_win = (n_samples + win - 1) / win;
float *rms_vals = (float *)malloc((size_t)n_win * sizeof(float));
float *sorted = (float *)malloc((size_t)n_win * sizeof(float));
float *smooth_vals = (float *)malloc((size_t)n_win * sizeof(float));
unsigned char *is_voice = (unsigned char *)malloc((size_t)n_win);
if (!rms_vals || !sorted || !smooth_vals || !is_voice) {
free(rms_vals);
free(sorted);
free(smooth_vals);
free(is_voice);
return NULL;
}
for (int w = 0; w < n_win; w++) {
int start = w * win;
int end = start + win;
if (end > n_samples) end = n_samples;
int len = end - start;
float energy = 0.0f;
for (int i = 0; i < len; i++) {
float v = samples[start + i];
energy += v * v;
}
rms_vals[w] = sqrtf(energy / (float)(len > 0 ? len : 1));
}
/* Smooth RMS so tiny impulsive noise does not flip decisions. */
float smooth = rms_vals[0];
for (int w = 0; w < n_win; w++) {
smooth = (1.0f - smooth_alpha) * smooth + smooth_alpha * rms_vals[w];
smooth_vals[w] = smooth;
}
memcpy(sorted, smooth_vals, (size_t)n_win * sizeof(float));
qsort(sorted, (size_t)n_win, sizeof(float), cmp_float_asc);
/* Adaptive threshold from low-energy percentile (robust to loud clips). */
int p25 = (int)((n_win - 1) * 0.25f);
float noise_floor = sorted[p25];
float thresh = noise_floor * 1.8f;
if (thresh < base_thresh) thresh = base_thresh;
if (thresh > max_thresh) thresh = max_thresh;
free(sorted);
for (int w = 0; w < n_win; w++) {
is_voice[w] = (smooth_vals[w] > thresh) ? 1 : 0;
}
free(smooth_vals);
/* Remove very short voice bursts (usually clicks/hiss spikes). */
for (int i = 0; i < n_win; ) {
if (!is_voice[i]) { i++; continue; }
int j = i + 1;
while (j < n_win && is_voice[j]) j++;
if (j - i < min_voice_windows) {
memset(is_voice + i, 0, (size_t)(j - i));
}
i = j;
}
/* Add a small speech edge pad to avoid clipping word boundaries. */
unsigned char *padded = (unsigned char *)calloc((size_t)n_win, 1);
if (!padded) {
free(is_voice);
free(rms_vals);
return NULL;
}
for (int w = 0; w < n_win; w++) {
if (!is_voice[w]) continue;
int a = w - pad_voice_windows;
int b = w + pad_voice_windows;
if (a < 0) a = 0;
if (b >= n_win) b = n_win - 1;
for (int k = a; k <= b; k++) padded[k] = 1;
}
free(is_voice);
float *out = (float *)malloc((size_t)n_samples * sizeof(float));
if (!out) {
free(rms_vals);
free(padded);
return NULL;
}
int out_n = 0;
int silence_count = 0;
for (int w = 0; w < n_win; w++) {
int start = w * win;
int end = start + win;
if (end > n_samples) end = n_samples;
int len = end - start;
if (padded[w]) {
memcpy(out + out_n, samples + start, (size_t)len * sizeof(float));
out_n += len;
silence_count = 0;
} else {
silence_count++;
if (silence_count <= pass_windows) {
memcpy(out + out_n, samples + start, (size_t)len * sizeof(float));
out_n += len;
}
}
}
free(padded);
free(rms_vals);
if (out_n == 0) {
int keep = n_samples;
int min_keep = QWEN_SAMPLE_RATE / 2;
if (keep > min_keep) keep = min_keep;
memcpy(out, samples, (size_t)keep * sizeof(float));
out_n = keep;
}
*out_samples = out_n;
return out;
}
/* Prepare cached prompt-related tokens once per context. */
static int prepare_prompt_tokens(qwen_ctx_t *ctx, qwen_tokenizer_t *tokenizer) {
if (ctx->prompt_tokens_ready) return 0;
reset_prompt_cache(ctx);
if (ctx->prompt && ctx->prompt[0] != '\0') {
ctx->prompt_tokens = qwen_tokenizer_encode(tokenizer, ctx->prompt, &ctx->n_prompt_tokens);
if (!ctx->prompt_tokens) {
fprintf(stderr, "qwen: failed to encode --prompt text\n");
return -1;
}
}
if (ctx->force_language && ctx->force_language[0] != '\0') {
char force_text[128];
snprintf(force_text, sizeof(force_text), "language %s", ctx->force_language);
int n_lang_txt = 0;
int *lang_txt_tokens = qwen_tokenizer_encode(tokenizer, force_text, &n_lang_txt);
if (!lang_txt_tokens) {
fprintf(stderr, "qwen: failed to encode --language text\n");
return -1;
}
ctx->n_force_prompt_tokens = n_lang_txt + 1; /* + <asr_text> marker */
ctx->force_prompt_tokens = (int *)malloc((size_t)ctx->n_force_prompt_tokens * sizeof(int));
if (!ctx->force_prompt_tokens) {
free(lang_txt_tokens);
return -1;
}
if (n_lang_txt > 0) {
memcpy(ctx->force_prompt_tokens, lang_txt_tokens, (size_t)n_lang_txt * sizeof(int));
}
ctx->force_prompt_tokens[n_lang_txt] = QWEN_TOKEN_ASR_TEXT;
free(lang_txt_tokens);
}
ctx->prompt_tokens_ready = 1;
return 0;
}
/* ---- Segment-based transcription ---- */
#define ENERGY_WINDOW_MS 100
/*
* Find the best split point near target_sample by looking for the
* lowest-energy 100ms window within +/-search_sec seconds.
*/
static int find_split_point(const float *samples, int n_samples,
int target_sample, float search_sec) {
int search_half = (int)(search_sec * QWEN_SAMPLE_RATE);
int lo = target_sample - search_half;
int hi = target_sample + search_half;
if (lo < 0) lo = 0;
if (hi > n_samples) hi = n_samples;
int win_samples = (ENERGY_WINDOW_MS * QWEN_SAMPLE_RATE) / 1000; /* 1600 */
float best_energy = 1e30f;
int best_center = target_sample;
for (int pos = lo; pos + win_samples <= hi; pos += win_samples / 2) {
float energy = 0;
int end = pos + win_samples;
if (end > n_samples) end = n_samples;
for (int j = pos; j < end; j++) {
energy += samples[j] * samples[j];
}
energy /= (end - pos);
if (energy < best_energy) {
best_energy = energy;
best_center = pos + (end - pos) / 2;
}
}
return best_center;
}
/*
* Transcribe a single audio segment. Returns malloc'd text or NULL.
* The tokenizer is passed in so we only load it once.
*/
static char *transcribe_segment(qwen_ctx_t *ctx, const float *samples,
int n_samples, qwen_tokenizer_t *tokenizer,
const int *past_tokens, int n_past_tokens,
int *out_text_tokens) {
const qwen_config_t *cfg = &ctx->config;
int dim = cfg->dec_hidden;
double seg_t0 = get_time_ms();
int n_text_tokens = 0;
/* ---- Mel spectrogram ---- */
double t0 = get_time_ms();
int mel_frames = 0;
float *mel = qwen_mel_spectrogram(samples, n_samples, &mel_frames);
if (!mel) return NULL;
double mel_ms = get_time_ms() - t0;
if (qwen_verbose >= 2)
fprintf(stderr, " Mel: %d frames (%.0f ms)\n", mel_frames, mel_ms);
/* ---- Encoder ---- */
t0 = get_time_ms();
int enc_seq_len = 0;
float *enc_output = qwen_encoder_forward(ctx, mel, mel_frames, &enc_seq_len);
free(mel);
if (!enc_output) return NULL;
double enc_ms = get_time_ms() - t0;
if (qwen_verbose >= 2)
fprintf(stderr, " Encoder: %d tokens (%.0f ms)\n", enc_seq_len, enc_ms);
if (prepare_prompt_tokens(ctx, tokenizer) != 0) {
free(enc_output);
return NULL;
}
/* ---- Build input embeddings ---- */
int prefix_len = PREFIX_HEAD_LEN + ctx->n_prompt_tokens + PREFIX_TAIL_LEN;
int suffix_len = SUFFIX_BASE_LEN + ctx->n_force_prompt_tokens;
int n_past_prompt_tokens = (n_past_tokens > 0) ? (n_past_tokens + 1) : 0; /* + <asr_text> */
int total_seq = prefix_len + enc_seq_len + suffix_len + n_past_prompt_tokens;
float *input_embeds = (float *)malloc((size_t)total_seq * dim * sizeof(float));
float *tmp_embed = (float *)malloc(dim * sizeof(float));
if (!input_embeds || !tmp_embed) {
free(enc_output);
free(input_embeds);
free(tmp_embed);
return NULL;
}
/* Embed prefix head: <|im_start|>system\n */
int off = 0;
for (int i = 0; i < PREFIX_HEAD_LEN; i++) {
tok_embed_bf16_to_f32(input_embeds + off * dim,
ctx->decoder.tok_embeddings_bf16,
PROMPT_PREFIX_HEAD[i], dim);
off++;
}
/* Embed optional prompt text (system content) */
for (int i = 0; i < ctx->n_prompt_tokens; i++) {
tok_embed_bf16_to_f32(input_embeds + off * dim,
ctx->decoder.tok_embeddings_bf16,
ctx->prompt_tokens[i], dim);
off++;
}
/* Embed prefix tail: <|im_end|>\n<|im_start|>user\n<|audio_start|> */
for (int i = 0; i < PREFIX_TAIL_LEN; i++) {
tok_embed_bf16_to_f32(input_embeds + off * dim,
ctx->decoder.tok_embeddings_bf16,
PROMPT_PREFIX_TAIL[i], dim);
off++;
}
/* Replace audio_pad positions with encoder output */
for (int i = 0; i < enc_seq_len; i++) {
memcpy(input_embeds + (prefix_len + i) * dim,
enc_output + i * dim,
dim * sizeof(float));
}
free(enc_output);
/* Embed suffix base: <|audio_end|><|im_end|>\n<|im_start|>assistant\n */
int suffix_off = prefix_len + enc_seq_len;
for (int i = 0; i < SUFFIX_BASE_LEN; i++) {
tok_embed_bf16_to_f32(input_embeds + (suffix_off + i) * dim,
ctx->decoder.tok_embeddings_bf16,
PROMPT_SUFFIX_BASE[i], dim);
}
/* Optional forced-language suffix: "language X" + <asr_text> */
for (int i = 0; i < ctx->n_force_prompt_tokens; i++) {
tok_embed_bf16_to_f32(input_embeds + (suffix_off + SUFFIX_BASE_LEN + i) * dim,
ctx->decoder.tok_embeddings_bf16,
ctx->force_prompt_tokens[i], dim);
}
/* Optional past-text conditioning tokens (for segmented mode).
* Put a fresh <asr_text> marker AFTER the past text so generation
* restarts from a new ASR span instead of terminating immediately. */
int past_off = suffix_off + suffix_len;
for (int i = 0; i < n_past_tokens; i++) {
tok_embed_bf16_to_f32(input_embeds + (past_off + i) * dim,
ctx->decoder.tok_embeddings_bf16,
past_tokens[i], dim);
}
if (n_past_tokens > 0) {
tok_embed_bf16_to_f32(input_embeds + (past_off + n_past_tokens) * dim,
ctx->decoder.tok_embeddings_bf16,
QWEN_TOKEN_ASR_TEXT, dim);
}
/* ---- Decoder prefill ---- */
t0 = get_time_ms();
ctx->kv_cache_len = 0; /* Reset KV cache for this segment */
int prefill_len = total_seq - 1; /* prefill all but last */
qwen_decoder_prefill(ctx, input_embeds, prefill_len);
/* First token from last prefill position */
float *last_embed = input_embeds + (size_t)prefill_len * dim;
int token = qwen_decoder_forward(ctx, last_embed);
free(input_embeds);
double prefill_ms = get_time_ms() - t0;
if (qwen_verbose >= 2)
fprintf(stderr, " Prefill: %d tokens (%.0f ms)\n", total_seq, prefill_ms);
/* ---- Autoregressive decode ---- */
t0 = get_time_ms();
int max_tokens = 2048;
int n_generated = 0;
/* If language is forced, <asr_text> is already part of prompt suffix. */
int past_asr_text = (ctx->n_force_prompt_tokens > 0 || n_past_tokens > 0) ? 1 : 0;
size_t text_cap = 4096;
size_t text_len = 0;
char *text = (char *)malloc(text_cap);
text[0] = '\0';
while (n_generated < max_tokens) {
n_generated++;
/* Check EOS */
if (token == QWEN_TOKEN_ENDOFTEXT || token == QWEN_TOKEN_IM_END) break;
/* Track <asr_text> marker */
if (token == QWEN_TOKEN_ASR_TEXT) {
past_asr_text = 1;
} else if (past_asr_text) {
/* Decode and emit this text token */
const char *piece = qwen_tokenizer_decode(tokenizer, token);
size_t piece_len = strlen(piece);
if (text_len + piece_len + 1 > text_cap) {
while (text_len + piece_len + 1 > text_cap) text_cap *= 2;
text = (char *)realloc(text, text_cap);
}
memcpy(text + text_len, piece, piece_len);
text_len += piece_len;
text[text_len] = '\0';
n_text_tokens++;
/* Stream token via callback */
if (ctx->token_cb)
ctx->token_cb(piece, ctx->token_cb_userdata);
}
/* Embed and generate next token */
tok_embed_bf16_to_f32(tmp_embed, ctx->decoder.tok_embeddings_bf16, token, dim);
token = qwen_decoder_forward(ctx, tmp_embed);
}
double decode_ms = get_time_ms() - t0;
if (qwen_verbose >= 2)
fprintf(stderr, " Decode: %d tokens (%.0f ms, %.1f ms/token)\n",
n_generated, decode_ms,
n_generated > 0 ? decode_ms / n_generated : 0);
free(tmp_embed);
/* Trim whitespace */
size_t rlen = strlen(text);
while (rlen > 0 && isspace((unsigned char)text[rlen - 1])) text[--rlen] = '\0';
char *start = text;
while (*start && isspace((unsigned char)*start)) start++;
if (start != text) memmove(text, start, strlen(start) + 1);
ctx->perf_total_ms += get_time_ms() - seg_t0;
ctx->perf_text_tokens += n_text_tokens;
ctx->perf_encode_ms += mel_ms + enc_ms;
ctx->perf_decode_ms += prefill_ms + decode_ms;
if (out_text_tokens) *out_text_tokens = n_text_tokens;
return text;
}
static int should_retry_unconditioned_segment(const char *full_result,
const char *seg_text,
int core_samples,
int n_text_tokens) {
if (!seg_text || seg_text[0] == '\0') return 1;
/* A segment producing very few tokens under conditioning is usually
* a collapse (model repeats/terminates early instead of following audio).
* Use stricter checks from ~8s upward to catch common -S 10 failures. */
float core_sec = (float)core_samples / (float)QWEN_SAMPLE_RATE;
if (core_sec >= 8.0f) {
int min_tokens = (int)(core_sec * 1.75f);
if (min_tokens < 12) min_tokens = 12;
if (n_text_tokens < min_tokens) return 1;
}
/* Exact duplicate span already present in accumulated text: likely drift. */
if (full_result && full_result[0] != '\0') {
size_t seg_len = strlen(seg_text);
if (seg_len >= 48 && strstr(full_result, seg_text) != NULL) return 1;
}
return 0;
}
static int should_insert_boundary_space(int prev_ch, int next_ch) {
if (prev_ch <= 0 || next_ch <= 0) return 0;
if (isspace((unsigned char)prev_ch)) return 0;
if (isspace((unsigned char)next_ch)) return 0;
if (ispunct((unsigned char)next_ch)) return 0;
return 1;
}
typedef struct {
qwen_token_cb downstream_cb;
void *downstream_userdata;
int maybe_prepend_space;
int saw_first_piece;
} segment_emit_state_t;
static void segment_emit_cb(const char *piece, void *userdata) {
segment_emit_state_t *st = (segment_emit_state_t *)userdata;
if (!st || !st->downstream_cb || !piece) return;
if (!st->saw_first_piece) {
st->saw_first_piece = 1;
if (st->maybe_prepend_space) {
unsigned char c0 = (unsigned char)piece[0];
if (c0 != '\0' && !isspace(c0) && !ispunct(c0)) {
st->downstream_cb(" ", st->downstream_userdata);
}
}
}
st->downstream_cb(piece, st->downstream_userdata);
}
char *qwen_transcribe_audio(qwen_ctx_t *ctx, const float *samples, int n_samples) {
ctx->perf_total_ms = 0;
ctx->perf_text_tokens = 0;
ctx->perf_audio_ms = 1000.0 * (double)n_samples / (double)QWEN_SAMPLE_RATE;
ctx->perf_encode_ms = 0;
ctx->perf_decode_ms = 0;
const float *audio_samples = samples;
int audio_n_samples = n_samples;
float *compacted_samples = NULL;
if (ctx->skip_silence) {
compacted_samples = compact_silence(samples, n_samples, &audio_n_samples);
if (compacted_samples) audio_samples = compacted_samples;
if (qwen_verbose >= 1) {
float used_pct = 100.0f * (float)audio_n_samples /
(float)(n_samples > 0 ? n_samples : 1);
float skipped_pct = 100.0f - used_pct;
if (skipped_pct < 0.0f) skipped_pct = 0.0f;
fprintf(stderr, "Silence skip: used %.1f%%, skipped %.1f%% (%d -> %d samples)\n",
used_pct, skipped_pct, n_samples, audio_n_samples);
}
}
if (qwen_verbose >= 2)
fprintf(stderr, "Audio: %d samples (%.1f seconds)\n",
audio_n_samples, (float)audio_n_samples / QWEN_SAMPLE_RATE);
/* Load tokenizer once for all segments */
char vocab_path[1024];
snprintf(vocab_path, sizeof(vocab_path), "%s/vocab.json", ctx->model_dir);
qwen_tokenizer_t *tokenizer = qwen_tokenizer_load(vocab_path);
if (!tokenizer) {
free(compacted_samples);
return NULL;
}
if (prepare_prompt_tokens(ctx, tokenizer) != 0) {
qwen_tokenizer_free(tokenizer);
free(compacted_samples);
return NULL;
}
/* Determine segment boundaries.
* Clamp search window to half the segment size so split points
* can never overlap and produce zero-length segments. */
float search = ctx->search_sec;
if (search > ctx->segment_sec / 2.0f) search = ctx->segment_sec / 2.0f;
int target_samples = (int)(ctx->segment_sec * QWEN_SAMPLE_RATE);
int margin_samples = (int)(search * QWEN_SAMPLE_RATE);
/* No splitting if segment_sec is 0 or audio fits in one segment */
if (ctx->segment_sec <= 0 || audio_n_samples <= target_samples + margin_samples) {
char *text = transcribe_segment(ctx, audio_samples, audio_n_samples, tokenizer, NULL, 0, NULL);
qwen_tokenizer_free(tokenizer);
free(compacted_samples);
return text;
}
/* Build split points */
int splits[128]; /* max 128 segments */
int n_splits = 0;
splits[n_splits++] = 0;
int pos = 0;
while (pos + target_samples + margin_samples < audio_n_samples) {
int split = find_split_point(audio_samples, audio_n_samples,
pos + target_samples, search);
splits[n_splits++] = split;
pos = split;
if (n_splits >= 127) break; /* safety */
}
splits[n_splits] = audio_n_samples; /* end sentinel */
if (qwen_verbose >= 2)
fprintf(stderr, "Splitting into %d segments\n", n_splits);
/* Transcribe each segment and concatenate */
size_t result_cap = 4096;
size_t result_len = 0;
char *result = (char *)malloc(result_cap);
result[0] = '\0';
int min_samples = QWEN_SAMPLE_RATE / 2; /* 0.5s minimum, like official */
int do_boundary_cleanup = (ctx->past_text_conditioning != 0);
int use_past_conditioning = ctx->past_text_conditioning;
int conditioning_collapses = 0;
qwen_token_cb saved_cb = ctx->token_cb;
void *saved_cb_userdata = ctx->token_cb_userdata;
for (int s = 0; s < n_splits; s++) {
int core_start = splits[s];
int core_end = splits[s + 1];
int seg_start = core_start;
int seg_end = core_end;
int seg_samples = seg_end - seg_start;
if (qwen_verbose >= 2)
fprintf(stderr, "Segment %d/%d: core %.1f-%.1fs, decode %.1f-%.1fs (%d samples)\n",
s + 1, n_splits,
(float)core_start / QWEN_SAMPLE_RATE,
(float)core_end / QWEN_SAMPLE_RATE,
(float)seg_start / QWEN_SAMPLE_RATE,
(float)seg_end / QWEN_SAMPLE_RATE,
seg_samples);
/* Pad short segments to 0.5s with zeros (like official pipeline) */
float *seg_buf = NULL;
const float *seg_ptr = audio_samples + seg_start;
if (seg_samples < min_samples) {
seg_buf = (float *)calloc(min_samples, sizeof(float));
memcpy(seg_buf, seg_ptr, seg_samples * sizeof(float));
seg_ptr = seg_buf;
seg_samples = min_samples;
}
int *past_tokens = NULL;
int n_past_tokens = 0;
if (use_past_conditioning && result_len > 0) {
past_tokens = qwen_tokenizer_encode(tokenizer, result, &n_past_tokens);
if (!past_tokens) n_past_tokens = 0;
}
segment_emit_state_t emit_state = {0};
if (do_boundary_cleanup) {
/* Cleanup mode buffers segment output and emits finalized text only. */
ctx->token_cb = NULL;
ctx->token_cb_userdata = NULL;
} else if (saved_cb) {
/* Fast segmented mode: emit each generated token immediately.
* Add one separating space before the first token of the segment
* only when needed and only if the first piece does not already
* begin with whitespace/punctuation. */
emit_state.downstream_cb = saved_cb;
emit_state.downstream_userdata = saved_cb_userdata;
emit_state.maybe_prepend_space =
(result_len > 0 && !isspace((unsigned char)result[result_len - 1]));
emit_state.saw_first_piece = 0;
ctx->token_cb = segment_emit_cb;
ctx->token_cb_userdata = &emit_state;
}
int seg_text_tokens = 0;
char *seg_text = transcribe_segment(ctx, seg_ptr, seg_samples, tokenizer,
past_tokens, n_past_tokens,
&seg_text_tokens);
if (do_boundary_cleanup &&
use_past_conditioning && n_past_tokens > 0 &&
should_retry_unconditioned_segment(result, seg_text,
core_end - core_start,
seg_text_tokens)) {
conditioning_collapses++;
if (qwen_verbose >= 2) {
fprintf(stderr,
"Segment mode: retrying segment %d/%d without past-text conditioning "
"(core=%.1fs, tokens=%d)\n",
s + 1, n_splits,
(float)(core_end - core_start) / QWEN_SAMPLE_RATE,
seg_text_tokens);
}
/* Guardrail: if conditioned decode collapses or drifts,
* retry this segment without past-text conditioning. */
free(seg_text);