Debian Codegraph @

external/whispercpp/whisper.cpp

raw
1 #include "whisper.h"
2 #include "whisper-arch.h"
3
4 #include "ggml.h"
5 #include "ggml-cpp.h"
6 #include "ggml-alloc.h"
7 #include "ggml-backend.h"
8
9 #ifdef WHISPER_USE_COREML
10 #include "coreml/whisper-encoder.h"
11 #endif
12
13 #ifdef WHISPER_USE_OPENVINO
14 #include "openvino/whisper-openvino-encoder.h"
15 #endif
16
17 #include <atomic>
18 #include <algorithm>
19 #include <cassert>
20 #include <cfloat>
21 #define _USE_MATH_DEFINES
22 #include <cmath>
23 #include <climits>
24 #include <cstdarg>
25 #include <cstdio>
26 #include <cstring>
27 #include <fstream>
28 #include <functional>
29 #include <map>
30 #include <random>
31 #include <regex>
32 #include <set>
33 #include <string>
34 #include <thread>
35 #include <vector>
36
37 #ifdef _MSC_VER
38 #include <codecvt>
39 #endif
40
41 #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
42 template<typename T>
43 static T byteswap(T value) {
44 T value_swapped;
45 char * source = reinterpret_cast<char *>(&value);
46 char * target = reinterpret_cast<char *>(&value_swapped);
47 int size = sizeof(T);
48 for (int i = 0; i < size; i++) {
49 target[size - 1 - i] = source[i];
50 }
51 return value_swapped;
52 }
53
54 template<typename T>
55 static void byteswap_tensor_data(ggml_tensor * tensor) {
56 T * datum = reinterpret_cast<T *>(tensor->data);
57 for (int i = 0; i < ggml_nelements(tensor); i++) {
58 datum[i] = byteswap(datum[i]);
59 }
60 }
61
62 static void byteswap_tensor(ggml_tensor * tensor) {
63 switch (tensor->type) {
64 case GGML_TYPE_I16: {
65 byteswap_tensor_data<int16_t>(tensor);
66 break;
67 }
68 case GGML_TYPE_F16: {
69 byteswap_tensor_data<ggml_fp16_t>(tensor);
70 break;
71 }
72 case GGML_TYPE_I32: {
73 byteswap_tensor_data<int32_t>(tensor);
74 break;
75 }
76 case GGML_TYPE_F32: {
77 byteswap_tensor_data<float>(tensor);
78 break;
79 }
80 default: { // GML_TYPE_I8
81 break;
82 }
83 }
84 }
85
86 #define BYTESWAP_VALUE(d) d = byteswap(d)
87 #define BYTESWAP_FILTERS(f) \
88 do { \
89 for (auto & datum : f.data) { \
90 datum = byteswap(datum); \
91 } \
92 } while (0)
93 #define BYTESWAP_TENSOR(t) \
94 do { \
95 byteswap_tensor(t); \
96 } while (0)
97 #else
98 #define BYTESWAP_VALUE(d) do {} while (0)
99 #define BYTESWAP_FILTERS(f) do {} while (0)
100 #define BYTESWAP_TENSOR(t) do {} while (0)
101 #endif
102
103 #ifdef __GNUC__
104 #ifdef __MINGW32__
105 #define WHISPER_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
106 #else
107 #define WHISPER_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
108 #endif
109 #else
110 #define WHISPER_ATTRIBUTE_FORMAT(...)
111 #endif
112
113 //
114 // logging
115 //
116
117 WHISPER_ATTRIBUTE_FORMAT(2, 3)
118 static void whisper_log_internal (ggml_log_level level, const char * format, ...);
119 static void whisper_log_callback_default(ggml_log_level level, const char * text, void * user_data);
120
121 #define WHISPER_LOG_ERROR(...) whisper_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
122 #define WHISPER_LOG_WARN(...) whisper_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
123 #define WHISPER_LOG_INFO(...) whisper_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
124
125 // define this to enable verbose trace logging - useful for debugging purposes
126 //#define WHISPER_DEBUG
127
128 #if defined(WHISPER_DEBUG)
129 #define WHISPER_LOG_DEBUG(...) whisper_log_internal(GGML_LOG_LEVEL_DEBUG, __VA_ARGS__)
130 #else
131 #define WHISPER_LOG_DEBUG(...)
132 #endif
133
134 #define WHISPER_ASSERT(x) \
135 do { \
136 if (!(x)) { \
137 WHISPER_LOG_ERROR("WHISPER_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
138 abort(); \
139 } \
140 } while (0)
141
142 #define WHISPER_MAX_DECODERS 8
143
144 // temperature below which we condition on past text history
145 static constexpr float WHISPER_HISTORY_CONDITIONING_TEMP_CUTOFF = 0.5f;
146
147 #define WHISPER_MAX_NODES 4096
148
149 static std::string format(const char * fmt, ...) {
150 va_list ap;
151 va_list ap2;
152 va_start(ap, fmt);
153 va_copy(ap2, ap);
154 int size = vsnprintf(NULL, 0, fmt, ap);
155 GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
156 std::vector<char> buf(size + 1);
157 int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
158 GGML_ASSERT(size2 == size);
159 va_end(ap2);
160 va_end(ap);
161 return std::string(buf.data(), size);
162 }
163
164 //
165 // ggml helpers
166 //
167
168 static bool ggml_graph_compute_helper(
169 struct ggml_cgraph * graph,
170 int n_threads,
171 ggml_abort_callback abort_callback,
172 void * abort_callback_data) {
173 ggml_backend_ptr backend { ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr) };
174
175 auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
176
177 auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
178 if (set_abort_callback_fn) {
179 set_abort_callback_fn(backend.get(), abort_callback, abort_callback_data);
180 }
181
182 auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
183 if (ggml_backend_set_n_threads_fn) {
184 ggml_backend_set_n_threads_fn(backend.get(), n_threads);
185 }
186
187 return ggml_backend_graph_compute(backend.get(), graph) == GGML_STATUS_SUCCESS;
188 }
189
190 static bool ggml_graph_compute_helper(
191 ggml_backend_sched_t sched,
192 struct ggml_cgraph * graph,
193 int n_threads,
194 bool sched_reset = true) {
195 for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) {
196 ggml_backend_t backend = ggml_backend_sched_get_backend(sched, i);
197 ggml_backend_dev_t dev = ggml_backend_get_device(backend);
198 ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
199
200 auto * fn_set_n_threads = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
201 if (fn_set_n_threads) {
202 fn_set_n_threads(backend, n_threads);
203 }
204 }
205
206 const bool t = (ggml_backend_sched_graph_compute(sched, graph) == GGML_STATUS_SUCCESS);
207
208 if (!t || sched_reset) {
209 ggml_backend_sched_reset(sched);
210 }
211
212 return t;
213 }
214
215 // TODO: move these functions to ggml-base with support for ggml-backend?
216
217 static ggml_tensor * whisper_set_f32(struct ggml_tensor * t, float v) {
218 GGML_ASSERT(t->type == GGML_TYPE_F32);
219 GGML_ASSERT(ggml_is_contiguous(t));
220 size_t nels = ggml_nelements(t);
221 for (size_t i = 0; i < nels; ++i) {
222 ((float *) t->data)[i] = v;
223 }
224 return t;
225 }
226
227 static ggml_tensor * whisper_set_i32(struct ggml_tensor * t, int32_t v) {
228 GGML_ASSERT(t->type == GGML_TYPE_I32);
229 GGML_ASSERT(ggml_is_contiguous(t));
230 size_t nels = ggml_nelements(t);
231 for (size_t i = 0; i < nels; ++i) {
232 ((int32_t *) t->data)[i] = v;
233 }
234 return t;
235 }
236
237 static float whisper_get_f32_nd(const struct ggml_tensor * t, int64_t i0, int64_t i1, int64_t i2, int64_t i3) {
238 GGML_ASSERT(t->type == GGML_TYPE_F32);
239 void * data = (char *) t->data + i0*t->nb[0] + i1*t->nb[1] + i2*t->nb[2] + i3*t->nb[3];
240 return *(float *) data;
241 }
242
243 static void whisper_set_f32_nd(struct ggml_tensor * t, int64_t i0, int64_t i1, int64_t i2, int64_t i3, float v) {
244 GGML_ASSERT(t->type == GGML_TYPE_F32);
245 void * data = (char *) t->data + i0*t->nb[0] + i1*t->nb[1] + i2*t->nb[2] + i3*t->nb[3];
246 *(float *) data = v;
247 }
248
249 static int32_t whisper_get_i32_nd(const struct ggml_tensor * t, int64_t i0, int64_t i1, int64_t i2, int64_t i3) {
250 GGML_ASSERT(t->type == GGML_TYPE_I32);
251 void * data = (char *) t->data + i0*t->nb[0] + i1*t->nb[1] + i2*t->nb[2] + i3*t->nb[3];
252 return *(int32_t *) data;
253 }
254
255 static void whisper_set_i32_nd(struct ggml_tensor * t, int64_t i0, int64_t i1, int64_t i2, int64_t i3, int32_t v) {
256 GGML_ASSERT(t->type == GGML_TYPE_I32);
257 void * data = (char *) t->data + i0*t->nb[0] + i1*t->nb[1] + i2*t->nb[2] + i3*t->nb[3];
258 *(int32_t *) data = v;
259 }
260
261 // available whisper models
262 enum e_model {
263 MODEL_UNKNOWN,
264 MODEL_TINY,
265 MODEL_BASE,
266 MODEL_SMALL,
267 MODEL_MEDIUM,
268 MODEL_LARGE,
269 };
270
271 static const std::map<e_model, std::string> g_model_name = {
272 { MODEL_UNKNOWN, "unknown" },
273 { MODEL_TINY, "tiny" },
274 { MODEL_BASE, "base" },
275 { MODEL_SMALL, "small" },
276 { MODEL_MEDIUM, "medium" },
277 { MODEL_LARGE, "large" },
278 };
279
280 static const std::map<std::string, std::pair<int, std::string>> g_lang = {
281 { "en", { 0, "english", } },
282 { "zh", { 1, "chinese", } },
283 { "de", { 2, "german", } },
284 { "es", { 3, "spanish", } },
285 { "ru", { 4, "russian", } },
286 { "ko", { 5, "korean", } },
287 { "fr", { 6, "french", } },
288 { "ja", { 7, "japanese", } },
289 { "pt", { 8, "portuguese", } },
290 { "tr", { 9, "turkish", } },
291 { "pl", { 10, "polish", } },
292 { "ca", { 11, "catalan", } },
293 { "nl", { 12, "dutch", } },
294 { "ar", { 13, "arabic", } },
295 { "sv", { 14, "swedish", } },
296 { "it", { 15, "italian", } },
297 { "id", { 16, "indonesian", } },
298 { "hi", { 17, "hindi", } },
299 { "fi", { 18, "finnish", } },
300 { "vi", { 19, "vietnamese", } },
301 { "he", { 20, "hebrew", } },
302 { "uk", { 21, "ukrainian", } },
303 { "el", { 22, "greek", } },
304 { "ms", { 23, "malay", } },
305 { "cs", { 24, "czech", } },
306 { "ro", { 25, "romanian", } },
307 { "da", { 26, "danish", } },
308 { "hu", { 27, "hungarian", } },
309 { "ta", { 28, "tamil", } },
310 { "no", { 29, "norwegian", } },
311 { "th", { 30, "thai", } },
312 { "ur", { 31, "urdu", } },
313 { "hr", { 32, "croatian", } },
314 { "bg", { 33, "bulgarian", } },
315 { "lt", { 34, "lithuanian", } },
316 { "la", { 35, "latin", } },
317 { "mi", { 36, "maori", } },
318 { "ml", { 37, "malayalam", } },
319 { "cy", { 38, "welsh", } },
320 { "sk", { 39, "slovak", } },
321 { "te", { 40, "telugu", } },
322 { "fa", { 41, "persian", } },
323 { "lv", { 42, "latvian", } },
324 { "bn", { 43, "bengali", } },
325 { "sr", { 44, "serbian", } },
326 { "az", { 45, "azerbaijani", } },
327 { "sl", { 46, "slovenian", } },
328 { "kn", { 47, "kannada", } },
329 { "et", { 48, "estonian", } },
330 { "mk", { 49, "macedonian", } },
331 { "br", { 50, "breton", } },
332 { "eu", { 51, "basque", } },
333 { "is", { 52, "icelandic", } },
334 { "hy", { 53, "armenian", } },
335 { "ne", { 54, "nepali", } },
336 { "mn", { 55, "mongolian", } },
337 { "bs", { 56, "bosnian", } },
338 { "kk", { 57, "kazakh", } },
339 { "sq", { 58, "albanian", } },
340 { "sw", { 59, "swahili", } },
341 { "gl", { 60, "galician", } },
342 { "mr", { 61, "marathi", } },
343 { "pa", { 62, "punjabi", } },
344 { "si", { 63, "sinhala", } },
345 { "km", { 64, "khmer", } },
346 { "sn", { 65, "shona", } },
347 { "yo", { 66, "yoruba", } },
348 { "so", { 67, "somali", } },
349 { "af", { 68, "afrikaans", } },
350 { "oc", { 69, "occitan", } },
351 { "ka", { 70, "georgian", } },
352 { "be", { 71, "belarusian", } },
353 { "tg", { 72, "tajik", } },
354 { "sd", { 73, "sindhi", } },
355 { "gu", { 74, "gujarati", } },
356 { "am", { 75, "amharic", } },
357 { "yi", { 76, "yiddish", } },
358 { "lo", { 77, "lao", } },
359 { "uz", { 78, "uzbek", } },
360 { "fo", { 79, "faroese", } },
361 { "ht", { 80, "haitian creole", } },
362 { "ps", { 81, "pashto", } },
363 { "tk", { 82, "turkmen", } },
364 { "nn", { 83, "nynorsk", } },
365 { "mt", { 84, "maltese", } },
366 { "sa", { 85, "sanskrit", } },
367 { "lb", { 86, "luxembourgish", } },
368 { "my", { 87, "myanmar", } },
369 { "bo", { 88, "tibetan", } },
370 { "tl", { 89, "tagalog", } },
371 { "mg", { 90, "malagasy", } },
372 { "as", { 91, "assamese", } },
373 { "tt", { 92, "tatar", } },
374 { "haw", { 93, "hawaiian", } },
375 { "ln", { 94, "lingala", } },
376 { "ha", { 95, "hausa", } },
377 { "ba", { 96, "bashkir", } },
378 { "jw", { 97, "javanese", } },
379 { "su", { 98, "sundanese", } },
380 { "yue", { 99, "cantonese", } },
381 };
382
383 // [EXPERIMENTAL] Token-level timestamps with DTW
384 static const whisper_ahead g_aheads_tiny_en[] = { {1, 0}, {2, 0}, {2, 5}, {3, 0}, {3, 1}, {3, 2}, {3, 3}, {3, 4} };
385 static const whisper_ahead g_aheads_tiny[] = { {2, 2}, {3, 0}, {3, 2}, {3, 3}, {3, 4}, {3, 5} };
386 static const whisper_ahead g_aheads_base_en[] = { {3, 3}, {4, 7}, {5, 1}, {5, 5}, {5, 7} };
387 static const whisper_ahead g_aheads_base[] = { {3, 1}, {4, 2}, {4, 3}, {4, 7}, {5, 1}, {5, 2}, {5, 4}, {5, 6} };
388 static const whisper_ahead g_aheads_small_en[] = { {6, 6}, {7, 0}, {7, 3}, {7, 8}, {8, 2}, {8, 5}, {8, 7}, {9, 0}, {9, 4}, {9, 8}, {9, 10}, {10, 0}, {10, 1}, {10, 2}, {10, 3}, {10, 6}, {10, 11}, {11, 2}, {11, 4} };
389 static const whisper_ahead g_aheads_small[] = { {5, 3}, {5, 9}, {8, 0}, {8, 4}, {8, 7}, {8, 8}, {9, 0}, {9, 7}, {9, 9}, {10, 5} };
390 static const whisper_ahead g_aheads_medium_en[] = { {11, 4}, {14, 1}, {14, 12}, {14, 14}, {15, 4}, {16, 0}, {16, 4}, {16, 9}, {17, 12}, {17, 14}, {18, 7}, {18, 10}, {18, 15}, {20, 0}, {20, 3}, {20, 9}, {20, 14}, {21, 12} };
391 static const whisper_ahead g_aheads_medium[] = { {13, 15}, {15, 4}, {15, 15}, {16, 1}, {20, 0}, {23, 4} };
392 static const whisper_ahead g_aheads_large_v1[] = { {9, 19}, {11, 2}, {11, 4}, {11, 17}, {22, 7}, {22, 11}, {22, 17}, {23, 2}, {23, 15} };
393 static const whisper_ahead g_aheads_large_v2[] = { {10, 12}, {13, 17}, {16, 11}, {16, 12}, {16, 13}, {17, 15}, {17, 16}, {18, 4}, {18, 11}, {18, 19}, {19, 11}, {21, 2}, {21, 3}, {22, 3}, {22, 9}, {22, 12}, {23, 5}, {23, 7}, {23, 13}, {25, 5}, {26, 1}, {26, 12}, {27, 15} };
394 static const whisper_ahead g_aheads_large_v3[] = { {7, 0}, {10, 17}, {12, 18}, {13, 12}, {16, 1}, {17, 14}, {19, 11}, {21, 4}, {24, 1}, {25, 6} };
395 static const whisper_ahead g_aheads_large_v3_turbo[] = { {2, 4}, {2, 11}, {3, 3}, {3, 6}, {3, 11}, {3, 14} };
396
397 static const std::map<whisper_alignment_heads_preset, whisper_aheads> g_aheads {
398 { WHISPER_AHEADS_TINY_EN, { 8, g_aheads_tiny_en } },
399 { WHISPER_AHEADS_TINY, { 6, g_aheads_tiny } },
400 { WHISPER_AHEADS_BASE_EN, { 5, g_aheads_base_en } },
401 { WHISPER_AHEADS_BASE, { 8, g_aheads_base } },
402 { WHISPER_AHEADS_SMALL_EN, { 19, g_aheads_small_en } },
403 { WHISPER_AHEADS_SMALL, { 10, g_aheads_small } },
404 { WHISPER_AHEADS_MEDIUM_EN, { 18, g_aheads_medium_en } },
405 { WHISPER_AHEADS_MEDIUM, { 6, g_aheads_medium } },
406 { WHISPER_AHEADS_LARGE_V1, { 9, g_aheads_large_v1 } },
407 { WHISPER_AHEADS_LARGE_V2, { 23, g_aheads_large_v2 } },
408 { WHISPER_AHEADS_LARGE_V3, { 10, g_aheads_large_v3 } },
409 { WHISPER_AHEADS_LARGE_V3_TURBO, { 6, g_aheads_large_v3_turbo } },
410 };
411
412 static std::vector<uint32_t> get_alignment_heads_by_layer(const whisper_context_params & cparams, int il, int32_t n_text_layer, int32_t n_head);
413
414 struct whisper_mel {
415 int n_len;
416 int n_len_org;
417 int n_mel;
418
419 std::vector<float> data;
420 };
421
422 struct whisper_filters {
423 int32_t n_mel;
424 int32_t n_fft;
425
426 std::vector<float> data;
427 };
428
429 struct whisper_vocab {
430 using id = int32_t;
431 using token = std::string;
432
433 int n_vocab = 51864;
434
435 std::map<token, id> token_to_id;
436 std::map<id, token> id_to_token;
437
438 // reference: https://github.com/openai/whisper/blob/248b6cb124225dd263bb9bd32d060b6517e067f8/whisper/tokenizer.py#L334-L349
439 id token_eot = 50256;
440 id token_sot = 50257;
441 // task tokens (used only for multilingual models)
442 id token_translate = 50357;
443 id token_transcribe = 50358;
444 // other special tokens
445 id token_solm = 50359; // [TDRZ] used by tinydiarize models to indicate speaker turn
446 id token_prev = 50360;
447 id token_nosp = 50361;
448 id token_not = 50362; // no timestamps
449 id token_beg = 50363; // begin timestamps
450
451 bool is_multilingual() const {
452 return n_vocab >= 51865;
453 }
454
455 int num_languages() const {
456 return n_vocab - 51765 - (is_multilingual() ? 1 : 0);
457 }
458 };
459
460 struct whisper_segment {
461 int64_t t0;
462 int64_t t1;
463
464 std::string text;
465 float no_speech_prob;
466
467 std::vector<whisper_token_data> tokens;
468
469 bool speaker_turn_next;
470 };
471
472 struct whisper_batch {
473 int32_t n_tokens;
474
475 whisper_token * token;
476 whisper_pos * pos;
477 int32_t * n_seq_id; // always 1, here for consistency with llama.cpp
478 whisper_seq_id ** seq_id; // null terminated
479 int8_t * logits;
480 };
481
482 static struct whisper_batch whisper_batch_init(int32_t n_tokens, int32_t n_seq_max) {
483 whisper_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, };
484
485 batch.token = (whisper_token * ) ggml_malloc(sizeof(whisper_token) * (n_tokens));
486 batch.pos = (whisper_pos *) ggml_malloc(sizeof(whisper_pos) * (n_tokens));
487 batch.n_seq_id = (int32_t *) ggml_malloc(sizeof(int32_t) * (n_tokens));
488 batch.seq_id = (whisper_seq_id **) ggml_malloc(sizeof(whisper_seq_id *) * (n_tokens + 1));
489 for (int i = 0; i < n_tokens; ++i) {
490 batch.seq_id[i] = (whisper_seq_id *) ggml_malloc(sizeof(whisper_seq_id) * n_seq_max);
491 }
492 batch.seq_id[n_tokens] = nullptr;
493 batch.logits = (int8_t *) ggml_malloc(sizeof(int8_t) * n_tokens);
494
495 return batch;
496 }
497
498 static void whisper_batch_free(struct whisper_batch batch) {
499 if (batch.token) ggml_raw_free(batch.token);
500 if (batch.pos) ggml_raw_free(batch.pos);
501 if (batch.n_seq_id) ggml_raw_free(batch.n_seq_id);
502 if (batch.seq_id) {
503 for (int i = 0; batch.seq_id[i]; ++i) {
504 ggml_raw_free(batch.seq_id[i]);
505 }
506 ggml_raw_free(batch.seq_id);
507 }
508 if (batch.logits) ggml_raw_free(batch.logits);
509 }
510
511 static void whisper_batch_prep_legacy(whisper_batch & batch, const whisper_token * tokens, int n_tokens, int n_past, int seq_id) {
512 batch.n_tokens = n_tokens;
513 for (int i = 0; i < n_tokens; ++i) {
514 if (tokens) {
515 batch.token[i] = tokens[i];
516 }
517 batch.pos [i] = n_past + i;
518 batch.n_seq_id[i] = 1;
519 batch.seq_id [i][0] = seq_id;
520 batch.logits [i] = 0;
521 }
522 batch.logits[n_tokens - 1] = 1;
523 }
524
525 // replace std::pair by using customized pair struct (reason: std::pair is very slow)
526 template<typename A, typename B>
527 struct whisper_pair {
528 A first;
529 B second;
530
531 // Define a constructor that takes two arguments.
532 whisper_pair(const A& a, const B& b) : first(a), second(b) {}
533 // Define a constructor that takes no argument.
534 whisper_pair() : first(A()), second(B()) {}
535 };
536
537 // ggml_backend_sched wrapper for whisper usage
538 struct whisper_sched {
539 ggml_backend_sched_t sched = nullptr;
540
541 std::vector<uint8_t> meta;
542 };
543
544 static size_t whisper_sched_size(struct whisper_sched & allocr) {
545 size_t size = allocr.meta.size();
546 for (int i = 0; i < ggml_backend_sched_get_n_backends(allocr.sched); ++i) {
547 ggml_backend_t backend = ggml_backend_sched_get_backend(allocr.sched, i);
548 size += ggml_backend_sched_get_buffer_size(allocr.sched, backend);
549 }
550 return size;
551 }
552
553 // measure the memory usage of a graph and prepare the allocr's internal data buffer
554 static bool whisper_sched_graph_init(struct whisper_sched & allocr, std::vector<ggml_backend_t> backends, std::function<struct ggml_cgraph *()> && get_graph) {
555 auto & sched = allocr.sched;
556 auto & meta = allocr.meta;
557
558 sched = ggml_backend_sched_new(backends.data(), nullptr, backends.size(), WHISPER_MAX_NODES, false, true);
559
560 meta.resize(ggml_tensor_overhead()*WHISPER_MAX_NODES + ggml_graph_overhead());
561
562 // since there are dependencies between the different graphs,
563 // we need to allocate them instead of only reserving to get the correct compute buffer size
564 if (!ggml_backend_sched_alloc_graph(sched, get_graph())) {
565 // failed to allocate the compute buffer
566 WHISPER_LOG_ERROR("%s: failed to allocate the compute buffer\n", __func__);
567 return false;
568 }
569
570 ggml_backend_sched_reset(sched);
571
572 return true;
573 }
574
575 // medium
576 // hparams: {
577 // 'n_mels': 80,
578 // 'n_vocab': 51864,
579 // 'n_audio_ctx': 1500,
580 // 'n_audio_state': 1024,
581 // 'n_audio_head': 16,
582 // 'n_audio_layer': 24,
583 // 'n_text_ctx': 448,
584 // 'n_text_state': 1024,
585 // 'n_text_head': 16,
586 // 'n_text_layer': 24
587 // }
588 //
589 // default hparams (Whisper tiny)
590 struct whisper_hparams {
591 int32_t n_vocab = 51864;
592 int32_t n_audio_ctx = 1500;
593 int32_t n_audio_state = 384;
594 int32_t n_audio_head = 6;
595 int32_t n_audio_layer = 4;
596 int32_t n_text_ctx = 448;
597 int32_t n_text_state = 384;
598 int32_t n_text_head = 6;
599 int32_t n_text_layer = 4;
600 int32_t n_mels = 80;
601 int32_t ftype = 1;
602 float eps = 1e-5f;
603 };
604
605 // audio encoding layer
606 struct whisper_layer_encoder {
607 // encoder.blocks.*.attn_ln
608 struct ggml_tensor * attn_ln_0_w;
609 struct ggml_tensor * attn_ln_0_b;
610
611 // encoder.blocks.*.attn.out
612 struct ggml_tensor * attn_ln_1_w;
613 struct ggml_tensor * attn_ln_1_b;
614
615 // encoder.blocks.*.attn.query
616 struct ggml_tensor * attn_q_w;
617 struct ggml_tensor * attn_q_b;
618
619 // encoder.blocks.*.attn.key
620 struct ggml_tensor * attn_k_w;
621
622 // encoder.blocks.*.attn.value
623 struct ggml_tensor * attn_v_w;
624 struct ggml_tensor * attn_v_b;
625
626 // encoder.blocks.*.mlp_ln
627 struct ggml_tensor * mlp_ln_w;
628 struct ggml_tensor * mlp_ln_b;
629
630 // encoder.blocks.*.mlp.0
631 struct ggml_tensor * mlp_0_w;
632 struct ggml_tensor * mlp_0_b;
633
634 // encoder.blocks.*.mlp.2
635 struct ggml_tensor * mlp_1_w;
636 struct ggml_tensor * mlp_1_b;
637 };
638
639 // token decoding layer
640 struct whisper_layer_decoder {
641 // decoder.blocks.*.attn_ln
642 struct ggml_tensor * attn_ln_0_w;
643 struct ggml_tensor * attn_ln_0_b;
644
645 // decoder.blocks.*.attn.out
646 struct ggml_tensor * attn_ln_1_w;
647 struct ggml_tensor * attn_ln_1_b;
648
649 // decoder.blocks.*.attn.query
650 struct ggml_tensor * attn_q_w;
651 struct ggml_tensor * attn_q_b;
652
653 // decoder.blocks.*.attn.key
654 struct ggml_tensor * attn_k_w;
655
656 // decoder.blocks.*.attn.value
657 struct ggml_tensor * attn_v_w;
658 struct ggml_tensor * attn_v_b;
659
660 // decoder.blocks.*.cross_attn_ln
661 struct ggml_tensor * cross_attn_ln_0_w;
662 struct ggml_tensor * cross_attn_ln_0_b;
663
664 // decoder.blocks.*.cross_attn.out
665 struct ggml_tensor * cross_attn_ln_1_w;
666 struct ggml_tensor * cross_attn_ln_1_b;
667
668 // decoder.blocks.*.cross_attn.query
669 struct ggml_tensor * cross_attn_q_w;
670 struct ggml_tensor * cross_attn_q_b;
671
672 // decoder.blocks.*.cross_attn.key
673 struct ggml_tensor * cross_attn_k_w;
674
675 // decoder.blocks.*.cross_attn.value
676 struct ggml_tensor * cross_attn_v_w;
677 struct ggml_tensor * cross_attn_v_b;
678
679 // decoder.blocks.*.mlp_ln
680 struct ggml_tensor * mlp_ln_w;
681 struct ggml_tensor * mlp_ln_b;
682
683 // decoder.blocks.*.mlp.0
684 struct ggml_tensor * mlp_0_w;
685 struct ggml_tensor * mlp_0_b;
686
687 // decoder.blocks.*.mlp.2
688 struct ggml_tensor * mlp_1_w;
689 struct ggml_tensor * mlp_1_b;
690 };
691
692 struct whisper_kv_cell {
693 whisper_pos pos = -1;
694
695 std::set<whisper_seq_id> seq_id;
696
697 bool has_seq_id(const whisper_seq_id & id) const {
698 return seq_id.find(id) != seq_id.end();
699 }
700 };
701
702 struct whisper_kv_cache {
703 uint32_t head = 0;
704 uint32_t size = 0;
705
706 // computed before each graph build
707 uint32_t n = 0;
708
709 std::vector<whisper_kv_cell> cells;
710
711 struct ggml_tensor * k;
712 struct ggml_tensor * v;
713
714 ggml_backend_buffer_t buffer = nullptr;
715
716 std::vector<uint8_t> ctx_buf;
717 };
718
719 struct whisper_model {
720 e_model type = MODEL_UNKNOWN;
721
722 whisper_hparams hparams;
723 whisper_filters filters;
724
725 // encoder.positional_embedding
726 struct ggml_tensor * e_pe;
727
728 // encoder.conv1
729 struct ggml_tensor * e_conv_1_w;
730 struct ggml_tensor * e_conv_1_b;
731
732 // encoder.conv2
733 struct ggml_tensor * e_conv_2_w;
734 struct ggml_tensor * e_conv_2_b;
735
736 // encoder.ln_post
737 struct ggml_tensor * e_ln_w;
738 struct ggml_tensor * e_ln_b;
739
740 // decoder.positional_embedding
741 struct ggml_tensor * d_pe;
742
743 // decoder.token_embedding
744 struct ggml_tensor * d_te;
745
746 // decoder.ln
747 struct ggml_tensor * d_ln_w;
748 struct ggml_tensor * d_ln_b;
749
750 std::vector<whisper_layer_encoder> layers_encoder;
751 std::vector<whisper_layer_decoder> layers_decoder;
752
753 // ggml context that contains all the meta information about the model tensors
754 std::vector<ggml_context *> ctxs;
755
756 // the model backend data is read-only and can be shared between processors
757 std::vector<ggml_backend_buffer_t> buffers;
758
759 // tensors
760 int n_loaded;
761 std::map<std::string, struct ggml_tensor *> tensors;
762 };
763
764 struct whisper_partial_utf8 {
765 uint32_t value; // bit value so far (unshifted)
766 int n_remain; // num bytes remaining; -1 indicates invalid sequence
767 };
768
769 struct whisper_grammar {
770 /*const*/ std::vector<std::vector<whisper_grammar_element>> rules;
771 std::vector<std::vector<const whisper_grammar_element *>> stacks;
772
773 // buffer for partially generated UTF-8 sequence from accepted tokens
774 whisper_partial_utf8 partial_utf8;
775 };
776
777 struct whisper_grammar_candidate {
778 whisper_token id;
779 const uint32_t * code_points;
780 whisper_partial_utf8 partial_utf8;
781 };
782
783 struct whisper_sequence {
784 std::vector<whisper_token_data> tokens;
785
786 // the accumulated transcription in the current iteration (used to truncate the tokens array)
787 int result_len;
788
789 double sum_logprobs_all; // the sum of the log probabilities of the tokens
790 double sum_logprobs; // the sum of the log probabilities of the tokens (first result_len tokens)
791 double avg_logprobs; // the average log probability of the tokens
792 double entropy; // the entropy of the tokens
793 double score; // likelihood rank score
794 };
795
796 // TAGS: WHISPER_DECODER_INIT
797 struct whisper_decoder {
798 // the currently generated sequence of tokens
799 whisper_sequence sequence;
800
801 // grammar parse state of generated sequence of tokens
802 whisper_grammar grammar;
803
804 int i_batch; // the index of the token in the current batch
805 int seek_delta; // the window shift found so far based on the decoded timestamp tokens
806
807 bool failed; // has the current segment failed to decode?
808 bool completed; // has the decoder completed the current segment?
809 bool has_ts; // have we already sampled a non-beg timestamp token for the current segment?
810
811 // new token probs, logits and logprobs after the last whisper_decode (1-dimensional array: [n_vocab])
812 std::vector<float> probs;
813 std::vector<float> logits;
814 std::vector<float> logprobs;
815
816 // work container used to avoid memory allocations
817 std::vector<whisper_pair<double, whisper_vocab::id>> logits_id;
818
819 mutable std::mt19937 rng; // used for sampling at t > 0.0
820 };
821
822 // [EXPERIMENTAL] Token-level timestamps with DTW
823 struct whisper_aheads_masks {
824 std::vector<struct ggml_tensor *> m; // One mask per text layer.
825 struct ggml_context * ctx = nullptr;
826 ggml_backend_buffer_t buffer = nullptr;
827 };
828
829 struct vad_time_mapping {
830 int64_t processed_time; // Time in processed (VAD) audio
831 int64_t original_time; // Corresponding time in original audio
832 };
833
834 struct whisper_state {
835 int64_t t_sample_us = 0;
836 int64_t t_encode_us = 0;
837 int64_t t_decode_us = 0;
838 int64_t t_batchd_us = 0;
839 int64_t t_prompt_us = 0;
840 int64_t t_mel_us = 0;
841
842 int32_t n_sample = 0; // number of tokens sampled
843 int32_t n_encode = 0; // number of encoder calls
844 int32_t n_decode = 0; // number of decoder calls with n_tokens == 1 (text-generation)
845 int32_t n_batchd = 0; // number of decoder calls with n_tokens < 16 (batch decoding)
846 int32_t n_prompt = 0; // number of decoder calls with n_tokens > 1 (prompt encoding)
847 int32_t n_fail_p = 0; // number of logprob threshold failures
848 int32_t n_fail_h = 0; // number of entropy threshold failures
849
850 // number of decoders for which we have constructed the KV cache
851 int32_t kv_self_n_dec = 0;
852
853 // unified self-attention KV cache for all decoders
854 whisper_kv_cache kv_self;
855
856 // cross-attention KV cache for the decoders
857 // shared between all decoders
858 whisper_kv_cache kv_cross;
859
860 // padded buffer for flash-attention
861 whisper_kv_cache kv_pad;
862
863 whisper_mel mel;
864
865 whisper_batch batch;
866
867 whisper_decoder decoders[WHISPER_MAX_DECODERS];
868
869 std::vector<ggml_backend_t> backends;
870
871 // - stores meta info about the intermediate tensors into the `meta` buffers
872 whisper_sched sched_conv;
873 whisper_sched sched_encode;
874 whisper_sched sched_cross;
875 whisper_sched sched_decode;
876
877 // result of the encoder
878 struct ggml_tensor * embd_conv = nullptr;
879 struct ggml_tensor * embd_enc = nullptr;
880
881 // helpers for GPU offloading
882 std::vector<float> inp_mel;
883 std::vector<float> inp_mask;
884
885 // decode output (2-dimensional array: [n_tokens][n_vocab])
886 std::vector<float> logits;
887
888 std::vector<whisper_segment> result_all;
889
890 // prompt history split into static prefix (prompt_past0) and dynamic rolling context (prompt_past1)
891 std::vector<whisper_token> prompt_past0; // static carried initial prompt (if enabled)
892 std::vector<whisper_token> prompt_past1; // dynamic context from decoded output
893
894 int lang_id = 0; // english by default
895
896 std::string path_model; // populated by whisper_init_from_file_with_params()
897
898 #ifdef WHISPER_USE_COREML
899 whisper_coreml_context * ctx_coreml = nullptr;
900 #endif
901
902 #ifdef WHISPER_USE_OPENVINO
903 whisper_openvino_context * ctx_openvino = nullptr;
904 #endif
905
906 // [EXPERIMENTAL] token-level timestamps data
907 int64_t t_beg = 0;
908 int64_t t_last = 0;
909
910 whisper_token tid_last;
911
912 std::vector<float> energy; // PCM signal energy
913 float no_speech_prob = 0.0f;
914
915 // [EXPERIMENTAL] Token-level timestamps with DTW
916 whisper_aheads_masks aheads_masks;
917 ggml_tensor * aheads_cross_QKs = nullptr;
918 std::vector<float> aheads_cross_QKs_data;
919
920 // [EXPERIMENTAL] speed-up techniques
921 int32_t exp_n_audio_ctx = 0; // 0 - use default
922
923 whisper_vad_context * vad_context = nullptr;
924
925 struct vad_segment_info {
926 int64_t orig_start;
927 int64_t orig_end;
928 int64_t vad_start;
929 int64_t vad_end;
930 };
931 std::vector<vad_segment_info> vad_segments;
932 bool has_vad_segments = false;
933
934 std::vector<vad_time_mapping> vad_mapping_table;
935 };
936
937 struct whisper_context {
938 int64_t t_load_us = 0;
939 int64_t t_start_us = 0;
940
941 ggml_type wtype = ggml_type::GGML_TYPE_F16; // weight type (FP32 / FP16 / QX)
942 ggml_type itype = ggml_type::GGML_TYPE_F16; // intermediate type (FP32 or FP16)
943
944 whisper_context_params params;
945
946 whisper_model model;
947 whisper_vocab vocab;
948
949 whisper_state * state = nullptr;
950
951 std::string path_model; // populated by whisper_init_from_file_with_params()
952 };
953
954 struct whisper_global {
955 // We save the log callback globally
956 ggml_log_callback log_callback = whisper_log_callback_default;
957 void * log_callback_user_data = nullptr;
958 };
959
960 static whisper_global g_state;
961
962 template<typename T>
963 static void read_safe(whisper_model_loader * loader, T & dest) {
964 loader->read(loader->context, &dest, sizeof(T));
965 BYTESWAP_VALUE(dest);
966 }
967
968 static bool whisper_kv_cache_init(
969 struct whisper_kv_cache & cache,
970 ggml_backend_t backend,
971 ggml_type wtype,
972 int64_t n_text_state,
973 int64_t n_text_layer,
974 int n_ctx) {
975 const int64_t n_mem = n_text_layer*n_ctx;
976 const int64_t n_elements = n_text_state*n_mem;
977
978 cache.ctx_buf.resize(2*ggml_tensor_overhead());
979
980 struct ggml_init_params params = {
981 /*.mem_size =*/ cache.ctx_buf.size(),
982 /*.mem_buffer =*/ cache.ctx_buf.data(),
983 /*.no_alloc =*/ true,
984 };
985
986 cache.head = 0;
987 cache.size = n_ctx;
988
989 cache.cells.clear();
990 cache.cells.resize(n_ctx);
991
992 struct ggml_context * ctx = ggml_init(params);
993
994 if (!ctx) {
995 WHISPER_LOG_ERROR("%s: failed to allocate memory for the kv cache context\n", __func__);
996 return false;
997 }
998
999 cache.k = ggml_new_tensor_1d(ctx, wtype, n_elements);
1000 cache.v = ggml_new_tensor_1d(ctx, wtype, n_elements);
1001
1002 cache.buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
1003 if (!cache.buffer) {
1004 WHISPER_LOG_ERROR("%s: failed to allocate memory for the kv cache\n", __func__);
1005 return false;
1006 }
1007
1008 ggml_backend_buffer_clear(cache.buffer, 0);
1009
1010 ggml_free(ctx);
1011
1012 return true;
1013 }
1014
1015 static void whisper_kv_cache_free(struct whisper_kv_cache & cache) {
1016 ggml_backend_buffer_free(cache.buffer);
1017 }
1018
1019 static bool whisper_kv_cache_find_slot(
1020 struct whisper_kv_cache & cache,
1021 const struct whisper_batch & batch) {
1022 const uint32_t n_ctx = cache.size;
1023 const uint32_t n_tokens = batch.n_tokens;
1024
1025 if (n_tokens > n_ctx) {
1026 WHISPER_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
1027 return false;
1028 }
1029
1030 uint32_t n_tested = 0;
1031
1032 while (true) {
1033 if (cache.head + n_tokens > n_ctx) {
1034 n_tested += n_ctx - cache.head;
1035 cache.head = 0;
1036 continue;
1037 }
1038
1039 bool found = true;
1040 for (uint32_t i = 0; i < n_tokens; i++) {
1041 if (cache.cells[cache.head + i].pos >= 0) {
1042 found = false;
1043 cache.head += i + 1;
1044 n_tested += i + 1;
1045 break;
1046 }
1047 }
1048
1049 if (found) {
1050 break;
1051 }
1052
1053 if (n_tested >= n_ctx) {
1054 //WHISPER_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
1055 return false;
1056 }
1057 }
1058
1059 for (uint32_t i = 0; i < n_tokens; i++) {
1060 cache.cells[cache.head + i].pos = batch.pos[i];
1061
1062 for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
1063 cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
1064 }
1065 }
1066
1067 return true;
1068 }
1069
1070 // find how many cells are currently in use
1071 static int32_t whisper_kv_cache_cell_max(const struct whisper_kv_cache & cache) {
1072 for (uint32_t i = cache.size - 1; i > 0; --i) {
1073 if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
1074 return i + 1;
1075 }
1076 }
1077
1078 return 1;
1079 }
1080
1081 static void whisper_kv_cache_clear(struct whisper_kv_cache & cache) {
1082 for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
1083 cache.cells[i].pos = -1;
1084 cache.cells[i].seq_id.clear();
1085 }
1086 cache.head = 0;
1087
1088 ggml_backend_buffer_clear(cache.buffer, 0);
1089 }
1090
1091 static void whisper_kv_cache_seq_rm(
1092 struct whisper_kv_cache & cache,
1093 whisper_seq_id seq_id,
1094 whisper_pos p0,
1095 whisper_pos p1) {
1096 uint32_t new_head = cache.size;
1097
1098 if (p0 < 0) p0 = 0;
1099 if (p1 < 0) p1 = std::numeric_limits<whisper_pos>::max();
1100
1101 for (uint32_t i = 0; i < cache.size; ++i) {
1102 if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
1103 if (seq_id < 0) {
1104 cache.cells[i].seq_id.clear();
1105 } else if (cache.cells[i].has_seq_id(seq_id)) {
1106 cache.cells[i].seq_id.erase(seq_id);
1107 } else {
1108 continue;
1109 }
1110 if (cache.cells[i].seq_id.empty()) {
1111 cache.cells[i].pos = -1;
1112 if (new_head == cache.size) new_head = i;
1113 }
1114 }
1115 }
1116
1117 // If we freed up a slot, set head to it so searching can start there.
1118 if (new_head != cache.size) cache.head = new_head;
1119 }
1120
1121 static void whisper_kv_cache_seq_cp(
1122 struct whisper_kv_cache & cache,
1123 whisper_seq_id seq_id_src,
1124 whisper_seq_id seq_id_dst,
1125 whisper_pos p0,
1126 whisper_pos p1) {
1127 if (p0 < 0) p0 = 0;
1128 if (p1 < 0) p1 = std::numeric_limits<whisper_pos>::max();
1129
1130 cache.head = 0;
1131
1132 for (uint32_t i = 0; i < cache.size; ++i) {
1133 if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
1134 cache.cells[i].seq_id.insert(seq_id_dst);
1135 }
1136 }
1137 }
1138
1139 static uint32_t whisper_kv_cache_get_padding(const struct whisper_context & wctx) {
1140 if (!wctx.params.flash_attn || !wctx.params.use_gpu) {
1141 return 1u;
1142 }
1143
1144 #ifdef GGML_USE_METAL
1145 if (wctx.params.use_gpu) {
1146 return 32u;
1147 }
1148 #endif
1149
1150 #ifdef GGML_USE_CUDA
1151 if (wctx.params.use_gpu) {
1152 return 256u;
1153 }
1154 #endif
1155
1156 return 1u;
1157 }
1158
1159 // [EXPERIMENTAL] Token-level timestamps with DTW
1160 static bool aheads_masks_init(
1161 const whisper_context_params & cparams,
1162 const whisper_hparams & hparams,
1163 struct whisper_aheads_masks & aheads_masks,
1164 ggml_backend_t backend) {
1165
1166 const int32_t n_text_layer = hparams.n_text_layer;
1167 const int32_t n_head = hparams.n_text_head;
1168
1169 // Sanity checks
1170 if (cparams.dtw_aheads_preset == WHISPER_AHEADS_NONE) {
1171 WHISPER_LOG_ERROR("%s: dtw_aheads_preset should be != DTW_AHEADS_NONE\n", __func__);
1172 return false;
1173 } else if (cparams.dtw_aheads_preset == WHISPER_AHEADS_N_TOP_MOST) {
1174 if (cparams.dtw_n_top > n_text_layer || cparams.dtw_n_top <= 0) {
1175 WHISPER_LOG_ERROR("%s: dtw_n_top must be between %d and %d for this model.", __func__, 1, n_text_layer);
1176 return false;
1177 }
1178 } else {
1179 const auto aheads = cparams.dtw_aheads_preset == WHISPER_AHEADS_CUSTOM ? cparams.dtw_aheads : g_aheads.at(cparams.dtw_aheads_preset);
1180 if (cparams.dtw_aheads_preset == WHISPER_AHEADS_CUSTOM) {
1181 if (aheads.n_heads == 0) {
1182 WHISPER_LOG_ERROR("%s: dtw_aheads.n_heads should be > 0", __func__);
1183 return false;
1184 }
1185 if (aheads.heads == NULL) {
1186 WHISPER_LOG_ERROR("%s: dtw_aheads.heads unset", __func__);
1187 return false;
1188 }
1189 }
1190 for (size_t i = 0; i < aheads.n_heads; ++i) {
1191 if (aheads.heads[i].n_text_layer >= n_text_layer) {
1192 WHISPER_LOG_ERROR("%s: tried to set alignment head on text layer %d, but model only has %d text layers", __func__, aheads.heads[i].n_text_layer + 1, n_text_layer);
1193 return false;
1194 }
1195 if (aheads.heads[i].n_text_layer < 0) {
1196 WHISPER_LOG_ERROR("%s: tried to set alignment head on text layer < 0", __func__);
1197 return false;
1198 }
1199 if (aheads.heads[i].n_head >= n_head) {
1200 WHISPER_LOG_ERROR("%s: tried to set alignment head on head %d, but model only has %d heads", __func__, aheads.heads[i].n_head + 1, n_head);
1201 return false;
1202 }
1203 if (aheads.heads[i].n_head < 0) {
1204 WHISPER_LOG_ERROR("%s: tried to set alignment head on head < 0", __func__);
1205 return false;
1206 }
1207 }
1208 }
1209
1210 struct ggml_init_params params = {
1211 /*.mem_size =*/ (size_t) static_cast<size_t>(n_text_layer)*ggml_tensor_overhead(),
1212 /*.mem_buffer =*/ nullptr,
1213 /*.no_alloc =*/ true,
1214 };
1215
1216 aheads_masks.ctx = ggml_init(params);
1217
1218 if (!aheads_masks.ctx) {
1219 WHISPER_LOG_ERROR("%s: failed to allocate memory for the aheads_masks context\n", __func__);
1220 return false;
1221 }
1222
1223 for (int64_t il = 0; il < n_text_layer; ++il) {
1224 auto aheads = get_alignment_heads_by_layer(cparams, il, n_text_layer, n_head);
1225 if (!aheads.empty()) {
1226 aheads_masks.m.push_back(ggml_new_tensor_2d(aheads_masks.ctx, GGML_TYPE_F32, n_head, aheads.size()));
1227 } else {
1228 aheads_masks.m.push_back(nullptr);
1229 }
1230 }
1231
1232 aheads_masks.buffer = ggml_backend_alloc_ctx_tensors(aheads_masks.ctx, backend);
1233 if (!aheads_masks.buffer) {
1234 WHISPER_LOG_ERROR("%s: failed to allocate memory for aheads_masks\n", __func__);
1235 return false;
1236 }
1237
1238 // Set data on mask tensors
1239 // Since this must be backend agnostic, we write our desired values on mask_data,
1240 // and send it to backend with ggml_backend_tensor_set.
1241 // Each mask in N_HEADS*N_ALIGNMENT_HEADS, one per text layer containing alignment
1242 // heads. Each row of the mask "marks" one alignment head. E.g. if some text layer
1243 // has a total of 10 heads and of those, heads 0,5,6 are alignment heads, the mask
1244 // should read:
1245 // 1 0 0 0 0 0 0 0 0 0
1246 // 0 0 0 0 0 1 0 0 0 0
1247 // 0 0 0 0 0 0 1 0 0 0
1248 std::vector<float> mask_data;
1249 for (int64_t il = 0; il < n_text_layer; ++il) {
1250 if (aheads_masks.m[il] != nullptr) {
1251 auto aheads = get_alignment_heads_by_layer(cparams, il, n_text_layer, n_head);
1252
1253 size_t data_size = aheads_masks.m[il]->ne[0] * aheads_masks.m[il]->ne[1];
1254 size_t data_size_bytes = data_size * sizeof(float);
1255 mask_data.resize(data_size);
1256
1257 std::fill(mask_data.begin(), mask_data.end(), 0);
1258 for (size_t ih = 0; ih < aheads.size(); ++ih) {
1259 size_t pos = (aheads[ih] + (ih * aheads_masks.m[il]->ne[0]));
1260 mask_data[pos] = 1.0f;
1261 }
1262
1263 ggml_backend_tensor_set(aheads_masks.m[il], mask_data.data(), 0, data_size_bytes);
1264 }
1265 }
1266
1267 if (aheads_masks.m.empty()) {
1268 WHISPER_LOG_ERROR("%s: \n", __func__);
1269 return false;
1270 }
1271
1272 return true;
1273 }
1274
1275 static void aheads_masks_free(struct whisper_aheads_masks & aheads_masks) {
1276 ggml_free(aheads_masks.ctx);
1277 ggml_backend_buffer_free(aheads_masks.buffer);
1278 aheads_masks.ctx = nullptr;
1279 }
1280
1281 static size_t aheads_masks_nbytes(struct whisper_aheads_masks & aheads_masks) {
1282 size_t size = 0;
1283 for (size_t i = 0; i < aheads_masks.m.size(); ++i) {
1284 if (aheads_masks.m[i] != nullptr)
1285 size += ggml_nbytes(aheads_masks.m[i]);
1286 }
1287 return size;
1288 }
1289
1290 static ggml_backend_t whisper_backend_init_gpu(const whisper_context_params & params) {
1291 ggml_log_set(g_state.log_callback, g_state.log_callback_user_data);
1292
1293 ggml_backend_dev_t dev = nullptr;
1294
1295 int cnt = 0;
1296 if (params.use_gpu) {
1297 for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
1298 ggml_backend_dev_t dev_cur = ggml_backend_dev_get(i);
1299 enum ggml_backend_dev_type dev_type = ggml_backend_dev_type(dev_cur);
1300 const char * dev_name = ggml_backend_dev_name(dev_cur);
1301 WHISPER_LOG_INFO("%s: device %zu: %s (type: %d)\n", __func__, i, dev_name, dev_type);
1302 if (dev_type == GGML_BACKEND_DEVICE_TYPE_GPU || dev_type == GGML_BACKEND_DEVICE_TYPE_IGPU) {
1303 WHISPER_LOG_INFO("%s: found GPU device %zu: %s (type: %d, cnt: %d)\n", __func__, i, dev_name, dev_type, cnt);
1304 if (cnt == params.gpu_device) {
1305 dev = dev_cur;
1306 }
1307
1308 if (++cnt > params.gpu_device) {
1309 break;
1310 }
1311 }
1312 }
1313 }
1314
1315 if (dev == nullptr) {
1316 WHISPER_LOG_INFO("%s: no GPU found\n", __func__);
1317 return nullptr;
1318 }
1319
1320 WHISPER_LOG_INFO("%s: using %s backend\n", __func__, ggml_backend_dev_name(dev));
1321 ggml_backend_t result = ggml_backend_dev_init(dev, nullptr);
1322 if (!result) {
1323 WHISPER_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
1324 }
1325
1326 return result;
1327 }
1328
1329 static std::vector<ggml_backend_t> whisper_backend_init(const whisper_context_params & params) {
1330 std::vector<ggml_backend_t> result;
1331
1332 ggml_backend_t backend_gpu = whisper_backend_init_gpu(params);
1333
1334 if (backend_gpu) {
1335 result.push_back(backend_gpu);
1336 }
1337
1338 // ACCEL backends
1339 for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
1340 ggml_backend_dev_t dev = ggml_backend_dev_get(i);
1341 if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
1342 WHISPER_LOG_INFO("%s: using %s backend\n", __func__, ggml_backend_dev_name(dev));
1343 ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
1344 if (!backend) {
1345 WHISPER_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
1346 continue;
1347 }
1348 result.push_back(backend);
1349 }
1350 }
1351
1352 ggml_backend_t backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
1353 if (backend_cpu == nullptr) {
1354 throw std::runtime_error("failed to initialize CPU backend");
1355 }
1356 result.push_back(backend_cpu);
1357
1358 return result;
1359 }
1360
1361 using buft_list_t = std::vector<std::pair<ggml_backend_dev_t, ggml_backend_buffer_type_t>>;
1362
1363 static buft_list_t make_buft_list(whisper_context_params & params) {
1364 // Prio order: GPU -> CPU Extra -> CPU
1365 buft_list_t buft_list;
1366
1367 // GPU
1368 if (params.use_gpu) {
1369 int cnt = 0;
1370 for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
1371 ggml_backend_dev_t dev = ggml_backend_dev_get(i);
1372 if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU || ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_IGPU) {
1373 if (cnt == params.gpu_device) {
1374 auto * buft = ggml_backend_dev_buffer_type(dev);
1375 if (buft) {
1376 buft_list.emplace_back(dev, buft);
1377 }
1378 }
1379
1380 if (++cnt > params.gpu_device) {
1381 break;
1382 }
1383 }
1384 }
1385 }
1386
1387 // CPU Extra
1388 auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
1389 auto * cpu_reg = ggml_backend_dev_backend_reg(cpu_dev);
1390 auto get_extra_bufts_fn = (ggml_backend_dev_get_extra_bufts_t)
1391 ggml_backend_reg_get_proc_address(cpu_reg, "ggml_backend_dev_get_extra_bufts");
1392 if (get_extra_bufts_fn) {
1393 ggml_backend_buffer_type_t * extra_bufts = get_extra_bufts_fn(cpu_dev);
1394 while (extra_bufts && *extra_bufts) {
1395 buft_list.emplace_back(cpu_dev, *extra_bufts);
1396 ++extra_bufts;
1397 }
1398 }
1399
1400 // CPU
1401 buft_list.emplace_back(cpu_dev, ggml_backend_cpu_buffer_type());
1402
1403 return buft_list;
1404 }
1405
1406 static bool weight_buft_supported(const whisper_hparams & hparams, ggml_tensor * w, ggml_op op, ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev) {
1407 bool op_supported = true;
1408
1409 if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU ||
1410 ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_IGPU ||
1411 (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU && buft == ggml_backend_cpu_buffer_type())) {
1412 // GPU and default CPU backend support all operators
1413 op_supported = true;
1414 } else {
1415 switch (op) {
1416 // The current extra_buffer_type implementations only support GGML_OP_MUL_MAT and GGML_OP_GET_ROWS
1417 case GGML_OP_GET_ROWS:
1418 case GGML_OP_MUL_MAT: {
1419 ggml_init_params params = {
1420 /*.mem_size =*/ 2 * ggml_tensor_overhead(),
1421 /*.mem_buffer =*/ nullptr,
1422 /*.no_alloc =*/ true,
1423 };
1424
1425 ggml_context_ptr ctx_ptr { ggml_init(params) };
1426 if (!ctx_ptr) {
1427 throw std::runtime_error("failed to create ggml context");
1428 }
1429 ggml_context * ctx = ctx_ptr.get();
1430
1431 ggml_tensor * op_tensor = nullptr;
1432
1433 if (op == GGML_OP_MUL_MAT) {
1434 int64_t n_ctx = hparams.n_audio_ctx;
1435 ggml_tensor * b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], n_ctx, w->ne[2], w->ne[3]);
1436 op_tensor = ggml_mul_mat(ctx, w, b);
1437 } else if (op == GGML_OP_GET_ROWS) {
1438 int64_t num_indices = 8;
1439 ggml_tensor * indices = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, num_indices);
1440 op_tensor = ggml_get_rows(ctx, w, indices);
1441 }
1442
1443 // create a temporary dummy buffer for the weight so that supports_op can check the buffer type
1444 GGML_ASSERT(w->buffer == nullptr);
1445 w->buffer = ggml_backend_buft_alloc_buffer(buft, 0);
1446 op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
1447 ggml_backend_buffer_free(w->buffer);
1448 w->buffer = nullptr;
1449 break;
1450 }
1451 default: {
1452 op_supported = false;
1453 break;
1454 }
1455 };
1456 }
1457
1458 return op_supported;
1459 }
1460
1461 static ggml_backend_buffer_type_t select_weight_buft(const whisper_hparams & hparams, ggml_tensor * w, ggml_op op, buft_list_t buft_list) {
1462 GGML_ASSERT(!buft_list.empty());
1463 for (const auto & p : buft_list) {
1464 ggml_backend_dev_t dev = p.first;
1465 ggml_backend_buffer_type_t buft = p.second;
1466 if (weight_buft_supported(hparams, w, op, buft, dev)) {
1467 return buft;
1468 }
1469 }
1470
1471 return nullptr;
1472 }
1473
1474 // load the model from a ggml file
1475 //
1476 // file format:
1477 //
1478 // - hparams
1479 // - pre-computed mel filters
1480 // - vocab
1481 // - weights
1482 //
1483 // see the convert-pt-to-ggml.py script for details
1484 //
1485 static bool whisper_model_load(struct whisper_model_loader * loader, whisper_context & wctx) {
1486 WHISPER_LOG_INFO("%s: loading model\n", __func__);
1487
1488 const int64_t t_start_us = ggml_time_us();
1489
1490 wctx.t_start_us = t_start_us;
1491
1492 auto & model = wctx.model;
1493 auto & vocab = wctx.vocab;
1494
1495 // verify magic
1496 {
1497 uint32_t magic;
1498 read_safe(loader, magic);
1499 if (magic != GGML_FILE_MAGIC) {
1500 WHISPER_LOG_ERROR("%s: invalid model data (bad magic)\n", __func__);
1501 return false;
1502 }
1503 }
1504
1505 //load hparams
1506 {
1507 auto & hparams = model.hparams;
1508
1509 read_safe(loader, hparams.n_vocab);
1510 read_safe(loader, hparams.n_audio_ctx);
1511 read_safe(loader, hparams.n_audio_state);
1512 read_safe(loader, hparams.n_audio_head);
1513 read_safe(loader, hparams.n_audio_layer);
1514 read_safe(loader, hparams.n_text_ctx);
1515 read_safe(loader, hparams.n_text_state);
1516 read_safe(loader, hparams.n_text_head);
1517 read_safe(loader, hparams.n_text_layer);
1518 read_safe(loader, hparams.n_mels);
1519 read_safe(loader, hparams.ftype);
1520
1521 assert(hparams.n_text_state == hparams.n_audio_state);
1522
1523 std::string mver = "";
1524
1525 if (hparams.n_audio_layer == 4) {
1526 model.type = e_model::MODEL_TINY;
1527 }
1528
1529 if (hparams.n_audio_layer == 6) {
1530 model.type = e_model::MODEL_BASE;
1531 }
1532
1533 if (hparams.n_audio_layer == 12) {
1534 model.type = e_model::MODEL_SMALL;
1535 }
1536
1537 if (hparams.n_audio_layer == 24) {
1538 model.type = e_model::MODEL_MEDIUM;
1539 }
1540
1541 if (hparams.n_audio_layer == 32) {
1542 model.type = e_model::MODEL_LARGE;
1543
1544 if (hparams.n_vocab == 51866) {
1545 mver = " v3";
1546 }
1547 }
1548
1549 const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
1550
1551 hparams.ftype %= GGML_QNT_VERSION_FACTOR;
1552
1553 // for the big tensors, we have the option to store the data in 16-bit floats or quantized
1554 // in order to save memory and also to speed up the computation
1555 wctx.wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
1556 if (wctx.wtype == GGML_TYPE_COUNT) {
1557 WHISPER_LOG_ERROR("%s: invalid model (bad ftype value %d)\n", __func__, model.hparams.ftype);
1558 return false;
1559 }
1560
1561 WHISPER_LOG_INFO("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
1562 WHISPER_LOG_INFO("%s: n_audio_ctx = %d\n", __func__, hparams.n_audio_ctx);
1563 WHISPER_LOG_INFO("%s: n_audio_state = %d\n", __func__, hparams.n_audio_state);
1564 WHISPER_LOG_INFO("%s: n_audio_head = %d\n", __func__, hparams.n_audio_head);
1565 WHISPER_LOG_INFO("%s: n_audio_layer = %d\n", __func__, hparams.n_audio_layer);
1566 WHISPER_LOG_INFO("%s: n_text_ctx = %d\n", __func__, hparams.n_text_ctx);
1567 WHISPER_LOG_INFO("%s: n_text_state = %d\n", __func__, hparams.n_text_state);
1568 WHISPER_LOG_INFO("%s: n_text_head = %d\n", __func__, hparams.n_text_head);
1569 WHISPER_LOG_INFO("%s: n_text_layer = %d\n", __func__, hparams.n_text_layer);
1570 WHISPER_LOG_INFO("%s: n_mels = %d\n", __func__, hparams.n_mels);
1571 WHISPER_LOG_INFO("%s: ftype = %d\n", __func__, model.hparams.ftype);
1572 WHISPER_LOG_INFO("%s: qntvr = %d\n", __func__, qntvr);
1573 WHISPER_LOG_INFO("%s: type = %d (%s%s)\n", __func__, model.type, g_model_name.at(model.type).c_str(), mver.c_str());
1574 }
1575
1576 // load mel filters
1577 {
1578 auto & filters = wctx.model.filters;
1579
1580 read_safe(loader, filters.n_mel);
1581 read_safe(loader, filters.n_fft);
1582
1583 filters.data.resize(filters.n_mel * filters.n_fft);
1584 loader->read(loader->context, filters.data.data(), filters.data.size() * sizeof(float));
1585 BYTESWAP_FILTERS(filters);
1586 }
1587
1588 // load vocab
1589 {
1590 int32_t n_vocab = 0;
1591 read_safe(loader, n_vocab);
1592
1593 //if (n_vocab != model.hparams.n_vocab) {
1594 // WHISPER_LOG_ERROR("%s: invalid model file '%s' (bad vocab size %d != %d)\n",
1595 // __func__, fname.c_str(), n_vocab, model.hparams.n_vocab);
1596 // return false;
1597 //}
1598
1599 std::string word;
1600 std::vector<char> tmp;
1601
1602 tmp.reserve(128);
1603
1604 for (int i = 0; i < n_vocab; i++) {
1605 uint32_t len;
1606 read_safe(loader, len);
1607
1608 if (len > 0) {
1609 tmp.resize(len);
1610 loader->read(loader->context, &tmp[0], tmp.size()); // read to buffer
1611 word.assign(&tmp[0], tmp.size());
1612 } else {
1613 // seems like we have an empty-string token in multi-language models (i = 50256)
1614 //WHISPER_LOG_WARN("%s: warning: empty-string token in vocab, i = %d\n", __func__, i);
1615 word = "";
1616 }
1617
1618 vocab.token_to_id[word] = i;
1619 vocab.id_to_token[i] = word;
1620
1621 //printf("%s: vocab[%d] = '%s'\n", __func__, i, word.c_str());
1622 }
1623
1624 vocab.n_vocab = model.hparams.n_vocab;
1625 if (vocab.is_multilingual()) {
1626 vocab.token_eot++;
1627 vocab.token_sot++;
1628
1629 // account for variable number of language tokens
1630 const int dt = vocab.num_languages() - 98;
1631
1632 vocab.token_translate += dt;
1633 vocab.token_transcribe += dt;
1634 vocab.token_solm += dt;
1635 vocab.token_prev += dt;
1636 vocab.token_nosp += dt;
1637 vocab.token_not += dt;
1638 vocab.token_beg += dt;
1639 }
1640
1641 if (n_vocab < model.hparams.n_vocab) {
1642 WHISPER_LOG_INFO("%s: adding %d extra tokens\n", __func__, model.hparams.n_vocab - n_vocab);
1643 for (int i = n_vocab; i < model.hparams.n_vocab; i++) {
1644 if (i > vocab.token_beg) {
1645 word = "[_TT_" + std::to_string(i - vocab.token_beg) + "]";
1646 } else if (i == vocab.token_eot) {
1647 word = "[_EOT_]";
1648 } else if (i == vocab.token_sot) {
1649 word = "[_SOT_]";
1650 } else if (i == vocab.token_translate) {
1651 word = "[_TRANSLATE_]";
1652 } else if (i == vocab.token_transcribe) {
1653 word = "[_TRANSCRIBE_]";
1654 } else if (i == vocab.token_solm) {
1655 word = "[_SOLM_]";
1656 } else if (i == vocab.token_prev) {
1657 word = "[_PREV_]";
1658 } else if (i == vocab.token_nosp) {
1659 word = "[_NOSP_]";
1660 } else if (i == vocab.token_not) {
1661 word = "[_NOT_]";
1662 } else if (i == vocab.token_beg) {
1663 word = "[_BEG_]";
1664 } else if (i > vocab.token_sot && i <= vocab.token_sot + vocab.num_languages()) {
1665 word = "[_LANG_" + std::string(whisper_lang_str(i - vocab.token_sot - 1)) + "]";
1666 } else {
1667 word = "[_extra_token_" + std::to_string(i) + "]";
1668 }
1669 vocab.token_to_id[word] = i;
1670 vocab.id_to_token[i] = word;
1671 }
1672 }
1673
1674 WHISPER_LOG_INFO("%s: n_langs = %d\n", __func__, vocab.num_languages());
1675 }
1676
1677 const ggml_type wtype = wctx.wtype;
1678 const ggml_type vtype = wctx.wtype == GGML_TYPE_F32 ? GGML_TYPE_F32 : GGML_TYPE_F16; // conv type
1679
1680 const auto & hparams = model.hparams;
1681
1682 const int n_audio_layer = hparams.n_audio_layer;
1683 const int n_text_layer = hparams.n_text_layer;
1684
1685 const size_t n_tensors = 10 /* input */ + 15 + 15*n_audio_layer + 24*n_text_layer;
1686
1687 std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
1688 auto get_ctx = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
1689 auto it = ctx_map.find(buft);
1690 if (it == ctx_map.end()) {
1691 ggml_init_params params = {
1692 /*.mem_size =*/ n_tensors * ggml_tensor_overhead(),
1693 /*.mem_buffer =*/ nullptr,
1694 /*.no_alloc =*/ true,
1695 };
1696
1697 ggml_context * ctx = ggml_init(params);
1698 if (!ctx) {
1699 throw std::runtime_error("failed to create ggml context");
1700 }
1701
1702 ctx_map[buft] = ctx;
1703 model.ctxs.emplace_back(ctx);
1704
1705 return ctx;
1706 }
1707
1708 return it->second;
1709 };
1710
1711 // Create a list of available bufts, in priority order
1712 buft_list_t buft_list = make_buft_list(wctx.params);
1713
1714 auto create_tensor = [&](asr_tensor type, asr_system system, ggml_tensor * meta, int layer = 0) -> ggml_tensor * {
1715 ggml_op op = ASR_TENSOR_INFO.at(type);
1716 ggml_backend_buffer_type_t buft = select_weight_buft(hparams, meta, op, buft_list);
1717 if (!buft) {
1718 throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", ASR_TENSOR_NAMES.at(system).at(type)));
1719 }
1720
1721 ggml_context * ctx = get_ctx(buft);
1722 ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
1723
1724 model.tensors[format(ASR_TENSOR_NAMES.at(system).at(type), layer)] = tensor;
1725
1726 return tensor;
1727 };
1728
1729
1730 // prepare tensors for the weights
1731 {
1732 ggml_init_params params = {
1733 /*.mem_size =*/ n_tensors * ggml_tensor_overhead(),
1734 /*.mem_buffer =*/ nullptr,
1735 /*.no_alloc =*/ true,
1736 };
1737
1738 ggml_context * ctx = ggml_init(params);
1739
1740 const auto & hparams = model.hparams;
1741
1742 const int n_vocab = hparams.n_vocab;
1743
1744 const int n_audio_ctx = hparams.n_audio_ctx;
1745 const int n_audio_state = hparams.n_audio_state;
1746 const int n_audio_layer = hparams.n_audio_layer;
1747
1748 const int n_text_ctx = hparams.n_text_ctx;
1749 const int n_text_state = hparams.n_text_state;
1750 const int n_text_layer = hparams.n_text_layer;
1751
1752 const int n_mels = hparams.n_mels;
1753
1754 model.layers_encoder.resize(n_audio_layer);
1755 model.layers_decoder.resize(n_text_layer);
1756
1757 // encoder
1758 model.e_pe = create_tensor(ASR_TENSOR_ENC_POS_EMBD, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_state, n_audio_ctx));
1759
1760 model.e_conv_1_w = create_tensor(ASR_TENSOR_CONV1_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_3d(ctx, vtype, 3, n_mels, n_audio_state));
1761 model.e_conv_1_b = create_tensor(ASR_TENSOR_CONV1_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, n_audio_state));
1762
1763 model.e_conv_2_w = create_tensor(ASR_TENSOR_CONV2_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_3d(ctx, vtype, 3, n_audio_state, n_audio_state));
1764 model.e_conv_2_b = create_tensor(ASR_TENSOR_CONV2_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, n_audio_state));
1765
1766 model.e_ln_w = create_tensor(ASR_TENSOR_LN_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state));
1767 model.e_ln_b = create_tensor(ASR_TENSOR_LN_POST_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state));
1768
1769 for (int i = 0; i < n_audio_layer; ++i) {
1770 auto & layer = model.layers_encoder[i];
1771
1772 layer.mlp_ln_w = create_tensor(ASR_TENSOR_MLP_LN_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1773 layer.mlp_ln_b = create_tensor(ASR_TENSOR_MLP_LN_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1774
1775 layer.mlp_0_w = create_tensor(ASR_TENSOR_MLP_0_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, wtype, n_audio_state, 4*n_audio_state), i);
1776 layer.mlp_0_b = create_tensor(ASR_TENSOR_MLP_0_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_audio_state), i);
1777
1778 layer.mlp_1_w = create_tensor(ASR_TENSOR_MLP_2_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, wtype, 4*n_audio_state, n_audio_state), i);
1779 layer.mlp_1_b = create_tensor(ASR_TENSOR_MLP_2_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1780
1781 layer.attn_ln_0_w = create_tensor(ASR_TENSOR_ATTN_LN_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1782 layer.attn_ln_0_b = create_tensor(ASR_TENSOR_ATTN_LN_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1783
1784 layer.attn_q_w = create_tensor(ASR_TENSOR_ATTN_QUERY_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state), i);
1785 layer.attn_q_b = create_tensor(ASR_TENSOR_ATTN_QUERY_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1786
1787 layer.attn_k_w = create_tensor(ASR_TENSOR_ATTN_KEY_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state), i);
1788
1789 layer.attn_v_w = create_tensor(ASR_TENSOR_ATTN_VALUE_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state), i);
1790 layer.attn_v_b = create_tensor(ASR_TENSOR_ATTN_VALUE_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1791
1792 layer.attn_ln_1_w = create_tensor(ASR_TENSOR_ATTN_OUT_WEIGHT, ASR_SYSTEM_ENCODER, ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state), i);
1793 layer.attn_ln_1_b = create_tensor(ASR_TENSOR_ATTN_OUT_BIAS, ASR_SYSTEM_ENCODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state), i);
1794 }
1795
1796 // decoder
1797 model.d_pe = create_tensor(ASR_TENSOR_DEC_POS_EMBD, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_text_state, n_text_ctx));
1798
1799 model.d_te = create_tensor(ASR_TENSOR_DEC_TOKEN_EMBD_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_vocab));
1800
1801 model.d_ln_w = create_tensor(ASR_TENSOR_LN_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state));
1802 model.d_ln_b = create_tensor(ASR_TENSOR_LN_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state));
1803
1804 for (int i = 0; i < n_text_layer; ++i) {
1805 auto & layer = model.layers_decoder[i];
1806
1807 layer.mlp_ln_w = create_tensor(ASR_TENSOR_MLP_LN_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1808 layer.mlp_ln_b = create_tensor(ASR_TENSOR_MLP_LN_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1809
1810 layer.mlp_0_w = create_tensor(ASR_TENSOR_MLP_0_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, n_text_state, 4*n_text_state), i);
1811 layer.mlp_0_b = create_tensor(ASR_TENSOR_MLP_0_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_text_state), i);
1812
1813 layer.mlp_1_w = create_tensor(ASR_TENSOR_MLP_2_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, 4*n_text_state, n_text_state), i);
1814 layer.mlp_1_b = create_tensor(ASR_TENSOR_MLP_2_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1815
1816 layer.attn_ln_0_w = create_tensor(ASR_TENSOR_ATTN_LN_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1817 layer.attn_ln_0_b = create_tensor(ASR_TENSOR_ATTN_LN_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1818
1819 layer.attn_q_w = create_tensor(ASR_TENSOR_ATTN_QUERY_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1820 layer.attn_q_b = create_tensor(ASR_TENSOR_ATTN_QUERY_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1821
1822 layer.attn_k_w = create_tensor(ASR_TENSOR_ATTN_KEY_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1823
1824 layer.attn_v_w = create_tensor(ASR_TENSOR_ATTN_VALUE_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1825 layer.attn_v_b = create_tensor(ASR_TENSOR_ATTN_VALUE_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1826
1827 layer.attn_ln_1_w = create_tensor(ASR_TENSOR_ATTN_OUT_WEIGHT, ASR_SYSTEM_DECODER, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1828 layer.attn_ln_1_b = create_tensor(ASR_TENSOR_ATTN_OUT_BIAS, ASR_SYSTEM_DECODER, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1829
1830 layer.cross_attn_ln_0_w = create_tensor(ASR_TENSOR_ATTN_LN_WEIGHT, ASR_SYSTEM_CROSS, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1831 layer.cross_attn_ln_0_b = create_tensor(ASR_TENSOR_ATTN_LN_BIAS, ASR_SYSTEM_CROSS, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1832
1833 layer.cross_attn_q_w = create_tensor(ASR_TENSOR_ATTN_QUERY_WEIGHT, ASR_SYSTEM_CROSS, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1834 layer.cross_attn_q_b = create_tensor(ASR_TENSOR_ATTN_QUERY_BIAS, ASR_SYSTEM_CROSS, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1835
1836 layer.cross_attn_k_w = create_tensor(ASR_TENSOR_ATTN_KEY_WEIGHT, ASR_SYSTEM_CROSS, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1837
1838 layer.cross_attn_v_w = create_tensor(ASR_TENSOR_ATTN_VALUE_WEIGHT, ASR_SYSTEM_CROSS, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1839 layer.cross_attn_v_b = create_tensor(ASR_TENSOR_ATTN_VALUE_BIAS, ASR_SYSTEM_CROSS, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1840
1841 layer.cross_attn_ln_1_w = create_tensor(ASR_TENSOR_ATTN_OUT_WEIGHT, ASR_SYSTEM_CROSS, ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state), i);
1842 layer.cross_attn_ln_1_b = create_tensor(ASR_TENSOR_ATTN_OUT_BIAS, ASR_SYSTEM_CROSS, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state), i);
1843 }
1844
1845 ggml_free(ctx);
1846 }
1847
1848 // allocate tensors in the backend buffers
1849 for (auto & p : ctx_map) {
1850 ggml_backend_buffer_type_t buft = p.first;
1851 ggml_context * ctx = p.second;
1852 ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
1853 if (buf) {
1854 model.buffers.emplace_back(buf);
1855
1856 size_t size_main = ggml_backend_buffer_get_size(buf);
1857 WHISPER_LOG_INFO("%s: %12s total size = %8.2f MB\n", __func__, ggml_backend_buffer_name(buf), size_main / 1e6);
1858 }
1859 }
1860
1861 // load weights
1862 {
1863 size_t total_size = 0;
1864
1865 model.n_loaded = 0;
1866
1867 std::vector<char> read_buf;
1868
1869 while (true) {
1870 int32_t n_dims;
1871 int32_t length;
1872 int32_t ttype;
1873
1874 read_safe(loader, n_dims);
1875 read_safe(loader, length);
1876 read_safe(loader, ttype);
1877
1878 if (loader->eof(loader->context)) {
1879 break;
1880 }
1881
1882 int32_t nelements = 1;
1883 int32_t ne[4] = { 1, 1, 1, 1 };
1884 for (int i = 0; i < n_dims; ++i) {
1885 read_safe(loader, ne[i]);
1886 nelements *= ne[i];
1887 }
1888
1889 std::string name;
1890 std::vector<char> tmp(length); // create a buffer
1891 loader->read(loader->context, &tmp[0], tmp.size()); // read to buffer
1892 name.assign(&tmp[0], tmp.size());
1893
1894 if (model.tensors.find(name) == model.tensors.end()) {
1895 WHISPER_LOG_ERROR("%s: unknown tensor '%s' in model file\n", __func__, name.data());
1896 return false;
1897 }
1898
1899 auto tensor = model.tensors[name.data()];
1900
1901 if (ggml_nelements(tensor) != nelements) {
1902 WHISPER_LOG_ERROR("%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
1903 WHISPER_LOG_ERROR("%s: shape: [%d, %d, %d], expected: [%d, %d, %d]\n",
1904 __func__, ne[0], ne[1], ne[2], (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2]);
1905 return false;
1906 }
1907
1908 if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1] || tensor->ne[2] != ne[2]) {
1909 WHISPER_LOG_ERROR("%s: tensor '%s' has wrong shape in model file: got [%d, %d, %d], expected [%d, %d, %d]\n",
1910 __func__, name.data(), (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2], ne[0], ne[1], ne[2]);
1911 return false;
1912 }
1913
1914 const size_t bpe = ggml_type_size(ggml_type(ttype));
1915
1916 if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
1917 WHISPER_LOG_ERROR("%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
1918 __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
1919 return false;
1920 }
1921
1922 if (ggml_backend_buffer_is_host(tensor->buffer)) {
1923 // for the CPU and Metal backend, we can read directly into the tensor
1924 loader->read(loader->context, tensor->data, ggml_nbytes(tensor));
1925 BYTESWAP_TENSOR(tensor);
1926 } else {
1927 // read into a temporary buffer first, then copy to device memory
1928 read_buf.resize(ggml_nbytes(tensor));
1929
1930 loader->read(loader->context, read_buf.data(), read_buf.size());
1931
1932 ggml_backend_tensor_set(tensor, read_buf.data(), 0, ggml_nbytes(tensor));
1933 }
1934
1935 total_size += ggml_nbytes(tensor);
1936 model.n_loaded++;
1937 }
1938
1939 WHISPER_LOG_INFO("%s: model size = %7.2f MB\n", __func__, total_size/1e6);
1940
1941 if (model.n_loaded == 0) {
1942 WHISPER_LOG_WARN("%s: WARN no tensors loaded from model file - assuming empty model for testing\n", __func__);
1943 } else if (model.n_loaded != (int) model.tensors.size()) {
1944 WHISPER_LOG_ERROR("%s: ERROR not all tensors loaded from model file - expected %zu, got %d\n", __func__, model.tensors.size(), model.n_loaded);
1945 return false;
1946 }
1947 }
1948
1949 for (auto & buf : model.buffers) {
1950 ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
1951 }
1952
1953 wctx.t_load_us = ggml_time_us() - t_start_us;
1954
1955 return true;
1956 }
1957
1958 static bool whisper_encode_external(const whisper_state & wstate) {
1959 GGML_UNUSED(wstate);
1960
1961 #ifndef WHISPER_USE_COREML
1962 const bool use_coreml = false;
1963 #else
1964 const bool use_coreml = wstate.ctx_coreml != nullptr;
1965 #endif
1966
1967 #ifndef WHISPER_USE_OPENVINO
1968 const bool use_openvino = false;
1969 #else
1970 const bool use_openvino = wstate.ctx_openvino != nullptr;
1971 #endif
1972
1973 return use_coreml || use_openvino;
1974 }
1975
1976 static struct ggml_cgraph * whisper_build_graph_conv(
1977 whisper_context & wctx,
1978 whisper_state & wstate) {
1979 const auto & model = wctx.model;
1980 const auto & hparams = model.hparams;
1981
1982 const int n_ctx = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : hparams.n_audio_ctx;
1983 const int n_state = hparams.n_audio_state; GGML_UNUSED(n_state);
1984
1985 const int n_mels = hparams.n_mels;
1986
1987 struct ggml_init_params params = {
1988 /*.mem_size =*/ wstate.sched_conv.meta.size(),
1989 /*.mem_buffer =*/ wstate.sched_conv.meta.data(),
1990 /*.no_alloc =*/ true,
1991 };
1992
1993 struct ggml_context * ctx0 = ggml_init(params);
1994
1995 ggml_cgraph * gf = ggml_new_graph(ctx0);
1996
1997 struct ggml_tensor * mel = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 2*n_ctx, n_mels);
1998 ggml_set_name(mel, "mel");
1999 ggml_set_input(mel);
2000
2001 struct ggml_tensor * cur = nullptr;
2002
2003 if (!whisper_encode_external(wstate)) {
2004 // convolution + gelu
2005 {
2006 cur = ggml_conv_1d_ph(ctx0, model.e_conv_1_w, mel, 1, 1);
2007 cur = ggml_add(ctx0, cur, model.e_conv_1_b);
2008
2009 cur = ggml_gelu(ctx0, cur);
2010
2011 cur = ggml_conv_1d_ph(ctx0, model.e_conv_2_w, cur, 2, 1);
2012 cur = ggml_add(ctx0, cur, model.e_conv_2_b);
2013
2014 cur = ggml_gelu(ctx0, cur);
2015 }
2016
2017 ggml_set_name(cur, "embd_conv");
2018 wstate.embd_conv = cur;
2019 } else {
2020 ggml_build_forward_expand(gf, mel);
2021
2022 cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_state, n_ctx);
2023 ggml_set_input(cur); // the external encoder will write into this tensor
2024
2025 ggml_set_name(cur, "embd_enc");
2026 wstate.embd_enc = cur;
2027 }
2028
2029 ggml_set_output(cur);
2030
2031 ggml_build_forward_expand(gf, cur);
2032
2033 ggml_free(ctx0);
2034
2035 return gf;
2036 }
2037
2038 static struct ggml_cgraph * whisper_build_graph_encoder(
2039 whisper_context & wctx,
2040 whisper_state & wstate) {
2041 const auto & model = wctx.model;
2042 const auto & hparams = model.hparams;
2043
2044 const int n_ctx = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : hparams.n_audio_ctx;
2045 const int n_state = hparams.n_audio_state;
2046 const int n_head = hparams.n_audio_head;
2047 const int n_layer = hparams.n_audio_layer;
2048
2049 const int n_state_head = n_state/n_head;
2050
2051 auto & kv_pad = wstate.kv_pad;
2052
2053 WHISPER_ASSERT(!!kv_pad.buffer);
2054
2055 const int n_ctx_pad = GGML_PAD(n_ctx, 256);
2056
2057 struct ggml_init_params params = {
2058 /*.mem_size =*/ wstate.sched_encode.meta.size(),
2059 /*.mem_buffer =*/ wstate.sched_encode.meta.data(),
2060 /*.no_alloc =*/ true,
2061 };
2062
2063 struct ggml_context * ctx0 = ggml_init(params);
2064
2065 ggml_cgraph * gf = ggml_new_graph_custom(ctx0, WHISPER_MAX_NODES, false);
2066
2067 struct ggml_tensor * cur = ggml_view_tensor(ctx0, wstate.embd_conv);
2068
2069 const float KQscale = 1.0f/sqrtf(float(n_state_head));
2070
2071 // ===================================================================
2072 // NOTE: experimenting with partial evaluation of the encoder (ignore)
2073 //static int iter = -1;
2074 //const int n_iter = 1500/n_ctx;
2075
2076 //iter = (iter + 1) % n_iter;
2077
2078 //if (iter == 0) {
2079 // memset(model.memory_cross_k->data, 0, ggml_nbytes(model.memory_cross_k));
2080 // memset(model.memory_cross_v->data, 0, ggml_nbytes(model.memory_cross_v));
2081 //}
2082
2083 static int iter = 0;
2084
2085 const size_t e_pe_stride = model.e_pe->ne[0]*ggml_element_size(model.e_pe);
2086 const size_t e_pe_offset = model.e_pe->ne[0]*ggml_element_size(model.e_pe)*n_ctx*iter;
2087
2088 struct ggml_tensor * e_pe = ggml_view_2d(ctx0, model.e_pe, model.e_pe->ne[0], n_ctx, e_pe_stride, e_pe_offset);
2089 cur = ggml_add(ctx0, e_pe, ggml_cont(ctx0, ggml_transpose(ctx0, cur)));
2090
2091 // ===================================================================
2092
2093 // original:
2094 //cur = ggml_add(ctx0, model.e_pe, ggml_transpose(ctx0, cur));
2095
2096 struct ggml_tensor * inpL = cur;
2097
2098 for (int il = 0; il < n_layer; ++il) {
2099 const auto & layer = model.layers_encoder[il];
2100
2101 // norm
2102 {
2103 cur = ggml_norm(ctx0, inpL, hparams.eps);
2104
2105 // cur = ln_0_w*cur + ln_0_b
2106 cur = ggml_add(ctx0,
2107 ggml_mul(ctx0, cur, layer.attn_ln_0_w),
2108 layer.attn_ln_0_b);
2109 }
2110
2111 // self-attention
2112 {
2113 struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
2114 layer.attn_q_w,
2115 cur);
2116
2117 Qcur = ggml_add(ctx0, Qcur, layer.attn_q_b);
2118
2119 //Qcur = ggml_scale(ctx0, Qcur, pow(float(n_state_head), -0.25));
2120
2121 // note: no bias for Key
2122 struct ggml_tensor * Kcur = ggml_mul_mat(ctx0,
2123 layer.attn_k_w,
2124 cur);
2125
2126 //Kcur = ggml_scale(ctx0, Kcur, pow(float(n_state_head), -0.25));
2127
2128 struct ggml_tensor * Vcur = ggml_mul_mat(ctx0,
2129 layer.attn_v_w,
2130 cur);
2131
2132 Vcur = ggml_add(ctx0, Vcur, layer.attn_v_b);
2133
2134 // ------
2135
2136 struct ggml_tensor * Q =
2137 ggml_permute(ctx0,
2138 ggml_reshape_3d(ctx0, Qcur, n_state_head, n_head, n_ctx),
2139 0, 2, 1, 3);
2140
2141 if (wctx.params.flash_attn) {
2142 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, ggml_view_1d(ctx0, kv_pad.k, n_ctx*n_state, 0)));
2143 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, ggml_view_1d(ctx0, kv_pad.v, n_ctx*n_state, 0)));
2144
2145 struct ggml_tensor * K =
2146 ggml_view_3d(ctx0, kv_pad.k,
2147 n_state_head, n_ctx_pad, n_head,
2148 ggml_element_size(kv_pad.k)*n_state,
2149 ggml_element_size(kv_pad.k)*n_state_head,
2150 0);
2151
2152 struct ggml_tensor * V =
2153 ggml_view_3d(ctx0, kv_pad.v,
2154 n_state_head, n_ctx_pad, n_head,
2155 ggml_element_size(kv_pad.v)*n_state,
2156 ggml_element_size(kv_pad.v)*n_state_head,
2157 0);
2158
2159 cur = ggml_flash_attn_ext(ctx0, Q, K, V, nullptr, KQscale, 0.0f, 0.0f);
2160
2161 cur = ggml_reshape_2d(ctx0, cur, n_state, n_ctx);
2162 } else {
2163 struct ggml_tensor * K =
2164 ggml_permute(ctx0,
2165 ggml_cast(ctx0,
2166 ggml_reshape_3d(ctx0, Kcur, n_state_head, n_head, n_ctx),
2167 wctx.itype),
2168 0, 2, 1, 3);
2169
2170 // K * Q
2171 struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
2172
2173 struct ggml_tensor * KQ_soft_max = ggml_soft_max_ext(ctx0, KQ, nullptr, KQscale, 0.0f);
2174
2175 struct ggml_tensor * V =
2176 ggml_cast(ctx0,
2177 ggml_permute(ctx0,
2178 ggml_reshape_3d(ctx0,
2179 Vcur,
2180 n_state_head, n_head, n_ctx),
2181 1, 2, 0, 3),
2182 wctx.itype);
2183
2184 struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
2185
2186 struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
2187
2188 cur = ggml_cont_2d(ctx0, KQV_merged, n_state, n_ctx);
2189 }
2190 }
2191
2192 // projection
2193 {
2194 cur = ggml_mul_mat(ctx0,
2195 layer.attn_ln_1_w,
2196 cur);
2197
2198 cur = ggml_add(ctx0, cur, layer.attn_ln_1_b);
2199 }
2200
2201 // add the input
2202 cur = ggml_add(ctx0, cur, inpL);
2203
2204 struct ggml_tensor * inpFF = cur;
2205
2206 // feed-forward network
2207 {
2208 // norm
2209 {
2210 cur = ggml_norm(ctx0, inpFF, hparams.eps);
2211
2212 // cur = mlp_ln_w*cur + mlp_ln_b
2213 cur = ggml_add(ctx0,
2214 ggml_mul(ctx0, cur, layer.mlp_ln_w),
2215 layer.mlp_ln_b);
2216 }
2217
2218 // fully connected
2219 cur = ggml_mul_mat(ctx0,
2220 layer.mlp_0_w,
2221 cur);
2222
2223 cur = ggml_add(ctx0, cur, layer.mlp_0_b);
2224
2225 // GELU activation
2226 cur = ggml_gelu(ctx0, cur);
2227
2228 // projection
2229 cur = ggml_mul_mat(ctx0,
2230 layer.mlp_1_w,
2231 cur);
2232
2233 cur = ggml_add(ctx0, cur, layer.mlp_1_b);
2234 }
2235
2236 inpL = ggml_add(ctx0, cur, inpFF);
2237 }
2238
2239 cur = inpL;
2240
2241 // norm
2242 {
2243 cur = ggml_norm(ctx0, cur, hparams.eps);
2244
2245 // cur = ln_f_g*cur + ln_f_b
2246 cur = ggml_add(ctx0,
2247 ggml_mul(ctx0, cur, model.e_ln_w),
2248 model.e_ln_b);
2249 }
2250
2251 ggml_build_forward_expand(gf, cur);
2252
2253 wstate.embd_enc = cur;
2254
2255 //ggml_graph_print(gf);
2256
2257 ////////////////////////////////////////////////////////////////////////////
2258
2259 //printf("%s: used_mem = %f MB, %f MB, %f MB %f MB %f MB\n", __func__,
2260 // ggml_used_mem(ctx0)/1e6,
2261 // wstate.get_buf_max_mem(0)/1e6,
2262 // wstate.get_buf_max_mem(1)/1e6,
2263 // wstate.get_buf_max_mem(2)/1e6,
2264 // wstate.get_buf_max_mem(3)/1e6);
2265
2266 ggml_free(ctx0);
2267
2268 return gf;
2269 }
2270
2271 // pre-compute cross-attention memory
2272 static struct ggml_cgraph * whisper_build_graph_cross(
2273 whisper_context & wctx,
2274 whisper_state & wstate) {
2275 const auto & model = wctx.model;
2276 const auto & hparams = model.hparams;
2277
2278 const int n_ctx = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : hparams.n_audio_ctx;
2279 const int n_state = hparams.n_audio_state;
2280 const int n_head = hparams.n_audio_head;
2281
2282 const int n_state_head = n_state/n_head;
2283
2284 const int n_ctx_pad = GGML_PAD(n_ctx, 256);
2285
2286 struct ggml_init_params params = {
2287 /*.mem_size =*/ wstate.sched_cross.meta.size(),
2288 /*.mem_buffer =*/ wstate.sched_cross.meta.data(),
2289 /*.no_alloc =*/ true,
2290 };
2291
2292 struct ggml_context * ctx0 = ggml_init(params);
2293
2294 ggml_cgraph * gf = ggml_new_graph(ctx0);
2295
2296 struct ggml_tensor * cur = ggml_view_tensor(ctx0, wstate.embd_enc);
2297
2298 const float Kscale = pow(float(n_state_head), -0.25);
2299
2300 for (int il = 0; il < model.hparams.n_text_layer; ++il) {
2301 auto & layer = model.layers_decoder[il];
2302
2303 struct ggml_tensor * Kcross = ggml_mul_mat(ctx0,
2304 layer.cross_attn_k_w,
2305 cur);
2306
2307 Kcross = ggml_scale(ctx0, Kcross, Kscale);
2308
2309 struct ggml_tensor * Vcross = ggml_mul_mat(ctx0,
2310 layer.cross_attn_v_w,
2311 cur);
2312
2313 Vcross = ggml_add(ctx0,
2314 Vcross,
2315 layer.cross_attn_v_b);
2316
2317 struct ggml_tensor * k;
2318 struct ggml_tensor * v;
2319
2320 if (wctx.params.flash_attn) {
2321 k = ggml_view_1d(ctx0, wstate.kv_cross.k, n_state*n_ctx,
2322 (ggml_element_size(wstate.kv_cross.k)*n_state)*(il*n_ctx_pad));
2323
2324 v = ggml_view_1d(ctx0, wstate.kv_cross.v, n_state*n_ctx,
2325 (ggml_element_size(wstate.kv_cross.v)*n_state)*(il*n_ctx_pad));
2326 } else {
2327 Vcross = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcross, n_state, n_ctx));
2328
2329 k = ggml_view_1d(ctx0, wstate.kv_cross.k, n_state*n_ctx,
2330 (ggml_element_size(wstate.kv_cross.k)*n_state)*(il*n_ctx));
2331
2332 v = ggml_view_2d(ctx0, wstate.kv_cross.v, n_ctx, n_state,
2333 ( n_ctx)*ggml_element_size(wstate.kv_cross.v),
2334 (il*n_ctx)*ggml_element_size(wstate.kv_cross.v)*n_state);
2335 }
2336
2337 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcross, k));
2338 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcross, v));
2339 }
2340
2341 //ggml_graph_print(gf);
2342
2343 ggml_free(ctx0);
2344
2345 return gf;
2346 }
2347
2348 // evaluate the encoder with the given state
2349 //
2350 // given audio recording (more specifically, its log mel spectrogram), runs forward pass of the encoder
2351 // part of the transformer model and returns the encoded features
2352 //
2353 // - wctx: the model
2354 // - wstate: the state of the encoder
2355 // - n_threads: number of threads to use
2356 // - mel_offset: offset in the mel spectrogram (i.e. audio offset)
2357 //
2358 static bool whisper_encode_internal(
2359 whisper_context & wctx,
2360 whisper_state & wstate,
2361 const int mel_offset,
2362 const int n_threads,
2363 ggml_abort_callback abort_callback,
2364 void * abort_callback_data) {
2365 const int64_t t_start_us = ggml_time_us();
2366
2367 // conv
2368 {
2369 auto & sched = wstate.sched_conv.sched;
2370
2371 ggml_cgraph * gf = whisper_build_graph_conv(wctx, wstate);
2372
2373 if (!ggml_backend_sched_alloc_graph(sched, gf)) {
2374 // should never happen as we pre-allocate the memory
2375 return false;
2376 }
2377
2378 struct ggml_tensor * mel = ggml_graph_get_tensor(gf, "mel");
2379
2380 // set the input
2381 {
2382 const auto & mel_inp = wstate.mel;
2383 const int n_ctx = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : wctx.model.hparams.n_audio_ctx;
2384
2385 assert(mel->type == GGML_TYPE_F32);
2386 assert(mel_inp.n_mel == wctx.model.hparams.n_mels);
2387
2388 wstate.inp_mel.resize(ggml_nelements(mel));
2389
2390 float * dst = wstate.inp_mel.data();
2391 memset(dst, 0, ggml_nbytes(mel));
2392
2393 const int i0 = std::min(mel_offset, mel_inp.n_len);
2394 const int i1 = std::min(mel_offset + 2*n_ctx, mel_inp.n_len);
2395
2396 for (int j = 0; j < mel_inp.n_mel; ++j) {
2397 for (int i = i0; i < i1; ++i) {
2398 dst[j*2*n_ctx + (i - i0)] = mel_inp.data[j*mel_inp.n_len + i];
2399 }
2400 }
2401
2402 ggml_backend_tensor_set(mel, wstate.inp_mel.data(), 0, ggml_nelements(mel)*sizeof(float));
2403 }
2404
2405 if (!whisper_encode_external(wstate)) {
2406 if (!ggml_graph_compute_helper(sched, gf, n_threads)) {
2407 return false;
2408 }
2409 } else {
2410 ggml_backend_sched_reset(sched);
2411
2412 #if defined(WHISPER_USE_COREML)
2413 whisper_coreml_encode(wstate.ctx_coreml, mel->ne[0], mel->ne[1], (float *) mel->data, (float *) wstate.embd_enc->data);
2414 #elif defined(WHISPER_USE_OPENVINO)
2415 whisper_openvino_encode(wstate.ctx_openvino, mel, wstate.embd_enc);
2416 #endif
2417 }
2418 }
2419
2420 // encoder
2421 if (!whisper_encode_external(wstate)) {
2422 auto & sched = wstate.sched_encode.sched;
2423
2424 ggml_cgraph * gf = whisper_build_graph_encoder(wctx, wstate);
2425
2426 if (!ggml_backend_sched_alloc_graph(sched, gf)) {
2427 // should never happen as we pre-allocate the memory
2428 return false;
2429 }
2430
2431 if (!ggml_graph_compute_helper(sched, gf, n_threads)) {
2432 return false;
2433 }
2434 }
2435
2436 // cross
2437 {
2438 auto & sched = wstate.sched_cross.sched;
2439
2440 ggml_cgraph * gf = whisper_build_graph_cross(wctx, wstate);
2441
2442 if (!ggml_backend_sched_alloc_graph(sched, gf)) {
2443 // should never happen as we pre-allocate the memory
2444 return false;
2445 }
2446
2447 if (!ggml_graph_compute_helper(sched, gf, n_threads)) {
2448 return false;
2449 }
2450 }
2451
2452 wstate.t_encode_us += ggml_time_us() - t_start_us;
2453 wstate.n_encode++;
2454
2455 return !(abort_callback && abort_callback(abort_callback_data));
2456 }
2457
2458 static struct ggml_cgraph * whisper_build_graph_decoder(
2459 whisper_context & wctx,
2460 whisper_state & wstate,
2461 const whisper_batch & batch,
2462 bool save_alignment_heads_QKs,
2463 bool worst_case) {
2464 const auto & model = wctx.model;
2465 const auto & hparams = model.hparams;
2466
2467 auto & kv_self = wstate.kv_self;
2468
2469 WHISPER_ASSERT(!!kv_self.buffer);
2470
2471 const int n_ctx = kv_self.size;
2472 const int n_state = hparams.n_text_state;
2473 const int n_head = hparams.n_text_head;
2474 const int n_layer = hparams.n_text_layer;
2475
2476 const int n_state_head = n_state/n_head;
2477
2478 const int n_tokens = batch.n_tokens;
2479 const int n_audio_ctx = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : hparams.n_audio_ctx;
2480
2481 const int n_audio_ctx_pad = GGML_PAD(n_audio_ctx, 256);
2482
2483 const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
2484 const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
2485
2486 //WHISPER_LOG_DEBUG("%s: n_past = %d, n_tokens = %d, n_audio_ctx = %d, n_ctx = %d\n", __func__, n_past, n_tokens, n_audio_ctx, n_ctx);
2487
2488 struct ggml_init_params params = {
2489 /*.mem_size =*/ wstate.sched_decode.meta.size(),
2490 /*.mem_buffer =*/ wstate.sched_decode.meta.data(),
2491 /*.no_alloc =*/ true,
2492 };
2493
2494 struct ggml_context * ctx0 = ggml_init(params);
2495
2496 ggml_cgraph * gf = ggml_new_graph_custom(ctx0, WHISPER_MAX_NODES, false);
2497
2498 struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
2499 ggml_set_name(embd, "embd");
2500 ggml_set_input(embd);
2501
2502 struct ggml_tensor * position = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
2503 ggml_set_name(position, "position");
2504 ggml_set_input(position);
2505
2506 const float KQscale = pow(float(n_state_head), -0.25);
2507
2508 struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
2509 ggml_set_name(KQ_mask, "KQ_mask");
2510 ggml_set_input(KQ_mask);
2511
2512 struct ggml_tensor * KQ_mask_f16 = ggml_cast(ctx0, KQ_mask, GGML_TYPE_F16);
2513
2514 // token encoding + position encoding
2515 struct ggml_tensor * cur =
2516 ggml_add(ctx0,
2517 ggml_get_rows(ctx0, model.d_te, embd),
2518 ggml_get_rows(ctx0, model.d_pe, position));
2519
2520 struct ggml_tensor * inpL = cur;
2521
2522 // [EXPERIMENTAL] Token-level timestamps with DTW
2523 struct ggml_tensor * aheads_cross_QKs = nullptr;
2524
2525 for (int il = 0; il < n_layer; ++il) {
2526 const auto & layer = model.layers_decoder[il];
2527
2528 // norm
2529 {
2530 cur = ggml_norm(ctx0, inpL, hparams.eps);
2531
2532 // cur = ln_0_w*cur + ln_0_b
2533 cur = ggml_add(ctx0,
2534 ggml_mul(ctx0,
2535 cur,
2536 layer.attn_ln_0_w),
2537 layer.attn_ln_0_b);
2538 }
2539
2540 // self-attention
2541 {
2542 struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
2543 layer.attn_q_w,
2544 cur);
2545
2546 Qcur = ggml_add(ctx0,
2547 Qcur,
2548 layer.attn_q_b);
2549
2550 Qcur = ggml_scale(ctx0, Qcur, KQscale);
2551
2552 // note: no bias for Key
2553 struct ggml_tensor * Kcur = ggml_mul_mat(ctx0,
2554 layer.attn_k_w,
2555 cur);
2556
2557 Kcur = ggml_scale(ctx0, Kcur, KQscale);
2558
2559 // store key and value to memory
2560 {
2561 struct ggml_tensor * Vcur = ggml_mul_mat(ctx0,
2562 layer.attn_v_w,
2563 cur);
2564
2565 Vcur = ggml_add(ctx0,
2566 Vcur,
2567 layer.attn_v_b);
2568
2569 struct ggml_tensor * k;
2570 struct ggml_tensor * v;
2571
2572 if (wctx.params.flash_attn) {
2573 k = ggml_view_1d(ctx0, kv_self.k, n_tokens*n_state,
2574 (ggml_element_size(kv_self.k)*n_state)*(il*n_ctx + kv_head));
2575
2576 v = ggml_view_1d(ctx0, kv_self.v, n_tokens*n_state,
2577 (ggml_element_size(kv_self.v)*n_state)*(il*n_ctx + kv_head));
2578 } else {
2579 Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_state, n_tokens));
2580
2581 k = ggml_view_1d(ctx0, kv_self.k, n_tokens*n_state,
2582 (ggml_element_size(kv_self.k)*n_state)*(il*n_ctx + kv_head));
2583
2584 v = ggml_view_2d(ctx0, kv_self.v, n_tokens, n_state,
2585 ( n_ctx)*ggml_element_size(kv_self.v),
2586 (il*n_ctx)*ggml_element_size(kv_self.v)*n_state + kv_head*ggml_element_size(kv_self.v));
2587 }
2588
2589 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
2590 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
2591 }
2592
2593 // ------
2594
2595 struct ggml_tensor * Q =
2596 ggml_permute(ctx0,
2597 ggml_reshape_3d(ctx0, Qcur, n_state_head, n_head, n_tokens),
2598 0, 2, 1, 3);
2599
2600 struct ggml_tensor * K =
2601 ggml_view_3d(ctx0, kv_self.k,
2602 n_state_head, n_kv, n_head,
2603 ggml_element_size(kv_self.k)*n_state,
2604 ggml_element_size(kv_self.k)*n_state_head,
2605 ggml_element_size(kv_self.k)*n_state*n_ctx*il);
2606
2607 if (wctx.params.flash_attn) {
2608 struct ggml_tensor * V =
2609 ggml_view_3d(ctx0, kv_self.v,
2610 n_state_head, n_kv, n_head,
2611 ggml_element_size(kv_self.v)*n_state,
2612 ggml_element_size(kv_self.v)*n_state_head,
2613 ggml_element_size(kv_self.v)*n_state*n_ctx*il);
2614
2615 cur = ggml_flash_attn_ext(ctx0, Q, K, V, KQ_mask_f16, 1.0f, 0.0f, 0.0f);
2616
2617 cur = ggml_reshape_2d(ctx0, cur, n_state, n_tokens);
2618 } else {
2619 // K * Q
2620 struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
2621
2622 struct ggml_tensor * KQ_soft_max = ggml_soft_max_ext(ctx0, KQ, KQ_mask, 1.0f, 0.0f);
2623
2624 struct ggml_tensor * V =
2625 ggml_view_3d(ctx0, kv_self.v,
2626 n_kv, n_state_head, n_head,
2627 n_ctx*ggml_element_size(kv_self.v),
2628 n_ctx*ggml_element_size(kv_self.v)*n_state_head,
2629 n_ctx*ggml_element_size(kv_self.v)*n_state*il);
2630
2631 struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
2632
2633 struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
2634
2635 cur = ggml_cont_2d(ctx0, KQV_merged, n_state, n_tokens);
2636 }
2637 }
2638
2639 // projection
2640 {
2641 cur = ggml_mul_mat(ctx0,
2642 layer.attn_ln_1_w,
2643 cur);
2644
2645 cur = ggml_add(ctx0,
2646 cur,
2647 layer.attn_ln_1_b);
2648 }
2649
2650 // add the input
2651 struct ggml_tensor * inpCA = ggml_add(ctx0, cur, inpL);
2652
2653 // norm
2654 {
2655 cur = ggml_norm(ctx0, inpCA, hparams.eps); // note: we use inpCA here
2656
2657 // cur = ln_0_w*cur + ln_0_b
2658 cur = ggml_add(ctx0,
2659 ggml_mul(ctx0,
2660 cur,
2661 layer.cross_attn_ln_0_w),
2662 layer.cross_attn_ln_0_b);
2663 }
2664
2665 // cross-attention
2666 {
2667 struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
2668 layer.cross_attn_q_w,
2669 cur);
2670
2671 Qcur = ggml_add(ctx0,
2672 Qcur,
2673 layer.cross_attn_q_b);
2674
2675 struct ggml_tensor * Q =
2676 ggml_permute(ctx0,
2677 ggml_reshape_3d(ctx0, Qcur, n_state_head, n_head, n_tokens),
2678 0, 2, 1, 3);
2679
2680 if (wctx.params.flash_attn) {
2681 struct ggml_tensor * Kcross =
2682 ggml_view_3d(ctx0, wstate.kv_cross.k,
2683 n_state_head, n_audio_ctx_pad, n_head,
2684 ggml_element_size(wstate.kv_cross.k)*n_state,
2685 ggml_element_size(wstate.kv_cross.k)*n_state_head,
2686 ggml_element_size(wstate.kv_cross.k)*n_state*n_audio_ctx_pad*il);
2687
2688 struct ggml_tensor * Vcross =
2689 ggml_view_3d(ctx0, wstate.kv_cross.v,
2690 n_state_head, n_audio_ctx_pad, n_head,
2691 ggml_element_size(wstate.kv_cross.v)*n_state,
2692 ggml_element_size(wstate.kv_cross.v)*n_state_head,
2693 ggml_element_size(wstate.kv_cross.v)*n_state*n_audio_ctx_pad*il);
2694
2695 cur = ggml_flash_attn_ext(ctx0, Q, Kcross, Vcross, nullptr, KQscale, 0.0f, 0.0f);
2696
2697 cur = ggml_reshape_2d(ctx0, cur, n_state, n_tokens);
2698 } else {
2699 struct ggml_tensor * Kcross =
2700 ggml_view_3d(ctx0, wstate.kv_cross.k,
2701 n_state_head, n_audio_ctx, n_head,
2702 ggml_element_size(wstate.kv_cross.k)*n_state,
2703 ggml_element_size(wstate.kv_cross.k)*n_state_head,
2704 ggml_element_size(wstate.kv_cross.k)*n_state*n_audio_ctx*il);
2705
2706 struct ggml_tensor * Vcross =
2707 ggml_view_3d(ctx0, wstate.kv_cross.v,
2708 n_audio_ctx, n_state_head, n_head,
2709 n_audio_ctx*ggml_element_size(wstate.kv_cross.v),
2710 n_audio_ctx*ggml_element_size(wstate.kv_cross.v)*n_state_head,
2711 n_audio_ctx*ggml_element_size(wstate.kv_cross.v)*n_state*il);
2712
2713 // ------
2714
2715 // K * Q
2716 struct ggml_tensor * KQ = ggml_mul_mat(ctx0, Kcross, Q);
2717
2718 struct ggml_tensor * KQ_soft_max = ggml_soft_max_ext(ctx0, KQ, nullptr, KQscale, 0.0f);
2719
2720 // [EXPERIMENTAL] Token-level timestamps with DTW
2721 if (wctx.params.dtw_token_timestamps) {
2722 if (wstate.aheads_masks.m[il] != nullptr) {
2723 struct ggml_tensor * aheads_KQs = ggml_reshape_2d(ctx0, KQ_soft_max, KQ_soft_max->ne[0] * KQ_soft_max->ne[1], KQ_soft_max->ne[2]);
2724 aheads_KQs = ggml_transpose(ctx0, aheads_KQs);
2725 aheads_KQs = ggml_cont(ctx0, aheads_KQs);
2726 aheads_KQs = ggml_mul_mat(ctx0, wstate.aheads_masks.m[il], aheads_KQs);
2727 aheads_KQs = ggml_transpose(ctx0, aheads_KQs);
2728 aheads_KQs = ggml_cont(ctx0, aheads_KQs);
2729 aheads_KQs = ggml_reshape_3d(ctx0, aheads_KQs, KQ_soft_max->ne[0], KQ_soft_max->ne[1], wstate.aheads_masks.m[il]->ne[1]);
2730 if (aheads_cross_QKs == NULL) {
2731 aheads_cross_QKs = aheads_KQs;
2732 } else {
2733 aheads_cross_QKs = ggml_concat(ctx0, aheads_cross_QKs, aheads_KQs, 2);
2734 }
2735 }
2736 }
2737
2738 struct ggml_tensor * KQV = ggml_mul_mat(ctx0, Vcross, KQ_soft_max);
2739
2740 struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
2741
2742 cur = ggml_cont_2d(ctx0, KQV_merged, n_state, n_tokens);
2743 }
2744 }
2745
2746 // projection
2747 {
2748 cur = ggml_mul_mat(ctx0,
2749 layer.cross_attn_ln_1_w,
2750 cur);
2751
2752 cur = ggml_add(ctx0,
2753 cur,
2754 layer.cross_attn_ln_1_b);
2755 }
2756
2757 // add the input
2758 cur = ggml_add(ctx0, cur, inpCA);
2759
2760 struct ggml_tensor * inpFF = cur;
2761
2762 // feed-forward network
2763 {
2764 // norm
2765 {
2766 cur = ggml_norm(ctx0, inpFF, hparams.eps);
2767
2768 // cur = mlp_ln_w*cur + mlp_ln_b
2769 cur = ggml_add(ctx0,
2770 ggml_mul(ctx0,
2771 cur,
2772 layer.mlp_ln_w),
2773 layer.mlp_ln_b);
2774 }
2775
2776 // fully connected
2777 cur = ggml_mul_mat(ctx0,
2778 layer.mlp_0_w,
2779 cur);
2780
2781 cur = ggml_add(ctx0,
2782 cur,
2783 layer.mlp_0_b);
2784
2785 // GELU activation
2786 cur = ggml_gelu(ctx0, cur);
2787
2788 // projection
2789 cur = ggml_mul_mat(ctx0,
2790 layer.mlp_1_w,
2791 cur);
2792
2793 cur = ggml_add(ctx0,
2794 cur,
2795 layer.mlp_1_b);
2796 }
2797
2798 inpL = ggml_add(ctx0, cur, inpFF);
2799 }
2800
2801 cur = inpL;
2802
2803 // norm
2804 {
2805 cur = ggml_norm(ctx0, cur, hparams.eps);
2806
2807 cur = ggml_add(ctx0,
2808 ggml_mul(ctx0,
2809 cur,
2810 model.d_ln_w),
2811 model.d_ln_b);
2812 }
2813
2814 // compute logits only for the last token
2815 // comment this line to compute logits for all n_tokens
2816 // might be useful in the future
2817 //cur = ggml_view_2d(ctx0, cur, cur->ne[0], 1, cur->nb[1], (cur->ne[1] - 1)*cur->nb[1]);
2818
2819 struct ggml_tensor * logits = ggml_mul_mat(ctx0, model.d_te, cur);
2820
2821 // [EXPERIMENTAL] Token-level timestamps with DTW
2822 if (wctx.params.dtw_token_timestamps && aheads_cross_QKs != nullptr) {
2823 aheads_cross_QKs = ggml_transpose(ctx0, aheads_cross_QKs);
2824 aheads_cross_QKs = ggml_cont(ctx0, aheads_cross_QKs);
2825 if (save_alignment_heads_QKs) {
2826 ggml_build_forward_expand(gf, aheads_cross_QKs);
2827 wstate.aheads_cross_QKs = aheads_cross_QKs;
2828 }
2829 }
2830
2831 ggml_build_forward_expand(gf, logits);
2832
2833 ggml_free(ctx0);
2834
2835 return gf;
2836 }
2837
2838 // evaluate the decoder
2839 //
2840 // given text prompt + audio features -> computes the logits for the next token
2841 //
2842 // - model: the model
2843 // - n_threads: number of threads to use
2844 // - tokens: text prompt
2845 // - n_tokens: number of tokens in the prompt
2846 // - n_past: number of past tokens to prefix the prompt with
2847 //
2848 static bool whisper_decode_internal(
2849 whisper_context & wctx,
2850 whisper_state & wstate,
2851 const whisper_batch & batch,
2852 const int n_threads,
2853 bool save_alignment_heads_QKs,
2854 ggml_abort_callback abort_callback,
2855 void * abort_callback_data) {
2856 const int64_t t_start_us = ggml_time_us();
2857
2858 const auto & model = wctx.model;
2859 const auto & hparams = model.hparams;
2860
2861 const int n_vocab = hparams.n_vocab;
2862 const int n_tokens = batch.n_tokens;
2863
2864 auto & logits_out = wstate.logits;
2865
2866 struct ggml_tensor * logits;
2867
2868 // find KV slot for the batch
2869 {
2870 auto & kv_self = wstate.kv_self;
2871
2872 if (!whisper_kv_cache_find_slot(kv_self, batch)) {
2873 return false;
2874 }
2875
2876 const uint32_t pad = whisper_kv_cache_get_padding(wctx);
2877 kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(whisper_kv_cache_cell_max(kv_self), pad)));
2878
2879 //kv_self.n = std::min((int32_t) hparams.n_text_ctx, std::max(32, whisper_kv_cache_cell_max(kv_self)));
2880 //printf("n_tokens = %5d, kv_self.head = %5d, kv_self.n = %5d, seq_id = %5d\n", batch.n_tokens, kv_self.head, kv_self.n, batch.seq_id[0][0]);
2881 }
2882
2883 // decoder
2884 {
2885 auto & sched = wstate.sched_decode.sched;
2886
2887 ggml_cgraph * gf = whisper_build_graph_decoder(wctx, wstate, batch, save_alignment_heads_QKs, false);
2888
2889 if (!ggml_backend_sched_alloc_graph(sched, gf)) {
2890 // should never happen as we pre-allocate the memory
2891 return false;
2892 }
2893
2894 // set the inputs
2895 {
2896 struct ggml_tensor * embd = ggml_graph_get_tensor(gf, "embd");
2897 ggml_backend_tensor_set(embd, batch.token, 0, n_tokens*ggml_element_size(embd));
2898 }
2899
2900 {
2901 struct ggml_tensor * position = ggml_graph_get_tensor(gf, "position");
2902 for (int i = 0; i < n_tokens; ++i) {
2903 const int32_t val = batch.pos[i];
2904 ggml_backend_tensor_set(position, &val, i*sizeof(int32_t), sizeof(int32_t));
2905 }
2906 }
2907
2908 {
2909 struct ggml_tensor * KQ_mask = ggml_graph_get_tensor(gf, "KQ_mask");
2910
2911 auto & kv_self = wstate.kv_self;
2912
2913 const int32_t n_kv = kv_self.n;
2914
2915 wstate.inp_mask.resize(ggml_nelements(KQ_mask));
2916
2917 float * data = wstate.inp_mask.data();
2918 memset(data, 0, ggml_nbytes(KQ_mask));
2919
2920 for (int h = 0; h < 1; ++h) {
2921 for (int j = 0; j < n_tokens; ++j) {
2922 const whisper_pos pos = batch.pos[j];
2923 const whisper_seq_id seq_id = batch.seq_id[j][0];
2924
2925 for (int i = 0; i < n_kv; ++i) {
2926 if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
2927 data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
2928 }
2929 }
2930 }
2931
2932 for (int i = n_tokens; i < n_tokens; ++i) {
2933 for (int j = 0; j < n_kv; ++j) {
2934 data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
2935 }
2936 }
2937 }
2938
2939 ggml_backend_tensor_set(KQ_mask, wstate.inp_mask.data(), 0, ggml_nelements(KQ_mask)*sizeof(float));
2940 }
2941
2942 logits = ggml_graph_node(gf, -1);
2943
2944 if (!ggml_graph_compute_helper(sched, gf, n_threads)) {
2945 return false;
2946 }
2947 }
2948
2949 logits_out.resize(n_tokens*n_vocab);
2950 for (int i = 0; i < n_tokens; i++) {
2951 if (batch.logits[i] == 0) {
2952 continue;
2953 }
2954 ggml_backend_tensor_get(logits, logits_out.data() + (n_vocab*i), sizeof(float)*(n_vocab*i), sizeof(float)*n_vocab);
2955 }
2956
2957 if (batch.n_tokens > 1) {
2958 //printf("%s: used_mem = %f MB, %f MB, %f MB %f MB %f MB\n", __func__,
2959 // ggml_used_mem(ctx0)/1e6,
2960 // wstate.get_buf_max_mem(0)/1e6,
2961 // wstate.get_buf_max_mem(1)/1e6,
2962 // wstate.get_buf_max_mem(2)/1e6,
2963 // wstate.get_buf_max_mem(3)/1e6);
2964 }
2965
2966 if (batch.n_tokens == 1) {
2967 wstate.t_decode_us += ggml_time_us() - t_start_us;
2968 wstate.n_decode++;
2969 } else if (batch.n_tokens < 16) {
2970 wstate.t_batchd_us += ggml_time_us() - t_start_us;
2971 wstate.n_batchd += n_tokens;
2972 } else {
2973 wstate.t_prompt_us += ggml_time_us() - t_start_us;
2974 wstate.n_prompt += n_tokens;
2975 }
2976
2977 return !(abort_callback && abort_callback(abort_callback_data));
2978 }
2979
2980 // 500 -> 00:05.000
2981 // 6000 -> 01:00.000
2982 static std::string to_timestamp(int64_t t, bool comma = false) {
2983 int64_t msec = t * 10;
2984 int64_t hr = msec / (1000 * 60 * 60);
2985 msec = msec - hr * (1000 * 60 * 60);
2986 int64_t min = msec / (1000 * 60);
2987 msec = msec - min * (1000 * 60);
2988 int64_t sec = msec / 1000;
2989 msec = msec - sec * 1000;
2990
2991 char buf[32];
2992 snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int) hr, (int) min, (int) sec, comma ? "," : ".", (int) msec);
2993
2994 return std::string(buf);
2995 }
2996
2997 #define SIN_COS_N_COUNT WHISPER_N_FFT
2998 namespace {
2999 struct whisper_global_cache {
3000 // In FFT, we frequently use sine and cosine operations with the same values.
3001 // We can use precalculated values to speed up the process.
3002 float sin_vals[SIN_COS_N_COUNT];
3003 float cos_vals[SIN_COS_N_COUNT];
3004
3005 // Hann window (Use cosf to eliminate difference)
3006 // ref: https://pytorch.org/docs/stable/generated/torch.hann_window.html
3007 // ref: https://github.com/openai/whisper/blob/main/whisper/audio.py#L147
3008 float hann_window[WHISPER_N_FFT];
3009
3010 whisper_global_cache() {
3011 fill_sin_cos_table();
3012 fill_hann_window(sizeof(hann_window)/sizeof(hann_window[0]), true, hann_window);
3013 }
3014
3015 void fill_sin_cos_table() {
3016 for (int i = 0; i < SIN_COS_N_COUNT; i++) {
3017 double theta = (2 * M_PI * i) / SIN_COS_N_COUNT;
3018 sin_vals[i] = sinf(theta);
3019 cos_vals[i] = cosf(theta);
3020 }
3021 }
3022
3023 void fill_hann_window(int length, bool periodic, float * output) {
3024 int offset = -1;
3025 if (periodic) {
3026 offset = 0;
3027 }
3028 for (int i = 0; i < length; i++) {
3029 output[i] = 0.5 * (1.0 - cosf((2.0 * M_PI * i) / (length + offset)));
3030 }
3031 }
3032 } global_cache;
3033 }
3034
3035 // naive Discrete Fourier Transform
3036 // input is real-valued
3037 // output is complex-valued
3038 static void dft(const float* in, int N, float* out) {
3039 const int sin_cos_step = SIN_COS_N_COUNT / N;
3040
3041 for (int k = 0; k < N; k++) {
3042 float re = 0;
3043 float im = 0;
3044
3045 for (int n = 0; n < N; n++) {
3046 int idx = (k * n * sin_cos_step) % (SIN_COS_N_COUNT); // t = 2*M_PI*k*n/N
3047 re += in[n]*global_cache.cos_vals[idx]; // cos(t)
3048 im -= in[n]*global_cache.sin_vals[idx]; // sin(t)
3049 }
3050
3051 out[k*2 + 0] = re;
3052 out[k*2 + 1] = im;
3053 }
3054 }
3055
3056 // Cooley-Tukey FFT
3057 // poor man's implementation - use something better
3058 // input is real-valued
3059 // output is complex-valued
3060 static void fft(float* in, int N, float* out) {
3061 if (N == 1) {
3062 out[0] = in[0];
3063 out[1] = 0;
3064 return;
3065 }
3066
3067 const int half_N = N / 2;
3068 if (N - half_N*2 == 1) {
3069 dft(in, N, out);
3070 return;
3071 }
3072
3073 float* even = in + N;
3074 for (int i = 0; i < half_N; ++i) {
3075 even[i]= in[2*i];
3076 }
3077 float* even_fft = out + 2 * N;
3078 fft(even, half_N, even_fft);
3079
3080 float* odd = even;
3081 for (int i = 0; i < half_N; ++i) {
3082 odd[i] = in[2*i + 1];
3083 }
3084 float* odd_fft = even_fft + N;
3085 fft(odd, half_N, odd_fft);
3086
3087 const int sin_cos_step = SIN_COS_N_COUNT / N;
3088 for (int k = 0; k < half_N; k++) {
3089 int idx = k * sin_cos_step; // t = 2*M_PI*k/N
3090 float re = global_cache.cos_vals[idx]; // cos(t)
3091 float im = -global_cache.sin_vals[idx]; // sin(t)
3092
3093 float re_odd = odd_fft[2*k + 0];
3094 float im_odd = odd_fft[2*k + 1];
3095
3096 out[2*k + 0] = even_fft[2*k + 0] + re*re_odd - im*im_odd;
3097 out[2*k + 1] = even_fft[2*k + 1] + re*im_odd + im*re_odd;
3098
3099 out[2*(k + half_N) + 0] = even_fft[2*k + 0] - re*re_odd + im*im_odd;
3100 out[2*(k + half_N) + 1] = even_fft[2*k + 1] - re*im_odd - im*re_odd;
3101 }
3102 }
3103
3104 static void log_mel_spectrogram_worker_thread(int ith, const float * hann, const std::vector<float> & samples,
3105 int n_samples, int frame_size, int frame_step, int n_threads,
3106 const whisper_filters & filters, whisper_mel & mel) {
3107 std::vector<float> fft_in(frame_size * 2, 0.0);
3108 std::vector<float> fft_out(frame_size * 2 * 2 * 2);
3109
3110 int n_fft = filters.n_fft;
3111 int i = ith;
3112
3113 // make sure n_fft == 1 + (WHISPER_N_FFT / 2), bin_0 to bin_nyquist
3114 assert(n_fft == 1 + (frame_size / 2));
3115
3116 // calculate FFT only when fft_in are not all zero
3117 for (; i < std::min(n_samples / frame_step + 1, mel.n_len); i += n_threads) {
3118 const int offset = i * frame_step;
3119
3120 // apply Hann window (~10% faster)
3121 for (int j = 0; j < std::min(frame_size, n_samples - offset); j++) {
3122 fft_in[j] = hann[j] * samples[offset + j];
3123 }
3124
3125 // fill the rest with zeros
3126 if (n_samples - offset < frame_size) {
3127 std::fill(fft_in.begin() + (n_samples - offset), fft_in.end(), 0.0);
3128 }
3129
3130 // FFT
3131 fft(fft_in.data(), frame_size, fft_out.data());
3132
3133 // Calculate modulus^2 of complex numbers
3134 // Use pow(fft_out[2 * j + 0], 2) + pow(fft_out[2 * j + 1], 2) causes inference quality problem? Interesting.
3135 for (int j = 0; j < n_fft; j++) {
3136 fft_out[j] = (fft_out[2 * j + 0] * fft_out[2 * j + 0] + fft_out[2 * j + 1] * fft_out[2 * j + 1]);
3137 }
3138
3139 // mel spectrogram
3140 for (int j = 0; j < mel.n_mel; j++) {
3141 double sum = 0.0;
3142 // unroll loop (suggested by GH user @lunixbochs)
3143 int k = 0;
3144 for (k = 0; k < n_fft - 3; k += 4) {
3145 sum +=
3146 fft_out[k + 0] * filters.data[j * n_fft + k + 0] +
3147 fft_out[k + 1] * filters.data[j * n_fft + k + 1] +
3148 fft_out[k + 2] * filters.data[j * n_fft + k + 2] +
3149 fft_out[k + 3] * filters.data[j * n_fft + k + 3];
3150 }
3151 // handle n_fft remainder
3152 for (; k < n_fft; k++) {
3153 sum += fft_out[k] * filters.data[j * n_fft + k];
3154 }
3155 sum = log10(std::max(sum, 1e-10));
3156 mel.data[j * mel.n_len + i] = sum;
3157 }
3158 }
3159
3160 // Otherwise fft_out are all zero
3161 double sum = log10(1e-10);
3162 for (; i < mel.n_len; i += n_threads) {
3163 for (int j = 0; j < mel.n_mel; j++) {
3164 mel.data[j * mel.n_len + i] = sum;
3165 }
3166 }
3167 }
3168
3169 // ref: https://github.com/openai/whisper/blob/main/whisper/audio.py#L110-L157
3170 static bool log_mel_spectrogram(
3171 whisper_state & wstate,
3172 const float * samples,
3173 const int n_samples,
3174 const int /*sample_rate*/,
3175 const int frame_size,
3176 const int frame_step,
3177 const int n_mel,
3178 const int n_threads,
3179 const whisper_filters & filters,
3180 const bool debug,
3181 whisper_mel & mel) {
3182 const int64_t t_start_us = ggml_time_us();
3183
3184 // Hann window
3185 WHISPER_ASSERT(frame_size == WHISPER_N_FFT && "Unsupported frame_size");
3186 const float * hann = global_cache.hann_window;
3187
3188 // Calculate the length of padding
3189 int64_t stage_1_pad = WHISPER_SAMPLE_RATE * 30;
3190 int64_t stage_2_pad = frame_size / 2;
3191
3192 // Initialize a vector and copy data from C array to it.
3193 std::vector<float> samples_padded;
3194 samples_padded.resize(n_samples + stage_1_pad + stage_2_pad * 2);
3195 std::copy(samples, samples + n_samples, samples_padded.begin() + stage_2_pad);
3196
3197 // pad 30 seconds of zeros at the end of audio (480,000 samples) + reflective pad 200 samples at the end of audio
3198 std::fill(samples_padded.begin() + n_samples + stage_2_pad, samples_padded.begin() + n_samples + stage_1_pad + 2 * stage_2_pad, 0);
3199
3200 // reflective pad 200 samples at the beginning of audio
3201 std::reverse_copy(samples + 1, samples + 1 + stage_2_pad, samples_padded.begin());
3202
3203 mel.n_mel = n_mel;
3204 // https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/SpectralOps.cpp#L936
3205 // Calculate number of frames + remove the last frame
3206 mel.n_len = (samples_padded.size() - frame_size) / frame_step;
3207 // Calculate semi-padded sample length to ensure compatibility
3208 mel.n_len_org = 1 + (n_samples + stage_2_pad - frame_size) / frame_step;
3209 mel.data.resize(mel.n_mel * mel.n_len);
3210
3211 {
3212 std::vector<std::thread> workers(n_threads - 1);
3213 for (int iw = 0; iw < n_threads - 1; ++iw) {
3214 workers[iw] = std::thread(
3215 log_mel_spectrogram_worker_thread, iw + 1, hann, std::cref(samples_padded),
3216 n_samples + stage_2_pad, frame_size, frame_step, n_threads,
3217 std::cref(filters), std::ref(mel));
3218 }
3219
3220 // main thread
3221 log_mel_spectrogram_worker_thread(0, hann, samples_padded, n_samples + stage_2_pad, frame_size, frame_step, n_threads, filters, mel);
3222
3223 for (int iw = 0; iw < n_threads - 1; ++iw) {
3224 workers[iw].join();
3225 }
3226 }
3227
3228 // clamping and normalization
3229 double mmax = -1e20;
3230 for (int i = 0; i < mel.n_mel*mel.n_len; i++) {
3231 if (mel.data[i] > mmax) {
3232 mmax = mel.data[i];
3233 }
3234 }
3235
3236 mmax -= 8.0;
3237
3238 for (int i = 0; i < mel.n_mel*mel.n_len; i++) {
3239 if (mel.data[i] < mmax) {
3240 mel.data[i] = mmax;
3241 }
3242
3243 mel.data[i] = (mel.data[i] + 4.0)/4.0;
3244 }
3245
3246 wstate.t_mel_us += ggml_time_us() - t_start_us;
3247
3248 // Dump log_mel_spectrogram
3249 if (debug) {
3250 std::ofstream outFile("log_mel_spectrogram.json");
3251 outFile << "[";
3252 for (uint64_t i = 0; i < mel.data.size() - 1; i++) {
3253 outFile << mel.data[i] << ", ";
3254 }
3255 outFile << mel.data[mel.data.size() - 1] << "]";
3256 outFile.close();
3257 }
3258
3259 return true;
3260 }
3261
3262 // split text into tokens
3263 //
3264 // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
3265 //
3266 // Regex (Python):
3267 // r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
3268 //
3269 // Regex (C++):
3270 // R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)"
3271 //
3272 static std::vector<whisper_vocab::id> tokenize(const whisper_vocab & vocab, const std::string & text) {
3273 std::vector<std::string> words;
3274
3275 // first split the text into words
3276 {
3277 std::string str = text;
3278 std::string pat = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
3279
3280 std::regex re(pat);
3281 std::smatch m;
3282
3283 while (std::regex_search(str, m, re)) {
3284 for (auto x : m) {
3285 words.push_back(x);
3286 }
3287 str = m.suffix();
3288 }
3289 }
3290
3291 // find the longest tokens that form the words:
3292 std::vector<whisper_vocab::id> tokens;
3293 for (const auto & word : words) {
3294 if (word.empty()) continue;
3295
3296 int i = 0;
3297 int n = word.size();
3298 while (i < n) {
3299 int j = n;
3300 bool found = false;
3301 while (j > i) {
3302 auto sub = word.substr(i, j-i);
3303 auto it = vocab.token_to_id.find(sub);
3304 if (it != vocab.token_to_id.end()) {
3305 tokens.push_back(it->second);
3306 i = j;
3307 found = true;
3308 break;
3309 }
3310 --j;
3311 }
3312 if (!found) {
3313 WHISPER_LOG_ERROR("unknown token\n");
3314 ++i;
3315 }
3316 }
3317 }
3318
3319 return tokens;
3320 }
3321
3322 //
3323 // interface implementation
3324 //
3325
3326 #ifdef WHISPER_USE_COREML
3327 // replace .bin with -encoder.mlmodelc
3328 static std::string whisper_get_coreml_path_encoder(std::string path_bin) {
3329 auto pos = path_bin.rfind('.');
3330 if (pos != std::string::npos) {
3331 path_bin = path_bin.substr(0, pos);
3332 }
3333
3334 // match "-qx_x"
3335 pos = path_bin.rfind('-');
3336 if (pos != std::string::npos) {
3337 auto sub = path_bin.substr(pos);
3338 if (sub.size() == 5 && sub[1] == 'q' && sub[3] == '_') {
3339 path_bin = path_bin.substr(0, pos);
3340 }
3341 }
3342
3343 path_bin += "-encoder.mlmodelc";
3344
3345 return path_bin;
3346 }
3347 #endif
3348
3349 #ifdef WHISPER_USE_OPENVINO
3350 // replace .bin with-encoder-openvino.xml
3351 static std::string whisper_openvino_get_path_encoder(std::string path_bin) {
3352 auto pos = path_bin.rfind('.');
3353 if (pos != std::string::npos) {
3354 path_bin = path_bin.substr(0, pos);
3355 }
3356
3357 path_bin += "-encoder-openvino.xml";
3358
3359 return path_bin;
3360 }
3361
3362 static std::string whisper_openvino_get_path_cache(std::string path_bin) {
3363 auto pos = path_bin.rfind('.');
3364 if (pos != std::string::npos) {
3365 path_bin = path_bin.substr(0, pos);
3366 }
3367
3368 path_bin += "-encoder-openvino-cache";
3369
3370 return path_bin;
3371 }
3372 #endif
3373
3374 struct whisper_state * whisper_init_state(whisper_context * ctx) {
3375 whisper_state * state = new whisper_state;
3376
3377 state->backends = whisper_backend_init(ctx->params);
3378 if (state->backends.empty()) {
3379 WHISPER_LOG_ERROR("%s: whisper_backend_init() failed\n", __func__);
3380 whisper_free_state(state);
3381 return nullptr;
3382 }
3383
3384 // at this point, we don't know yet how many decoders will be used
3385 // later during decoding, if more decoders are used, we will recreate the KV cache respectively
3386 state->kv_self_n_dec = 1;
3387 if (!whisper_kv_cache_init(state->kv_self, state->backends[0], ctx->itype,
3388 ctx->model.hparams.n_text_state,
3389 ctx->model.hparams.n_text_layer,
3390 GGML_PAD(ctx->model.hparams.n_text_ctx, 256))) {
3391 WHISPER_LOG_ERROR("%s: whisper_kv_cache_init() failed for self-attention cache\n", __func__);
3392 whisper_free_state(state);
3393 return nullptr;
3394 }
3395
3396 {
3397 const size_t memory_size = ggml_nbytes(state->kv_self.k) + ggml_nbytes(state->kv_self.v);
3398 WHISPER_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1e6);
3399 }
3400
3401 if (!whisper_kv_cache_init(state->kv_cross, state->backends[0], ctx->itype,
3402 ctx->model.hparams.n_text_state,
3403 ctx->model.hparams.n_text_layer,
3404 GGML_PAD(ctx->model.hparams.n_audio_ctx, 256))) {
3405 WHISPER_LOG_ERROR("%s: whisper_kv_cache_init() failed for cross-attention cache\n", __func__);
3406 whisper_free_state(state);
3407 return nullptr;
3408 }
3409
3410 {
3411 const size_t memory_size = ggml_nbytes(state->kv_cross.k) + ggml_nbytes(state->kv_cross.v);
3412 WHISPER_LOG_INFO("%s: kv cross size = %7.2f MB\n", __func__, memory_size / 1e6);
3413 }
3414
3415 if (!whisper_kv_cache_init(state->kv_pad, state->backends[0], ctx->itype,
3416 ctx->model.hparams.n_audio_state,
3417 1,
3418 GGML_PAD(ctx->model.hparams.n_audio_ctx, 256))) {
3419 WHISPER_LOG_ERROR("%s: whisper_kv_cache_init() failed for self-attention cache\n", __func__);
3420 whisper_free_state(state);
3421 return nullptr;
3422 }
3423
3424 {
3425 const size_t memory_size = ggml_nbytes(state->kv_pad.k) + ggml_nbytes(state->kv_pad.v);
3426 WHISPER_LOG_INFO("%s: kv pad size = %7.2f MB\n", __func__, memory_size / 1e6);
3427 }
3428
3429 // [EXPERIMENTAL] Token-level timestamps with DTW
3430 if (ctx->params.dtw_token_timestamps) {
3431 if (!aheads_masks_init(ctx->params, ctx->model.hparams, state->aheads_masks, state->backends[0])) {
3432 WHISPER_LOG_ERROR("%s: aheads_masks_init() failed for alignment heads masks\n", __func__);
3433 whisper_free_state(state);
3434 return nullptr;
3435 }
3436 const size_t memory_size = aheads_masks_nbytes(state->aheads_masks);
3437 WHISPER_LOG_INFO("%s: alignment heads masks size = %ld B\n", __func__, memory_size);
3438 }
3439
3440 #ifdef WHISPER_USE_COREML
3441 const auto path_coreml = whisper_get_coreml_path_encoder(ctx->path_model);
3442
3443 WHISPER_LOG_INFO("%s: loading Core ML model from '%s'\n", __func__, path_coreml.c_str());
3444 WHISPER_LOG_INFO("%s: first run on a device may take a while ...\n", __func__);
3445
3446 state->ctx_coreml = whisper_coreml_init(path_coreml.c_str());
3447 if (!state->ctx_coreml) {
3448 WHISPER_LOG_ERROR("%s: failed to load Core ML model from '%s'\n", __func__, path_coreml.c_str());
3449 #ifndef WHISPER_COREML_ALLOW_FALLBACK
3450 whisper_free_state(state);
3451 return nullptr;
3452 #endif
3453 } else {
3454 WHISPER_LOG_INFO("%s: Core ML model loaded\n", __func__);
3455 }
3456 #endif
3457
3458 state->logits.reserve(ctx->vocab.n_vocab * ctx->model.hparams.n_text_ctx);
3459
3460 state->batch = whisper_batch_init(ctx->model.hparams.n_text_ctx, WHISPER_MAX_DECODERS);
3461
3462 // TAGS: WHISPER_DECODER_INIT
3463 state->decoders[0].sequence.tokens.reserve(ctx->model.hparams.n_text_ctx);
3464
3465 state->decoders[0].probs.reserve (ctx->vocab.n_vocab);
3466 state->decoders[0].logits.reserve (ctx->vocab.n_vocab);
3467 state->decoders[0].logprobs.reserve (ctx->vocab.n_vocab);
3468 state->decoders[0].logits_id.reserve(ctx->model.hparams.n_vocab);
3469
3470 state->decoders[0].rng = std::mt19937(0);
3471
3472 // conv allocator
3473 {
3474 bool ok = whisper_sched_graph_init(state->sched_conv, state->backends,
3475 [&]() {
3476 return whisper_build_graph_conv(*ctx, *state);
3477 });
3478
3479 if (!ok) {
3480 WHISPER_LOG_ERROR("%s: failed to init conv allocator\n", __func__);
3481 whisper_free_state(state);
3482 return nullptr;
3483 }
3484
3485 WHISPER_LOG_INFO("%s: compute buffer (conv) = %7.2f MB\n", __func__, whisper_sched_size(state->sched_conv) / 1e6);
3486 }
3487
3488 // encoder allocator
3489 if (!whisper_encode_external(*state)) {
3490 bool ok = whisper_sched_graph_init(state->sched_encode, state->backends,
3491 [&]() {
3492 return whisper_build_graph_encoder(*ctx, *state);
3493 });
3494
3495 if (!ok) {
3496 WHISPER_LOG_ERROR("%s: failed to init encoder allocator\n", __func__);
3497 whisper_free_state(state);
3498 return nullptr;
3499 }
3500
3501 WHISPER_LOG_INFO("%s: compute buffer (encode) = %7.2f MB\n", __func__, whisper_sched_size(state->sched_encode) / 1e6);
3502 }
3503
3504 // cross allocator
3505 {
3506 bool ok = whisper_sched_graph_init(state->sched_cross, state->backends,
3507 [&]() {
3508 return whisper_build_graph_cross(*ctx, *state);
3509 });
3510
3511 if (!ok) {
3512 WHISPER_LOG_ERROR("%s: failed to init cross allocator\n", __func__);
3513 whisper_free_state(state);
3514 return nullptr;
3515 }
3516
3517 WHISPER_LOG_INFO("%s: compute buffer (cross) = %7.2f MB\n", __func__, whisper_sched_size(state->sched_cross) / 1e6);
3518 }
3519
3520 // decoder allocator
3521 {
3522 bool ok = whisper_sched_graph_init(state->sched_decode, state->backends,
3523 [&]() {
3524 const auto & hparams = ctx->model.hparams;
3525
3526 // TODO: make sure this is the worst-case scenario
3527 const int n_tokens = hparams.n_text_ctx;
3528 const int n_past = 0;
3529
3530 whisper_batch_prep_legacy(state->batch, nullptr, n_tokens, n_past, 0);
3531
3532 return whisper_build_graph_decoder(*ctx, *state, state->batch, ctx->params.dtw_token_timestamps, true);
3533 });
3534
3535 if (!ok) {
3536 WHISPER_LOG_ERROR("%s: failed to init decoder allocator\n", __func__);
3537 whisper_free_state(state);
3538 return nullptr;
3539 }
3540
3541 WHISPER_LOG_INFO("%s: compute buffer (decode) = %7.2f MB\n", __func__, whisper_sched_size(state->sched_decode) / 1e6);
3542 }
3543
3544 return state;
3545 }
3546
3547 int whisper_ctx_init_openvino_encoder_with_state(
3548 struct whisper_context * ctx,
3549 struct whisper_state * state,
3550 const char * model_path,
3551 const char * device,
3552 const char * cache_dir) {
3553 #ifndef WHISPER_USE_OPENVINO
3554 (void)(ctx);
3555 (void)(state);
3556 (void)(model_path);
3557 (void)(device);
3558 (void)(cache_dir);
3559
3560 return 1;
3561 #else
3562 if (!model_path && ctx->path_model.empty()) {
3563 WHISPER_LOG_ERROR("%s: model_path is nullptr, and ctx has no model_path set.\n", __func__);
3564 return 1;
3565 }
3566
3567 std::string path_encoder;
3568 if (!model_path) {
3569 //if model_path is not set, attempt to find it in the same directory as ggml-<model>.bin model
3570 path_encoder = whisper_openvino_get_path_encoder(ctx->path_model);
3571 } else {
3572 path_encoder = model_path;
3573 }
3574
3575 std::string path_cache;
3576 if (!cache_dir) {
3577 //if cache_dir is not set, set it as a dir residing next to ggml-<model>.bin
3578 path_cache = whisper_openvino_get_path_cache(ctx->path_model);
3579 } else {
3580 path_cache = cache_dir;
3581 }
3582
3583 WHISPER_LOG_INFO("%s: loading OpenVINO model from '%s'\n", __func__, path_encoder.c_str());
3584 WHISPER_LOG_INFO("%s: first run on a device may take a while ...\n", __func__);
3585
3586 state->ctx_openvino = whisper_openvino_init(path_encoder.c_str(), device, path_cache.c_str());
3587 if (!state->ctx_openvino) {
3588 WHISPER_LOG_ERROR("%s: failed to init OpenVINO encoder from '%s'\n", __func__, path_encoder.c_str());
3589 return 1;
3590 } else {
3591 WHISPER_LOG_INFO("%s: OpenVINO model loaded\n", __func__);
3592 }
3593
3594 return 0;
3595 #endif
3596 }
3597
3598 int whisper_ctx_init_openvino_encoder(
3599 struct whisper_context * ctx,
3600 const char * model_path,
3601 const char * device,
3602 const char * cache_dir) {
3603 return whisper_ctx_init_openvino_encoder_with_state(ctx, ctx->state, model_path, device, cache_dir);
3604 }
3605
3606 struct whisper_context_params whisper_context_default_params() {
3607 struct whisper_context_params result = {
3608 /*.use_gpu =*/ true,
3609 /*.flash_attn =*/ true,
3610 /*.gpu_device =*/ 0,
3611
3612 /*.dtw_token_timestamps =*/ false,
3613 /*.dtw_aheads_preset =*/ WHISPER_AHEADS_NONE,
3614 /*.dtw_n_top =*/ -1,
3615 /*.dtw_aheads =*/ {
3616 /*.n_heads =*/ 0,
3617 /*.heads =*/ NULL,
3618 },
3619 /*.dtw_mem_size =*/ 1024*1024*128,
3620 };
3621 return result;
3622 }
3623
3624 struct whisper_context * whisper_init_from_file_with_params_no_state(const char * path_model, struct whisper_context_params params) {
3625 WHISPER_LOG_INFO("%s: loading model from '%s'\n", __func__, path_model);
3626 #ifdef _MSC_VER
3627 // Convert UTF-8 path to wide string (UTF-16) for Windows, resolving character encoding issues.
3628 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
3629 std::wstring path_model_wide = converter.from_bytes(path_model);
3630 auto fin = std::ifstream(path_model_wide, std::ios::binary);
3631 #else
3632 auto fin = std::ifstream(path_model, std::ios::binary);
3633 #endif
3634 if (!fin) {
3635 WHISPER_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_model);
3636 return nullptr;
3637 }
3638
3639 whisper_model_loader loader = {};
3640
3641 loader.context = &fin;
3642
3643 loader.read = [](void * ctx, void * output, size_t read_size) {
3644 std::ifstream * fin = (std::ifstream*)ctx;
3645 fin->read((char *)output, read_size);
3646 return read_size;
3647 };
3648
3649 loader.eof = [](void * ctx) {
3650 std::ifstream * fin = (std::ifstream*)ctx;
3651 return fin->eof();
3652 };
3653
3654 loader.close = [](void * ctx) {
3655 std::ifstream * fin = (std::ifstream*)ctx;
3656 fin->close();
3657 };
3658
3659 auto ctx = whisper_init_with_params_no_state(&loader, params);
3660
3661 if (ctx) {
3662 ctx->path_model = path_model;
3663 }
3664
3665 return ctx;
3666 }
3667
3668 struct whisper_context * whisper_init_from_buffer_with_params_no_state(void * buffer, size_t buffer_size, struct whisper_context_params params) {
3669 struct buf_context {
3670 uint8_t* buffer;
3671 size_t size;
3672 size_t current_offset;
3673 };
3674
3675 buf_context ctx = { reinterpret_cast<uint8_t*>(buffer), buffer_size, 0 };
3676
3677 WHISPER_LOG_INFO("%s: loading model from buffer\n", __func__);
3678
3679 whisper_model_loader loader = {};
3680
3681 loader.context = &ctx;
3682
3683 loader.read = [](void * ctx, void * output, size_t read_size) {
3684 buf_context * buf = reinterpret_cast<buf_context *>(ctx);
3685
3686 size_t size_to_copy = buf->current_offset + read_size < buf->size ? read_size : buf->size - buf->current_offset;
3687
3688 memcpy(output, buf->buffer + buf->current_offset, size_to_copy);
3689 buf->current_offset += size_to_copy;
3690
3691 return size_to_copy;
3692 };
3693
3694 loader.eof = [](void * ctx) {
3695 buf_context * buf = reinterpret_cast<buf_context *>(ctx);
3696
3697 return buf->current_offset >= buf->size;
3698 };
3699
3700 loader.close = [](void * /*ctx*/) { };
3701
3702 return whisper_init_with_params_no_state(&loader, params);
3703 }
3704
3705 struct whisper_context * whisper_init_with_params_no_state(struct whisper_model_loader * loader, struct whisper_context_params params) {
3706 ggml_time_init();
3707
3708 if (params.flash_attn && params.dtw_token_timestamps) {
3709 WHISPER_LOG_WARN("%s: dtw_token_timestamps is not supported with flash_attn - disabling\n", __func__);
3710 params.dtw_token_timestamps = false;
3711 }
3712
3713 WHISPER_LOG_INFO("%s: use gpu = %d\n", __func__, params.use_gpu);
3714 WHISPER_LOG_INFO("%s: flash attn = %d\n", __func__, params.flash_attn);
3715 WHISPER_LOG_INFO("%s: gpu_device = %d\n", __func__, params.gpu_device);
3716 WHISPER_LOG_INFO("%s: dtw = %d\n", __func__, params.dtw_token_timestamps);
3717 WHISPER_LOG_INFO("%s: devices = %zu\n", __func__, ggml_backend_dev_count());
3718 WHISPER_LOG_INFO("%s: backends = %zu\n", __func__, ggml_backend_reg_count());
3719
3720 whisper_context * ctx = new whisper_context;
3721 ctx->params = params;
3722
3723 if (!whisper_model_load(loader, *ctx)) {
3724 loader->close(loader->context);
3725 WHISPER_LOG_ERROR("%s: failed to load model\n", __func__);
3726 delete ctx;
3727 return nullptr;
3728 }
3729
3730 loader->close(loader->context);
3731
3732 return ctx;
3733 }
3734
3735 struct whisper_context * whisper_init_from_file_with_params(const char * path_model, struct whisper_context_params params) {
3736 whisper_context * ctx = whisper_init_from_file_with_params_no_state(path_model, params);
3737 if (!ctx) {
3738 return nullptr;
3739 }
3740
3741 ctx->state = whisper_init_state(ctx);
3742 if (!ctx->state) {
3743 whisper_free(ctx);
3744 return nullptr;
3745 }
3746
3747 return ctx;
3748 }
3749
3750 struct whisper_context * whisper_init_from_buffer_with_params(void * buffer, size_t buffer_size, struct whisper_context_params params) {
3751 whisper_context * ctx = whisper_init_from_buffer_with_params_no_state(buffer, buffer_size, params);
3752 if (!ctx) {
3753 return nullptr;
3754 }
3755
3756 ctx->state = whisper_init_state(ctx);
3757 if (!ctx->state) {
3758 whisper_free(ctx);
3759 return nullptr;
3760 }
3761
3762 return ctx;
3763 }
3764
3765 struct whisper_context * whisper_init_with_params(struct whisper_model_loader * loader, struct whisper_context_params params) {
3766 whisper_context * ctx = whisper_init_with_params_no_state(loader, params);
3767 if (!ctx) {
3768 return nullptr;
3769 }
3770
3771 ctx->state = whisper_init_state(ctx);
3772 if (!ctx->state) {
3773 whisper_free(ctx);
3774 return nullptr;
3775 }
3776
3777 return ctx;
3778 }
3779
3780 struct whisper_context * whisper_init_from_file(const char * path_model) {
3781 return whisper_init_from_file_with_params(path_model, whisper_context_default_params());
3782 }
3783
3784 struct whisper_context * whisper_init_from_buffer(void * buffer, size_t buffer_size) {
3785 return whisper_init_from_buffer_with_params(buffer, buffer_size, whisper_context_default_params());
3786 }
3787
3788 struct whisper_context * whisper_init(struct whisper_model_loader * loader) {
3789 return whisper_init_with_params(loader, whisper_context_default_params());
3790 }
3791
3792 struct whisper_context * whisper_init_from_file_no_state(const char * path_model) {
3793 return whisper_init_from_file_with_params_no_state(path_model, whisper_context_default_params());
3794 }
3795
3796 struct whisper_context * whisper_init_from_buffer_no_state(void * buffer, size_t buffer_size) {
3797 return whisper_init_from_buffer_with_params_no_state(buffer, buffer_size, whisper_context_default_params());
3798 }
3799
3800 struct whisper_context * whisper_init_no_state(struct whisper_model_loader * loader) {
3801 return whisper_init_with_params_no_state(loader, whisper_context_default_params());
3802 }
3803
3804 void whisper_free_state(struct whisper_state * state) {
3805 if (state) {
3806 whisper_kv_cache_free(state->kv_self);
3807 whisper_kv_cache_free(state->kv_cross);
3808 whisper_kv_cache_free(state->kv_pad);
3809
3810 #ifdef WHISPER_USE_COREML
3811 if (state->ctx_coreml != nullptr) {
3812 whisper_coreml_free(state->ctx_coreml);
3813 state->ctx_coreml = nullptr;
3814 }
3815 #endif
3816
3817 #ifdef WHISPER_USE_OPENVINO
3818 if (state->ctx_openvino != nullptr) {
3819 whisper_openvino_free(state->ctx_openvino);
3820 state->ctx_openvino = nullptr;
3821 }
3822 #endif
3823
3824 whisper_batch_free(state->batch);
3825
3826 ggml_backend_sched_free(state->sched_conv.sched);
3827 ggml_backend_sched_free(state->sched_encode.sched);
3828 ggml_backend_sched_free(state->sched_cross.sched);
3829 ggml_backend_sched_free(state->sched_decode.sched);
3830
3831 for (auto & backend : state->backends) {
3832 ggml_backend_free(backend);
3833 }
3834
3835 // [EXPERIMENTAL] Token-level timestamps with DTW
3836 aheads_masks_free(state->aheads_masks);
3837
3838 if (state->vad_context != nullptr) {
3839 whisper_vad_free(state->vad_context);
3840 state->vad_context = nullptr;
3841 }
3842
3843 delete state;
3844 }
3845 }
3846
3847 void whisper_free(struct whisper_context * ctx) {
3848 if (ctx) {
3849 for (ggml_context * context : ctx->model.ctxs) {
3850 ggml_free(context);
3851 }
3852
3853 for (ggml_backend_buffer_t buf : ctx->model.buffers) {
3854 ggml_backend_buffer_free(buf);
3855 }
3856
3857 whisper_free_state(ctx->state);
3858
3859 delete ctx;
3860 }
3861 }
3862
3863 void whisper_free_context_params(struct whisper_context_params * params) {
3864 if (params) {
3865 delete params;
3866 }
3867 }
3868
3869 void whisper_free_params(struct whisper_full_params * params) {
3870 if (params) {
3871 delete params;
3872 }
3873 }
3874
3875 int whisper_pcm_to_mel_with_state(struct whisper_context * ctx, struct whisper_state * state, const float * samples, int n_samples, int n_threads) {
3876 if (!log_mel_spectrogram(*state, samples, n_samples, WHISPER_SAMPLE_RATE, WHISPER_N_FFT, WHISPER_HOP_LENGTH, ctx->model.filters.n_mel, n_threads, ctx->model.filters, false, state->mel)) {
3877 WHISPER_LOG_ERROR("%s: failed to compute mel spectrogram\n", __func__);
3878 return -1;
3879 }
3880
3881 return 0;
3882 }
3883
3884 int whisper_pcm_to_mel(struct whisper_context * ctx, const float * samples, int n_samples, int n_threads) {
3885 return whisper_pcm_to_mel_with_state(ctx, ctx->state, samples, n_samples, n_threads);
3886 }
3887
3888 int whisper_set_mel_with_state(
3889 struct whisper_context * ctx,
3890 struct whisper_state * state,
3891 const float * data,
3892 int n_len,
3893 int n_mel) {
3894 if (n_mel != ctx->model.filters.n_mel) {
3895 WHISPER_LOG_ERROR("%s: invalid number of mel bands: %d (expected %d)\n", __func__, n_mel, ctx->model.filters.n_mel);
3896 return -1;
3897 }
3898
3899 state->mel.n_len = n_len;
3900 state->mel.n_len_org = n_len;
3901 state->mel.n_mel = n_mel;
3902
3903 state->mel.data.resize(n_len*n_mel);
3904 memcpy(state->mel.data.data(), data, n_len*n_mel*sizeof(float));
3905
3906 return 0;
3907 }
3908
3909 int whisper_set_mel(
3910 struct whisper_context * ctx,
3911 const float * data,
3912 int n_len,
3913 int n_mel) {
3914 return whisper_set_mel_with_state(ctx, ctx->state, data, n_len, n_mel);
3915 }
3916
3917 int whisper_encode_with_state(struct whisper_context * ctx, struct whisper_state * state, int offset, int n_threads) {
3918 if (!whisper_encode_internal(*ctx, *state, offset, n_threads, nullptr, nullptr)) {
3919 WHISPER_LOG_ERROR("%s: failed to eval\n", __func__);
3920 return -1;
3921 }
3922
3923 return 0;
3924 }
3925
3926 int whisper_encode(struct whisper_context * ctx, int offset, int n_threads) {
3927 if (!whisper_encode_internal(*ctx, *ctx->state, offset, n_threads, nullptr, nullptr)) {
3928 WHISPER_LOG_ERROR("%s: failed to eval\n", __func__);
3929 return -1;
3930 }
3931
3932 return 0;
3933 }
3934
3935 int whisper_decode_with_state(struct whisper_context * ctx, struct whisper_state * state, const whisper_token * tokens, int n_tokens, int n_past, int n_threads) {
3936 whisper_batch_prep_legacy(state->batch, tokens, n_tokens, n_past, 0);
3937
3938 whisper_kv_cache_seq_rm(state->kv_self, 0, n_past, -1);
3939
3940 if (!whisper_decode_internal(*ctx, *state, state->batch, n_threads, false, nullptr, nullptr)) {
3941 WHISPER_LOG_ERROR("%s: failed to eval\n", __func__);
3942 return 1;
3943 }
3944
3945 return 0;
3946 }
3947
3948 int whisper_decode(struct whisper_context * ctx, const whisper_token * tokens, int n_tokens, int n_past, int n_threads) {
3949 if (ctx->state == nullptr) {
3950 WHISPER_LOG_ERROR("%s: ERROR state was not loaded.\n", __func__);
3951 return -1;
3952 }
3953
3954 return whisper_decode_with_state(ctx, ctx->state, tokens, n_tokens, n_past, n_threads);
3955 }
3956
3957 int whisper_tokenize(struct whisper_context * ctx, const char * text, whisper_token * tokens, int n_max_tokens) {
3958 const auto res = tokenize(ctx->vocab, text);
3959
3960 if (n_max_tokens < (int) res.size()) {
3961 WHISPER_LOG_ERROR("%s: too many resulting tokens: %d (max %d)\n", __func__, (int) res.size(), n_max_tokens);
3962 return -(int) res.size();
3963 }
3964
3965 for (int i = 0; i < (int) res.size(); i++) {
3966 tokens[i] = res[i];
3967 }
3968
3969 return res.size();
3970 }
3971
3972 int whisper_token_count(struct whisper_context * ctx, const char * text) {
3973 return -whisper_tokenize(ctx, text, NULL, 0);
3974 }
3975
3976 int whisper_lang_max_id(void) {
3977 auto max_id = 0;
3978 for (const auto & kv : g_lang) {
3979 max_id = std::max(max_id, kv.second.first);
3980 }
3981
3982 return max_id;
3983 }
3984
3985 int whisper_lang_id(const char * lang) {
3986 if (!g_lang.count(lang)) {
3987 for (const auto & kv : g_lang) {
3988 if (kv.second.second == lang) {
3989 return kv.second.first;
3990 }
3991 }
3992
3993 WHISPER_LOG_ERROR("%s: unknown language '%s'\n", __func__, lang);
3994 return -1;
3995 }
3996 return g_lang.at(lang).first;
3997 }
3998
3999 const char * whisper_lang_str(int id) {
4000 for (const auto & kv : g_lang) {
4001 if (kv.second.first == id) {
4002 return kv.first.c_str();
4003 }
4004 }
4005
4006 WHISPER_LOG_ERROR("%s: unknown language id %d\n", __func__, id);
4007 return nullptr;
4008 }
4009
4010 const char * whisper_lang_str_full(int id) {
4011 for (const auto & kv : g_lang) {
4012 if (kv.second.first == id) {
4013 return kv.second.second.c_str();
4014 }
4015 }
4016
4017 WHISPER_LOG_ERROR("%s: unknown language id %d\n", __func__, id);
4018 return nullptr;
4019 }
4020
4021 int whisper_lang_auto_detect_with_state(
4022 struct whisper_context * ctx,
4023 struct whisper_state * state,
4024 int offset_ms,
4025 int n_threads,
4026 float * lang_probs) {
4027 const int seek = offset_ms/10;
4028
4029 if (seek < 0) {
4030 WHISPER_LOG_ERROR("%s: offset %dms is before the start of the audio\n", __func__, offset_ms);
4031 return -1;
4032 }
4033
4034 if (seek >= state->mel.n_len_org) {
4035 WHISPER_LOG_ERROR("%s: offset %dms is past the end of the audio (%dms)\n", __func__, offset_ms, state->mel.n_len_org*10);
4036 return -2;
4037 }
4038
4039 // run the encoder
4040 if (whisper_encode_with_state(ctx, state, seek, n_threads) != 0) {
4041 WHISPER_LOG_ERROR("%s: failed to encode\n", __func__);
4042 return -6;
4043 }
4044
4045 const std::vector<whisper_token> prompt = { whisper_token_sot(ctx) };
4046
4047 if (whisper_decode_with_state(ctx, state, prompt.data(), prompt.size(), 0, n_threads) != 0) {
4048 WHISPER_LOG_ERROR("%s: failed to decode\n", __func__);
4049 return -7;
4050 }
4051
4052 auto & logits_id = state->decoders[0].logits_id;
4053 logits_id.clear();
4054
4055 for (const auto & kv : g_lang) {
4056 const auto token_lang = whisper_token_lang(ctx, kv.second.first);
4057 logits_id.emplace_back(state->logits[token_lang], kv.second.first);
4058 }
4059
4060 // sort descending
4061 {
4062 using pair_type = std::remove_reference<decltype(logits_id)>::type::value_type;
4063 std::sort(logits_id.begin(), logits_id.end(), [](const pair_type & a, const pair_type & b) {
4064 return a.first > b.first;
4065 });
4066 }
4067
4068 // softmax
4069 {
4070 const auto max = logits_id[0].first;
4071
4072 double sum = 0.0f;
4073 for (auto & kv : logits_id) {
4074 kv.first = exp(kv.first - max);
4075 sum += kv.first;
4076 }
4077
4078 for (auto & kv : logits_id) {
4079 kv.first /= sum;
4080 }
4081 }
4082
4083 {
4084 for (const auto & prob : logits_id) {
4085 if (lang_probs) {
4086 lang_probs[prob.second] = prob.first;
4087 }
4088
4089 //printf("%s: lang %2d (%3s): %f\n", __func__, prob.second, whisper_lang_str(prob.second), prob.first);
4090 }
4091 }
4092
4093 return logits_id[0].second;
4094 }
4095
4096 int whisper_lang_auto_detect(
4097 struct whisper_context * ctx,
4098 int offset_ms,
4099 int n_threads,
4100 float * lang_probs) {
4101 return whisper_lang_auto_detect_with_state(ctx, ctx->state, offset_ms, n_threads, lang_probs);
4102 }
4103
4104 int whisper_model_n_vocab(struct whisper_context * ctx) {
4105 return ctx->model.hparams.n_vocab;
4106 }
4107
4108 int whisper_model_n_audio_ctx(struct whisper_context * ctx) {
4109 return ctx->model.hparams.n_audio_ctx;
4110 }
4111
4112 int whisper_model_n_audio_state(struct whisper_context * ctx) {
4113 return ctx->model.hparams.n_audio_state;
4114 }
4115
4116 int whisper_model_n_audio_head(struct whisper_context * ctx) {
4117 return ctx->model.hparams.n_audio_head;
4118 }
4119
4120 int whisper_model_n_audio_layer(struct whisper_context * ctx) {
4121 return ctx->model.hparams.n_audio_layer;
4122 }
4123
4124 int whisper_model_n_text_ctx(struct whisper_context * ctx) {
4125 return ctx->model.hparams.n_text_ctx;
4126 }
4127
4128 int whisper_model_n_text_state(struct whisper_context * ctx) {
4129 return ctx->model.hparams.n_text_state;
4130 }
4131
4132 int whisper_model_n_text_head(struct whisper_context * ctx) {
4133 return ctx->model.hparams.n_text_head;
4134 }
4135
4136 int whisper_model_n_text_layer(struct whisper_context * ctx) {
4137 return ctx->model.hparams.n_text_layer;
4138 }
4139
4140 int whisper_model_n_mels(struct whisper_context * ctx) {
4141 return ctx->model.hparams.n_mels;
4142 }
4143
4144 int whisper_model_ftype(struct whisper_context * ctx) {
4145 return ctx->model.hparams.ftype;
4146 }
4147
4148 int whisper_model_type(struct whisper_context * ctx) {
4149 return ctx->model.type;
4150 }
4151
4152 const char *whisper_model_type_readable(struct whisper_context * ctx) {
4153 switch (ctx->model.type) {
4154 case e_model::MODEL_TINY:
4155 return "tiny";
4156 case e_model::MODEL_BASE:
4157 return "base";
4158 case e_model::MODEL_SMALL:
4159 return "small";
4160 case e_model::MODEL_MEDIUM:
4161 return "medium";
4162 case e_model::MODEL_LARGE:
4163 return "large";
4164 default:
4165 return "unknown";
4166 }
4167 }
4168
4169 int whisper_n_len_from_state(struct whisper_state * state) {
4170 return state->mel.n_len_org;
4171 }
4172
4173 int whisper_n_len(struct whisper_context * ctx) {
4174 return ctx->state->mel.n_len_org;
4175 }
4176
4177 int whisper_n_vocab(struct whisper_context * ctx) {
4178 return ctx->vocab.n_vocab;
4179 }
4180
4181 int whisper_n_text_ctx(struct whisper_context * ctx) {
4182 return ctx->model.hparams.n_text_ctx;
4183 }
4184
4185 int whisper_n_audio_ctx(struct whisper_context * ctx) {
4186 return ctx->model.hparams.n_audio_ctx;
4187 }
4188
4189 int whisper_is_multilingual(struct whisper_context * ctx) {
4190 return ctx->vocab.is_multilingual() ? 1 : 0;
4191 }
4192
4193 float * whisper_get_logits(struct whisper_context * ctx) {
4194 return ctx->state->logits.data();
4195 }
4196
4197 float * whisper_get_logits_from_state(struct whisper_state * state) {
4198 return state->logits.data();
4199 }
4200
4201 const char * whisper_token_to_str(struct whisper_context * ctx, whisper_token token) {
4202 return ctx->vocab.id_to_token.at(token).c_str();
4203 }
4204
4205 whisper_token whisper_token_eot(struct whisper_context * ctx) {
4206 return ctx->vocab.token_eot;
4207 }
4208
4209 whisper_token whisper_token_sot(struct whisper_context * ctx) {
4210 return ctx->vocab.token_sot;
4211 }
4212
4213 whisper_token whisper_token_solm(struct whisper_context * ctx) {
4214 return ctx->vocab.token_solm;
4215 }
4216
4217 whisper_token whisper_token_prev(struct whisper_context * ctx) {
4218 return ctx->vocab.token_prev;
4219 }
4220
4221 whisper_token whisper_token_nosp(struct whisper_context * ctx) {
4222 return ctx->vocab.token_nosp;
4223 }
4224
4225 whisper_token whisper_token_not(struct whisper_context * ctx) {
4226 return ctx->vocab.token_not;
4227 }
4228
4229 whisper_token whisper_token_beg(struct whisper_context * ctx) {
4230 return ctx->vocab.token_beg;
4231 }
4232
4233 whisper_token whisper_token_lang(struct whisper_context * ctx, int lang_id) {
4234 return whisper_token_sot(ctx) + 1 + lang_id;
4235 }
4236
4237 whisper_token whisper_token_translate(struct whisper_context * ctx) {
4238 return ctx->vocab.token_translate;
4239 }
4240
4241 whisper_token whisper_token_transcribe(struct whisper_context * ctx) {
4242 return ctx->vocab.token_transcribe;
4243 }
4244
4245 struct whisper_timings * whisper_get_timings(struct whisper_context * ctx) {
4246 if (ctx->state == nullptr) {
4247 return nullptr;
4248 }
4249 whisper_timings * timings = new whisper_timings;
4250 timings->sample_ms = 1e-3f * ctx->state->t_sample_us / std::max(1, ctx->state->n_sample);
4251 timings->encode_ms = 1e-3f * ctx->state->t_encode_us / std::max(1, ctx->state->n_encode);
4252 timings->decode_ms = 1e-3f * ctx->state->t_decode_us / std::max(1, ctx->state->n_decode);
4253 timings->batchd_ms = 1e-3f * ctx->state->t_batchd_us / std::max(1, ctx->state->n_batchd);
4254 timings->prompt_ms = 1e-3f * ctx->state->t_prompt_us / std::max(1, ctx->state->n_prompt);
4255 return timings;
4256 }
4257
4258 void whisper_print_timings(struct whisper_context * ctx) {
4259 const int64_t t_end_us = ggml_time_us();
4260
4261 WHISPER_LOG_INFO("\n");
4262 WHISPER_LOG_INFO("%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0f);
4263 if (ctx->state != nullptr) {
4264
4265 const int32_t n_sample = std::max(1, ctx->state->n_sample);
4266 const int32_t n_encode = std::max(1, ctx->state->n_encode);
4267 const int32_t n_decode = std::max(1, ctx->state->n_decode);
4268 const int32_t n_batchd = std::max(1, ctx->state->n_batchd);
4269 const int32_t n_prompt = std::max(1, ctx->state->n_prompt);
4270
4271 WHISPER_LOG_INFO("%s: fallbacks = %3d p / %3d h\n", __func__, ctx->state->n_fail_p, ctx->state->n_fail_h);
4272 WHISPER_LOG_INFO("%s: mel time = %8.2f ms\n", __func__, ctx->state->t_mel_us / 1000.0f);
4273 WHISPER_LOG_INFO("%s: sample time = %8.2f ms / %5d runs ( %8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_sample_us, n_sample, 1e-3f * ctx->state->t_sample_us / n_sample);
4274 WHISPER_LOG_INFO("%s: encode time = %8.2f ms / %5d runs ( %8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_encode_us, n_encode, 1e-3f * ctx->state->t_encode_us / n_encode);
4275 WHISPER_LOG_INFO("%s: decode time = %8.2f ms / %5d runs ( %8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_decode_us, n_decode, 1e-3f * ctx->state->t_decode_us / n_decode);
4276 WHISPER_LOG_INFO("%s: batchd time = %8.2f ms / %5d runs ( %8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_batchd_us, n_batchd, 1e-3f * ctx->state->t_batchd_us / n_batchd);
4277 WHISPER_LOG_INFO("%s: prompt time = %8.2f ms / %5d runs ( %8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_prompt_us, n_prompt, 1e-3f * ctx->state->t_prompt_us / n_prompt);
4278 }
4279 WHISPER_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0f);
4280 }
4281
4282 void whisper_reset_timings(struct whisper_context * ctx) {
4283 ctx->t_start_us = ggml_time_us();
4284 if (ctx->state != nullptr) {
4285 ctx->state->t_mel_us = 0;
4286 ctx->state->t_sample_us = 0;
4287 ctx->state->t_encode_us = 0;
4288 ctx->state->t_decode_us = 0;
4289 ctx->state->t_batchd_us = 0;
4290 ctx->state->t_prompt_us = 0;
4291 ctx->state->n_sample = 0;
4292 ctx->state->n_encode = 0;
4293 ctx->state->n_decode = 0;
4294 ctx->state->n_batchd = 0;
4295 ctx->state->n_prompt = 0;
4296 }
4297 }
4298
4299 static int whisper_has_coreml(void) {
4300 #ifdef WHISPER_USE_COREML
4301 return 1;
4302 #else
4303 return 0;
4304 #endif
4305 }
4306
4307 static int whisper_has_openvino(void) {
4308 #ifdef WHISPER_USE_OPENVINO
4309 return 1;
4310 #else
4311 return 0;
4312 #endif
4313 }
4314
4315 const char * whisper_print_system_info(void) {
4316 static std::string s;
4317
4318 s = "";
4319 s += "WHISPER : ";
4320 s += "COREML = " + std::to_string(whisper_has_coreml()) + " | ";
4321 s += "OPENVINO = " + std::to_string(whisper_has_openvino()) + " | ";
4322
4323 for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
4324 auto * reg = ggml_backend_reg_get(i);
4325 auto * get_features_fn = (ggml_backend_get_features_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_features");
4326 if (get_features_fn) {
4327 ggml_backend_feature * features = get_features_fn(reg);
4328 s += ggml_backend_reg_name(reg);
4329 s += " : ";
4330 for (; features->name; features++) {
4331 s += features->name;
4332 s += " = ";
4333 s += features->value;
4334 s += " | ";
4335 }
4336 }
4337 }
4338 return s.c_str();
4339 }
4340
4341 //////////////////////////////////
4342 // Voice Activity Detection (VAD)
4343 //////////////////////////////////
4344
4345 struct whisper_vad_hparams {
4346 int32_t n_encoder_layers;
4347 int32_t * encoder_in_channels;
4348 int32_t * encoder_out_channels;
4349 int32_t * kernel_sizes;
4350 int32_t lstm_input_size;
4351 int32_t lstm_hidden_size;
4352 int32_t final_conv_in;
4353 int32_t final_conv_out;
4354 };
4355
4356 struct whisper_vad_model {
4357 std::string type;
4358 std::string version;
4359 whisper_vad_hparams hparams;
4360
4361 struct ggml_tensor * stft_forward_basis; // [256, 1, 258]
4362
4363 // Encoder tensors - 4 convolutional layers
4364 struct ggml_tensor * encoder_0_weight; // [3, 129, 128]
4365 struct ggml_tensor * encoder_0_bias; // [128]
4366
4367 // Second encoder layer
4368 struct ggml_tensor * encoder_1_weight; // [3, 128, 64]
4369 struct ggml_tensor * encoder_1_bias; // [64]
4370
4371 // Third encoder layer
4372 struct ggml_tensor * encoder_2_weight; // [3, 64, 64]
4373 struct ggml_tensor * encoder_2_bias; // [64]
4374
4375 // Fourth encoder layer
4376 struct ggml_tensor * encoder_3_weight; // [3, 64, 128]
4377 struct ggml_tensor * encoder_3_bias; // [128]
4378
4379 // LSTM decoder tensors
4380 struct ggml_tensor * lstm_ih_weight; // [128, 512] input-to-hidden
4381 struct ggml_tensor * lstm_ih_bias; // [512]
4382 struct ggml_tensor * lstm_hh_weight; // [128, 512] hidden-to-hidden
4383 struct ggml_tensor * lstm_hh_bias; // [512]
4384
4385 // Final conv layer
4386 struct ggml_tensor * final_conv_weight; // [128]
4387 struct ggml_tensor * final_conv_bias; // [1]
4388
4389 // ggml contexts
4390 std::vector<ggml_context *> ctxs;
4391
4392 // buffer for the model tensors
4393 std::vector<ggml_backend_buffer_t> buffers;
4394
4395 // tensors
4396 int n_loaded;
4397 std::map<std::string, struct ggml_tensor *> tensors;
4398 };
4399
4400 struct whisper_vad_segment {
4401 int64_t start;
4402 int64_t end;
4403 };
4404
4405 struct whisper_vad_segments {
4406 std::vector<whisper_vad_segment> data;
4407 };
4408
4409 struct whisper_vad_context {
4410 int64_t t_vad_us = 0;
4411
4412 int n_window;
4413 int n_context;
4414 int n_threads;
4415
4416 std::vector<ggml_backend_t> backends;
4417 ggml_backend_buffer_t buffer = nullptr;
4418 whisper_context_params params;
4419 std::vector<uint8_t> ctx_buf;
4420 whisper_sched sched;
4421
4422 whisper_vad_model model;
4423 std::string path_model;
4424 struct ggml_tensor * h_state;
4425 struct ggml_tensor * c_state;
4426 std::vector<float> probs;
4427 };
4428
4429 struct whisper_vad_context_params whisper_vad_default_context_params(void) {
4430 whisper_vad_context_params result = {
4431 /*.n_thread = */ 4,
4432 /*.use_gpu = */ false,
4433 /*.gpu_device = */ 0,
4434 };
4435 return result;
4436 }
4437
4438 struct whisper_vad_params whisper_vad_default_params(void) {
4439 whisper_vad_params result = {
4440 /* threshold = */ 0.5f,
4441 /* min_speech_duration_ms = */ 250,
4442 /* min_silence_duration_ms = */ 100,
4443 /* max_speech_duration_s = */ FLT_MAX,
4444 /* speech_pad_ms = */ 30,
4445 /* samples_overlap = */ 0.1,
4446 };
4447 return result;
4448 }
4449
4450 // Time conversion utility functions for whisper VAD
4451 static int cs_to_samples(int64_t cs) {
4452 return (int)((cs / 100.0) * WHISPER_SAMPLE_RATE + 0.5);
4453 }
4454
4455 static int64_t samples_to_cs(int samples) {
4456 return (int64_t)((samples / (double)WHISPER_SAMPLE_RATE) * 100.0 + 0.5);
4457 }
4458
4459 static bool weight_buft_supported(const whisper_vad_hparams & hparams, ggml_tensor * w, ggml_op op, ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev) {
4460 bool op_supported = true;
4461
4462 if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU ||
4463 ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_IGPU ||
4464 (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU && buft == ggml_backend_cpu_buffer_type())) {
4465 // GPU and default CPU backend support all operators
4466 op_supported = true;
4467 } else {
4468 switch (op) {
4469 // The current extra_buffer_type implementations only support GGML_OP_MUL_MAT
4470 case GGML_OP_MUL_MAT: {
4471 ggml_init_params params = {
4472 /*.mem_size =*/ 2 * ggml_tensor_overhead(),
4473 /*.mem_buffer =*/ nullptr,
4474 /*.no_alloc =*/ true,
4475 };
4476
4477 ggml_context_ptr ctx_ptr { ggml_init(params) };
4478 if (!ctx_ptr) {
4479 throw std::runtime_error("failed to create ggml context");
4480 }
4481 ggml_context * ctx = ctx_ptr.get();
4482
4483 ggml_tensor * op_tensor = nullptr;
4484
4485 int64_t n_ctx = hparams.lstm_hidden_size;
4486 ggml_tensor * b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], n_ctx, w->ne[2], w->ne[3]);
4487 op_tensor = ggml_mul_mat(ctx, w, b);
4488
4489 // create a temporary dummy buffer for the weight so that supports_op can check the buffer type
4490 GGML_ASSERT(w->buffer == nullptr);
4491 w->buffer = ggml_backend_buft_alloc_buffer(buft, 0);
4492 op_supported = ggml_backend_dev_supports_op(dev, op_tensor);
4493 ggml_backend_buffer_free(w->buffer);
4494 w->buffer = nullptr;
4495 break;
4496 }
4497 default: {
4498 op_supported = false;
4499 break;
4500 }
4501 };
4502 }
4503 return op_supported;
4504 }
4505
4506 static ggml_backend_buffer_type_t select_weight_buft(const whisper_vad_hparams & hparams, ggml_tensor * w, ggml_op op, buft_list_t buft_list) {
4507 GGML_ASSERT(!buft_list.empty());
4508 for (const auto & p : buft_list) {
4509 ggml_backend_dev_t dev = p.first;
4510 ggml_backend_buffer_type_t buft = p.second;
4511 if (weight_buft_supported(hparams, w, op, buft, dev)) {
4512 return buft;
4513 }
4514 }
4515
4516 return nullptr;
4517 }
4518
4519 static ggml_tensor * whisper_vad_build_stft_layer(ggml_context * ctx0,
4520 const whisper_vad_model & model, ggml_tensor * cur) {
4521 // Apply reflective padding to the input tensor
4522 ggml_tensor * padded = ggml_pad_reflect_1d(ctx0, cur, 64, 64);
4523
4524 struct ggml_tensor * stft = ggml_conv_1d(ctx0, model.stft_forward_basis, padded, model.hparams.lstm_input_size, 0, 1);
4525
4526 // Calculate cutoff for real/imaginary parts
4527 int cutoff = model.stft_forward_basis->ne[2] / 2;
4528
4529 // Extract real part (first half of the STFT output).
4530 struct ggml_tensor * real_part = ggml_view_2d(ctx0, stft, 4, cutoff, stft->nb[1], 0);
4531 // Extract imaginary part (second half of the STFT output).
4532 struct ggml_tensor * img_part = ggml_view_2d(ctx0, stft, 4, cutoff, stft->nb[1], cutoff * stft->nb[1]);
4533
4534 // Calculate magnitude: sqrt(real^2 + imag^2)
4535 struct ggml_tensor * real_squared = ggml_mul(ctx0, real_part, real_part);
4536 struct ggml_tensor * img_squared = ggml_mul(ctx0, img_part, img_part);
4537 struct ggml_tensor * sum_squares = ggml_add(ctx0, real_squared, img_squared);
4538 struct ggml_tensor * magnitude = ggml_sqrt(ctx0, sum_squares);
4539 return magnitude;
4540 }
4541
4542 static ggml_tensor * whisper_vad_build_encoder_layer(ggml_context * ctx0,
4543 const whisper_vad_model & model, ggml_tensor * cur) {
4544 // First Conv1D: expands to 128 channels.
4545 cur = ggml_conv_1d(ctx0, model.encoder_0_weight, cur, 1, 1, 1);
4546 cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.encoder_0_bias, 1, 128, 1));
4547 cur = ggml_relu(ctx0, cur);
4548
4549 // Second Conv1D: reduces to 64 channels.
4550 cur = ggml_conv_1d(ctx0, model.encoder_1_weight, cur, 2, 1, 1);
4551 cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.encoder_1_bias, 1, 64, 1));
4552 cur = ggml_relu(ctx0, cur);
4553
4554 // Third Conv1D: maintains 64 channels
4555 cur = ggml_conv_1d(ctx0, model.encoder_2_weight, cur, 2, 1, 1);
4556 cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.encoder_2_bias, 1, 64, 1));
4557 cur = ggml_relu(ctx0, cur);
4558
4559 // Fourth Conv1D: expands to 128 channels
4560 cur = ggml_conv_1d(ctx0, model.encoder_3_weight, cur, 1, 1, 1);
4561 cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.encoder_3_bias, 1, 128, 1));
4562 cur = ggml_relu(ctx0, cur);
4563
4564 return cur;
4565 }
4566
4567 static ggml_tensor * whisper_vad_build_lstm_layer(ggml_context * ctx0,
4568 const whisper_vad_context & vctx, ggml_tensor * cur, ggml_cgraph * gf) {
4569 const whisper_vad_model & model = vctx.model;
4570 const int hdim = model.hparams.lstm_hidden_size;
4571
4572 struct ggml_tensor * x_t = ggml_transpose(ctx0, cur);
4573
4574 // Create operations using the input-to-hidden weights.
4575 struct ggml_tensor * inp_gate = ggml_mul_mat(ctx0, model.lstm_ih_weight, x_t);
4576 inp_gate = ggml_add(ctx0, inp_gate, model.lstm_ih_bias);
4577
4578 // Create operations using the hidden-to-hidden weights.
4579 struct ggml_tensor * hid_gate = ggml_mul_mat(ctx0, model.lstm_hh_weight, vctx.h_state);
4580 hid_gate = ggml_add(ctx0, hid_gate, model.lstm_hh_bias);
4581
4582 // Create add operation to get preactivations for all gates.
4583 struct ggml_tensor * out_gate = ggml_add(ctx0, inp_gate, hid_gate);
4584
4585 const size_t hdim_size = ggml_row_size(out_gate->type, hdim);
4586
4587 // Create sigmoid for input gate (using the first 128 bytes from the preactivations).
4588 struct ggml_tensor * i_t = ggml_sigmoid(ctx0, ggml_view_1d(ctx0, out_gate, hdim, 0 * hdim_size));
4589
4590 // Create sigmoid for the forget gate (using the second 128 bytes from the preactivations).
4591 struct ggml_tensor * f_t = ggml_sigmoid(ctx0, ggml_view_1d(ctx0, out_gate, hdim, 1 * hdim_size));
4592
4593 // Create sigmoid for the cell gate (using the third 128 bytes from the preactivations).
4594 struct ggml_tensor * g_t = ggml_tanh(ctx0, ggml_view_1d(ctx0, out_gate, hdim, 2 * hdim_size));
4595
4596 // Create sigmoid for the output gate (using the fourth 128 bytes from the preactivations).
4597 struct ggml_tensor * o_t = ggml_sigmoid(ctx0, ggml_view_1d(ctx0, out_gate, hdim, 3 * hdim_size));
4598
4599 // Update cell state
4600 struct ggml_tensor * c_out = ggml_add(ctx0,
4601 ggml_mul(ctx0, f_t, vctx.c_state),
4602 ggml_mul(ctx0, i_t, g_t));
4603 ggml_build_forward_expand(gf, ggml_cpy(ctx0, c_out, vctx.c_state));
4604
4605 // Update hidden state
4606 struct ggml_tensor * out = ggml_mul(ctx0, o_t, ggml_tanh(ctx0, c_out));
4607 ggml_build_forward_expand(gf, ggml_cpy(ctx0, out, vctx.h_state));
4608
4609 return out;
4610 }
4611
4612 static struct ggml_cgraph * whisper_vad_build_graph(whisper_vad_context & vctx) {
4613 const auto & model = vctx.model;
4614
4615 struct ggml_init_params params = {
4616 /*.mem_size =*/ vctx.sched.meta.size(),
4617 /*.mem_buffer =*/ vctx.sched.meta.data(),
4618 /*.no_alloc =*/ true,
4619 };
4620
4621 struct ggml_context * ctx0 = ggml_init(params);
4622
4623 ggml_cgraph * gf = ggml_new_graph(ctx0);
4624
4625 struct ggml_tensor * frame = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, vctx.n_window, 1);
4626 ggml_set_name(frame, "frame");
4627 ggml_set_input(frame);
4628
4629 struct ggml_tensor * cur = nullptr;
4630 {
4631 cur = whisper_vad_build_stft_layer(ctx0, model, frame);
4632
4633 cur = whisper_vad_build_encoder_layer(ctx0, model, cur);
4634
4635 // Extract the first element of the first dimension
4636 // (equivalent to pytorch's [:, :, 0])
4637 cur = ggml_view_2d(ctx0, cur, 1, 128, cur->nb[1], 0);
4638
4639 cur = whisper_vad_build_lstm_layer(ctx0, vctx, cur, gf);
4640 cur = ggml_relu(ctx0, cur);
4641 cur = ggml_conv_1d(ctx0, model.final_conv_weight, cur, 1, 0, 1);
4642 cur = ggml_add(ctx0, cur, model.final_conv_bias);
4643 cur = ggml_sigmoid(ctx0, cur);
4644 ggml_set_name(cur, "prob");
4645 ggml_set_output(cur);
4646 }
4647
4648 ggml_build_forward_expand(gf, cur);
4649
4650 ggml_free(ctx0);
4651
4652 return gf;
4653 }
4654
4655 static bool whisper_vad_init_context(whisper_vad_context * vctx) {
4656
4657 auto whisper_context_params = whisper_context_default_params();
4658 // TODO: GPU VAD is forced disabled until the performance is improved
4659 //whisper_context_params.use_gpu = vctx->params.use_gpu;
4660 whisper_context_params.use_gpu = false;
4661 whisper_context_params.gpu_device = vctx->params.gpu_device;
4662
4663 vctx->backends = whisper_backend_init(whisper_context_params);
4664 if (vctx->backends.empty()) {
4665 WHISPER_LOG_ERROR("%s: whisper_backend_init() failed\n", __func__);
4666 return false;
4667 }
4668
4669 const int32_t lstm_hidden_size = vctx->model.hparams.lstm_hidden_size;
4670
4671 vctx->ctx_buf.resize(2u*ggml_tensor_overhead());
4672
4673 struct ggml_init_params params = {
4674 /*.mem_size =*/ vctx->ctx_buf.size(),
4675 /*.mem_buffer =*/ vctx->ctx_buf.data(),
4676 /*.no_alloc =*/ true,
4677 };
4678
4679 ggml_context * ctx = ggml_init(params);
4680 if (!ctx) {
4681 WHISPER_LOG_ERROR("%s: failed to init LSTM state ggml context\n", __func__);
4682 return false;
4683 }
4684
4685 // LSTM Hidden state
4686 vctx->h_state = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, lstm_hidden_size);
4687 ggml_set_name(vctx->h_state, "h_state");
4688
4689 // LSTM Cell state
4690 vctx->c_state = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, lstm_hidden_size);
4691 ggml_set_name(vctx->c_state, "c_state");
4692
4693 vctx->buffer = ggml_backend_alloc_ctx_tensors(ctx, vctx->backends[0]);
4694 ggml_free(ctx);
4695 if (!vctx->buffer) {
4696 WHISPER_LOG_ERROR("%s: failed to allocate memory for the VAD state\n", __func__);
4697 return false;
4698 }
4699
4700 {
4701 bool ok = whisper_sched_graph_init(vctx->sched, vctx->backends,
4702 [&]() {
4703 return whisper_vad_build_graph(*vctx);
4704 });
4705
4706 if (!ok) {
4707 WHISPER_LOG_ERROR("%s: failed to init VAD allocator\n", __func__);
4708 return false;
4709 }
4710
4711 WHISPER_LOG_INFO("%s: compute buffer (VAD) = %7.2f MB\n", __func__, whisper_sched_size(vctx->sched) / 1e6);
4712 }
4713
4714 return true;
4715 }
4716
4717 struct whisper_vad_context * whisper_vad_init_from_file_with_params(
4718 const char * path_model,
4719 struct whisper_vad_context_params params) {
4720 WHISPER_LOG_INFO("%s: loading VAD model from '%s'\n", __func__, path_model);
4721 #ifdef _MSC_VER
4722 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
4723 std::wstring path_model_wide = converter.from_bytes(path_model);
4724 auto fin = std::ifstream(path_model_wide, std::ios::binary);
4725 #else
4726 auto fin = std::ifstream(path_model, std::ios::binary);
4727 #endif
4728 if (!fin) {
4729 WHISPER_LOG_ERROR("%s: failed to open VAD model '%s'\n", __func__, path_model);
4730 return nullptr;
4731 }
4732
4733 whisper_model_loader loader = {};
4734 loader.context = &fin;
4735
4736 loader.read = [](void * ctx, void * output, size_t read_size) {
4737 std::ifstream * fin = (std::ifstream*)ctx;
4738 fin->read((char *)output, read_size);
4739 return read_size;
4740 };
4741
4742 loader.eof = [](void * ctx) {
4743 std::ifstream * fin = (std::ifstream*)ctx;
4744 return fin->eof();
4745 };
4746
4747 loader.close = [](void * ctx) {
4748 std::ifstream * fin = (std::ifstream*)ctx;
4749 fin->close();
4750 };
4751
4752 auto ctx = whisper_vad_init_with_params(&loader, params);
4753 if (!ctx) {
4754 whisper_vad_free(ctx);
4755 return nullptr;
4756 }
4757 ctx->path_model = path_model;
4758 return ctx;
4759 }
4760
4761 /*
4762 Function whisper_vad_init_from_memory_with_params() is added by Anastasia Shchupak on behalf of inclusion into Praat.
4763 In the original whisper.cpp version, whisper_vad_init_from_file_with_params() is always used.
4764 Praat contains Silero-VAD model in memory, therefore whisper_vad_init_from_memory_with_params() is added.
4765 */
4766 struct whisper_vad_context * whisper_vad_init_from_memory_with_params (
4767 const void * data, size_t size,
4768 whisper_vad_context_params params) {
4769 WHISPER_LOG_INFO("%s: loading VAD model from memory\n", __func__);
4770 struct SileroVadStream {
4771 const void * data;
4772 size_t size;
4773 size_t pos;
4774 };
4775 SileroVadStream stream {
4776 data,
4777 size,
4778 0
4779 };
4780 whisper_model_loader loader {};
4781 loader.context = &stream;
4782
4783 loader.read = [](void * ctx, void * output, size_t read_size) -> size_t {
4784 auto * s = (SileroVadStream *)ctx;
4785 size_t available = s->size - s->pos;
4786 size_t to_read = std::min(read_size, available);
4787 memcpy(output, (const unsigned char *)s->data + s->pos, to_read);
4788 s->pos += to_read;
4789 return to_read;
4790 };
4791 loader.eof = [](void * ctx) -> bool {
4792 auto * s = (SileroVadStream *)ctx;
4793 return s->pos >= s->size;
4794 };
4795 loader.close = [](void * ctx) { };
4796 return whisper_vad_init_with_params(&loader, params);
4797 }
4798
4799 struct whisper_vad_context * whisper_vad_init_with_params(
4800 struct whisper_model_loader * loader,
4801 struct whisper_vad_context_params params) {
4802 // Read the VAD model
4803 {
4804 uint32_t magic;
4805 read_safe(loader, magic);
4806 if (magic != GGML_FILE_MAGIC) {
4807 WHISPER_LOG_ERROR("%s: invalid model data (bad magic)\n", __func__);
4808 return nullptr;
4809 }
4810 }
4811
4812 whisper_vad_context * vctx = new whisper_vad_context;
4813 vctx->n_threads = params.n_threads;
4814 vctx->params.use_gpu = params.use_gpu;
4815 vctx->params.gpu_device = params.gpu_device;
4816
4817 auto & model = vctx->model;
4818 auto & hparams = model.hparams;
4819
4820 // load model context params.
4821 {
4822 int32_t str_len;
4823 read_safe(loader, str_len);
4824 std::vector<char> buffer(str_len + 1, 0);
4825 loader->read(loader->context, buffer.data(), str_len);
4826 std::string model_type(buffer.data(), str_len);
4827 model.type = model_type;
4828 WHISPER_LOG_INFO("%s: model type: %s\n", __func__, model.type.c_str());
4829
4830 int32_t major, minor, patch;
4831 read_safe(loader, major);
4832 read_safe(loader, minor);
4833 read_safe(loader, patch);
4834 std::string version_str = std::to_string(major) + "." +
4835 std::to_string(minor) + "." +
4836 std::to_string(patch);
4837 model.version = version_str;
4838 WHISPER_LOG_INFO("%s: model version: %s\n", __func__, model.version.c_str());
4839
4840 read_safe(loader, vctx->n_window);
4841 read_safe(loader, vctx->n_context);
4842 }
4843
4844 // load model hyper params (hparams).
4845 {
4846 read_safe(loader, hparams.n_encoder_layers);
4847
4848 hparams.encoder_in_channels = new int32_t[hparams.n_encoder_layers];
4849 hparams.encoder_out_channels = new int32_t[hparams.n_encoder_layers];
4850 hparams.kernel_sizes = new int32_t[hparams.n_encoder_layers];
4851
4852 for (int32_t i = 0; i < hparams.n_encoder_layers; i++) {
4853 read_safe(loader, hparams.encoder_in_channels[i]);
4854 read_safe(loader, hparams.encoder_out_channels[i]);
4855 read_safe(loader, hparams.kernel_sizes[i]);
4856 }
4857
4858 read_safe(loader, hparams.lstm_input_size);
4859 read_safe(loader, hparams.lstm_hidden_size);
4860 read_safe(loader, hparams.final_conv_in);
4861 read_safe(loader, hparams.final_conv_out);
4862
4863 WHISPER_LOG_INFO("%s: n_encoder_layers = %d\n", __func__, hparams.n_encoder_layers);
4864 for (int32_t i = 0; i < hparams.n_encoder_layers; i++) {
4865 WHISPER_LOG_INFO("%s: encoder_in_channels[%d] = %d\n", __func__, i, hparams.encoder_in_channels[i]);
4866 }
4867 for (int32_t i = 0; i < hparams.n_encoder_layers; i++) {
4868 WHISPER_LOG_INFO("%s: encoder_out_channels[%d] = %d\n", __func__, i, hparams.encoder_out_channels[i]);
4869 }
4870 WHISPER_LOG_INFO("%s: lstm_input_size = %d\n", __func__, hparams.lstm_input_size);
4871 WHISPER_LOG_INFO("%s: lstm_hidden_size = %d\n", __func__, hparams.lstm_hidden_size);
4872 WHISPER_LOG_INFO("%s: final_conv_in = %d\n", __func__, hparams.final_conv_in);
4873 WHISPER_LOG_INFO("%s: final_conv_out = %d\n", __func__, hparams.final_conv_out);
4874 }
4875
4876 // 1 STFT tensor, 4*2 encoder tensors, 4 LSTM tensors, 2 final output tensors
4877 const size_t n_tensors = hparams.n_encoder_layers * 2 + 4 + 2 + 1;
4878
4879 std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
4880 auto get_ctx = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
4881 auto it = ctx_map.find(buft);
4882 if (it == ctx_map.end()) {
4883 ggml_init_params params = {
4884 /*.mem_size =*/ n_tensors * ggml_tensor_overhead(),
4885 /*.mem_buffer =*/ nullptr,
4886 /*.no_alloc =*/ true,
4887 };
4888
4889 ggml_context * ctx = ggml_init(params);
4890 if (!ctx) {
4891 throw std::runtime_error("failed to create ggml context");
4892 }
4893
4894 ctx_map[buft] = ctx;
4895 model.ctxs.emplace_back(ctx);
4896
4897 return ctx;
4898 }
4899
4900 return it->second;
4901 };
4902
4903 whisper_context_params wparams = whisper_context_default_params();
4904 wparams.use_gpu = params.use_gpu;
4905 wparams.gpu_device = params.gpu_device;
4906 buft_list_t buft_list = make_buft_list(wparams);
4907
4908 auto create_tensor = [&](vad_tensor type, ggml_tensor * meta) -> ggml_tensor * {
4909 ggml_op op = VAD_TENSOR_OPS.at(type);
4910 ggml_backend_buffer_type_t buft = select_weight_buft(hparams, meta, op, buft_list);
4911 if (!buft) {
4912 throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", VAD_TENSOR_NAMES.at(type)));
4913 }
4914 ggml_context * ctx = get_ctx(buft);
4915 ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
4916 model.tensors[VAD_TENSOR_NAMES.at(type)] = tensor;
4917
4918 return tensor;
4919 };
4920
4921 // create tensors
4922 {
4923 ggml_init_params params = {
4924 /*.mem_size =*/ n_tensors * ggml_tensor_overhead(),
4925 /*.mem_buffer =*/ nullptr,
4926 /*.no_alloc =*/ true,
4927 };
4928
4929 ggml_context * ctx = ggml_init(params);
4930 const auto & hparams = model.hparams;
4931
4932 // SFTF precomputed basis matrix
4933 model.stft_forward_basis = create_tensor(VAD_TENSOR_STFT_BASIS,
4934 ggml_new_tensor_3d(ctx, GGML_TYPE_F16, 256, 1, 258));
4935
4936 model.encoder_0_weight = create_tensor(VAD_TENSOR_ENC_0_WEIGHT,
4937 ggml_new_tensor_3d(
4938 ctx,
4939 GGML_TYPE_F16,
4940 hparams.kernel_sizes[0],
4941 hparams.encoder_in_channels[0],
4942 hparams.encoder_out_channels[0]
4943 ));
4944 model.encoder_0_bias = create_tensor(VAD_TENSOR_ENC_0_BIAS,
4945 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.encoder_out_channels[0]));
4946
4947 model.encoder_1_weight = create_tensor(VAD_TENSOR_ENC_1_WEIGHT,
4948 ggml_new_tensor_3d(
4949 ctx,
4950 GGML_TYPE_F16,
4951 hparams.kernel_sizes[1],
4952 hparams.encoder_in_channels[1],
4953 hparams.encoder_out_channels[1]
4954 ));
4955 model.encoder_1_bias = create_tensor(VAD_TENSOR_ENC_1_BIAS,
4956 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.encoder_out_channels[1]));
4957
4958 model.encoder_2_weight = create_tensor(VAD_TENSOR_ENC_2_WEIGHT,
4959 ggml_new_tensor_3d(
4960 ctx,
4961 GGML_TYPE_F16,
4962 hparams.kernel_sizes[2],
4963 hparams.encoder_in_channels[2],
4964 hparams.encoder_out_channels[2]
4965 ));
4966 model.encoder_2_bias = create_tensor(VAD_TENSOR_ENC_2_BIAS,
4967 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.encoder_out_channels[2]));
4968
4969 model.encoder_3_weight = create_tensor(VAD_TENSOR_ENC_3_WEIGHT,
4970 ggml_new_tensor_3d(
4971 ctx,
4972 GGML_TYPE_F16,
4973 hparams.kernel_sizes[3],
4974 hparams.encoder_in_channels[3],
4975 hparams.encoder_out_channels[3]
4976 ));
4977 model.encoder_3_bias = create_tensor(VAD_TENSOR_ENC_3_BIAS,
4978 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.encoder_out_channels[3]));
4979
4980 // Hidden State dimension (input gate, forget gate, cell gate, output gate)
4981 const int hstate_dim = hparams.lstm_hidden_size * 4;
4982
4983 // LSTM weights - input to hidden
4984 model.lstm_ih_weight = create_tensor(
4985 VAD_TENSOR_LSTM_WEIGHT_IH,
4986 ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hparams.lstm_hidden_size, hstate_dim)
4987 );
4988 model.lstm_ih_bias = create_tensor(
4989 VAD_TENSOR_LSTM_BIAS_IH,
4990 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hstate_dim)
4991 );
4992
4993 // LSTM weights - hidden to hidden
4994 model.lstm_hh_weight = create_tensor(
4995 VAD_TENSOR_LSTM_WEIGHT_HH,
4996 ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hparams.lstm_hidden_size, hstate_dim)
4997 );
4998 model.lstm_hh_bias = create_tensor(
4999 VAD_TENSOR_LSTM_BIAS_HH,
5000 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hstate_dim)
5001 );
5002
5003 // Final conv layer weight
5004 model.final_conv_weight = create_tensor(
5005 VAD_TENSOR_FINAL_CONV_WEIGHT,
5006 ggml_new_tensor_2d(ctx, GGML_TYPE_F16, hparams.final_conv_in, 1)
5007 );
5008 model.final_conv_bias = create_tensor(
5009 VAD_TENSOR_FINAL_CONV_BIAS,
5010 ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1)
5011 );
5012
5013 ggml_free(ctx);
5014 }
5015
5016 // allocate tensors in the backend buffers
5017 for (auto & p : ctx_map) {
5018 ggml_backend_buffer_type_t buft = p.first;
5019 ggml_context * ctx = p.second;
5020 ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
5021 if (buf) {
5022 model.buffers.emplace_back(buf);
5023
5024 size_t size_main = ggml_backend_buffer_get_size(buf);
5025 WHISPER_LOG_INFO("%s: %12s total size = %8.2f MB\n", __func__, ggml_backend_buffer_name(buf), size_main / 1e6);
5026 }
5027 }
5028
5029 // load weights
5030 {
5031 size_t total_size = 0;
5032 model.n_loaded = 0;
5033 std::vector<char> read_buf;
5034
5035 while (true) {
5036 int32_t n_dims;
5037 int32_t length;
5038 int32_t ttype;
5039
5040 read_safe(loader, n_dims);
5041 read_safe(loader, length);
5042 read_safe(loader, ttype);
5043
5044 if (loader->eof(loader->context)) {
5045 break;
5046 }
5047
5048 int32_t nelements = 1;
5049 int32_t ne[4] = { 1, 1, 1, 1 };
5050 for (int i = 0; i < n_dims; ++i) {
5051 read_safe(loader, ne[i]);
5052 nelements *= ne[i];
5053 }
5054
5055 std::string name;
5056 std::vector<char> tmp(length);
5057 loader->read(loader->context, &tmp[0], tmp.size());
5058 name.assign(&tmp[0], tmp.size());
5059
5060 if (model.tensors.find(name) == model.tensors.end()) {
5061 WHISPER_LOG_ERROR("%s: unknown tensor '%s' in model file\n", __func__, name.data());
5062 return nullptr;
5063 }
5064
5065 auto tensor = model.tensors[name.data()];
5066
5067 if (ggml_nelements(tensor) != nelements) {
5068 WHISPER_LOG_ERROR("%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
5069 WHISPER_LOG_ERROR("%s: shape: [%d, %d, %d], expected: [%d, %d, %d]\n",
5070 __func__, ne[0], ne[1], ne[2], (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2]);
5071 return nullptr;
5072 }
5073
5074 if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1] || tensor->ne[2] != ne[2]) {
5075 WHISPER_LOG_ERROR("%s: tensor '%s' has wrong shape in model file: got [%d, %d, %d], expected [%d, %d, %d]\n",
5076 __func__, name.data(), (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2], ne[0], ne[1], ne[2]);
5077 return nullptr;
5078 }
5079
5080 const size_t bpe = ggml_type_size(ggml_type(ttype));
5081
5082 if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
5083 WHISPER_LOG_ERROR("%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
5084 __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
5085 return nullptr;
5086 }
5087
5088 if (ggml_backend_buffer_is_host(tensor->buffer)) {
5089 // for the CPU and Metal backend, we can read directly into the tensor
5090 loader->read(loader->context, tensor->data, ggml_nbytes(tensor));
5091 BYTESWAP_TENSOR(tensor);
5092 } else {
5093 // read into a temporary buffer first, then copy to device memory
5094 read_buf.resize(ggml_nbytes(tensor));
5095
5096 loader->read(loader->context, read_buf.data(), read_buf.size());
5097
5098 ggml_backend_tensor_set(tensor, read_buf.data(), 0, ggml_nbytes(tensor));
5099 }
5100
5101 total_size += ggml_nbytes(tensor);
5102 model.n_loaded++;
5103 }
5104
5105 WHISPER_LOG_INFO("%s: model size = %7.2f MB\n", __func__, total_size/1e6);
5106
5107 if (model.n_loaded == 0) {
5108 WHISPER_LOG_WARN("%s: WARN no tensors loaded from model file - assuming empty model for testing\n", __func__);
5109 } else if (model.n_loaded != (int) model.tensors.size()) {
5110 WHISPER_LOG_ERROR("%s: ERROR not all tensors loaded from model file - expected %zu, got %d\n", __func__, model.tensors.size(), model.n_loaded);
5111 return nullptr;
5112 }
5113
5114 }
5115
5116 if (!whisper_vad_init_context(vctx)) {
5117 whisper_vad_free(vctx);
5118 return nullptr;
5119 }
5120
5121 return vctx;
5122 }
5123
5124 bool whisper_vad_detect_speech(
5125 struct whisper_vad_context * vctx,
5126 const float * samples,
5127 int n_samples) {
5128 int n_chunks = n_samples / vctx->n_window;
5129 if (n_samples % vctx->n_window != 0) {
5130 n_chunks += 1; // Add one more chunk for remaining samples.
5131 }
5132
5133 WHISPER_LOG_INFO("%s: detecting speech in %d samples\n", __func__, n_samples);
5134 WHISPER_LOG_INFO("%s: n_chunks: %d\n", __func__, n_chunks);
5135
5136 // Reset LSTM hidden/cell states
5137 ggml_backend_buffer_clear(vctx->buffer, 0);
5138
5139 vctx->probs.resize(n_chunks);
5140 WHISPER_LOG_INFO("%s: props size: %u\n", __func__, n_chunks);
5141
5142 std::vector<float> window(vctx->n_window, 0.0f);
5143
5144 auto & sched = vctx->sched.sched;
5145
5146 ggml_cgraph * gf = whisper_vad_build_graph(*vctx);
5147
5148 if (!ggml_backend_sched_alloc_graph(sched, gf)) {
5149 WHISPER_LOG_ERROR("%s: failed to allocate the compute buffer\n", __func__);
5150 return false;
5151 }
5152
5153 struct ggml_tensor * frame = ggml_graph_get_tensor(gf, "frame");
5154 struct ggml_tensor * prob = ggml_graph_get_tensor(gf, "prob");
5155
5156 // we are going to reuse the graph multiple times for each chunk
5157 const int64_t t_start_vad_us = ggml_time_us();
5158
5159 for (int i = 0; i < n_chunks; i++) {
5160 const int idx_start = i * vctx->n_window;
5161 const int idx_end = std::min(idx_start + vctx->n_window, n_samples);
5162
5163 const int chunk_len = idx_end - idx_start;
5164
5165 if (chunk_len < vctx->n_window) {
5166 WHISPER_LOG_INFO("%s: chunk_len: %d < n_window: %d\n", __func__, chunk_len, vctx->n_window);
5167 std::vector<float> partial_chunk(vctx->n_window, 0.0f);
5168 std::copy(samples + idx_start, samples + idx_end, partial_chunk.begin());
5169
5170 // Copy the zero-padded chunk to the window.
5171 const int samples_to_copy_max = vctx->n_window;
5172 const int samples_to_copy_cur = std::min(samples_to_copy_max, (int)partial_chunk.size());
5173 std::copy(partial_chunk.begin(), partial_chunk.begin() + samples_to_copy_cur, window.begin());
5174 if (samples_to_copy_cur < samples_to_copy_max) {
5175 std::fill(window.begin() + samples_to_copy_cur, window.end(), 0.0f);
5176 }
5177 } else {
5178 // Copy current frame samples to the window.
5179 const int samples_to_copy = std::min(idx_end - idx_start, vctx->n_window);
5180 std::copy(samples + idx_start, samples + idx_start + samples_to_copy, window.begin());
5181 }
5182
5183 // Set the frame tensor data with the samples.
5184 ggml_backend_tensor_set(frame, window.data(), 0, ggml_nelements(frame) * sizeof(float));
5185
5186 // do not reset the scheduler - we will reuse the graph in the next chunk
5187 if (!ggml_graph_compute_helper(sched, gf, vctx->n_threads, false)) {
5188 WHISPER_LOG_ERROR("%s: failed to compute VAD graph\n", __func__);
5189 break;
5190 }
5191
5192 // Get the probability for this chunk.
5193 ggml_backend_tensor_get(prob, &vctx->probs[i], 0, sizeof(float));
5194
5195 //WHISPER_LOG_DEBUG("chunk %d: p = %7.3f\n", i, probs[i]);
5196 }
5197
5198 vctx->t_vad_us += ggml_time_us() - t_start_vad_us;
5199 WHISPER_LOG_INFO("%s: vad time = %.2f ms processing %d samples\n", __func__, 1e-3f * vctx->t_vad_us, n_samples);
5200
5201 ggml_backend_sched_reset(sched);
5202
5203 return true;
5204 }
5205
5206 int whisper_vad_segments_n_segments(struct whisper_vad_segments * segments) {
5207 return segments->data.size();
5208 }
5209
5210 float whisper_vad_segments_get_segment_t0(struct whisper_vad_segments * segments, int i_segment) {
5211 return segments->data[i_segment].start;
5212 }
5213
5214 float whisper_vad_segments_get_segment_t1(struct whisper_vad_segments * segments, int i_segment) {
5215 return segments->data[i_segment].end;
5216 }
5217
5218 int whisper_vad_n_probs(struct whisper_vad_context * vctx) {
5219 return vctx->probs.size();
5220 }
5221
5222 float * whisper_vad_probs(struct whisper_vad_context * vctx) {
5223 return vctx->probs.data();
5224 }
5225
5226 struct whisper_vad_segments * whisper_vad_segments_from_probs(
5227 struct whisper_vad_context * vctx,
5228 whisper_vad_params params) {
5229 WHISPER_LOG_INFO("%s: detecting speech timestamps using %d probabilities\n", __func__, whisper_vad_n_probs(vctx));
5230
5231 int n_probs = whisper_vad_n_probs(vctx);
5232 float * probs = whisper_vad_probs(vctx);
5233 float threshold = params.threshold;
5234 int min_speech_duration_ms = params.min_speech_duration_ms;
5235 int min_silence_duration_ms = params.min_silence_duration_ms;
5236 float max_speech_duration_s = params.max_speech_duration_s;
5237 int speech_pad_ms = params.speech_pad_ms;
5238 int n_window = vctx->n_window;
5239 int sample_rate = WHISPER_SAMPLE_RATE;
5240 int min_silence_samples = sample_rate * min_silence_duration_ms / 1000;
5241 int audio_length_samples = n_probs * n_window;
5242
5243 // Min number of samples to be considered valid speech.
5244 int min_speech_samples = sample_rate * min_speech_duration_ms / 1000;
5245 int speech_pad_samples = sample_rate * speech_pad_ms / 1000;
5246
5247 // Max number of samples that a speech segment can contain before it is
5248 // split into multiple segments.
5249 int max_speech_samples;
5250 if (max_speech_duration_s > 100000.0f) {
5251 max_speech_samples = INT_MAX / 2;
5252 } else {
5253 int64_t temp = (int64_t)sample_rate * (int64_t)(max_speech_duration_s) - n_window - 2 * speech_pad_samples;
5254 max_speech_samples = (temp > INT_MAX) ? INT_MAX / 2 : (int)temp;
5255 if (max_speech_samples < 0) {
5256 max_speech_samples = INT_MAX / 2;
5257 }
5258 }
5259 // Detect silence period that exceeds this value, then that location (sample)
5260 // is marked as a potential place where the segment could be split if
5261 // max_speech_samples is reached. The value 98 was taken from the original
5262 // silaro-vad python implementation:
5263 //https://github.com/snakers4/silero-vad/blob/0dd45f0bcd7271463c234f3bae5ad25181f9df8b/src/silero_vad/utils_vad.py#L291
5264 int min_silence_samples_at_max_speech = sample_rate * 98 / 1000;
5265
5266 // Calculate lower threshold for detecting end of speech segments.
5267 float neg_threshold = threshold - 0.15f;
5268 if (neg_threshold < 0.01f) {
5269 neg_threshold = 0.01f;
5270 }
5271
5272 struct speech_segment_t {
5273 int start;
5274 int end;
5275 };
5276
5277 std::vector<speech_segment_t> speeches;
5278 speeches.reserve(256);
5279
5280 bool is_speech_segment = false;
5281 int temp_end = 0;
5282 int prev_end = 0;
5283 int next_start = 0;
5284 int curr_speech_start = 0;
5285 bool has_curr_speech = false;
5286
5287 for (int i = 0; i < n_probs; i++) {
5288 float curr_prob = probs[i];
5289 int curr_sample = n_window * i;
5290
5291 // Reset temp_end when we get back to speech
5292 if ((curr_prob >= threshold) && temp_end) {
5293 temp_end = 0;
5294 if (next_start < prev_end) {
5295 next_start = curr_sample;
5296 }
5297 }
5298
5299 // Start a new speech segment when probability exceeds threshold and not already in speech
5300 if ((curr_prob >= threshold) && !is_speech_segment) {
5301 is_speech_segment = true;
5302 curr_speech_start = curr_sample;
5303 has_curr_speech = true;
5304 continue;
5305 }
5306
5307 // Handle maximum speech duration
5308 if (is_speech_segment && (curr_sample - curr_speech_start) > max_speech_samples) {
5309 if (prev_end) {
5310 speeches.push_back({ curr_speech_start, prev_end });
5311 has_curr_speech = true;
5312
5313 if (next_start < prev_end) { // Previously reached silence and is still not speech
5314 is_speech_segment = false;
5315 has_curr_speech = false;
5316 } else {
5317 curr_speech_start = next_start;
5318 }
5319 prev_end = next_start = temp_end = 0;
5320 } else {
5321 speeches.push_back({ curr_speech_start, curr_sample });
5322
5323 prev_end = next_start = temp_end = 0;
5324 is_speech_segment = false;
5325 has_curr_speech = false;
5326 continue;
5327 }
5328 }
5329
5330 // Handle silence after speech
5331 if ((curr_prob < neg_threshold) && is_speech_segment) {
5332 if (!temp_end) {
5333 temp_end = curr_sample;
5334 }
5335
5336 // Track potential segment ends for max_speech handling
5337 if ((curr_sample - temp_end) > min_silence_samples_at_max_speech) {
5338 prev_end = temp_end;
5339 }
5340
5341 // Check if silence is long enough to end the segment
5342 if ((curr_sample - temp_end) < min_silence_samples) {
5343 continue;
5344 } else {
5345 // End the segment if it's long enough
5346 if ((temp_end - curr_speech_start) > min_speech_samples) {
5347 speeches.push_back({ curr_speech_start, temp_end });
5348 }
5349
5350 prev_end = next_start = temp_end = 0;
5351 is_speech_segment = false;
5352 has_curr_speech = false;
5353 continue;
5354 }
5355 }
5356 }
5357
5358 // Handle the case if we're still in a speech segment at the end
5359 if (has_curr_speech && (audio_length_samples - curr_speech_start) > min_speech_samples) {
5360 speeches.push_back({ curr_speech_start, audio_length_samples });
5361 }
5362
5363 // Merge adjacent segments with small gaps in between (post-processing)
5364 if (speeches.size() > 1) {
5365 int merged_count = 0;
5366 for (int i = 0; i < (int) speeches.size() - 1; i++) {
5367 // Define maximum gap allowed for merging (e.g., 200ms converted to samples)
5368 int max_merge_gap_samples = sample_rate * 200 / 1000;
5369
5370 // If the gap between this segment and the next is small enough
5371 if (speeches[i+1].start - speeches[i].end < max_merge_gap_samples) {
5372 // Merge by extending current segment to the end of next segment
5373 speeches[i].end = speeches[i+1].end;
5374 speeches.erase(speeches.begin() + i + 1);
5375
5376 i--;
5377 merged_count++;
5378 }
5379 }
5380 WHISPER_LOG_INFO("%s: Merged %d adjacent segments, now have %d segments\n",
5381 __func__, merged_count, (int) speeches.size());
5382 }
5383
5384 // Double-check for minimum speech duration
5385 for (int i = 0; i < (int) speeches.size(); i++) {
5386 if (speeches[i].end - speeches[i].start < min_speech_samples) {
5387 WHISPER_LOG_INFO("%s: Removing segment %d (too short: %d samples)\n",
5388 __func__, i, speeches[i].end - speeches[i].start);
5389
5390 speeches.erase(speeches.begin() + i);
5391 i--;
5392 }
5393 }
5394
5395 WHISPER_LOG_INFO("%s: Final speech segments after filtering: %d\n", __func__, (int) speeches.size());
5396
5397 // Allocate final segments
5398 std::vector<whisper_vad_segment> segments;
5399 if (speeches.size() > 0) {
5400 try {
5401 segments.resize(speeches.size());
5402 } catch (const std::bad_alloc &) {
5403 WHISPER_LOG_ERROR("%s: failed to allocate memory for final segments\n", __func__);
5404 return nullptr;
5405 }
5406 }
5407
5408 // Apply padding to segments and copy to final segments
5409 for (int i = 0; i < (int) speeches.size(); i++) {
5410 // Apply padding to the start of the first segment
5411 if (i == 0) {
5412 speeches[i].start =
5413 (speeches[i].start > speech_pad_samples) ?
5414 (speeches[i].start - speech_pad_samples) : 0;
5415 }
5416
5417 // Handle spacing between segments
5418 if (i < (int) speeches.size() - 1) {
5419 int silence_duration = speeches[i+1].start - speeches[i].end;
5420
5421 if (silence_duration < 2 * speech_pad_samples) {
5422 // If segments are close, split the difference
5423 speeches[i].end += silence_duration / 2;
5424 speeches[i+1].start =
5425 (speeches[i+1].start > silence_duration / 2) ?
5426 (speeches[i+1].start - silence_duration / 2) : 0;
5427 } else {
5428 // Otherwise, apply full padding to both
5429 speeches[i].end =
5430 (speeches[i].end + speech_pad_samples < audio_length_samples) ?
5431 (speeches[i].end + speech_pad_samples) : audio_length_samples;
5432 speeches[i+1].start =
5433 (speeches[i+1].start > speech_pad_samples) ?
5434 (speeches[i+1].start - speech_pad_samples) : 0;
5435 }
5436 } else {
5437 // Apply padding to the end of the last segment
5438 speeches[i].end =
5439 (speeches[i].end + speech_pad_samples < audio_length_samples) ?
5440 (speeches[i].end + speech_pad_samples) : audio_length_samples;
5441 }
5442
5443 // Convert from samples to centiseconds
5444 segments[i].start = samples_to_cs(speeches[i].start);
5445 segments[i].end = samples_to_cs(speeches[i].end);
5446
5447 WHISPER_LOG_INFO("%s: VAD segment %d: start = %.2f, end = %.2f (duration: %.2f)\n",
5448 __func__, i, segments[i].start/100.0, segments[i].end/100.0, (segments[i].end - segments[i].start)/100.0);
5449 }
5450
5451 whisper_vad_segments * vad_segments = new whisper_vad_segments;
5452 if (vad_segments == NULL) {
5453 WHISPER_LOG_ERROR("%s: failed to allocate memory for whisper_vad_segments\n", __func__);
5454 return nullptr;
5455 }
5456
5457 vad_segments->data = std::move(segments);
5458
5459 return vad_segments;
5460 }
5461
5462 struct whisper_vad_segments * whisper_vad_segments_from_samples(
5463 whisper_vad_context * vctx,
5464 whisper_vad_params params,
5465 const float * samples,
5466 int n_samples) {
5467 WHISPER_LOG_INFO("%s: detecting speech timestamps in %d samples\n", __func__, n_samples);
5468 if (!whisper_vad_detect_speech(vctx, samples, n_samples)) {
5469 WHISPER_LOG_ERROR("%s: failed to detect speech\n", __func__);
5470 return nullptr;
5471 }
5472 return whisper_vad_segments_from_probs(vctx, params);
5473 }
5474
5475 void whisper_vad_free(whisper_vad_context * ctx) {
5476 if (ctx) {
5477 if (ctx->buffer) {
5478 ggml_backend_buffer_free(ctx->buffer);
5479 }
5480 for (ggml_context * context : ctx->model.ctxs) {
5481 ggml_free(context);
5482 }
5483
5484 for (ggml_backend_buffer_t buf : ctx->model.buffers) {
5485 ggml_backend_buffer_free(buf);
5486 }
5487
5488 ggml_backend_sched_free(ctx->sched.sched);
5489
5490 for (auto & backend : ctx->backends) {
5491 ggml_backend_free(backend);
5492 }
5493
5494 delete[] ctx->model.hparams.encoder_in_channels;
5495 delete[] ctx->model.hparams.encoder_out_channels;
5496 delete[] ctx->model.hparams.kernel_sizes;
5497
5498 delete ctx;
5499 }
5500 }
5501
5502 void whisper_vad_free_segments(whisper_vad_segments * segments) {
5503 if (segments) {
5504 delete segments;
5505 }
5506 }
5507
5508 //////////////////////////////////
5509 // Grammar - ported from llama.cpp
5510 //////////////////////////////////
5511
5512 // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
5513 // pointer. If an invalid sequence is encountered, returns `whisper_partial_utf8.n_remain == -1`.
5514 static std::pair<std::vector<uint32_t>, whisper_partial_utf8> decode_utf8(
5515 const char * src,
5516 whisper_partial_utf8 partial_start) {
5517 static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
5518 const char * pos = src;
5519 std::vector<uint32_t> code_points;
5520 uint32_t value = partial_start.value;
5521 int n_remain = partial_start.n_remain;
5522
5523 // continue previous decode, if applicable
5524 while (*pos != 0 && n_remain > 0) {
5525 uint8_t next_byte = static_cast<uint8_t>(*pos);
5526 if ((next_byte >> 6) != 2) {
5527 // invalid sequence, abort
5528 code_points.push_back(0);
5529 return std::make_pair(std::move(code_points), whisper_partial_utf8{ 0, -1 });
5530 }
5531 value = (value << 6) + (next_byte & 0x3F);
5532 ++pos;
5533 --n_remain;
5534 }
5535
5536 if (partial_start.n_remain > 0 && n_remain == 0) {
5537 code_points.push_back(value);
5538 }
5539
5540 // decode any subsequent utf-8 sequences, which may end in an incomplete one
5541 while (*pos != 0) {
5542 uint8_t first_byte = static_cast<uint8_t>(*pos);
5543 uint8_t highbits = first_byte >> 4;
5544 n_remain = lookup[highbits] - 1;
5545
5546 if (n_remain < 0) {
5547 // invalid sequence, abort
5548 code_points.clear();
5549 code_points.push_back(0);
5550 return std::make_pair(std::move(code_points), whisper_partial_utf8{ 0, n_remain });
5551 }
5552
5553 uint8_t mask = (1 << (7 - n_remain)) - 1;
5554 value = first_byte & mask;
5555 ++pos;
5556 while (*pos != 0 && n_remain > 0) {
5557 value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
5558 ++pos;
5559 --n_remain;
5560 }
5561 if (n_remain == 0) {
5562 code_points.push_back(value);
5563 }
5564 }
5565 code_points.push_back(0);
5566
5567 return std::make_pair(std::move(code_points), whisper_partial_utf8{ value, n_remain });
5568 }
5569
5570 // returns true iff pos points to the end of one of the definitions of a rule
5571 static bool whisper_grammar_is_end_of_sequence(const whisper_grammar_element * pos) {
5572 switch (pos->type) {
5573 case WHISPER_GRETYPE_END: return true; // NOLINT
5574 case WHISPER_GRETYPE_ALT: return true; // NOLINT
5575 default: return false;
5576 }
5577 }
5578
5579 // returns true iff chr satisfies the char range at pos (regular or inverse range)
5580 // asserts that pos is pointing to a char range element
5581 static std::pair<bool, const whisper_grammar_element *> whisper_grammar_match_char(
5582 const whisper_grammar_element * pos,
5583 const uint32_t chr) {
5584
5585 bool found = false;
5586 bool is_positive_char = pos->type == WHISPER_GRETYPE_CHAR;
5587
5588 WHISPER_ASSERT(is_positive_char || pos->type == WHISPER_GRETYPE_CHAR_NOT); // NOLINT
5589
5590 do {
5591 if (pos[1].type == WHISPER_GRETYPE_CHAR_RNG_UPPER) {
5592 // inclusive range, e.g. [a-z]
5593 found = found || (pos->value <= chr && chr <= pos[1].value);
5594 pos += 2;
5595 } else {
5596 // exact char match, e.g. [a] or "a"
5597 found = found || pos->value == chr;
5598 pos += 1;
5599 }
5600 } while (pos->type == WHISPER_GRETYPE_CHAR_ALT);
5601
5602 return std::make_pair(found == is_positive_char, pos);
5603 }
5604
5605 // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
5606 // range at pos (regular or inverse range)
5607 // asserts that pos is pointing to a char range element
5608 static bool whisper_grammar_match_partial_char(
5609 const whisper_grammar_element * pos,
5610 const whisper_partial_utf8 partial_utf8) {
5611
5612 bool is_positive_char = pos->type == WHISPER_GRETYPE_CHAR;
5613 WHISPER_ASSERT(is_positive_char || pos->type == WHISPER_GRETYPE_CHAR_NOT);
5614
5615 uint32_t partial_value = partial_utf8.value;
5616 int n_remain = partial_utf8.n_remain;
5617
5618 // invalid sequence or 7-bit char split across 2 bytes (overlong)
5619 if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
5620 return false;
5621 }
5622
5623 // range of possible code points this partial UTF-8 sequence could complete to
5624 uint32_t low = partial_value << (n_remain * 6);
5625 uint32_t high = low | ((1 << (n_remain * 6)) - 1);
5626
5627 if (low == 0) {
5628 if (n_remain == 2) {
5629 low = 1 << 11;
5630 } else if (n_remain == 3) {
5631 low = 1 << 16;
5632 }
5633 }
5634
5635 do {
5636 if (pos[1].type == WHISPER_GRETYPE_CHAR_RNG_UPPER) {
5637 // inclusive range, e.g. [a-z]
5638 if (pos->value <= high && low <= pos[1].value) {
5639 return is_positive_char;
5640 }
5641 pos += 2;
5642 } else {
5643 // exact char match, e.g. [a] or "a"
5644 if (low <= pos->value && pos->value <= high) {
5645 return is_positive_char;
5646 }
5647 pos += 1;
5648 }
5649 } while (pos->type == WHISPER_GRETYPE_CHAR_ALT);
5650
5651 return !is_positive_char;
5652 }
5653
5654
5655 // transforms a grammar pushdown stack into N possible stacks, all ending
5656 // at a character range (terminal element)
5657 static void whisper_grammar_advance_stack(
5658 const std::vector<std::vector<whisper_grammar_element>> & rules,
5659 const std::vector<const whisper_grammar_element *> & stack,
5660 std::vector<std::vector<const whisper_grammar_element *>> & new_stacks) {
5661
5662 if (stack.empty()) {
5663 new_stacks.emplace_back();
5664 return;
5665 }
5666
5667 const whisper_grammar_element * pos = stack.back();
5668
5669 switch (pos->type) {
5670 case WHISPER_GRETYPE_RULE_REF: {
5671 const size_t rule_id = static_cast<size_t>(pos->value);
5672 const whisper_grammar_element * subpos = rules[rule_id].data();
5673 do {
5674 // init new stack without the top (pos)
5675 std::vector<const whisper_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
5676 if (!whisper_grammar_is_end_of_sequence(pos + 1)) {
5677 // if this rule ref is followed by another element, add that to stack
5678 new_stack.push_back(pos + 1);
5679 }
5680 if (!whisper_grammar_is_end_of_sequence(subpos)) {
5681 // if alternate is nonempty, add to stack
5682 new_stack.push_back(subpos);
5683 }
5684 whisper_grammar_advance_stack(rules, new_stack, new_stacks);
5685 while (!whisper_grammar_is_end_of_sequence(subpos)) {
5686 // scan to end of alternate def
5687 subpos++;
5688 }
5689 if (subpos->type == WHISPER_GRETYPE_ALT) {
5690 // there's another alternate def of this rule to process
5691 subpos++;
5692 } else {
5693 break;
5694 }
5695 } while (true);
5696 break;
5697 }
5698 case WHISPER_GRETYPE_CHAR:
5699 case WHISPER_GRETYPE_CHAR_NOT:
5700 new_stacks.push_back(stack);
5701 break;
5702 default:
5703 // end of alternate (WHISPER_GRETYPE_END, WHISPER_GRETYPE_ALT) or middle of char range
5704 // (WHISPER_GRETYPE_CHAR_ALT, WHISPER_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
5705 // those
5706 WHISPER_ASSERT(false);
5707 }
5708 }
5709
5710 // takes a set of possible pushdown stacks on a grammar, which are required to
5711 // be positioned at a character range (see `whisper_grammar_advance_stack`), and
5712 // produces the N possible stacks if the given char is accepted at those
5713 // positions
5714 static std::vector<std::vector<const whisper_grammar_element *>> whisper_grammar_accept(
5715 const std::vector<std::vector<whisper_grammar_element>> & rules,
5716 const std::vector<std::vector<const whisper_grammar_element *>> & stacks,
5717 const uint32_t chr) {
5718
5719 std::vector<std::vector<const whisper_grammar_element *>> new_stacks;
5720
5721 for (const auto & stack : stacks) {
5722 if (stack.empty()) {
5723 continue;
5724 }
5725
5726 auto match = whisper_grammar_match_char(stack.back(), chr);
5727 if (match.first) {
5728 const whisper_grammar_element * pos = match.second;
5729
5730 // update top of stack to next element, if any
5731 std::vector<const whisper_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
5732 if (!whisper_grammar_is_end_of_sequence(pos)) {
5733 new_stack.push_back(pos);
5734 }
5735 whisper_grammar_advance_stack(rules, new_stack, new_stacks);
5736 }
5737 }
5738
5739 return new_stacks;
5740 }
5741
5742 static std::vector<whisper_grammar_candidate> whisper_grammar_reject_candidates(
5743 const std::vector<std::vector<whisper_grammar_element>> & rules,
5744 const std::vector<std::vector<const whisper_grammar_element *>> & stacks,
5745 const std::vector<whisper_grammar_candidate> & candidates);
5746
5747 static std::vector<whisper_grammar_candidate> whisper_grammar_reject_candidates_for_stack(
5748 const std::vector<std::vector<whisper_grammar_element>> & rules,
5749 const std::vector<const whisper_grammar_element *> & stack,
5750 const std::vector<whisper_grammar_candidate> & candidates) {
5751
5752 std::vector<whisper_grammar_candidate> rejects;
5753
5754 if (stack.empty()) {
5755 for (auto tok : candidates) {
5756 if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
5757 rejects.push_back(tok);
5758 }
5759 }
5760 return rejects;
5761 }
5762
5763 const whisper_grammar_element * stack_pos = stack.back();
5764
5765 std::vector<whisper_grammar_candidate> next_candidates;
5766 for (auto tok : candidates) {
5767 if (*tok.code_points == 0) {
5768 // reached end of full codepoints in token, reject iff it ended in a partial sequence
5769 // that cannot satisfy this position in grammar
5770 if (tok.partial_utf8.n_remain != 0 && !whisper_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
5771 rejects.push_back(tok);
5772 }
5773 } else if (whisper_grammar_match_char(stack_pos, *tok.code_points).first) {
5774 next_candidates.push_back({ tok.id, tok.code_points + 1, tok.partial_utf8 });
5775 } else {
5776 rejects.push_back(tok);
5777 }
5778 }
5779
5780 const auto * stack_pos_after = whisper_grammar_match_char(stack_pos, 0).second;
5781
5782 // update top of stack to next element, if any
5783 std::vector<const whisper_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
5784 if (!whisper_grammar_is_end_of_sequence(stack_pos_after)) {
5785 stack_after.push_back(stack_pos_after);
5786 }
5787 std::vector<std::vector<const whisper_grammar_element *>> next_stacks;
5788 whisper_grammar_advance_stack(rules, stack_after, next_stacks);
5789
5790 auto next_rejects = whisper_grammar_reject_candidates(rules, next_stacks, next_candidates);
5791 for (auto tok : next_rejects) {
5792 rejects.push_back({ tok.id, tok.code_points - 1, tok.partial_utf8 });
5793 }
5794
5795 return rejects;
5796 }
5797
5798 static std::vector<whisper_grammar_candidate> whisper_grammar_reject_candidates(
5799 const std::vector<std::vector<whisper_grammar_element>> & rules,
5800 const std::vector<std::vector<const whisper_grammar_element *>> & stacks,
5801 const std::vector<whisper_grammar_candidate> & candidates) {
5802 if (candidates.empty() || stacks.empty()) {
5803 return std::vector<whisper_grammar_candidate>();
5804 }
5805
5806 auto rejects = whisper_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
5807
5808 for (size_t i = 1, size = stacks.size(); i < size; ++i) {
5809 rejects = whisper_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
5810 }
5811 return rejects;
5812 }
5813
5814 static struct whisper_grammar whisper_grammar_init(
5815 const whisper_grammar_element ** rules,
5816 size_t n_rules,
5817 size_t i_start_rule) {
5818 const whisper_grammar_element * pos;
5819
5820 // copy rule definitions into vectors
5821 std::vector<std::vector<whisper_grammar_element>> vec_rules(n_rules);
5822 for (size_t i = 0; i < n_rules; i++) {
5823 for (pos = rules[i]; pos->type != WHISPER_GRETYPE_END; pos++) {
5824 vec_rules[i].push_back(*pos);
5825 }
5826 vec_rules[i].push_back({WHISPER_GRETYPE_END, 0});
5827 }
5828
5829 // loop over alternates of start rule to build initial stacks
5830 std::vector<std::vector<const whisper_grammar_element *>> stacks;
5831 pos = rules[i_start_rule];
5832 do {
5833 std::vector<const whisper_grammar_element *> stack;
5834 if (!whisper_grammar_is_end_of_sequence(pos)) {
5835 // if alternate is nonempty, add to stack
5836 stack.push_back(pos);
5837 }
5838 whisper_grammar_advance_stack(vec_rules, stack, stacks);
5839 while (!whisper_grammar_is_end_of_sequence(pos)) {
5840 // scan to end of alternate def
5841 pos++;
5842 }
5843 if (pos->type == WHISPER_GRETYPE_ALT) {
5844 // there's another alternate def of this rule to process
5845 pos++;
5846 } else {
5847 break;
5848 }
5849 } while (true);
5850
5851 return { std::move(vec_rules), std::move(stacks), {} };
5852 }
5853
5854 static void whisper_suppress_invalid_grammar(
5855 whisper_context & ctx,
5856 const whisper_full_params & params,
5857 std::vector<float> & logits,
5858 const whisper_grammar & grammar) {
5859
5860 if (grammar.rules.empty() || grammar.stacks.empty()) {
5861 return;
5862 }
5863
5864 //bool allow_eot = false;
5865 //for (const auto & stack : grammar.stacks) {
5866 // if (stack.empty()) {
5867 // allow_eot = true;
5868 // break;
5869 // }
5870 //}
5871
5872 const whisper_token eot = whisper_token_eot(&ctx);
5873
5874 std::vector<std::pair<std::vector<uint32_t>, whisper_partial_utf8>> candidates_decoded;
5875 std::vector<whisper_grammar_candidate> candidates_grammar;
5876
5877 for (whisper_token id = 0; id < eot; ++id) {
5878 const std::string & text = ctx.vocab.id_to_token[id];
5879 if (!text.empty()) {
5880 candidates_decoded.push_back(decode_utf8(text.c_str(), grammar.partial_utf8));
5881 candidates_grammar.push_back({ id, candidates_decoded.back().first.data(), candidates_decoded.back().second });
5882 }
5883 }
5884
5885 const auto rejects = whisper_grammar_reject_candidates(grammar.rules, grammar.stacks, candidates_grammar);
5886
5887 for (const auto & reject : rejects) {
5888 logits[reject.id] -= params.grammar_penalty;
5889 }
5890
5891 // when the grammar allows a continuation, we penalize the end-of-text token
5892 //if (!allow_eot) {
5893 // logits[eot] -= params.grammar_penalty;
5894 //}
5895 //fprintf(stderr, "Allowed: (%zu tokens)\n", size - rejects.size());
5896 }
5897
5898 static void whisper_grammar_accept_token(whisper_context & ctx, whisper_grammar & grammar, whisper_token token) {
5899 if (grammar.rules.empty() || grammar.stacks.empty()) {
5900 return;
5901 }
5902
5903 //fprintf(stderr, "Accept: '%s'\n", ctx.vocab.id_to_token[token].c_str());
5904
5905 const std::string & text = ctx.vocab.id_to_token[token];
5906
5907 if (text.rfind("[_", 0) == 0) {
5908 // fprintf(stderr, " (skipped)\n");
5909 return;
5910 }
5911 // fprintf(stderr, "\n");
5912
5913 // Note terminating 0 in decoded string
5914 const auto decoded = decode_utf8(text.c_str(), grammar.partial_utf8);
5915 const auto & code_points = decoded.first;
5916 for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
5917 grammar.stacks = whisper_grammar_accept(grammar.rules, grammar.stacks, *it);
5918 }
5919 grammar.partial_utf8 = decoded.second;
5920 }
5921
5922 //////////////
5923 // END grammar
5924 //////////////
5925
5926 ////////////////////////////////////////////////////////////////////////////
5927
5928 struct whisper_context_params * whisper_context_default_params_by_ref(void) {
5929 struct whisper_context_params params = whisper_context_default_params();
5930
5931 struct whisper_context_params* result = new whisper_context_params();
5932 *result = params;
5933 return result;
5934 }
5935
5936 struct whisper_full_params * whisper_full_default_params_by_ref(enum whisper_sampling_strategy strategy) {
5937 struct whisper_full_params params = whisper_full_default_params(strategy);
5938
5939 struct whisper_full_params* result = new whisper_full_params();
5940 *result = params;
5941 return result;
5942 }
5943
5944 struct whisper_full_params whisper_full_default_params(enum whisper_sampling_strategy strategy) {
5945 struct whisper_full_params result = {
5946 /*.strategy =*/ strategy,
5947
5948 /*.n_threads =*/ std::min(4, (int32_t) std::thread::hardware_concurrency()),
5949 /*.n_max_text_ctx =*/ 16384,
5950 /*.offset_ms =*/ 0,
5951 /*.duration_ms =*/ 0,
5952
5953 /*.translate =*/ false,
5954 /*.no_context =*/ true,
5955 /*.no_timestamps =*/ false,
5956 /*.single_segment =*/ false,
5957 /*.print_special =*/ false,
5958 /*.print_progress =*/ true,
5959 /*.print_realtime =*/ false,
5960 /*.print_timestamps =*/ true,
5961
5962 /*.token_timestamps =*/ false,
5963 /*.thold_pt =*/ 0.01f,
5964 /*.thold_ptsum =*/ 0.01f,
5965 /*.max_len =*/ 0,
5966 /*.split_on_word =*/ false,
5967 /*.max_tokens =*/ 0,
5968
5969 /*.debug_mode =*/ false,
5970 /*.audio_ctx =*/ 0,
5971
5972 /*.tdrz_enable =*/ false,
5973
5974 /* suppress_regex =*/ nullptr,
5975
5976 /*.initial_prompt =*/ nullptr,
5977 /*.carry_initial_prompt =*/ false,
5978 /*.prompt_tokens =*/ nullptr,
5979 /*.prompt_n_tokens =*/ 0,
5980
5981 /*.language =*/ "en",
5982 /*.detect_language =*/ false,
5983
5984 /*.suppress_blank =*/ true,
5985 /*.suppress_nst =*/ false,
5986
5987 /*.temperature =*/ 0.0f,
5988 /*.max_initial_ts =*/ 1.0f,
5989 /*.length_penalty =*/ -1.0f,
5990
5991 /*.temperature_inc =*/ 0.2f,
5992 /*.entropy_thold =*/ 2.4f,
5993 /*.logprob_thold =*/ -1.0f,
5994 /*.no_speech_thold =*/ 0.6f,
5995
5996 /*.greedy =*/ {
5997 /*.best_of =*/ -1,
5998 },
5999
6000 /*.beam_search =*/ {
6001 /*.beam_size =*/ -1,
6002
6003 /*.patience =*/ -1.0f,
6004 },
6005
6006 /*.new_segment_callback =*/ nullptr,
6007 /*.new_segment_callback_user_data =*/ nullptr,
6008
6009 /*.progress_callback =*/ nullptr,
6010 /*.progress_callback_user_data =*/ nullptr,
6011
6012 /*.encoder_begin_callback =*/ nullptr,
6013 /*.encoder_begin_callback_user_data =*/ nullptr,
6014
6015 /*.abort_callback =*/ nullptr,
6016 /*.abort_callback_user_data =*/ nullptr,
6017
6018 /*.logits_filter_callback =*/ nullptr,
6019 /*.logits_filter_callback_user_data =*/ nullptr,
6020
6021 /*.grammar_rules =*/ nullptr,
6022 /*.n_grammar_rules =*/ 0,
6023 /*.i_start_rule =*/ 0,
6024 /*.grammar_penalty =*/ 100.0f,
6025
6026 /*.vad =*/ false,
6027 /*.vad_model_path =*/ nullptr,
6028 /*
6029 Following two variables are added by Anastasia Shchupak on behalf of inclusion into Praat.
6030 In the original whisper.cpp version, VAD model is loaded from a binary file.
6031 Praat contains Silero-VAD model in memory, therefore it needs variables to access this memory.
6032 */
6033 /*.vad_model_data =*/ nullptr,
6034 /*.vad_model_data_size =*/ 0,
6035
6036 /* vad_params =*/ whisper_vad_default_params(),
6037 };
6038
6039 switch (strategy) {
6040 case WHISPER_SAMPLING_GREEDY:
6041 {
6042 result.greedy = {
6043 /*.best_of =*/ 5,
6044 };
6045 } break;
6046 case WHISPER_SAMPLING_BEAM_SEARCH:
6047 {
6048 result.beam_search = {
6049 /*.beam_size =*/ 5,
6050
6051 /*.patience =*/ -1.0f,
6052 };
6053 } break;
6054 }
6055
6056 return result;
6057 }
6058
6059 // forward declarations
6060 static std::vector<float> get_signal_energy(const float * signal, int n_samples, int n_samples_per_half_window);
6061 static void whisper_exp_compute_token_level_timestamps(
6062 struct whisper_context & ctx,
6063 struct whisper_state & state,
6064 int i_segment,
6065 float thold_pt,
6066 float thold_ptsum);
6067
6068 static inline bool should_split_on_word(const char * txt, bool split_on_word) {
6069 if (!split_on_word) return true;
6070
6071 return txt[0] == ' ';
6072 }
6073
6074 // Count UTF-8 characters (not bytes) in a string
6075 static int utf8_len(const char * str) {
6076 int count = 0;
6077 while (*str) {
6078 // Skip continuation bytes (10xxxxxx)
6079 if ((*str & 0xC0) != 0x80) {
6080 count++;
6081 }
6082 str++;
6083 }
6084 return count;
6085 }
6086
6087 static void whisper_exp_compute_token_level_timestamps_dtw(
6088 struct whisper_context * ctx,
6089 struct whisper_state * state,
6090 struct whisper_full_params params,
6091 int i_segment,
6092 size_t n_segments,
6093 int seek,
6094 int n_frames,
6095 int medfilt_width,
6096 int n_threads);
6097
6098 // wrap the last segment to max_len characters
6099 // returns the number of new segments
6100 static int whisper_wrap_segment(struct whisper_context & ctx, struct whisper_state & state, int max_len, bool split_on_word) {
6101 auto segment = state.result_all.back();
6102
6103 int res = 1;
6104 int acc = 0;
6105
6106 std::string text;
6107
6108 for (int i = 0; i < (int) segment.tokens.size(); i++) {
6109 const auto & token = segment.tokens[i];
6110 if (token.id >= whisper_token_eot(&ctx)) {
6111 continue;
6112 }
6113
6114 const auto txt = whisper_token_to_str(&ctx, token.id);
6115 const int cur = utf8_len(txt); // Use UTF-8 character count instead of byte count
6116
6117 if (acc + cur > max_len && i > 0 && should_split_on_word(txt, split_on_word)) {
6118 state.result_all.back().text = std::move(text);
6119 state.result_all.back().t1 = token.t0;
6120 state.result_all.back().tokens.resize(i);
6121 state.result_all.back().speaker_turn_next = false;
6122
6123 state.result_all.push_back({});
6124 state.result_all.back().t0 = token.t0;
6125 state.result_all.back().t1 = segment.t1;
6126
6127 // add tokens [i, end] to the new segment
6128 state.result_all.back().tokens.insert(
6129 state.result_all.back().tokens.end(),
6130 segment.tokens.begin() + i,
6131 segment.tokens.end());
6132
6133 state.result_all.back().speaker_turn_next = segment.speaker_turn_next;
6134
6135 acc = 0;
6136 text = "";
6137
6138 segment = state.result_all.back();
6139 i = -1;
6140
6141 res++;
6142 } else {
6143 acc += cur;
6144 text += txt;
6145 }
6146 }
6147
6148 state.result_all.back().text = std::move(text);
6149
6150 return res;
6151 }
6152
6153 static const std::vector<std::string> non_speech_tokens = {
6154 "\"", "#", "(", ")", "*", "+", "/", ":", ";", "<", "=", ">", "@", "[", "\\", "]", "^",
6155 "_", "`", "{", "|", "}", "~", "「", "」", "『", "』", "<<", ">>", "<<<", ">>>", "--",
6156 "---", "-(", "-[", "('", "(\"", "((", "))", "(((", ")))", "[[", "]]", "{{", "}}", "♪♪",
6157 "♪♪♪","♩", "♪", "♫", "♬", "♭", "♮", "♯"
6158 };
6159
6160 static void whisper_compute_logprobs(
6161 const std::vector<float> & logits,
6162 const int n_logits,
6163 std::vector<float> & logprobs) {
6164 const float logit_max = *std::max_element(logits.begin(), logits.end());
6165 float logsumexp = 0.0f;
6166 for (int i = 0; i < n_logits; ++i) {
6167 if (logits[i] > -INFINITY) {
6168 logsumexp += expf(logits[i] - logit_max);
6169 }
6170 }
6171 logsumexp = logf(logsumexp) + logit_max;
6172
6173 for (int i = 0; i < n_logits; ++i) {
6174 if (logits[i] > -INFINITY) {
6175 logprobs[i] = logits[i] - logsumexp;
6176 } else {
6177 logprobs[i] = -INFINITY;
6178 }
6179 }
6180 }
6181
6182 static void whisper_compute_probs(
6183 const std::vector<float> & logits,
6184 const int n_logits,
6185 const std::vector<float> & logprobs,
6186 std::vector<float> & probs) {
6187 for (int i = 0; i < n_logits; ++i) {
6188 if (logits[i] == -INFINITY) {
6189 probs[i] = 0.0f;
6190 } else {
6191 probs[i] = expf(logprobs[i]);
6192 }
6193 }
6194 }
6195
6196 // process the logits for the selected decoder
6197 // - applies logit filters
6198 // - computes logprobs and probs
6199 // TODO: optimize
6200 static void whisper_process_logits(
6201 struct whisper_context & ctx,
6202 struct whisper_state & state,
6203 struct whisper_decoder & decoder,
6204 const struct whisper_full_params params,
6205 float temperature) {
6206 const auto & vocab = ctx.vocab;
6207 const auto & tokens_cur = decoder.sequence.tokens;
6208
6209 const bool is_initial = tokens_cur.size() == 0;
6210 const int n_logits = vocab.id_to_token.size();
6211
6212 WHISPER_ASSERT(n_logits == ctx.vocab.n_vocab);
6213
6214 // extract the logits for the last token
6215 // we will be mutating, and therefore we don't want to use the ctx.logits buffer directly
6216 auto & probs = decoder.probs;
6217 auto & logits = decoder.logits;
6218 auto & logprobs = decoder.logprobs;
6219 {
6220 logits.resize(n_logits);
6221 memcpy(logits.data(), state.logits.data() + decoder.i_batch*n_logits, n_logits*sizeof(float));
6222
6223 if (temperature > 0.0f) {
6224 for (int i = 0; i < n_logits; i++) {
6225 logits[i] /= temperature;
6226 }
6227 }
6228
6229 // will be populated a bit later
6230 probs.resize(n_logits);
6231 logprobs.resize(n_logits);
6232 }
6233
6234 // apply logit filters here
6235 // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L480-L493
6236 {
6237 // suppress blank
6238 // https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L388-L390
6239 if (params.suppress_blank) {
6240 if (is_initial) {
6241 logits[vocab.token_eot] = -INFINITY;
6242 logits[vocab.token_to_id.at(" ")] = -INFINITY;
6243 }
6244 }
6245
6246 // suppress <|notimestamps|> token
6247 // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L410-L412
6248 logits[vocab.token_not] = -INFINITY;
6249 if (params.no_timestamps) {
6250 for (int i = vocab.token_beg; i < n_logits; ++i) {
6251 logits[i] = -INFINITY;
6252 }
6253 }
6254
6255 // suppress sot and nosp tokens
6256 logits[vocab.token_sot] = -INFINITY;
6257 logits[vocab.token_nosp] = -INFINITY;
6258
6259 // [TDRZ] when tinydiarize is disabled, suppress solm token
6260 if (params.tdrz_enable == false) {
6261 logits[vocab.token_solm] = -INFINITY;
6262 }
6263
6264 // suppress task tokens
6265 logits[vocab.token_translate] = -INFINITY;
6266 logits[vocab.token_transcribe] = -INFINITY;
6267 logits[vocab.token_prev] = -INFINITY;
6268
6269 // suppress lang tokens
6270 for (size_t i = 0; i < g_lang.size(); ++i) {
6271 logits[whisper_token_lang(&ctx, i)] = -INFINITY;
6272 }
6273
6274 // suppress prev token
6275 logits[vocab.token_prev] = -INFINITY;
6276
6277 if (params.logits_filter_callback) {
6278 params.logits_filter_callback(&ctx, &state, tokens_cur.data(), tokens_cur.size(), logits.data(), params.logits_filter_callback_user_data);
6279 }
6280
6281 // suppress any tokens matching a regular expression
6282 // ref: https://github.com/openai/whisper/discussions/1041
6283 if (params.suppress_regex != nullptr) {
6284 std::regex re(params.suppress_regex);
6285 for (std::pair<whisper_vocab::token, whisper_vocab::id> token_id : vocab.token_to_id) {
6286 if (std::regex_match(token_id.first, re)) {
6287 logits[token_id.second] = -INFINITY;
6288 }
6289 }
6290 }
6291
6292 // suppress non-speech tokens
6293 // ref: https://github.com/openai/whisper/blob/7858aa9c08d98f75575035ecd6481f462d66ca27/whisper/tokenizer.py#L224-L253
6294 if (params.suppress_nst) {
6295 for (const std::string & token : non_speech_tokens) {
6296 const std::string suppress_tokens[] = {token, " " + token};
6297 for (const std::string & suppress_token : suppress_tokens) {
6298 if (vocab.token_to_id.find(suppress_token) != vocab.token_to_id.end()) {
6299 logits[vocab.token_to_id.at(suppress_token)] = -INFINITY;
6300 }
6301 }
6302 }
6303
6304 // allow hyphens "-" and single quotes "'" between words, but not at the beginning of a word
6305 if (vocab.token_to_id.find(" -") != vocab.token_to_id.end()) {
6306 logits[vocab.token_to_id.at(" -")] = -INFINITY;
6307 }
6308 if (vocab.token_to_id.find(" '") != vocab.token_to_id.end()) {
6309 logits[vocab.token_to_id.at(" '")] = -INFINITY;
6310 }
6311 }
6312
6313 // timestamps have to appear in pairs, except directly before EOT; mask logits accordingly
6314 // https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L414-L424
6315 {
6316 const bool last_was_timestamp = tokens_cur.size() > 0 && tokens_cur.back().id >= vocab.token_beg;
6317 const bool penultimate_was_timestamp = tokens_cur.size() < 2 || tokens_cur[tokens_cur.size() - 2].id >= vocab.token_beg;
6318
6319 //WHISPER_LOG_INFO("last_was_timestamp=%d penultimate_was_timestamp=%d\n", last_was_timestamp, penultimate_was_timestamp);
6320
6321 if (last_was_timestamp) {
6322 if (penultimate_was_timestamp) {
6323 for (int i = vocab.token_beg; i < n_logits; ++i) {
6324 logits[i] = -INFINITY;
6325 }
6326 } else {
6327 for (int i = 0; i < vocab.token_eot; ++i) {
6328 logits[i] = -INFINITY;
6329 }
6330 }
6331 }
6332 }
6333
6334 // the initial timestamp cannot be larger than max_initial_ts
6335 // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L426-L429
6336 if (is_initial && params.max_initial_ts > 0.0f) {
6337 const float precision = float(WHISPER_CHUNK_SIZE)/ctx.model.hparams.n_audio_ctx;
6338 const int tid0 = std::round(params.max_initial_ts/precision);
6339
6340 for (int i = vocab.token_beg + tid0 + 1; i < n_logits; ++i) {
6341 logits[i] = -INFINITY;
6342 }
6343 }
6344
6345 // condition timestamp tokens to be increasing
6346 // ref: https://github.com/openai/whisper/pull/831#issuecomment-1385910556
6347 if (decoder.has_ts) {
6348 const int tid0 = decoder.seek_delta/2;
6349
6350 for (int i = vocab.token_beg; i < vocab.token_beg + tid0; ++i) {
6351 logits[i] = -INFINITY;
6352 }
6353 }
6354
6355 // populate the logprobs array (log_softmax)
6356 whisper_compute_logprobs(logits, n_logits, logprobs);
6357
6358 // if sum of probability over timestamps is above any other token, sample timestamp
6359 // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L431-L437
6360 {
6361 // logsumexp over timestamps
6362 float timestamp_logprob = -INFINITY;
6363 {
6364 float logsumexp = 0.0f;
6365 const float logprob_max = *std::max_element(logprobs.begin() + vocab.token_beg, logprobs.end());
6366 for (int i = vocab.token_beg; i < n_logits; ++i) {
6367 if (logprobs[i] > -INFINITY) {
6368 logsumexp += expf(logprobs[i] - logprob_max);
6369 }
6370 }
6371 if (logsumexp > 0.0f) {
6372 timestamp_logprob = logf(logsumexp) + logprob_max;
6373 }
6374 }
6375
6376 const float max_text_token_logprob = *std::max_element(logprobs.begin(), logprobs.begin() + vocab.token_beg);
6377
6378 //WHISPER_LOG_INFO("timestamp_logprob=%f max_text_token_logprob=%f\n", timestamp_logprob, max_text_token_logprob);
6379
6380 if (timestamp_logprob > max_text_token_logprob) {
6381 for (int i = 0; i < vocab.token_beg; ++i) {
6382 logits[i] = -INFINITY;
6383 logprobs[i] = -INFINITY;
6384 }
6385 } else {
6386 if (params.n_grammar_rules > 0) {
6387 whisper_suppress_invalid_grammar(ctx, params, logits, decoder.grammar);
6388
6389 // populate the logprobs array (log_softmax)
6390 {
6391 const float logit_max = *std::max_element(logits.begin(), logits.end());
6392 float logsumexp = 0.0f;
6393 for (int i = 0; i < n_logits; ++i) {
6394 if (logits[i] > -INFINITY) {
6395 logsumexp += expf(logits[i] - logit_max);
6396 }
6397 }
6398 logsumexp = logf(logsumexp) + logit_max;
6399
6400 for (int i = 0; i < n_logits; ++i) {
6401 if (logits[i] > -INFINITY) {
6402 logprobs[i] = logits[i] - logsumexp;
6403 } else {
6404 logprobs[i] = -INFINITY;
6405 }
6406 }
6407 }
6408 }
6409 }
6410 }
6411 }
6412
6413 // compute probs
6414 whisper_compute_probs(logits, n_logits, logprobs, probs);
6415
6416 #if 0
6417 // print first 100 logits - token string : logit
6418 //for (int i = 0; i < 10; i++) {
6419 // const auto token = vocab.id_to_token.at(i);
6420 // const auto prob = probs[i];
6421 // const auto logit = logits[i];
6422 // const auto logprob = logprobs[i];
6423 // printf("%16s : prob=%9.5f logit=%9.5f logprob=%9.5f\n", token.c_str(), prob, logit, logprob);
6424 //}
6425
6426 // print sorted
6427 {
6428 std::vector<std::pair<float, int>> pairs;
6429
6430 for (int i = 0; i < n_logits; ++i) {
6431 pairs.push_back(std::make_pair(probs[i], i));
6432 }
6433
6434 std::sort(pairs.begin(), pairs.end(), [](const std::pair<float, int>& a, const std::pair<float, int>& b) {
6435 return a.first > b.first;
6436 });
6437
6438 for (int i = 0; i < 10; i++) {
6439 const auto token = vocab.id_to_token.at(pairs[i].second);
6440 const auto prob = pairs[i].first;
6441 const auto logit = logits[pairs[i].second];
6442 const auto logprob = logprobs[pairs[i].second];
6443 printf("%16s : id=%6d prob=%9.5f logit=%9.5f logprob=%9.5f '%s'\n", token.c_str(), pairs[i].second, prob, logit, logprob, token.c_str());
6444 }
6445
6446 printf("----------------\n");
6447 }
6448
6449 // "And", "and", " And", " and"
6450 //printf("logits[\"and\"] = %f\n", logits[vocab.token_to_id.at("and")]);
6451 //printf("logits[\"And\"] = %f\n", logits[vocab.token_to_id.at("And")]);
6452 //printf("logits[\" and\"] = %f\n", logits[vocab.token_to_id.at(" and")]);
6453 //printf("logits[\" And\"] = %f\n", logits[vocab.token_to_id.at(" And")]);
6454 //printf("logits[\" so\"] = %f\n", logits[vocab.token_to_id.at(" so")]);
6455
6456 //printf("logprobs[\"and\"] = %f\n", logprobs[vocab.token_to_id.at("and")]);
6457 //printf("logprobs[\"And\"] = %f\n", logprobs[vocab.token_to_id.at("And")]);
6458 //printf("logprobs[\" and\"] = %f\n", logprobs[vocab.token_to_id.at(" and")]);
6459 //printf("logprobs[\" And\"] = %f\n", logprobs[vocab.token_to_id.at(" And")]);
6460 //printf("logprobs[\" so\"] = %f\n", logprobs[vocab.token_to_id.at(" so")]);
6461
6462 //printf("probs[\"and\"] = %f\n", probs[vocab.token_to_id.at("and")]);
6463 //printf("probs[\"And\"] = %f\n", probs[vocab.token_to_id.at("And")]);
6464 //printf("probs[\" and\"] = %f\n", probs[vocab.token_to_id.at(" and")]);
6465 //printf("probs[\" And\"] = %f\n", probs[vocab.token_to_id.at(" And")]);
6466 //printf("probs[\" so\"] = %f\n", probs[vocab.token_to_id.at(" so")]);
6467 #endif
6468 }
6469
6470 static bool whisper_sequence_tokens_equal(const whisper_sequence & a, const whisper_sequence & b) {
6471 if (a.tokens.size() != b.tokens.size()) {
6472 return false;
6473 }
6474 // sequences are more likely to diverge at the end
6475 for (int i = a.tokens.size() - 1; i >= 0; i--) {
6476 if (a.tokens[i].id != b.tokens[i].id) {
6477 return false;
6478 }
6479 }
6480 return true;
6481 }
6482
6483 static whisper_token_data whisper_sample_token(
6484 whisper_context & ctx,
6485 const whisper_decoder & decoder,
6486 bool best) {
6487 whisper_token_data result = {
6488 0, 0, 0.0f, 0.0f, 0.0f, 0.0f, -1, -1, -1, 0.0f,
6489 };
6490
6491 const auto & vocab = ctx.vocab;
6492
6493 const auto & probs = decoder.probs;
6494 const auto & logprobs = decoder.logprobs;
6495
6496 const int n_logits = vocab.n_vocab;
6497
6498 {
6499 double sum_ts = 0.0;
6500 double max_ts = 0.0;
6501
6502 for (int i = vocab.token_beg; i < n_logits; i++) {
6503 if (probs[i] == -INFINITY) {
6504 continue;
6505 }
6506
6507 sum_ts += probs[i];
6508 if (max_ts < probs[i]) {
6509 max_ts = probs[i];
6510 result.tid = i;
6511 }
6512 }
6513
6514 result.pt = max_ts/(sum_ts + 1e-10);
6515 result.ptsum = sum_ts;
6516 }
6517
6518 if (best) {
6519 for (int i = 0; i < n_logits; ++i) {
6520 if (result.p < probs[i]) {
6521 result.id = i;
6522 result.p = probs[i];
6523 result.plog = logprobs[i];
6524 }
6525 }
6526 } else {
6527 std::discrete_distribution<> dist(probs.begin(), probs.end());
6528
6529 result.id = dist(decoder.rng);
6530 result.p = probs[result.id];
6531 result.plog = logprobs[result.id];
6532 }
6533
6534 if (result.id >= vocab.token_beg) {
6535 result.tid = result.id;
6536 result.pt = result.p;
6537 }
6538
6539 return result;
6540 }
6541
6542 static std::vector<whisper_token_data> whisper_sample_token_topk(
6543 whisper_context & ctx,
6544 whisper_decoder & decoder,
6545 int k) {
6546 const auto & vocab = ctx.vocab;
6547
6548 const auto & probs = decoder.probs;
6549 const auto & logits = decoder.logits;
6550 const auto & logprobs = decoder.logprobs;
6551
6552 const int n_logits = vocab.n_vocab;
6553
6554 auto & logits_id = decoder.logits_id;
6555
6556 logits_id.resize(n_logits);
6557 for (int i = 0; i < n_logits; ++i) {
6558 logits_id[i].first = logits[i];
6559 logits_id[i].second = i;
6560 }
6561
6562 {
6563 using pair_type = std::remove_reference<decltype(logits_id)>::type::value_type;
6564 std::partial_sort(
6565 logits_id.begin(),
6566 logits_id.begin() + k, logits_id.end(),
6567 [](const pair_type & a, const pair_type & b) {
6568 return a.first > b.first;
6569 });
6570 }
6571
6572 std::vector<whisper_token_data> result;
6573 result.reserve(k);
6574
6575 whisper_token tid = vocab.token_beg;
6576
6577 float pt = 0.0;
6578 float ptsum = 0.0;
6579
6580 {
6581 double sum_ts = 0.0;
6582 double max_ts = 0.0;
6583
6584 for (int i = vocab.token_beg; i < n_logits; i++) {
6585 if (probs[i] == -INFINITY) {
6586 continue;
6587 }
6588
6589 sum_ts += probs[i];
6590 if (max_ts < probs[i]) {
6591 max_ts = probs[i];
6592 tid = i;
6593 }
6594 }
6595
6596 pt = max_ts/(sum_ts + 1e-10);
6597 ptsum = sum_ts;
6598 }
6599
6600 std::discrete_distribution<> dist(probs.begin(), probs.end());
6601
6602 for (int i = 0; i < k; ++i) {
6603 const auto id = dist(decoder.rng);
6604 //printf("XXX %d %d %f %f %f %f\n", id, tid, probs[id], logprobs[id], pt, ptsum);
6605
6606 result.push_back({ id, tid, probs[id], logprobs[id], pt, ptsum, -1, -1, -1, 0.0f, });
6607
6608 if (result[i].id >= vocab.token_beg) {
6609 result[i].tid = result[i].id;
6610 result[i].pt = result[i].p;
6611 }
6612 }
6613
6614 return result;
6615 }
6616
6617 // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L178-L192
6618 static void whisper_sequence_score(
6619 const struct whisper_full_params & params,
6620 whisper_sequence & sequence) {
6621 if (sequence.result_len == 0) {
6622 return;
6623 }
6624
6625 double result = 0.0f;
6626
6627 for (int i = 0; i < sequence.result_len; ++i) {
6628 result += sequence.tokens[i].plog;
6629 }
6630
6631 sequence.sum_logprobs = result;
6632 sequence.avg_logprobs = result/sequence.result_len;
6633
6634 double penalty = sequence.result_len;
6635
6636 if (params.length_penalty > 0.0f) {
6637 penalty = pow((5.0 + penalty)/6.0, params.length_penalty);
6638 }
6639
6640 sequence.score = result/penalty;
6641
6642 // compute the entropy of the sequence of the last 32 tokens
6643 {
6644 const int n = 32;
6645
6646 int cnt = 0;
6647 double entropy = 0.0f;
6648
6649 std::map<whisper_token, int> token_counts;
6650 for (int i = std::max(0, sequence.result_len - n); i < sequence.result_len; ++i) {
6651 token_counts[sequence.tokens[i].id]++;
6652 cnt++;
6653 }
6654
6655 for (const auto & kv : token_counts) {
6656 const auto p = kv.second/(double)cnt;
6657 entropy -= p*log(p);
6658
6659 //WHISPER_LOG_DEBUG("entropy: %d %f %f, count %d\n", kv.first, p, log(p), kv.second);
6660 }
6661
6662 sequence.entropy = entropy;
6663 }
6664 }
6665
6666 static bool whisper_vad(
6667 struct whisper_context * ctx,
6668 struct whisper_state * state,
6669 struct whisper_full_params params,
6670 const float * samples,
6671 int n_samples,
6672 std::vector<float> & filtered_samples) {
6673 WHISPER_LOG_INFO("%s: VAD is enabled, processing speech segments only\n", __func__);
6674 int filtered_n_samples = 0;
6675
6676 // Clear any existing mapping table
6677 state->vad_mapping_table.clear();
6678 state->has_vad_segments = false;
6679
6680 if (state->vad_context == nullptr) {
6681 struct whisper_vad_context_params vad_ctx_params = whisper_vad_default_context_params();
6682 /*
6683 Following conditional is added by Anastasia Shchupak on behalf of inclusion into Praat.
6684 In the original whisper.cpp version, whisper_vad_init_from_file_with_params() is always used.
6685 Praat contains Silero-VAD model in memory, therefore whisper_vad_init_from_memory_with_params() is added.
6686 */
6687 struct whisper_vad_context * vctx = nullptr;
6688 if (params.vad_model_data && params.vad_model_data_size) {
6689 vctx = whisper_vad_init_from_memory_with_params((void*)params.vad_model_data, params.vad_model_data_size, vad_ctx_params);
6690 } else {
6691 vctx = whisper_vad_init_from_file_with_params(params.vad_model_path, vad_ctx_params);
6692 }
6693 if (vctx == nullptr) {
6694 WHISPER_LOG_ERROR("%s: failed to initialize VAD context\n", __func__);
6695 return false;
6696 }
6697 state->vad_context = vctx;
6698 }
6699 auto vctx = state->vad_context;
6700
6701 const whisper_vad_params & vad_params = params.vad_params;
6702
6703 whisper_vad_segments * vad_segments = whisper_vad_segments_from_samples(vctx, vad_params, samples, n_samples);
6704
6705 if (!vad_segments) {
6706 return false;
6707 }
6708
6709 if (vad_segments->data.size() > 0) {
6710 state->has_vad_segments = true;
6711 ctx->state->vad_segments.clear();
6712 ctx->state->vad_segments.reserve(vad_segments->data.size());
6713
6714 // Initialize the time mapping table
6715 state->vad_mapping_table.clear();
6716 state->vad_mapping_table.reserve(vad_segments->data.size() * 4);
6717
6718 WHISPER_LOG_INFO("%s: detected %d speech segments\n", __func__, (int)vad_segments->data.size());
6719 float overlap_seconds = vad_params.samples_overlap;
6720 int overlap_samples = overlap_seconds * WHISPER_SAMPLE_RATE;
6721
6722 for (int i = 0; i < (int)vad_segments->data.size(); i++) {
6723 int segment_start_samples = cs_to_samples(vad_segments->data[i].start);
6724 int segment_end_samples = cs_to_samples(vad_segments->data[i].end);
6725
6726 if (i < (int)vad_segments->data.size() - 1) {
6727 segment_end_samples += overlap_samples;
6728 }
6729 segment_end_samples = std::min(segment_end_samples, n_samples - 1);
6730 filtered_n_samples += (segment_end_samples - segment_start_samples);
6731
6732 WHISPER_LOG_INFO("%s: Including segment %d: %.2f - %.2f (duration: %.2f)\n",
6733 __func__, i, vad_segments->data[i].start/100.0,
6734 (vad_segments->data[i].end/100.0 + (i < (int)vad_segments->data.size() - 1 ? overlap_seconds : 0)),
6735 (vad_segments->data[i].end - vad_segments->data[i].start)/100.0 +
6736 (i < (int)vad_segments->data.size() - 1 ? overlap_seconds : 0));
6737 }
6738
6739 int silence_samples = 0.1 * WHISPER_SAMPLE_RATE;
6740 int total_silence_samples = (vad_segments->data.size() > 1) ? (vad_segments->data.size() - 1) * silence_samples : 0;
6741 int total_samples_needed = filtered_n_samples + total_silence_samples;
6742
6743 WHISPER_LOG_INFO("%s: total duration of speech segments: %.2f seconds\n",
6744 __func__, (float)filtered_n_samples / WHISPER_SAMPLE_RATE);
6745
6746 try {
6747 filtered_samples.resize(total_samples_needed);
6748 } catch (const std::bad_alloc & /* e */) {
6749 WHISPER_LOG_ERROR("%s: failed to allocate memory for filtered samples\n", __func__);
6750 whisper_vad_free_segments(vad_segments);
6751 return false;
6752 }
6753
6754 int offset = 0;
6755 for (int i = 0; i < (int)vad_segments->data.size(); i++) {
6756 int segment_start_samples = cs_to_samples(vad_segments->data[i].start);
6757 int segment_end_samples = cs_to_samples(vad_segments->data[i].end);
6758
6759 if (i < (int)vad_segments->data.size() - 1) {
6760 segment_end_samples += overlap_samples;
6761 }
6762
6763 segment_start_samples = std::min(segment_start_samples, n_samples - 1);
6764 segment_end_samples = std::min(segment_end_samples, n_samples - 1);
6765 int segment_length = segment_end_samples - segment_start_samples;
6766 if (segment_length > 0) {
6767 whisper_state::vad_segment_info segment;
6768
6769 segment.orig_start = vad_segments->data[i].start;
6770 segment.orig_end = vad_segments->data[i].end;
6771
6772 segment.vad_start = samples_to_cs(offset);
6773 segment.vad_end = samples_to_cs(offset + segment_length);
6774
6775 // Add segment boundaries to mapping table
6776 vad_time_mapping start_mapping = {segment.vad_start, segment.orig_start};
6777 vad_time_mapping end_mapping = {segment.vad_end, segment.orig_end};
6778
6779 state->vad_mapping_table.push_back(start_mapping);
6780 state->vad_mapping_table.push_back(end_mapping);
6781
6782 // Add intermediate points for longer segments to improve interpolation accuracy
6783 const int64_t min_segment_length = 100; // 1 second
6784 const int64_t point_interval = 20; // Add a point every 200ms
6785
6786 if (segment.vad_end - segment.vad_start > min_segment_length) {
6787 int64_t segment_duration = segment.vad_end - segment.vad_start;
6788 int num_points = (int)(segment_duration / point_interval) - 1;
6789
6790 for (int j = 1; j <= num_points; j++) {
6791 int64_t vad_time = segment.vad_start + j * point_interval;
6792
6793 if (vad_time >= segment.vad_end) continue;
6794
6795 int64_t vad_elapsed = vad_time - segment.vad_start;
6796 int64_t vad_total = segment.vad_end - segment.vad_start;
6797 int64_t orig_total = segment.orig_end - segment.orig_start;
6798 int64_t orig_time = segment.orig_start + (vad_elapsed * orig_total) / vad_total;
6799
6800 vad_time_mapping intermediate_mapping = {vad_time, orig_time};
6801 state->vad_mapping_table.push_back(intermediate_mapping);
6802 }
6803 }
6804
6805 WHISPER_LOG_INFO("%s: vad_segment_info: orig_start: %.2f, orig_end: %.2f, vad_start: %.2f, vad_end: %.2f\n",
6806 __func__, segment.orig_start/100.0, segment.orig_end/100.0, segment.vad_start/100.0, segment.vad_end/100.0);
6807 ctx->state->vad_segments.push_back(segment);
6808
6809 // Copy this speech segment
6810 memcpy(filtered_samples.data() + offset, samples + segment_start_samples, segment_length * sizeof(float));
6811 offset += segment_length;
6812
6813 // Add silence after this segment (except after the last segment)
6814 if (i < (int)vad_segments->data.size() - 1) {
6815 // Calculate the start and end time of the silence gap in processed audio
6816 int64_t silence_start_vad = samples_to_cs(offset);
6817 int64_t silence_end_vad = samples_to_cs(offset + silence_samples);
6818 // Calculate the corresponding original times
6819 int64_t orig_silence_start = segment.orig_end;
6820 int64_t orig_silence_end = vad_segments->data[i+1].start;
6821
6822 // Add mapping points for silence boundaries
6823 state->vad_mapping_table.push_back({silence_start_vad, orig_silence_start});
6824 state->vad_mapping_table.push_back({silence_end_vad, orig_silence_end});
6825
6826 // Fill with zeros (silence)
6827 memset(filtered_samples.data() + offset, 0, silence_samples * sizeof(float));
6828 offset += silence_samples;
6829 }
6830 }
6831 }
6832
6833 // Sort the mapping table by processed time
6834 std::sort(state->vad_mapping_table.begin(), state->vad_mapping_table.end(),
6835 [](const vad_time_mapping& a, const vad_time_mapping& b) {
6836 return a.processed_time < b.processed_time;
6837 });
6838
6839 // Remove any duplicate processed times to ensure monotonicity which is
6840 // needed for binary search and interpolation later.
6841 if (!state->vad_mapping_table.empty()) {
6842 auto last = std::unique(state->vad_mapping_table.begin(), state->vad_mapping_table.end(),
6843 [](const vad_time_mapping& a, const vad_time_mapping& b) {
6844 return a.processed_time == b.processed_time;
6845 });
6846 state->vad_mapping_table.erase(last, state->vad_mapping_table.end());
6847 }
6848
6849 WHISPER_LOG_INFO("%s: Created time mapping table with %d points\n", __func__, (int)state->vad_mapping_table.size());
6850
6851 filtered_n_samples = offset;
6852 WHISPER_LOG_INFO("%s: Reduced audio from %d to %d samples (%.1f%% reduction)\n",
6853 __func__, n_samples, filtered_n_samples, 100.0f * (1.0f - (float)filtered_n_samples / n_samples));
6854 }
6855
6856 whisper_vad_free_segments(vad_segments);
6857 return true;
6858 }
6859
6860 int whisper_full_with_state(
6861 struct whisper_context * ctx,
6862 struct whisper_state * state,
6863 struct whisper_full_params params,
6864 const float * samples,
6865 int n_samples) {
6866 // clear old results
6867 auto & result_all = state->result_all;
6868
6869 result_all.clear();
6870
6871 if (n_samples > 0) {
6872 // compute log mel spectrogram
6873 if (whisper_pcm_to_mel_with_state(ctx, state, samples, n_samples, params.n_threads) != 0) {
6874 WHISPER_LOG_ERROR("%s: failed to compute log mel spectrogram\n", __func__);
6875 return -2;
6876 }
6877 }
6878
6879 // auto-detect language if not specified
6880 if (params.language == nullptr || strlen(params.language) == 0 || strcmp(params.language, "auto") == 0 || params.detect_language) {
6881 std::vector<float> probs(whisper_lang_max_id() + 1, 0.0f);
6882
6883 const auto lang_id = whisper_lang_auto_detect_with_state(ctx, state, 0, params.n_threads, probs.data());
6884 if (lang_id < 0) {
6885 WHISPER_LOG_ERROR("%s: failed to auto-detect language\n", __func__);
6886 return -3;
6887 }
6888 state->lang_id = lang_id;
6889 params.language = whisper_lang_str(lang_id);
6890
6891 WHISPER_LOG_INFO("%s: auto-detected language: %s (p = %f)\n", __func__, params.language, probs[whisper_lang_id(params.language)]);
6892 if (params.detect_language) {
6893 return 0;
6894 }
6895 }
6896
6897 if (params.token_timestamps) {
6898 state->t_beg = 0;
6899 state->t_last = 0;
6900 state->tid_last = 0;
6901 if (n_samples > 0) {
6902 state->energy = get_signal_energy(samples, n_samples, 32);
6903 }
6904 }
6905
6906 const int seek_start = params.offset_ms/10;
6907 const int seek_end = params.duration_ms == 0 ? whisper_n_len_from_state(state) : seek_start + params.duration_ms/10;
6908
6909 // if length of spectrogram is less than 100ms (10 frames), then return
6910 // basically don't process anything that is less than 100ms
6911 // ref: https://github.com/ggml-org/whisper.cpp/issues/2065
6912 const int delta_min = 10;
6913
6914 if (seek_end < seek_start + delta_min) {
6915 WHISPER_LOG_WARN("%s: input is too short - %d ms < 100 ms. consider padding the input audio with silence\n", __func__, (seek_end - seek_start)*10);
6916 return 0;
6917 }
6918
6919 // a set of temperatures to use
6920 // [ t0, t0 + delta, t0 + 2*delta, ..., < 1.0f + 1e-6f ]
6921 std::vector<float> temperatures;
6922 if (params.temperature_inc > 0.0f) {
6923 for (float t = params.temperature; t < 1.0f + 1e-6f; t += params.temperature_inc) {
6924 temperatures.push_back(t);
6925 }
6926 } else {
6927 temperatures.push_back(params.temperature);
6928 }
6929
6930 // initialize the decoders
6931 int n_decoders = 1;
6932
6933 switch (params.strategy) {
6934 case WHISPER_SAMPLING_GREEDY:
6935 {
6936 n_decoders = params.greedy.best_of;
6937 } break;
6938 case WHISPER_SAMPLING_BEAM_SEARCH:
6939 {
6940 n_decoders = std::max(params.greedy.best_of, params.beam_search.beam_size);
6941 } break;
6942 };
6943
6944 n_decoders = std::max(1, n_decoders);
6945
6946 if (n_decoders > WHISPER_MAX_DECODERS) {
6947 WHISPER_LOG_ERROR("%s: too many decoders requested (%d), max = %d\n", __func__, n_decoders, WHISPER_MAX_DECODERS);
6948 return -4;
6949 }
6950
6951 // TAGS: WHISPER_DECODER_INIT
6952 for (int j = 1; j < n_decoders; j++) {
6953 auto & decoder = state->decoders[j];
6954
6955 decoder.sequence.tokens.reserve(state->decoders[0].sequence.tokens.capacity());
6956
6957 decoder.probs.resize (ctx->vocab.n_vocab);
6958 decoder.logits.resize (ctx->vocab.n_vocab);
6959 decoder.logprobs.resize(ctx->vocab.n_vocab);
6960 decoder.logits_id.reserve(ctx->model.hparams.n_vocab);
6961
6962 decoder.rng = std::mt19937(j);
6963 }
6964
6965 // the accumulated text context split into static (prompt_past0) and dynamic (prompt_past1)
6966 auto & prompt_past0 = state->prompt_past0;
6967 auto & prompt_past1 = state->prompt_past1;
6968 if (params.no_context) {
6969 prompt_past0.clear();
6970 prompt_past1.clear();
6971 }
6972
6973 // calculate the maximum context budget for prompt history
6974 const int max_prompt_ctx = std::min(params.n_max_text_ctx, whisper_n_text_ctx(ctx)/2);
6975
6976 // prepare prompt
6977 {
6978 std::vector<whisper_token> prompt_tokens;
6979
6980 // tokenize the initial prompt
6981 if (!params.prompt_tokens && params.initial_prompt) {
6982 prompt_tokens.resize(1024);
6983 int n_needed = whisper_tokenize(ctx, params.initial_prompt, prompt_tokens.data(), prompt_tokens.size());
6984 if (n_needed < 0) {
6985 prompt_tokens.resize(-n_needed);
6986 n_needed = whisper_tokenize(ctx, params.initial_prompt, prompt_tokens.data(), prompt_tokens.size());
6987 }
6988 prompt_tokens.resize(n_needed);
6989 params.prompt_tokens = prompt_tokens.data();
6990 params.prompt_n_tokens = prompt_tokens.size();
6991 }
6992 if (params.prompt_tokens && params.prompt_n_tokens > 0) {
6993 if (params.carry_initial_prompt) {
6994 if (prompt_past0.empty()) {
6995 const int max_tokens = std::max(1, max_prompt_ctx - 1);
6996
6997 if (params.prompt_n_tokens > max_tokens) {
6998 WHISPER_LOG_WARN("%s: initial prompt is too long (%d tokens), will use only the last %d tokens\n",
6999 __func__, params.prompt_n_tokens, max_tokens);
7000 }
7001
7002 const int n_tokens = std::min(params.prompt_n_tokens, max_tokens);
7003 prompt_past0.assign(params.prompt_tokens + (params.prompt_n_tokens - n_tokens), params.prompt_tokens + params.prompt_n_tokens);
7004 }
7005 } else {
7006 for (int i = 0; i < params.prompt_n_tokens; ++i) {
7007 prompt_past1.push_back(params.prompt_tokens[i]);
7008 }
7009 std::rotate(prompt_past1.begin(), prompt_past1.end() - params.prompt_n_tokens, prompt_past1.end());
7010 }
7011 }
7012 }
7013
7014 // overwrite audio_ctx, max allowed is hparams.n_audio_ctx
7015 if (params.audio_ctx > whisper_n_audio_ctx(ctx)) {
7016 WHISPER_LOG_ERROR("%s: audio_ctx is larger than the maximum allowed (%d > %d)\n", __func__, params.audio_ctx, whisper_n_audio_ctx(ctx));
7017 return -5;
7018 }
7019 state->exp_n_audio_ctx = params.audio_ctx;
7020
7021 // these tokens determine the task that will be performed
7022 std::vector<whisper_token> prompt_init = { whisper_token_sot(ctx), };
7023
7024 if (whisper_is_multilingual(ctx)) {
7025 const int lang_id = whisper_lang_id(params.language);
7026 state->lang_id = lang_id;
7027 prompt_init.push_back(whisper_token_lang(ctx, lang_id));
7028 if (params.translate) {
7029 prompt_init.push_back(whisper_token_translate(ctx));
7030 } else {
7031 prompt_init.push_back(whisper_token_transcribe(ctx));
7032 }
7033 }
7034
7035 // first release distilled models require the "no_timestamps" token
7036 {
7037 const bool is_distil = ctx->model.hparams.n_text_layer == 2 && ctx->model.hparams.n_vocab != 51866;
7038 if (is_distil && !params.no_timestamps) {
7039 WHISPER_LOG_WARN("%s: using first release distilled models - forcing no_timestamps\n", __func__);
7040 params.no_timestamps = true;
7041 }
7042 }
7043
7044 if (params.no_timestamps) {
7045 prompt_init.push_back(whisper_token_not(ctx));
7046 }
7047
7048 int seek = seek_start;
7049
7050 std::vector<whisper_token> prompt;
7051 prompt.reserve(whisper_n_text_ctx(ctx));
7052
7053 struct beam_candidate {
7054 int decoder_idx;
7055 int seek_delta;
7056
7057 bool has_ts;
7058
7059 whisper_sequence sequence;
7060 whisper_grammar grammar;
7061 };
7062
7063 std::vector<std::vector<beam_candidate>> bc_per_dec(n_decoders);
7064 std::vector<beam_candidate> beam_candidates;
7065
7066 // main loop
7067 while (true) {
7068 if (params.progress_callback) {
7069 const int progress_cur = (100*(seek - seek_start))/(seek_end - seek_start);
7070
7071 params.progress_callback(
7072 ctx, state, progress_cur, params.progress_callback_user_data);
7073 }
7074
7075 // if only 100ms left, then stop
7076 if (seek + delta_min >= seek_end) {
7077 break;
7078 }
7079
7080 if (params.encoder_begin_callback) {
7081 if (params.encoder_begin_callback(ctx, state, params.encoder_begin_callback_user_data) == false) {
7082 WHISPER_LOG_ERROR("%s: encoder_begin_callback returned false - aborting\n", __func__);
7083 break;
7084 }
7085 }
7086
7087 // encode audio features starting at offset seek
7088 if (!whisper_encode_internal(*ctx, *state, seek, params.n_threads, params.abort_callback, params.abort_callback_user_data)) {
7089 WHISPER_LOG_ERROR("%s: failed to encode\n", __func__);
7090 return -6;
7091 }
7092
7093 // if there is a very short audio segment left to process, we remove any past prompt since it tends
7094 // to confuse the decoder and often make it repeat or hallucinate stuff
7095 if (seek > seek_start && seek + 500 >= seek_end) {
7096 prompt_past0.clear();
7097 prompt_past1.clear();
7098 }
7099
7100 int best_decoder_id = 0;
7101
7102 for (int it = 0; it < (int) temperatures.size(); ++it) {
7103 const float t_cur = temperatures[it];
7104
7105 int n_decoders_cur = 1;
7106
7107 switch (params.strategy) {
7108 case whisper_sampling_strategy::WHISPER_SAMPLING_GREEDY:
7109 {
7110 if (t_cur > 0.0f) {
7111 n_decoders_cur = params.greedy.best_of;
7112 }
7113 } break;
7114 case whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH:
7115 {
7116 if (t_cur > 0.0f) {
7117 n_decoders_cur = params.greedy.best_of;
7118 } else {
7119 n_decoders_cur = params.beam_search.beam_size;
7120 }
7121 } break;
7122 };
7123
7124 n_decoders_cur = std::max(1, n_decoders_cur);
7125
7126 WHISPER_LOG_DEBUG("\n%s: strategy = %d, decoding with %d decoders, temperature = %.2f\n", __func__, params.strategy, n_decoders_cur, t_cur);
7127
7128 // TAGS: WHISPER_DECODER_INIT
7129 for (int j = 0; j < n_decoders_cur; ++j) {
7130 auto & decoder = state->decoders[j];
7131
7132 decoder.sequence.tokens.clear();
7133 decoder.sequence.result_len = 0;
7134 decoder.sequence.sum_logprobs_all = 0.0;
7135 decoder.sequence.sum_logprobs = -INFINITY;
7136 decoder.sequence.avg_logprobs = -INFINITY;
7137 decoder.sequence.entropy = 0.0;
7138 decoder.sequence.score = -INFINITY;
7139
7140 decoder.seek_delta = 100*WHISPER_CHUNK_SIZE;
7141
7142 decoder.failed = false;
7143 decoder.completed = false;
7144 decoder.has_ts = false;
7145
7146 if (params.grammar_rules != nullptr) {
7147 decoder.grammar = whisper_grammar_init(params.grammar_rules, params.n_grammar_rules, params.i_start_rule);
7148 } else {
7149 decoder.grammar = {};
7150 }
7151 }
7152
7153 // init prompt and kv cache for the current iteration
7154 // TODO: do not recompute the prompt if it is the same as previous time
7155 {
7156 prompt.clear();
7157
7158 if (params.n_max_text_ctx > 0 && t_cur < WHISPER_HISTORY_CONDITIONING_TEMP_CUTOFF) {
7159 const bool can_take0 = params.carry_initial_prompt && !prompt_past0.empty();
7160 const bool can_take1 = !prompt_past1.empty();
7161
7162 if (max_prompt_ctx > 0 && (can_take0 || can_take1)) {
7163 // Always start with previous token marker to connect continuity
7164 prompt.push_back(whisper_token_prev(ctx));
7165
7166 // Take static tokens (initial prompt) first
7167 int n_take0 = 0;
7168 if (can_take0) {
7169 n_take0 = prompt_past0.size();
7170 prompt.insert(prompt.end(), prompt_past0.end() - n_take0, prompt_past0.end());
7171 }
7172
7173 // Fill remaining budget with dynamic tokens (rolling context)
7174 const int n_take1 = std::min<int>(max_prompt_ctx - n_take0 - 1, prompt_past1.size());
7175 prompt.insert(prompt.end(), prompt_past1.end() - n_take1, prompt_past1.end());
7176 }
7177 }
7178
7179 // init new transcription with sot, language (opt) and task tokens
7180 prompt.insert(prompt.end(), prompt_init.begin(), prompt_init.end());
7181
7182 // print the prompt
7183 WHISPER_LOG_DEBUG("\n\n");
7184 for (int i = 0; i < (int) prompt.size(); i++) {
7185 WHISPER_LOG_DEBUG("%s: prompt[%d] = %s\n", __func__, i, ctx->vocab.id_to_token.at(prompt[i]).c_str());
7186 }
7187 WHISPER_LOG_DEBUG("\n\n");
7188
7189 // recreate the KV cache if the number of decoders has changed
7190 if (state->kv_self_n_dec < n_decoders_cur) {
7191 WHISPER_LOG_DEBUG("%s: recreating KV cache: n_decoders_cur = %d\n", __func__, n_decoders_cur);
7192
7193 whisper_kv_cache_free(state->kv_self);
7194
7195 // overallocate to workaround KV cache fragmentation issues
7196 const int factor = n_decoders_cur > 1 ? n_decoders_cur + 2 : 1;
7197
7198 if (!whisper_kv_cache_init(state->kv_self, state->backends[0], ctx->itype,
7199 ctx->model.hparams.n_text_state,
7200 ctx->model.hparams.n_text_layer,
7201 GGML_PAD(ctx->model.hparams.n_text_ctx, 256)*factor)) {
7202 WHISPER_LOG_ERROR("%s: whisper_kv_cache_init() failed for self-attention cache\n", __func__);
7203 whisper_free_state(state);
7204 return -7;
7205 }
7206
7207 state->kv_self_n_dec = n_decoders_cur;
7208 }
7209
7210 whisper_kv_cache_clear(state->kv_self);
7211
7212 whisper_batch_prep_legacy(state->batch, prompt.data(), prompt.size(), 0, 0);
7213
7214 if (!whisper_decode_internal(*ctx, *state, state->batch, params.n_threads, false, params.abort_callback, params.abort_callback_user_data)) {
7215 WHISPER_LOG_ERROR("%s: failed to decode\n", __func__);
7216 return -8;
7217 }
7218
7219 // Calculate no_speech probability after first decode.
7220 // This has to be done before any logit filtering. Hence we cannot use the probs from the whisper_process_logits.
7221 {
7222 const int n_logits = ctx->vocab.id_to_token.size();
7223 std::vector<float> logprobs(n_logits);
7224 std::vector<float> probs(n_logits);
7225
7226 whisper_compute_logprobs(state->logits, n_logits, logprobs);
7227 whisper_compute_probs(state->logits, n_logits, logprobs, probs);
7228 state->no_speech_prob = probs[whisper_token_nosp(ctx)];
7229 }
7230
7231 {
7232 const int64_t t_start_sample_us = ggml_time_us();
7233
7234 state->decoders[0].i_batch = prompt.size() - 1;
7235
7236 whisper_process_logits(*ctx, *state, state->decoders[0], params, t_cur);
7237
7238 for (int j = 1; j < n_decoders_cur; ++j) {
7239 auto & decoder = state->decoders[j];
7240
7241 whisper_kv_cache_seq_cp(state->kv_self, 0, j, -1, -1);
7242
7243 memcpy(decoder.probs.data(), state->decoders[0].probs.data(), decoder.probs.size()*sizeof(decoder.probs[0]));
7244 memcpy(decoder.logits.data(), state->decoders[0].logits.data(), decoder.logits.size()*sizeof(decoder.logits[0]));
7245 memcpy(decoder.logprobs.data(), state->decoders[0].logprobs.data(), decoder.logprobs.size()*sizeof(decoder.logprobs[0]));
7246 }
7247
7248 state->t_sample_us += ggml_time_us() - t_start_sample_us;
7249 }
7250 }
7251
7252 for (int i = 0, n_max = whisper_n_text_ctx(ctx)/2 - 4; i < n_max; ++i) {
7253 const int64_t t_start_sample_us = ggml_time_us();
7254
7255 if (params.strategy == whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH) {
7256 for (auto & bc : bc_per_dec) {
7257 bc.clear();
7258 }
7259 }
7260
7261 // sampling
7262 // TODO: avoid memory allocations, optimize, avoid threads?
7263 {
7264 std::atomic<int> j_cur(0);
7265
7266 auto process = [&]() {
7267 while (true) {
7268 const int j = j_cur.fetch_add(1);
7269
7270 if (j >= n_decoders_cur) {
7271 break;
7272 }
7273
7274 auto & decoder = state->decoders[j];
7275
7276 if (decoder.completed || decoder.failed) {
7277 continue;
7278 }
7279
7280 switch (params.strategy) {
7281 case whisper_sampling_strategy::WHISPER_SAMPLING_GREEDY:
7282 {
7283 if (t_cur < 1e-6f) {
7284 decoder.sequence.tokens.push_back(whisper_sample_token(*ctx, decoder, true));
7285 } else {
7286 decoder.sequence.tokens.push_back(whisper_sample_token(*ctx, decoder, false));
7287 }
7288
7289 decoder.sequence.sum_logprobs_all += decoder.sequence.tokens.back().plog;
7290 } break;
7291 case whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH:
7292 {
7293 const auto tokens_new = whisper_sample_token_topk(*ctx, decoder, params.beam_search.beam_size);
7294
7295 for (const auto & token : tokens_new) {
7296 bc_per_dec[j].push_back({ j, decoder.seek_delta, decoder.has_ts, decoder.sequence, decoder.grammar, });
7297 bc_per_dec[j].back().sequence.tokens.push_back(token);
7298 bc_per_dec[j].back().sequence.sum_logprobs_all += token.plog;
7299 }
7300 } break;
7301 };
7302 }
7303 };
7304
7305 const int n_threads = std::min(params.n_threads, n_decoders_cur);
7306
7307 if (n_threads == 1) {
7308 process();
7309 } else {
7310 std::vector<std::thread> threads(n_threads - 1);
7311
7312 for (int t = 0; t < n_threads - 1; ++t) {
7313 threads[t] = std::thread(process);
7314 }
7315
7316 process();
7317
7318 for (int t = 0; t < n_threads - 1; ++t) {
7319 threads[t].join();
7320 }
7321 }
7322 }
7323
7324 beam_candidates.clear();
7325 for (const auto & bc : bc_per_dec) {
7326 beam_candidates.insert(beam_candidates.end(), bc.begin(), bc.end());
7327
7328 if (!bc.empty()) {
7329 state->n_sample += 1;
7330 }
7331 }
7332
7333 // for beam-search, choose the top candidates and update the KV caches
7334 if (params.strategy == whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH) {
7335 std::sort(
7336 beam_candidates.begin(),
7337 beam_candidates.end(),
7338 [](const beam_candidate & a, const beam_candidate & b) {
7339 if (a.sequence.sum_logprobs_all != b.sequence.sum_logprobs_all) {
7340 return a.sequence.sum_logprobs_all > b.sequence.sum_logprobs_all;
7341 }
7342 return a.decoder_idx < b.decoder_idx;
7343 });
7344
7345 uint32_t cur_c = 0;
7346
7347 for (int j = 0; j < n_decoders_cur; ++j) {
7348 auto & decoder = state->decoders[j];
7349
7350 if (decoder.completed || decoder.failed) {
7351 continue;
7352 }
7353
7354 if (cur_c >= beam_candidates.size()) {
7355 cur_c = 0;
7356 }
7357
7358 auto & cur = beam_candidates[cur_c++];
7359
7360 while (beam_candidates.size() > cur_c && whisper_sequence_tokens_equal(beam_candidates[cur_c].sequence, cur.sequence) && i > 0) {
7361 ++cur_c;
7362 }
7363
7364 decoder.seek_delta = cur.seek_delta;
7365 decoder.has_ts = cur.has_ts;
7366 decoder.sequence = cur.sequence;
7367 decoder.grammar = cur.grammar;
7368
7369 whisper_kv_cache_seq_cp(state->kv_self, cur.decoder_idx, WHISPER_MAX_DECODERS + j, -1, -1);
7370
7371 WHISPER_LOG_DEBUG("%s: beam search: decoder %d: from decoder %d: token = %10s, plog = %8.5f, sum_logprobs = %8.5f\n",
7372 __func__, j, cur.decoder_idx, ctx->vocab.id_to_token.at(decoder.sequence.tokens.back().id).c_str(), decoder.sequence.tokens.back().plog, decoder.sequence.sum_logprobs_all);
7373 }
7374
7375 for (int j = 0; j < n_decoders_cur; ++j) {
7376 auto & decoder = state->decoders[j];
7377
7378 if (decoder.completed || decoder.failed) {
7379 continue;
7380 }
7381
7382 whisper_kv_cache_seq_rm(state->kv_self, j, -1, -1);
7383 whisper_kv_cache_seq_cp(state->kv_self, WHISPER_MAX_DECODERS + j, j, -1, -1);
7384 whisper_kv_cache_seq_rm(state->kv_self, WHISPER_MAX_DECODERS + j, -1, -1);
7385 }
7386 }
7387
7388 // update the decoder state
7389 // - check if the sequence is completed
7390 // - check if the sequence is failed
7391 // - update sliding window based on timestamp tokens
7392 for (int j = 0; j < n_decoders_cur; ++j) {
7393 auto & decoder = state->decoders[j];
7394
7395 if (decoder.completed || decoder.failed) {
7396 continue;
7397 }
7398
7399 auto & has_ts = decoder.has_ts;
7400 auto & failed = decoder.failed;
7401 auto & completed = decoder.completed;
7402 auto & seek_delta = decoder.seek_delta;
7403 auto & result_len = decoder.sequence.result_len;
7404
7405 {
7406 const auto & token = decoder.sequence.tokens.back();
7407
7408 // timestamp token - update sliding window
7409 if (token.id > whisper_token_beg(ctx)) {
7410 const int seek_delta_new = 2*(token.id - whisper_token_beg(ctx));
7411
7412 // do not allow to go back in time
7413 if (has_ts && seek_delta > seek_delta_new && result_len < i) {
7414 WHISPER_LOG_DEBUG("%s: decoder %d: failed due to seek_delta (%d > %d)\n", __func__, j, seek_delta, seek_delta_new);
7415 failed = true; // TODO: maybe this is not a failure ?
7416 continue;
7417 }
7418
7419 seek_delta = seek_delta_new;
7420 result_len = i + 1;
7421 has_ts = true;
7422 }
7423
7424 whisper_grammar_accept_token(*ctx, decoder.grammar, token.id);
7425
7426 #ifdef WHISPER_DEBUG
7427 {
7428 const auto tt = token.pt > 0.10 ? ctx->vocab.id_to_token.at(token.tid) : "[?]";
7429 WHISPER_LOG_DEBUG("%s: id = %3d, decoder = %d, token = %6d, p = %6.3f, ts = %10s, %6.3f, result_len = %4d '%s'\n",
7430 __func__, i, j, token.id, token.p, tt.c_str(), token.pt, result_len, ctx->vocab.id_to_token.at(token.id).c_str());
7431 }
7432 #endif
7433
7434 // end of segment
7435 if (token.id == whisper_token_eot(ctx) || // end of text token
7436 (params.max_tokens > 0 && i >= params.max_tokens) || // max tokens per segment reached
7437 (has_ts && seek + seek_delta + delta_min >= seek_end) // end of audio reached (100ms)
7438 ) {
7439 if (result_len == 0 && !params.no_timestamps) {
7440 if (seek + seek_delta + delta_min >= seek_end) {
7441 result_len = i + 1;
7442 } else {
7443 WHISPER_LOG_DEBUG("%s: decoder %d failed (result_len = 0)\n", __func__, j);
7444 failed = true;
7445 continue;
7446 }
7447 }
7448
7449 if (params.single_segment || params.no_timestamps) {
7450 result_len = i + 1;
7451 seek_delta = 100*WHISPER_CHUNK_SIZE;
7452 }
7453
7454 WHISPER_LOG_DEBUG("%s: decoder %d completed\n", __func__, j);
7455 completed = true;
7456 continue;
7457 }
7458
7459 // TESTS: if no tensors are loaded, it means we are running tests
7460 if (ctx->model.n_loaded == 0) {
7461 seek_delta = 100*WHISPER_CHUNK_SIZE;
7462 completed = true;
7463 continue;
7464 }
7465 }
7466
7467 // sometimes, the decoding can get stuck in a repetition loop
7468 // this is an attempt to mitigate such cases - we flag the decoding as failed and use a fallback strategy
7469 if (i == n_max - 1 && (result_len == 0 || seek_delta < 100*WHISPER_CHUNK_SIZE/2)) {
7470 WHISPER_LOG_DEBUG("%s: decoder %d: failed due to repetition loop\n", __func__, j);
7471 failed = true;
7472 continue;
7473 }
7474 }
7475
7476 // check if all decoders have finished (i.e. completed or failed)
7477 {
7478 bool completed_all = true;
7479
7480 for (int j = 0; j < n_decoders_cur; ++j) {
7481 auto & decoder = state->decoders[j];
7482
7483 if (decoder.completed || decoder.failed) {
7484 continue;
7485 }
7486
7487 completed_all = false;
7488 }
7489
7490 if (completed_all) {
7491 break;
7492 }
7493 }
7494
7495 state->t_sample_us += ggml_time_us() - t_start_sample_us;
7496
7497 // obtain logits for the next token
7498 {
7499 auto & batch = state->batch;
7500
7501 batch.n_tokens = 0;
7502
7503 const int n_past = prompt.size() + i;
7504
7505 for (int j = 0; j < n_decoders_cur; ++j) {
7506 auto & decoder = state->decoders[j];
7507
7508 if (decoder.failed || decoder.completed) {
7509 continue;
7510 }
7511
7512 //WHISPER_LOG_DEBUG("%s: decoder %d: token %d, seek_delta %d\n", __func__, j, decoder.sequence.tokens.back().id, decoder.seek_delta);
7513
7514 decoder.i_batch = batch.n_tokens;
7515
7516 batch.token [batch.n_tokens] = decoder.sequence.tokens.back().id;
7517 batch.pos [batch.n_tokens] = n_past;
7518 batch.n_seq_id[batch.n_tokens] = 1;
7519 batch.seq_id [batch.n_tokens][0] = j;
7520 batch.logits [batch.n_tokens] = 1;
7521 batch.n_tokens++;
7522 }
7523
7524 assert(batch.n_tokens > 0);
7525
7526 if (!whisper_decode_internal(*ctx, *state, state->batch, params.n_threads, false, params.abort_callback, params.abort_callback_user_data)) {
7527 WHISPER_LOG_ERROR("%s: failed to decode\n", __func__);
7528 return -9;
7529 }
7530
7531 const int64_t t_start_sample_us = ggml_time_us();
7532
7533 // TODO: avoid memory allocations, optimize, avoid threads?
7534 {
7535 std::atomic<int> j_cur(0);
7536
7537 auto process = [&]() {
7538 while (true) {
7539 const int j = j_cur.fetch_add(1);
7540
7541 if (j >= n_decoders_cur) {
7542 break;
7543 }
7544
7545 auto & decoder = state->decoders[j];
7546
7547 if (decoder.failed || decoder.completed) {
7548 continue;
7549 }
7550
7551 whisper_process_logits(*ctx, *state, decoder, params, t_cur);
7552 }
7553 };
7554
7555 const int n_threads = std::min(params.n_threads, n_decoders_cur);
7556
7557 if (n_threads == 1) {
7558 process();
7559 } else {
7560 std::vector<std::thread> threads(n_threads - 1);
7561
7562 for (int t = 0; t < n_threads - 1; ++t) {
7563 threads[t] = std::thread(process);
7564 }
7565
7566 process();
7567
7568 for (int t = 0; t < n_threads - 1; ++t) {
7569 threads[t].join();
7570 }
7571 }
7572 }
7573
7574 state->t_sample_us += ggml_time_us() - t_start_sample_us;
7575 }
7576 }
7577
7578 // rank the resulting sequences and select the best one
7579 {
7580 double best_score = -INFINITY;
7581
7582 for (int j = 0; j < n_decoders_cur; ++j) {
7583 auto & decoder = state->decoders[j];
7584
7585 if (decoder.failed) {
7586 continue;
7587 }
7588
7589 decoder.sequence.tokens.resize(decoder.sequence.result_len);
7590 whisper_sequence_score(params, decoder.sequence);
7591
7592 WHISPER_LOG_DEBUG("%s: decoder %2d: score = %8.5f, result_len = %3d, avg_logprobs = %8.5f, entropy = %8.5f\n",
7593 __func__, j, decoder.sequence.score, decoder.sequence.result_len, decoder.sequence.avg_logprobs, decoder.sequence.entropy);
7594
7595 if (decoder.sequence.result_len > 32 && decoder.sequence.entropy < params.entropy_thold) {
7596 WHISPER_LOG_DEBUG("%s: decoder %2d: failed due to entropy %8.5f < %8.5f\n",
7597 __func__, j, decoder.sequence.entropy, params.entropy_thold);
7598
7599 decoder.failed = true;
7600 state->n_fail_h++;
7601
7602 continue;
7603 }
7604
7605 if (best_score < decoder.sequence.score) {
7606 best_score = decoder.sequence.score;
7607 best_decoder_id = j;
7608 }
7609 }
7610
7611 WHISPER_LOG_DEBUG("%s: best decoder = %d\n", __func__, best_decoder_id);
7612 }
7613
7614 bool success = true;
7615
7616 // was the decoding successful for the current temperature?
7617 // do fallback only if:
7618 // - we are not at the last temperature
7619 if (it != (int) temperatures.size() - 1) {
7620 const auto & decoder = state->decoders[best_decoder_id];
7621
7622 if (decoder.failed ||
7623 (decoder.sequence.avg_logprobs < params.logprob_thold && state->no_speech_prob < params.no_speech_thold)) {
7624 WHISPER_LOG_DEBUG("%s: failed due to avg_logprobs %8.5f < %8.5f and no_speech_prob %8.5f < %8.5f\n", __func__, decoder.sequence.avg_logprobs, params.logprob_thold, state->no_speech_prob, params.no_speech_thold);
7625 success = false;
7626 state->n_fail_p++;
7627 }
7628 }
7629
7630 if (success) {
7631 //for (auto & token : ctx->decoders[best_decoder_id].sequence.tokens) {
7632 // WHISPER_LOG_DEBUG("%s: token = %d, p = %6.3f, pt = %6.3f, ts = %s, str = %s\n", __func__, token.id, token.p, token.pt, ctx->vocab.id_to_token.at(token.tid).c_str(), ctx->vocab.id_to_token.at(token.id).c_str());
7633 //}
7634
7635 break;
7636 }
7637
7638 WHISPER_LOG_DEBUG("\n%s: failed to decode with temperature = %.2f\n", __func__, t_cur);
7639 }
7640
7641 // output results through a user-provided callback
7642 {
7643 const auto & best_decoder = state->decoders[best_decoder_id];
7644
7645 auto seek_delta = best_decoder.seek_delta;
7646 const auto result_len = best_decoder.sequence.result_len;
7647
7648 const auto & tokens_cur = best_decoder.sequence.tokens;
7649
7650 // [EXPERIMENTAL] Token-level timestamps with DTW
7651 const auto n_segments_before = state->result_all.size();
7652
7653 const bool is_no_speech = (state->no_speech_prob > params.no_speech_thold &&
7654 best_decoder.sequence.avg_logprobs < params.logprob_thold);
7655
7656 //WHISPER_LOG_DEBUG("prompt_init.size() = %d, prompt.size() = %d, result_len = %d, seek_delta = %d\n", prompt_init.size(), prompt.size(), result_len, seek_delta);
7657
7658 // update prompt_past1
7659 prompt_past1.clear();
7660 if (!params.carry_initial_prompt && !prompt.empty() && prompt.front() == whisper_token_prev(ctx)) {
7661 prompt_past1.insert(prompt_past1.end(), prompt.begin() + 1, prompt.end() - prompt_init.size());
7662 }
7663
7664 // Add newly decoded tokens to the rolling context
7665 if (!is_no_speech) {
7666 for (int i = 0; i < result_len; ++i) {
7667 prompt_past1.push_back(tokens_cur[i].id);
7668 }
7669 }
7670
7671 if (!tokens_cur.empty() && ctx->model.n_loaded > 0 && !is_no_speech) {
7672 int i0 = 0;
7673 auto t0 = seek + 2*(tokens_cur.front().tid - whisper_token_beg(ctx));
7674
7675 std::string text;
7676 bool speaker_turn_next = false;
7677
7678 for (int i = 0; i < (int) tokens_cur.size(); i++) {
7679 //printf("%s: %18s %6.3f %18s %6.3f\n", __func__,
7680 // ctx->vocab.id_to_token[tokens_cur[i].id].c_str(), tokens_cur[i].p,
7681 // ctx->vocab.id_to_token[tokens_cur[i].tid].c_str(), tokens_cur[i].pt);
7682
7683 if (params.print_special || tokens_cur[i].id < whisper_token_eot(ctx)) {
7684 text += whisper_token_to_str(ctx, tokens_cur[i].id);
7685 }
7686
7687 // [TDRZ] record if speaker turn was predicted after current segment
7688 if (params.tdrz_enable && tokens_cur[i].id == whisper_token_solm(ctx)) {
7689 speaker_turn_next = true;
7690 }
7691
7692 if (tokens_cur[i].id > whisper_token_beg(ctx) && !params.single_segment) {
7693 const auto t1 = seek + 2*(tokens_cur[i].tid - whisper_token_beg(ctx));
7694
7695 if (!text.empty()) {
7696 const auto tt0 = t0;
7697 const auto tt1 = t1;
7698
7699 if (params.print_realtime) {
7700 if (params.print_timestamps) {
7701 printf("[%s --> %s] %s\n", to_timestamp(tt0).c_str(), to_timestamp(tt1).c_str(), text.c_str());
7702 } else {
7703 printf("%s", text.c_str());
7704 fflush(stdout);
7705 }
7706 }
7707
7708 //printf("tt0 = %d, tt1 = %d, text = %s, token = %s, token_id = %d, tid = %d\n", tt0, tt1, text.c_str(), ctx->vocab.id_to_token[tokens_cur[i].id].c_str(), tokens_cur[i].id, tokens_cur[i].tid);
7709
7710 result_all.push_back({ tt0, tt1, text, state->no_speech_prob, {}, speaker_turn_next });
7711 for (int j = i0; j <= i; j++) {
7712 result_all.back().tokens.push_back(tokens_cur[j]);
7713 }
7714
7715 int n_new = 1;
7716
7717 if (params.token_timestamps) {
7718 whisper_exp_compute_token_level_timestamps(
7719 *ctx, *state, result_all.size() - 1, params.thold_pt, params.thold_ptsum);
7720
7721 if (params.max_len > 0) {
7722 n_new = whisper_wrap_segment(*ctx, *state, params.max_len, params.split_on_word);
7723 }
7724 }
7725 if (params.new_segment_callback && !ctx->params.dtw_token_timestamps) {
7726 params.new_segment_callback(ctx, state, n_new, params.new_segment_callback_user_data);
7727 }
7728 }
7729 text = "";
7730 while (i < (int) tokens_cur.size() && tokens_cur[i].id > whisper_token_beg(ctx)) {
7731 i++;
7732 }
7733 i--;
7734 t0 = t1;
7735 i0 = i + 1;
7736 speaker_turn_next = false;
7737 }
7738 }
7739
7740 if (!text.empty()) {
7741 const auto t1 = seek + seek_delta;
7742
7743 const auto tt0 = t0;
7744 const auto tt1 = t1;
7745
7746 if (params.print_realtime) {
7747 if (params.print_timestamps) {
7748 printf("[%s --> %s] %s\n", to_timestamp(tt0).c_str(), to_timestamp(tt1).c_str(), text.c_str());
7749 } else {
7750 printf("%s", text.c_str());
7751 fflush(stdout);
7752 }
7753 }
7754
7755 result_all.push_back({ tt0, tt1, text, state->no_speech_prob, {}, speaker_turn_next });
7756 for (int j = i0; j < (int) tokens_cur.size(); j++) {
7757 result_all.back().tokens.push_back(tokens_cur[j]);
7758 }
7759
7760 int n_new = 1;
7761
7762 if (params.token_timestamps) {
7763 whisper_exp_compute_token_level_timestamps(
7764 *ctx, *state, result_all.size() - 1, params.thold_pt, params.thold_ptsum);
7765
7766 if (params.max_len > 0) {
7767 n_new = whisper_wrap_segment(*ctx, *state, params.max_len, params.split_on_word);
7768 }
7769 }
7770 if (params.new_segment_callback && !ctx->params.dtw_token_timestamps) {
7771 params.new_segment_callback(ctx, state, n_new, params.new_segment_callback_user_data);
7772 }
7773 }
7774 }
7775
7776 // FIXME: will timestamp offsets be correct?
7777 // [EXPERIMENTAL] Token-level timestamps with DTW
7778 {
7779 const int n_segments = state->result_all.size() - n_segments_before;
7780 if (ctx->params.dtw_token_timestamps && n_segments) {
7781 const int n_frames = std::min(std::min(WHISPER_CHUNK_SIZE * 100, seek_delta), seek_end - seek);
7782 whisper_exp_compute_token_level_timestamps_dtw(
7783 ctx, state, params, result_all.size() - n_segments, n_segments, seek, n_frames, 7, params.n_threads);
7784 if (params.new_segment_callback) {
7785 for (int seg = (int) result_all.size() - n_segments; seg < n_segments; seg++) {
7786 params.new_segment_callback(ctx, state, seg, params.new_segment_callback_user_data);
7787 }
7788 }
7789 }
7790 }
7791
7792 // ref: https://github.com/ggml-org/whisper.cpp/pull/2629
7793 const bool single_timestamp_ending = tokens_cur.size() > 1 &&
7794 tokens_cur[tokens_cur.size() - 2].id < whisper_token_beg(ctx) &&
7795 tokens_cur[tokens_cur.size() - 1].id > whisper_token_beg(ctx);
7796 if (single_timestamp_ending) {
7797 WHISPER_LOG_DEBUG("single timestamp ending - skip entire chunk\n");
7798 seek_delta = std::min(seek_end - seek, WHISPER_CHUNK_SIZE * 100);
7799 }
7800
7801 // update audio window
7802 seek += seek_delta;
7803
7804 WHISPER_LOG_DEBUG("seek = %d, seek_delta = %d\n", seek, seek_delta);
7805 }
7806 }
7807
7808 return 0;
7809 }
7810
7811 int whisper_full(
7812 struct whisper_context * ctx,
7813 struct whisper_full_params params,
7814 const float * samples,
7815 int n_samples) {
7816
7817 std::vector<float> vad_samples;
7818 if (params.vad) {
7819 WHISPER_LOG_INFO("%s: VAD is enabled, processing speech segments only\n", __func__);
7820 if (!whisper_vad(ctx, ctx->state, params, samples, n_samples, vad_samples)) {
7821 WHISPER_LOG_ERROR("%s: failed to compute VAD\n", __func__);
7822 return -1;
7823 }
7824 if (vad_samples.empty()) {
7825 ctx->state->result_all.clear();
7826 return 0;
7827 }
7828 samples = vad_samples.data();
7829 n_samples = vad_samples.size();
7830 }
7831 return whisper_full_with_state(ctx, ctx->state, params, samples, n_samples);
7832 }
7833
7834 int whisper_full_parallel(
7835 struct whisper_context * ctx,
7836 struct whisper_full_params params,
7837 const float * samples,
7838 int n_samples,
7839 int n_processors) {
7840
7841 if (n_processors == 1) {
7842 return whisper_full(ctx, params, samples, n_samples);
7843 }
7844
7845 std::vector<float> vad_samples;
7846 if (params.vad) {
7847 WHISPER_LOG_INFO("%s: VAD is enabled, processing speech segments only\n", __func__);
7848 if (!whisper_vad(ctx, ctx->state, params, samples, n_samples, vad_samples)) {
7849 WHISPER_LOG_ERROR("%s: failed to compute VAD\n", __func__);
7850 return -1;
7851 }
7852 if (vad_samples.empty()) {
7853 return 0;
7854 }
7855 samples = vad_samples.data();
7856 n_samples = vad_samples.size();
7857 }
7858 int ret = 0;
7859
7860 // prepare separate states for each thread
7861 std::vector<whisper_state*> states;
7862
7863 const int offset_samples = (WHISPER_SAMPLE_RATE*params.offset_ms)/1000;
7864 const int n_samples_per_processor = (n_samples - offset_samples)/n_processors;
7865
7866 // the calling thread will process the first chunk
7867 // while the other threads will process the remaining chunks
7868
7869 std::vector<std::thread> workers(n_processors - 1);
7870 for (int i = 0; i < n_processors - 1; ++i) {
7871 // create a new state for each thread
7872 states.push_back(whisper_init_state(ctx));
7873
7874 const int start_samples = offset_samples + (i + 1)*n_samples_per_processor;
7875 const int n_samples_cur = (i == n_processors - 2) ? n_samples - start_samples : n_samples_per_processor;
7876
7877 auto params_cur = params;
7878
7879 params_cur.offset_ms = 0;
7880 params_cur.print_progress = false;
7881 params_cur.print_realtime = false;
7882
7883 params_cur.new_segment_callback = nullptr;
7884 params_cur.new_segment_callback_user_data = nullptr;
7885
7886 params_cur.progress_callback = nullptr;
7887 params_cur.progress_callback_user_data = nullptr;
7888
7889 workers[i] = std::thread(whisper_full_with_state, ctx, states[i], std::move(params_cur), samples + start_samples, n_samples_cur);
7890 }
7891
7892 {
7893 auto params_cur = params;
7894
7895 // We need to disable the print real-time for this one as well, otherwise it will show only for the first chunk.
7896 params_cur.print_realtime = false;
7897
7898 // Run the first transformation using default state but only for the first chunk.
7899 ret = whisper_full_with_state(ctx, ctx->state, std::move(params_cur), samples, offset_samples + n_samples_per_processor);
7900 }
7901
7902 for (int i = 0; i < n_processors - 1; ++i) {
7903 workers[i].join();
7904 }
7905
7906 const int64_t offset_t = (int64_t) params.offset_ms/10.0;
7907
7908 // combine results into result_state->result_all from all other states
7909 for (int i = 0; i < n_processors - 1; ++i) {
7910 auto& results_i = states[i]->result_all;
7911
7912 for (auto& result : results_i) {
7913 // correct the segment timestamp taking into account the offset
7914 result.t0 += 100 * ((i + 1) * n_samples_per_processor) / WHISPER_SAMPLE_RATE + offset_t;
7915 result.t1 += 100 * ((i + 1) * n_samples_per_processor) / WHISPER_SAMPLE_RATE + offset_t;
7916
7917 // make sure that segments are not overlapping
7918 if (!ctx->state->result_all.empty()) {
7919 result.t0 = std::max(result.t0, ctx->state->result_all.back().t1);
7920 }
7921
7922 ctx->state->result_all.push_back(std::move(result));
7923
7924 // call the new_segment_callback for each segment
7925 if (params.new_segment_callback) {
7926 params.new_segment_callback(ctx, ctx->state, 1, params.new_segment_callback_user_data);
7927 }
7928 }
7929
7930 ctx->state->t_mel_us += states[i]->t_mel_us;
7931
7932 ctx->state->t_sample_us += states[i]->t_sample_us;
7933 ctx->state->t_encode_us += states[i]->t_encode_us;
7934 ctx->state->t_decode_us += states[i]->t_decode_us;
7935 ctx->state->t_batchd_us += states[i]->t_batchd_us;
7936 ctx->state->t_prompt_us += states[i]->t_prompt_us;
7937
7938 ctx->state->n_sample += states[i]->n_sample;
7939 ctx->state->n_encode += states[i]->n_encode;
7940 ctx->state->n_decode += states[i]->n_decode;
7941 ctx->state->n_batchd += states[i]->n_batchd;
7942 ctx->state->n_prompt += states[i]->n_prompt;
7943
7944 whisper_free_state(states[i]);
7945 }
7946
7947 // average the timings
7948 ctx->state->t_mel_us /= n_processors;
7949 ctx->state->t_sample_us /= n_processors;
7950 ctx->state->t_encode_us /= n_processors;
7951 ctx->state->t_decode_us /= n_processors;
7952
7953 // print information about the audio boundaries
7954 WHISPER_LOG_WARN("\n");
7955 WHISPER_LOG_WARN("%s: the audio has been split into %d chunks at the following times:\n", __func__, n_processors);
7956 for (int i = 0; i < n_processors - 1; ++i) {
7957 WHISPER_LOG_WARN("%s: split %d - %s\n", __func__, (i + 1), to_timestamp(100*((i + 1)*n_samples_per_processor)/WHISPER_SAMPLE_RATE + offset_t).c_str());
7958 }
7959 WHISPER_LOG_WARN("%s: the transcription quality may be degraded near these boundaries\n", __func__);
7960
7961 return ret;
7962 }
7963
7964 int whisper_full_n_segments_from_state(struct whisper_state * state) {
7965 return state->result_all.size();
7966 }
7967
7968 int whisper_full_n_segments(struct whisper_context * ctx) {
7969 return ctx->state->result_all.size();
7970 }
7971
7972 int whisper_full_lang_id_from_state(struct whisper_state * state) {
7973 return state->lang_id;
7974 }
7975
7976 int whisper_full_lang_id(struct whisper_context * ctx) {
7977 return ctx->state->lang_id;
7978 }
7979
7980 static int64_t map_processed_to_original_time(int64_t processed_time, const std::vector<vad_time_mapping> & mapping_table) {
7981 if (mapping_table.empty()) {
7982 return processed_time;
7983 }
7984
7985 if (processed_time <= mapping_table.front().processed_time) {
7986 return mapping_table.front().original_time; // Before first mapping point
7987 }
7988
7989 if (processed_time >= mapping_table.back().processed_time) {
7990 return mapping_table.back().original_time; // After last mapping point
7991 }
7992
7993 // Binary search over the time map that finds the first entry that has a
7994 // processed time greater than or equal to the current processed time.
7995 auto upper = std::lower_bound(mapping_table.begin(), mapping_table.end(), processed_time,
7996 [](const vad_time_mapping & entry, int64_t time) {
7997 return entry.processed_time < time;
7998 }
7999 );
8000
8001 // If exact match found
8002 if (upper->processed_time == processed_time) {
8003 return upper->original_time;
8004 }
8005
8006 // Need to interpolate between two points
8007 auto lower = upper - 1;
8008
8009 int64_t processed_diff = upper->processed_time - lower->processed_time;
8010 int64_t original_diff = upper->original_time - lower->original_time;
8011 int64_t offset = processed_time - lower->processed_time;
8012
8013 if (processed_diff == 0) {
8014 return lower->original_time;
8015 }
8016
8017 // Perform linear interpolation
8018 return lower->original_time + (offset * original_diff) / processed_diff;
8019 }
8020
8021 // Function to get the starting timestamp of a segment
8022 int64_t whisper_full_get_segment_t0_from_state(struct whisper_state * state, int i_segment) {
8023 // If VAD wasn't used, return the original timestamp
8024 if (!state->has_vad_segments || state->vad_mapping_table.empty()) {
8025 return state->result_all[i_segment].t0;
8026 }
8027
8028 // Get the processed timestamp
8029 int64_t t0 = state->result_all[i_segment].t0;
8030
8031 // Map to original time using the mapping table
8032 return map_processed_to_original_time(t0, state->vad_mapping_table);
8033 }
8034
8035 // Function to get the ending timestamp of a segment
8036 int64_t whisper_full_get_segment_t1_from_state(struct whisper_state * state, int i_segment) {
8037 // If VAD wasn't used, return the original timestamp
8038 if (!state->has_vad_segments || state->vad_mapping_table.empty()) {
8039 return state->result_all[i_segment].t1;
8040 }
8041
8042 // Get the processed timestamp
8043 int64_t t1 = state->result_all[i_segment].t1;
8044
8045 // Map to original time using the mapping table
8046 int64_t orig_t1 = map_processed_to_original_time(t1, state->vad_mapping_table);
8047
8048 // Get the corresponding t0 for this segment
8049 int64_t orig_t0 = whisper_full_get_segment_t0_from_state(state, i_segment);
8050
8051 // Ensure minimum duration to prevent zero-length segments
8052 const int64_t min_duration = 10; // 10ms minimum
8053 if (orig_t1 - orig_t0 < min_duration) {
8054 orig_t1 = orig_t0 + min_duration;
8055 }
8056
8057 return orig_t1;
8058 }
8059
8060
8061 int64_t whisper_full_get_segment_t0(struct whisper_context * ctx, int i_segment) {
8062 return whisper_full_get_segment_t0_from_state(ctx->state, i_segment);
8063 }
8064
8065 int64_t whisper_full_get_segment_t1(struct whisper_context * ctx, int i_segment) {
8066 return whisper_full_get_segment_t1_from_state(ctx->state, i_segment);
8067 }
8068
8069 bool whisper_full_get_segment_speaker_turn_next_from_state(struct whisper_state * state, int i_segment) {
8070 return state->result_all[i_segment].speaker_turn_next;
8071 }
8072
8073 bool whisper_full_get_segment_speaker_turn_next(struct whisper_context * ctx, int i_segment) {
8074 return ctx->state->result_all[i_segment].speaker_turn_next;
8075 }
8076
8077 const char * whisper_full_get_segment_text_from_state(struct whisper_state * state, int i_segment) {
8078 return state->result_all[i_segment].text.c_str();
8079 }
8080
8081 const char * whisper_full_get_segment_text(struct whisper_context * ctx, int i_segment) {
8082 return ctx->state->result_all[i_segment].text.c_str();
8083 }
8084
8085 int whisper_full_n_tokens_from_state(struct whisper_state * state, int i_segment) {
8086 return state->result_all[i_segment].tokens.size();
8087 }
8088
8089 int whisper_full_n_tokens(struct whisper_context * ctx, int i_segment) {
8090 return ctx->state->result_all[i_segment].tokens.size();
8091 }
8092
8093 const char * whisper_full_get_token_text_from_state(struct whisper_context * ctx, struct whisper_state * state, int i_segment, int i_token) {
8094 return ctx->vocab.id_to_token[state->result_all[i_segment].tokens[i_token].id].c_str();
8095 }
8096
8097 const char* whisper_full_get_token_text(struct whisper_context * ctx, int i_segment, int i_token) {
8098 return ctx->vocab.id_to_token[ctx->state->result_all[i_segment].tokens[i_token].id].c_str();
8099 }
8100
8101 whisper_token whisper_full_get_token_id_from_state(struct whisper_state * state, int i_segment, int i_token) {
8102 return state->result_all[i_segment].tokens[i_token].id;
8103 }
8104
8105 whisper_token whisper_full_get_token_id(struct whisper_context * ctx, int i_segment, int i_token) {
8106 return ctx->state->result_all[i_segment].tokens[i_token].id;
8107 }
8108
8109 struct whisper_token_data whisper_full_get_token_data_from_state(struct whisper_state * state, int i_segment, int i_token) {
8110 return state->result_all[i_segment].tokens[i_token];
8111 }
8112
8113 struct whisper_token_data whisper_full_get_token_data(struct whisper_context * ctx, int i_segment, int i_token) {
8114 return ctx->state->result_all[i_segment].tokens[i_token];
8115 }
8116
8117 float whisper_full_get_token_p_from_state(struct whisper_state * state, int i_segment, int i_token) {
8118 return state->result_all[i_segment].tokens[i_token].p;
8119 }
8120
8121 float whisper_full_get_token_p(struct whisper_context * ctx, int i_segment, int i_token) {
8122 return ctx->state->result_all[i_segment].tokens[i_token].p;
8123 }
8124
8125 /*
8126 Following five functions are added by Anastasia Shchupak on behalf of inclusion into Praat.
8127 It provides direct access to VAD segments.
8128 */
8129 int whisper_full_n_vad_segments(struct whisper_context * ctx) {
8130 if (!ctx->state->has_vad_segments) {
8131 return 0;
8132 }
8133 return static_cast<int>(ctx->state->vad_segments.size());
8134 }
8135
8136 int64_t whisper_full_get_vad_segment_orig_start(struct whisper_context * ctx, int i_vad_segment) {
8137 return ctx->state->vad_segments[i_vad_segment].orig_start;
8138 }
8139
8140 int64_t whisper_full_get_vad_segment_orig_end(struct whisper_context * ctx, int i_vad_segment) {
8141 return ctx->state->vad_segments[i_vad_segment].orig_end;
8142 }
8143
8144 int64_t whisper_full_get_vad_segment_vad_start(struct whisper_context * ctx, int i_vad_segment) {
8145 return ctx->state->vad_segments[i_vad_segment].vad_start;
8146 }
8147
8148 int64_t whisper_full_get_vad_segment_vad_end(struct whisper_context * ctx, int i_vad_segment) {
8149 return ctx->state->vad_segments[i_vad_segment].vad_end;
8150 }
8151
8152
8153
8154 float whisper_full_get_segment_no_speech_prob(struct whisper_context * ctx, int i_segment) {
8155 return ctx->state->result_all[i_segment].no_speech_prob;
8156 }
8157
8158 float whisper_full_get_segment_no_speech_prob_from_state(struct whisper_state * state, int i_segment) {
8159 return state->result_all[i_segment].no_speech_prob;
8160 }
8161
8162 // =================================================================================================
8163
8164 //
8165 // Temporary interface needed for exposing ggml interface
8166 // Will be removed in the future when ggml becomes a separate library
8167 //
8168
8169 WHISPER_API int whisper_bench_memcpy(int n_threads) {
8170 fputs(whisper_bench_memcpy_str(n_threads), stderr);
8171 return 0;
8172 }
8173
8174 WHISPER_API const char * whisper_bench_memcpy_str(int n_threads) {
8175 static std::string s;
8176 s = "";
8177 char strbuf[256];
8178
8179 ggml_time_init();
8180
8181 size_t n = 20;
8182 size_t arr = n_threads > 0 ? 1024llu : n_threads; // trick to avoid compiler optimizations
8183
8184 // 1GB array
8185 const size_t size = arr*1e6;
8186
8187 double sum = 0.0;
8188
8189 // heat-up
8190 {
8191 char * src = (char *) ggml_malloc(size);
8192 char * dst = (char *) ggml_malloc(size);
8193
8194 for (size_t i = 0; i < size; i++) src[i] = i;
8195
8196 memcpy(dst, src, size); // heat-up
8197
8198 double tsum = 0.0;
8199
8200 for (size_t i = 0; i < n; i++) {
8201 const int64_t t0 = ggml_time_us();
8202
8203 memcpy(dst, src, size);
8204
8205 const int64_t t1 = ggml_time_us();
8206
8207 tsum += (t1 - t0)*1e-6;
8208
8209 src[rand() % size] = rand() % 256;
8210 }
8211
8212 snprintf(strbuf, sizeof(strbuf), "memcpy: %7.2f GB/s (heat-up)\n", (double) (n*size)/(tsum*1e9));
8213 s += strbuf;
8214
8215 // needed to prevent the compiler from optimizing the memcpy away
8216 {
8217 for (size_t i = 0; i < size; i++) sum += dst[i];
8218 }
8219
8220 ggml_raw_free(src);
8221 ggml_raw_free(dst);
8222 }
8223
8224 // single-thread
8225 {
8226 char * src = (char *) ggml_malloc(size);
8227 char * dst = (char *) ggml_malloc(size);
8228
8229 for (size_t i = 0; i < size; i++) src[i] = i;
8230
8231 memcpy(dst, src, size); // heat-up
8232
8233 double tsum = 0.0;
8234
8235 for (size_t i = 0; i < n; i++) {
8236 const int64_t t0 = ggml_time_us();
8237
8238 memcpy(dst, src, size);
8239
8240 const int64_t t1 = ggml_time_us();
8241
8242 tsum += (t1 - t0)*1e-6;
8243
8244 src[rand() % size] = rand() % 256;
8245 }
8246
8247 snprintf(strbuf, sizeof(strbuf), "memcpy: %7.2f GB/s ( 1 thread)\n", (double) (n*size)/(tsum*1e9));
8248 s += strbuf;
8249
8250 // needed to prevent the compiler from optimizing the memcpy away
8251 {
8252 for (size_t i = 0; i < size; i++) sum += dst[i];
8253 }
8254
8255 ggml_raw_free(src);
8256 ggml_raw_free(dst);
8257 }
8258
8259 // multi-thread
8260
8261 for (int32_t k = 1; k <= n_threads; k++) {
8262 char * src = (char *) ggml_malloc(size);
8263 char * dst = (char *) ggml_malloc(size);
8264
8265 for (size_t i = 0; i < size; i++) src[i] = i;
8266
8267 memcpy(dst, src, size); // heat-up
8268
8269 double tsum = 0.0;
8270
8271 auto helper = [&](int th) {
8272 const int64_t i0 = (th + 0)*size/k;
8273 const int64_t i1 = (th + 1)*size/k;
8274
8275 for (size_t i = 0; i < n; i++) {
8276 memcpy(dst + i0, src + i0, i1 - i0);
8277
8278 src[i0 + rand() % (i1 - i0)] = rand() % 256;
8279 };
8280 };
8281
8282 const int64_t t0 = ggml_time_us();
8283
8284 std::vector<std::thread> threads(k - 1);
8285 for (int32_t th = 0; th < k - 1; ++th) {
8286 threads[th] = std::thread(helper, th);
8287 }
8288
8289 helper(k - 1);
8290
8291 for (int32_t th = 0; th < k - 1; ++th) {
8292 threads[th].join();
8293 }
8294
8295 const int64_t t1 = ggml_time_us();
8296
8297 tsum += (t1 - t0)*1e-6;
8298
8299 snprintf(strbuf, sizeof(strbuf), "memcpy: %7.2f GB/s (%2d thread)\n", (double) (n*size)/(tsum*1e9), k);
8300 s += strbuf;
8301
8302 // needed to prevent the compiler from optimizing the memcpy away
8303 {
8304 for (size_t i = 0; i < size; i++) sum += dst[i];
8305 }
8306
8307 ggml_raw_free(src);
8308 ggml_raw_free(dst);
8309 }
8310
8311 snprintf(strbuf, sizeof(strbuf), "sum: %f\n", sum);
8312 s += strbuf;
8313
8314 return s.c_str();
8315 }
8316
8317 WHISPER_API int whisper_bench_ggml_mul_mat(int n_threads) {
8318 fputs(whisper_bench_ggml_mul_mat_str(n_threads), stderr);
8319 return 0;
8320 }
8321
8322 WHISPER_API const char * whisper_bench_ggml_mul_mat_str(int n_threads) {
8323 static std::string s;
8324 s = "";
8325 char strbuf[256];
8326
8327 ggml_time_init();
8328
8329 const int n_max = 128;
8330
8331 const std::vector<size_t> sizes = {
8332 64, 128, 256, 512, 1024, 2048, 4096,
8333 };
8334
8335 const size_t N_max = sizes.back();
8336
8337 // a: N*N*sizeof(float)
8338 // b: N*N*sizeof(float)
8339 // c: N*N*sizeof(float)
8340 // when F16 is used, there is an extra work buffer of size N*N*sizeof(float)
8341 std::vector<uint8_t> buf(3llu*N_max*N_max*sizeof(float) + 3*ggml_tensor_overhead() + ggml_graph_overhead());
8342
8343 // put a bunch of random data in the buffer
8344 for (size_t i = 0; i < buf.size(); i++) buf[i] = i;
8345
8346 for (int j = 0; j < (int) sizes.size(); j++) {
8347 int n_q4_0 = 0;
8348 int n_q4_1 = 0;
8349 int n_q5_0 = 0;
8350 int n_q5_1 = 0;
8351 int n_q8_0 = 0;
8352 int n_fp16 = 0;
8353 int n_fp32 = 0;
8354
8355 // GFLOPS/s
8356 double s_q4_0 = 0.0;
8357 double s_q4_1 = 0.0;
8358 double s_q5_0 = 0.0;
8359 double s_q5_1 = 0.0;
8360 double s_q8_0 = 0.0;
8361 double s_fp16 = 0.0;
8362 double s_fp32 = 0.0;
8363
8364 const size_t N = sizes[j];
8365
8366 for (int k = 0; k < 7; ++k) {
8367 const ggml_type wtype =
8368 k == 0 ? GGML_TYPE_Q4_0 :
8369 k == 1 ? GGML_TYPE_Q4_1 :
8370 k == 2 ? GGML_TYPE_Q5_0 :
8371 k == 3 ? GGML_TYPE_Q5_1 :
8372 k == 4 ? GGML_TYPE_Q8_0 :
8373 k == 5 ? GGML_TYPE_F16 : GGML_TYPE_F32;
8374
8375 double & s = k == 0 ? s_q4_0 : k == 1 ? s_q4_1 : k == 2 ? s_q5_0 : k == 3 ? s_q5_1 : k == 4 ? s_q8_0 : k == 5 ? s_fp16 : /*k == 6*/ s_fp32;
8376 int & n = k == 0 ? n_q4_0 : k == 1 ? n_q4_1 : k == 2 ? n_q5_0 : k == 3 ? n_q5_1 : k == 4 ? n_q8_0 : k == 5 ? n_fp16 : /*k == 6*/ n_fp32;
8377
8378 struct ggml_init_params gparams = {
8379 /*.mem_size =*/ buf.size(),
8380 /*.mem_buffer =*/ buf.data(),
8381 /*.no_alloc =*/ false,
8382 };
8383
8384 struct ggml_context * ctx0 = ggml_init(gparams);
8385
8386 struct ggml_tensor * a = ggml_new_tensor_2d(ctx0, wtype, N, N);
8387 struct ggml_tensor * b = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, N, N);
8388
8389 struct ggml_tensor * c = ggml_mul_mat(ctx0, a, b);
8390
8391 struct ggml_cgraph * gf = ggml_new_graph(ctx0);
8392
8393 ggml_build_forward_expand(gf, c);
8394
8395 double tsum = 0.0;
8396
8397 // heat-up
8398 ggml_graph_compute_helper(gf, n_threads, nullptr, nullptr);
8399
8400 for (int i = 0; i < n_max; ++i) {
8401 const int64_t t0 = ggml_time_us();
8402
8403 ggml_graph_compute_helper(gf, n_threads, nullptr, nullptr);
8404
8405 const int64_t t1 = ggml_time_us();
8406
8407 tsum += (t1 - t0)*1e-6;
8408 n++;
8409
8410 if (tsum > 1.0 && n >= 3) {
8411 break;
8412 }
8413 }
8414
8415 ggml_free(ctx0);
8416
8417 s = ((2.0*N*N*N*n)/tsum)*1e-9;
8418 }
8419
8420 // Q4_0 | Q4_1
8421 snprintf(strbuf, sizeof(strbuf), "%4zu x %4zu: Q4_0 %7.1f GFLOPS (%3d runs) | Q4_1 %7.1f GFLOPS (%3d runs)\n",
8422 N, N, s_q4_0, n_q4_0, s_q4_1, n_q4_1);
8423 s += strbuf;
8424
8425 // Q5_0 | Q5_1 | Q8_0
8426 snprintf(strbuf, sizeof(strbuf), "%4zu x %4zu: Q5_0 %7.1f GFLOPS (%3d runs) | Q5_1 %7.1f GFLOPS (%3d runs) | Q8_0 %7.1f GFLOPS (%3d runs)\n",
8427 N, N, s_q5_0, n_q5_0, s_q5_1, n_q5_1, s_q8_0, n_q8_0);
8428 s += strbuf;
8429
8430 // F16 | F32
8431 snprintf(strbuf, sizeof(strbuf), "%4zu x %4zu: F16 %7.1f GFLOPS (%3d runs) | F32 %7.1f GFLOPS (%3d runs)\n",
8432 N, N, s_fp16, n_fp16, s_fp32, n_fp32);
8433 s += strbuf;
8434 }
8435
8436 return s.c_str();
8437 }
8438
8439 // =================================================================================================
8440
8441 // =================================================================================================
8442
8443 //
8444 // Experimental stuff below
8445 //
8446 // Not sure if these should be part of the library at all, because the quality of the results is not
8447 // guaranteed. Might get removed at some point unless a robust algorithm implementation is found
8448 //
8449
8450 // =================================================================================================
8451
8452 //
8453 // token-level timestamps
8454 //
8455
8456 static int64_t sample_to_timestamp(int i_sample) {
8457 return (100ll*i_sample)/WHISPER_SAMPLE_RATE;
8458 }
8459
8460 // a cost-function / heuristic that is high for text that takes longer to pronounce
8461 // obviously, can be improved
8462 static float voice_length(const std::string & text) {
8463 float res = 0.0f;
8464
8465 for (char c : text) {
8466 if (c == ' ') {
8467 res += 0.01f;
8468 } else if (c == ',') {
8469 res += 2.00f;
8470 } else if (c == '.') {
8471 res += 3.00f;
8472 } else if (c == '!') {
8473 res += 3.00f;
8474 } else if (c == '?') {
8475 res += 3.00f;
8476 } else if (c >= '0' && c <= '9') {
8477 res += 3.00f;
8478 } else {
8479 res += 1.00f;
8480 }
8481 }
8482
8483 return res;
8484 }
8485
8486 // average the fabs of the signal
8487 static std::vector<float> get_signal_energy(const float * signal, int n_samples, int n_samples_per_half_window) {
8488 const int hw = n_samples_per_half_window;
8489
8490 std::vector<float> result(n_samples);
8491
8492 for (int i = 0; i < n_samples; i++) {
8493 float sum = 0;
8494 for (int j = -hw; j <= hw; j++) {
8495 if (i + j >= 0 && i + j < n_samples) {
8496 sum += fabs(signal[i + j]);
8497 }
8498 }
8499 result[i] = sum/(2*hw + 1);
8500 }
8501
8502 return result;
8503 }
8504
8505 static int timestamp_to_sample(int64_t t, int64_t segment_t0, int n_samples) {
8506 // Convert absolute timestamp to segment-relative timestamp
8507 int64_t relative_t = t - segment_t0;
8508 int sample = (int)((relative_t * WHISPER_SAMPLE_RATE) / 100);
8509 return std::max(0, std::min(n_samples - 1, sample));
8510 }
8511
8512 static int64_t sample_to_timestamp(int i_sample, int64_t segment_t0) {
8513 int64_t relative_timestamp = (100ll * i_sample) / WHISPER_SAMPLE_RATE;
8514 return relative_timestamp + segment_t0;
8515 }
8516
8517 static void whisper_exp_compute_token_level_timestamps(
8518 struct whisper_context & ctx,
8519 struct whisper_state & state,
8520 int i_segment,
8521 float thold_pt,
8522 float thold_ptsum) {
8523 auto & segment = state.result_all[i_segment];
8524 auto & tokens = segment.tokens;
8525
8526 const int n_samples = state.energy.size();
8527
8528 if (n_samples == 0) {
8529 WHISPER_LOG_ERROR("%s: no signal data available\n", __func__);
8530 return;
8531 }
8532
8533 const int64_t t0 = segment.t0;
8534 const int64_t t1 = segment.t1;
8535
8536 const int n = tokens.size();
8537
8538 if (n == 0) {
8539 return;
8540 }
8541
8542 if (n == 1) {
8543 tokens[0].t0 = t0;
8544 tokens[0].t1 = t1;
8545
8546 return;
8547 }
8548
8549 auto & t_beg = state.t_beg;
8550 auto & t_last = state.t_last;
8551 auto & tid_last = state.tid_last;
8552
8553 for (int j = 0; j < n; ++j) {
8554 auto & token = tokens[j];
8555
8556 if (j == 0) {
8557 if (token.id == whisper_token_beg(&ctx)) {
8558 tokens[j ].t0 = t0;
8559 tokens[j ].t1 = t0;
8560 tokens[j + 1].t0 = t0;
8561
8562 t_beg = t0;
8563 t_last = t0;
8564 tid_last = whisper_token_beg(&ctx);
8565 } else {
8566 tokens[j ].t0 = t_last;
8567 }
8568 }
8569
8570 const int64_t tt = t_beg + 2*(token.tid - whisper_token_beg(&ctx));
8571
8572 tokens[j].vlen = voice_length(whisper_token_to_str(&ctx, token.id));
8573
8574 if (token.pt > thold_pt && token.ptsum > thold_ptsum && token.tid > tid_last && tt <= t1) {
8575 if (j > 0) {
8576 tokens[j - 1].t1 = tt;
8577 }
8578 tokens[j].t0 = tt;
8579 tid_last = token.tid;
8580 }
8581 }
8582
8583 tokens[n - 2].t1 = t1;
8584 tokens[n - 1].t0 = t1;
8585 tokens[n - 1].t1 = t1;
8586
8587 t_last = t1;
8588
8589 // find intervals of tokens with unknown timestamps
8590 // fill the timestamps by proportionally splitting the interval based on the token voice lengths
8591 {
8592 int p0 = 0;
8593 int p1 = 0;
8594
8595 while (true) {
8596 while (p1 < n && tokens[p1].t1 < 0) {
8597 p1++;
8598 }
8599
8600 if (p1 >= n) {
8601 p1--;
8602 }
8603
8604 //printf("p0=%d p1=%d t0=%lld t1=%lld\n", p0, p1, tokens[p0].t0, tokens[p1].t1);
8605
8606 if (p1 > p0) {
8607 double psum = 0.0;
8608 for (int j = p0; j <= p1; j++) {
8609 psum += tokens[j].vlen;
8610 }
8611
8612 //printf("analyzing %d - %d, psum = %f\n", p0, p1, psum);
8613
8614 const double dt = tokens[p1].t1 - tokens[p0].t0;
8615
8616 // split the time proportionally to the voice length
8617 for (int j = p0 + 1; j <= p1; j++) {
8618 const double ct = tokens[j - 1].t0 + dt*tokens[j - 1].vlen/psum;
8619
8620 tokens[j - 1].t1 = ct;
8621 tokens[j ].t0 = ct;
8622 }
8623 }
8624
8625 p1++;
8626 p0 = p1;
8627 if (p1 >= n) {
8628 break;
8629 }
8630 }
8631 }
8632
8633 // fix up (just in case)
8634 for (int j = 0; j < n - 1; j++) {
8635 if (tokens[j].t1 < 0) {
8636 tokens[j + 1].t0 = tokens[j].t1;
8637 }
8638
8639 if (j > 0) {
8640 if (tokens[j - 1].t1 > tokens[j].t0) {
8641 tokens[j].t0 = tokens[j - 1].t1;
8642 tokens[j].t1 = std::max(tokens[j].t0, tokens[j].t1);
8643 }
8644 }
8645 }
8646
8647 // VAD
8648 // expand or contract tokens based on voice activity
8649 {
8650 const int hw = WHISPER_SAMPLE_RATE/8;
8651
8652 for (int j = 0; j < n; j++) {
8653 if (tokens[j].id >= whisper_token_eot(&ctx)) {
8654 continue;
8655 }
8656
8657 int s0 = timestamp_to_sample(tokens[j].t0, segment.t0, n_samples);
8658 int s1 = timestamp_to_sample(tokens[j].t1, segment.t0, n_samples);
8659
8660 const int ss0 = std::max(s0 - hw, 0);
8661 const int ss1 = std::min(s1 + hw, n_samples);
8662
8663 const int ns = ss1 - ss0;
8664
8665 float sum = 0.0f;
8666
8667 for (int k = ss0; k < ss1; k++) {
8668 sum += state.energy[k];
8669 }
8670
8671 const float thold = 0.5*sum/ns;
8672
8673 {
8674 int k = s0;
8675 if (state.energy[k] > thold && j > 0) {
8676 while (k > 0 && state.energy[k] > thold) {
8677 k--;
8678 }
8679 tokens[j].t0 = sample_to_timestamp(k, segment.t0);
8680 if (tokens[j].t0 < tokens[j - 1].t1) {
8681 tokens[j].t0 = tokens[j - 1].t1;
8682 } else {
8683 s0 = k;
8684 }
8685 } else {
8686 while (state.energy[k] < thold && k < s1) {
8687 k++;
8688 }
8689 s0 = k;
8690 tokens[j].t0 = sample_to_timestamp(k, segment.t0);
8691 }
8692 }
8693
8694 {
8695 int k = s1;
8696 if (state.energy[k] > thold) {
8697 while (k < n_samples - 1 && state.energy[k] > thold) {
8698 k++;
8699 }
8700 tokens[j].t1 = sample_to_timestamp(k, segment.t0);
8701 if (j < n - 1 && tokens[j].t1 > tokens[j + 1].t0) {
8702 tokens[j].t1 = tokens[j + 1].t0;
8703 } else {
8704 s1 = k;
8705 }
8706 } else {
8707 while (state.energy[k] < thold && k > s0) {
8708 k--;
8709 }
8710 s1 = k;
8711 tokens[j].t1 = sample_to_timestamp(k, segment.t0);
8712 }
8713 }
8714 }
8715 }
8716
8717 // fixed token expand (optional)
8718 //{
8719 // const int t_expand = 0;
8720
8721 // for (int j = 0; j < n; j++) {
8722 // if (j > 0) {
8723 // tokens[j].t0 = std::max(0, (int) (tokens[j].t0 - t_expand));
8724 // }
8725 // if (j < n - 1) {
8726 // tokens[j].t1 = tokens[j].t1 + t_expand;
8727 // }
8728 // }
8729 //}
8730
8731 // debug info
8732 //for (int j = 0; j < n; ++j) {
8733 // const auto & token = tokens[j];
8734 // const auto tt = token.pt > thold_pt && token.ptsum > 0.01 ? whisper_token_to_str(&ctx, token.tid) : "[?]";
8735 // printf("%s: %10s %6.3f %6.3f %6.3f %6.3f %5d %5d '%s'\n", __func__,
8736 // tt, token.p, token.pt, token.ptsum, token.vlen, (int) token.t0, (int) token.t1, whisper_token_to_str(&ctx, token.id));
8737
8738 // if (tokens[j].id >= whisper_token_eot(&ctx)) {
8739 // continue;
8740 // }
8741 //}
8742 }
8743
8744 //
8745 // token level timestamps - dtw version
8746 //
8747
8748 // n_text_layer -> total text layers on model
8749 // n_head -> total heads per text layer on model
8750 static std::vector<uint32_t> get_alignment_heads_by_layer(const whisper_context_params & cparams, int il, int n_text_layer, int n_head) {
8751 std::vector<uint32_t> ret;
8752 if (cparams.dtw_aheads_preset == WHISPER_AHEADS_NONE) {
8753 return ret;
8754 } else if (cparams.dtw_aheads_preset == WHISPER_AHEADS_N_TOP_MOST) {
8755 if (il >= n_text_layer - cparams.dtw_n_top) {
8756 for (int32_t i = 0; i < n_head; ++i) {
8757 ret.push_back(i);
8758 }
8759 }
8760 } else {
8761 const auto aheads = cparams.dtw_aheads_preset == WHISPER_AHEADS_CUSTOM ? cparams.dtw_aheads : g_aheads.at(cparams.dtw_aheads_preset);
8762 for (size_t i = 0; i < aheads.n_heads; ++i) {
8763 if (aheads.heads[i].n_text_layer == il) {
8764 ret.push_back(aheads.heads[i].n_head);
8765 }
8766 }
8767 }
8768 return ret;
8769 }
8770
8771 // dtw + backtrace to return found path
8772 // based on
8773 // https://github.com/openai/whisper/blob/main/whisper/timing.py#L83
8774 static ggml_tensor * dtw_and_backtrace(ggml_context * ctx, ggml_tensor * x) {
8775 WHISPER_ASSERT(ggml_n_dims(x) == 2);
8776
8777 int64_t N = x->ne[0];
8778 int64_t M = x->ne[1];
8779 struct ggml_tensor * cost = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, N + 1, M + 1);
8780 struct ggml_tensor * trace = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, N + 1, M + 1);
8781
8782 cost = whisper_set_f32(cost, INFINITY);
8783 trace = whisper_set_i32(trace, -1);
8784 whisper_set_f32_nd(cost, 0, 0, 0, 0, 0.0);
8785
8786 // dtw
8787 // supposedly can be optmized by computing diagonals in parallel ?
8788 // Not sure it is worth it since x will be GENERATED_TOKENS*1500 size at most.
8789 for (int64_t j = 1; j < M + 1; ++j) {
8790 for (int64_t i = 1; i < N + 1; ++i) {
8791 float c0 = whisper_get_f32_nd(cost, i - 1, j - 1, 0, 0);
8792 float c1 = whisper_get_f32_nd(cost, i - 1, j, 0, 0);
8793 float c2 = whisper_get_f32_nd(cost, i, j - 1, 0, 0);
8794
8795 float c;
8796 int32_t t;
8797 if (c0 < c1 && c0 < c2) {
8798 c = c0;
8799 t = 0;
8800 } else if (c1 < c0 && c1 < c2) {
8801 c = c1;
8802 t = 1;
8803 } else {
8804 c = c2;
8805 t = 2;
8806 }
8807
8808 c = whisper_get_f32_nd(x, i - 1, j - 1, 0, 0) + c;
8809 whisper_set_f32_nd(cost, i, j, 0, 0, c);
8810 whisper_set_i32_nd(trace, i, j, 0, 0, t);
8811 }
8812 }
8813
8814 // Backtrace
8815 const int64_t BT_MAX_ROWS = N + M - 1;
8816 struct ggml_tensor * bt = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, BT_MAX_ROWS, 2);
8817 // trace[0, :] = 2;
8818 for (int64_t i = 0; i < M + 1; ++i)
8819 whisper_set_i32_nd(trace, 0, i, 0, 0, 2);
8820 //trace[:, 0] = 1;
8821 for (int64_t i = 0; i < N + 1; ++i)
8822 whisper_set_i32_nd(trace, i, 0, 0, 0, 1);
8823 int bt_row_idx = BT_MAX_ROWS - 1;
8824 int64_t i = N;
8825 int64_t j = M;
8826 while (i > 0 || j > 0) {
8827 whisper_set_i32_nd(bt, bt_row_idx, 0, 0, 0, i - 1);
8828 whisper_set_i32_nd(bt, bt_row_idx, 1, 0, 0, j - 1);
8829 --bt_row_idx;
8830
8831 int32_t t = whisper_get_i32_nd(trace, i, j, 0, 0);
8832 if (t == 0) {
8833 --i;
8834 --j;
8835 } else if (t == 1) {
8836 --i;
8837 } else if (t == 2) {
8838 --j;
8839 } else {
8840 WHISPER_ASSERT(0);
8841 }
8842 }
8843
8844 // FIXME: manual clip/transpose might not be the most efficient way? (e.g. use ggml funcs)
8845 // Clip + transpose
8846 // This might not be entirely necessary for our case, but leaving it for now so output matrix
8847 // is identical to dtw on openAI timing.py
8848 const int64_t result_n_cols = BT_MAX_ROWS-bt_row_idx-1;
8849 ggml_tensor * r = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 2, result_n_cols);
8850 for (int64_t i = 0; i < 2; ++i) {
8851 for (int64_t j = 0; j < result_n_cols; ++j) {
8852 int32_t v = whisper_get_i32_nd(bt, j+bt_row_idx+1, i, 0, 0);
8853 whisper_set_i32_nd(r, i, j, 0, 0, v);
8854 }
8855 }
8856
8857 return r;
8858 }
8859
8860 struct median_filter_user_data {
8861 int filter_width;
8862 };
8863
8864 static void median_filter(struct ggml_tensor * dst , const struct ggml_tensor * a, int ith, int /*nth*/, void * userdata) {
8865 if (ith != 0) {
8866 return;
8867 }
8868 int filter_width = ((median_filter_user_data *) userdata)->filter_width;
8869 WHISPER_ASSERT(filter_width < a->ne[2]);
8870 WHISPER_ASSERT(filter_width % 2);
8871 WHISPER_ASSERT(ggml_n_dims(a) == 3);
8872 WHISPER_ASSERT(a->type == GGML_TYPE_F32);
8873
8874 std::vector<float> filter;
8875 filter.reserve(filter_width);
8876 for (int64_t i = 0; i < a->ne[0]; ++i) {
8877 for (int64_t j = 0; j < a->ne[1]; ++j) {
8878 for (int64_t k = 0; k < a->ne[2]; ++k) {
8879 for (int64_t off = -filter_width/2; off <= filter_width/2; ++off) {
8880 // "reflect" padding
8881 int64_t idx = k + off;
8882 if (idx < 0) {
8883 idx = -idx;
8884 } else if (idx >= a->ne[2]) {
8885 idx = 2*(a->ne[2] - 1) - idx;
8886 }
8887
8888 filter.push_back(whisper_get_f32_nd(a, i, j, idx, 0));
8889 }
8890 std::sort(filter.begin(), filter.end());
8891 const float v = filter[filter.size()/2];
8892 whisper_set_f32_nd(dst, i, j, k, 0, v);
8893 filter.clear();
8894 }
8895 }
8896 }
8897 }
8898
8899 static void whisper_exp_compute_token_level_timestamps_dtw(
8900 struct whisper_context * ctx,
8901 struct whisper_state * state,
8902 struct whisper_full_params params,
8903 int i_segment,
8904 size_t n_segments,
8905 int seek,
8906 int n_frames,
8907 int medfilt_width,
8908 int n_threads)
8909 {
8910 const int n_audio_ctx = state->exp_n_audio_ctx > 0 ? state->exp_n_audio_ctx : ctx->model.hparams.n_audio_ctx;
8911 WHISPER_ASSERT(medfilt_width % 2);
8912 WHISPER_ASSERT(n_frames <= n_audio_ctx * 2);
8913 WHISPER_ASSERT(ctx->params.dtw_aheads_preset != WHISPER_AHEADS_NONE);
8914
8915 // FIXME: Allocating mem everytime we call this func
8916 // Our ggml buffer should be pre-allocated somewhere during init and reused
8917 // when we call this function
8918 struct ggml_init_params gparams = {
8919 /*.mem_size =*/ ctx->params.dtw_mem_size,
8920 /*.mem_buffer =*/ NULL,
8921 /*.no_alloc =*/ false,
8922 };
8923 struct ggml_context * gctx = ggml_init(gparams);
8924
8925 // Build token sequence that will be passed to decoder
8926 // sot + [lang] + text result + eot
8927 std::vector<whisper_token> tokens = { whisper_token_sot(ctx), };
8928 if (whisper_is_multilingual(ctx)) {
8929 const int lang_id = whisper_lang_id(params.language);
8930 state->lang_id = lang_id;
8931 tokens.push_back(whisper_token_lang(ctx, lang_id));
8932 }
8933 const size_t sot_sequence_length = tokens.size();
8934 tokens.push_back(whisper_token_not(ctx));
8935 for (size_t i = i_segment; i < i_segment + n_segments; ++i) {
8936 auto & segment = state->result_all[i];
8937 for (auto &t: segment.tokens) {
8938 // Only text tokens
8939 if (t.id < whisper_token_eot(ctx)) {
8940 tokens.push_back(t.id);
8941 }
8942 }
8943 }
8944 tokens.push_back(whisper_token_eot(ctx));
8945
8946 // Get result tokens, pass then along to decoder to get cross attention QKs
8947 // used in timestamping
8948 // Decoder already returns only alignment head QKs, already concatenated in
8949 // one tensor.
8950 whisper_kv_cache_clear(state->kv_self);
8951 whisper_batch_prep_legacy(state->batch, tokens.data(), tokens.size(), 0, 0);
8952 whisper_kv_cache_seq_rm(state->kv_self, 0, 0, -1);
8953 if (!whisper_decode_internal(*ctx, *state, state->batch, n_threads, true, nullptr, nullptr)) {
8954 WHISPER_LOG_INFO("DECODER FAILED\n");
8955 WHISPER_ASSERT(0);
8956 }
8957 WHISPER_ASSERT(state->aheads_cross_QKs != nullptr);
8958
8959 const auto n_audio_tokens = n_frames/2;
8960 WHISPER_ASSERT(state->aheads_cross_QKs != NULL);
8961 WHISPER_ASSERT(n_audio_tokens <= state->aheads_cross_QKs->ne[1]);
8962 const auto n_tokens = state->aheads_cross_QKs->ne[0];
8963 const auto n_heads = state->aheads_cross_QKs->ne[2];
8964
8965 // Copy data from decoder buffer to a local CPU tensor, discarding unused audio
8966 // tokens (i.e. discarding rows at the end of tensor)
8967 // IN: Tensor with N_TOKENS*audio_ctx*N_ALIGNMENT_HEADS dims
8968 // OUT: Tensor with N_TOKENS*N_AUDIO_TOKENS*N_ALIGNMENT_HEADS dims
8969 WHISPER_ASSERT(state->aheads_cross_QKs->type == GGML_TYPE_F32);
8970 WHISPER_ASSERT(ggml_is_contiguous(state->aheads_cross_QKs));
8971 ggml_tensor * w = ggml_new_tensor_3d(gctx, GGML_TYPE_F32, n_tokens, n_audio_tokens, n_heads);
8972 auto & data = state->aheads_cross_QKs_data;
8973 data.resize(n_tokens * n_audio_ctx * n_heads);
8974 ggml_backend_tensor_get(state->aheads_cross_QKs, data.data(), 0, sizeof(float) * n_tokens * n_audio_ctx * n_heads);
8975 for (int k = 0; k < n_heads; ++k) {
8976 for (int j = 0; j < n_audio_tokens; ++j) {
8977 memcpy(
8978 (char *) w->data + j * w->nb[1] + k * w->nb[2],
8979 data.data() + j * n_tokens + k * n_tokens * n_audio_ctx,
8980 n_tokens * sizeof(float)
8981 );
8982 }
8983 }
8984
8985 // Normalize - in original OpenAI code, this is done over dim=-2. In this case,
8986 // we already permuted N_TOKENS dimension to columns on last loop, becase ggml_norm
8987 // operates over columns. Afterwards, permute to a shape that facilitates mean
8988 // operation (after median filter)
8989 // IN: Tensor with N_TOKENS*N_AUDIO_TOKENS*N_ALIGNMENT_HEADS dims
8990 // OUT: Tensor with N_ALIGNMENT_HEADS*N_TOKENS*N_AUDIO_TOKENS dims
8991 w = ggml_norm(gctx, w, 1e-9f);
8992 w = ggml_permute(gctx, ggml_permute(gctx, w, 2, 1, 0 ,3), 0, 2, 1, 3);
8993
8994 // Pass median filter - this is done over AUDIO_TOKENS dimension.
8995 // IN: Tensor with N_ALIGNMENT_HEADS*N_TOKENS*N_AUDIO_TOKENS dims
8996 // OUT: Same dims
8997 median_filter_user_data mf_user_data = {medfilt_width};
8998 w = ggml_map_custom1(gctx, w, median_filter, 1, &mf_user_data);
8999
9000 // Take mean over columns, scale by -1, reshape to 2D tensor, remove SOT sequence and EOT
9001 // IN: Tensor with N_ALIGNMENT_HEADS*N_TOKENS*N_AUDIO_TOKENS dims
9002 // OUT: Tensor with N_TOKENS*N_AUDIO_TOKENS dims
9003 w = ggml_mean(gctx, w);
9004 w = ggml_scale(gctx, w, -1.0);
9005 w = ggml_reshape_2d(gctx, w, w->ne[1], w->ne[2]);
9006
9007 // Remove SOT sequence and EOT
9008 // Out dimension is (N_TOKENS-sot_sequence_length-1)*N_AUDIO_TOKENS
9009 w = ggml_view_2d(gctx, w, w->ne[0] - sot_sequence_length - 1, w->ne[1], w->nb[1], sot_sequence_length * w->nb[0]);
9010
9011 // Compute
9012 struct ggml_cgraph * gf = ggml_new_graph(gctx);
9013 ggml_build_forward_expand(gf, w);
9014
9015 ggml_backend_ptr backend { ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr) };
9016 ggml_backend_graph_compute(backend.get(), gf);
9017
9018 ggml_tensor * alignment = dtw_and_backtrace(gctx, w);
9019
9020 // Place timestamps on segments
9021 int32_t last_v = 0;
9022 auto seg_i = state->result_all.begin() + i_segment;
9023 auto tok_i = seg_i->tokens.begin();
9024 for (int i = 0; i < alignment->ne[1]; ++i) {
9025 int32_t v = whisper_get_i32_nd(alignment, 0, i, 0, 0);
9026 if (v != last_v) {
9027 int32_t time_index = whisper_get_i32_nd(alignment, 1, i, 0, 0);
9028 int64_t timestamp = (time_index * 2) + seek; // Each index on DTW result = 20mS audio
9029 last_v = v;
9030
9031 // Skip non-text tokens
9032 while (!(tok_i->id < whisper_token_eot(ctx))) {
9033 ++tok_i;
9034 if (tok_i == seg_i->tokens.end()) {
9035 ++seg_i;
9036 tok_i = seg_i->tokens.begin();
9037 }
9038 }
9039
9040 tok_i->t_dtw = timestamp;
9041 ++tok_i;
9042 if (tok_i == seg_i->tokens.end()) {
9043 ++seg_i;
9044 tok_i = seg_i->tokens.begin();
9045 }
9046 }
9047 }
9048
9049 // Print DTW timestamps
9050 /*for (size_t i = i_segment; i < i_segment + n_segments; ++i) {
9051 auto & segment = state->result_all[i];
9052 for (auto &t: segment.tokens) {
9053 const char * tok = whisper_token_to_str(ctx, t.id);
9054 fprintf(stderr, "|%s|(%.2f) ", tok, (float)t.t_dtw/100);
9055 }
9056 fprintf(stderr, "\n");
9057 }*/
9058
9059 ggml_free(gctx);
9060 }
9061
9062 void whisper_log_set(ggml_log_callback log_callback, void * user_data) {
9063 g_state.log_callback = log_callback ? log_callback : whisper_log_callback_default;
9064 g_state.log_callback_user_data = user_data;
9065 ggml_log_set(g_state.log_callback, g_state.log_callback_user_data);
9066 }
9067
9068 const char * whisper_version(void) {
9069 return WHISPER_VERSION;
9070 }
9071
9072 GGML_ATTRIBUTE_FORMAT(2, 3)
9073 static void whisper_log_internal(ggml_log_level level, const char * format, ...) {
9074 va_list args;
9075 va_start(args, format);
9076 char buffer[1024];
9077 int len = vsnprintf(buffer, 1024, format, args);
9078 if (len < 1024) {
9079 g_state.log_callback(level, buffer, g_state.log_callback_user_data);
9080 } else {
9081 char* buffer2 = new char[len+1];
9082 vsnprintf(buffer2, len+1, format, args);
9083 buffer2[len] = 0;
9084 g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
9085 delete[] buffer2;
9086 }
9087 va_end(args);
9088 }
9089
9090 static void whisper_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
9091 (void) level;
9092 (void) user_data;
9093 #ifndef WHISPER_DEBUG
9094 if (level == GGML_LOG_LEVEL_DEBUG) {
9095 return;
9096 }
9097 #endif
9098 fputs(text, stderr);
9099 fflush(stderr);
9100 }