llama-cpp-capacitor 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/cpp/LICENSE +21 -0
  2. package/cpp/README.md +4 -0
  3. package/cpp/anyascii.c +22223 -0
  4. package/cpp/anyascii.h +42 -0
  5. package/cpp/chat-parser.cpp +393 -0
  6. package/cpp/chat-parser.h +120 -0
  7. package/cpp/chat.cpp +2315 -0
  8. package/cpp/chat.h +221 -0
  9. package/cpp/common.cpp +1619 -0
  10. package/cpp/common.h +744 -0
  11. package/cpp/ggml-alloc.c +1028 -0
  12. package/cpp/ggml-alloc.h +76 -0
  13. package/cpp/ggml-backend-impl.h +255 -0
  14. package/cpp/ggml-backend-reg.cpp +600 -0
  15. package/cpp/ggml-backend.cpp +2118 -0
  16. package/cpp/ggml-backend.h +354 -0
  17. package/cpp/ggml-common.h +1878 -0
  18. package/cpp/ggml-cpp.h +39 -0
  19. package/cpp/ggml-cpu/amx/amx.cpp +221 -0
  20. package/cpp/ggml-cpu/amx/amx.h +8 -0
  21. package/cpp/ggml-cpu/amx/common.h +91 -0
  22. package/cpp/ggml-cpu/amx/mmq.cpp +2512 -0
  23. package/cpp/ggml-cpu/amx/mmq.h +10 -0
  24. package/cpp/ggml-cpu/arch/arm/cpu-feats.cpp +94 -0
  25. package/cpp/ggml-cpu/arch/arm/quants.c +3650 -0
  26. package/cpp/ggml-cpu/arch/arm/repack.cpp +1891 -0
  27. package/cpp/ggml-cpu/arch/x86/cpu-feats.cpp +327 -0
  28. package/cpp/ggml-cpu/arch/x86/quants.c +3820 -0
  29. package/cpp/ggml-cpu/arch/x86/repack.cpp +6307 -0
  30. package/cpp/ggml-cpu/arch-fallback.h +215 -0
  31. package/cpp/ggml-cpu/binary-ops.cpp +158 -0
  32. package/cpp/ggml-cpu/binary-ops.h +16 -0
  33. package/cpp/ggml-cpu/common.h +73 -0
  34. package/cpp/ggml-cpu/ggml-cpu-impl.h +525 -0
  35. package/cpp/ggml-cpu/ggml-cpu.c +3578 -0
  36. package/cpp/ggml-cpu/ggml-cpu.cpp +672 -0
  37. package/cpp/ggml-cpu/ops.cpp +10587 -0
  38. package/cpp/ggml-cpu/ops.h +114 -0
  39. package/cpp/ggml-cpu/quants.c +1193 -0
  40. package/cpp/ggml-cpu/quants.h +97 -0
  41. package/cpp/ggml-cpu/repack.cpp +1982 -0
  42. package/cpp/ggml-cpu/repack.h +120 -0
  43. package/cpp/ggml-cpu/simd-mappings.h +1184 -0
  44. package/cpp/ggml-cpu/traits.cpp +36 -0
  45. package/cpp/ggml-cpu/traits.h +38 -0
  46. package/cpp/ggml-cpu/unary-ops.cpp +186 -0
  47. package/cpp/ggml-cpu/unary-ops.h +28 -0
  48. package/cpp/ggml-cpu/vec.cpp +348 -0
  49. package/cpp/ggml-cpu/vec.h +1121 -0
  50. package/cpp/ggml-cpu.h +145 -0
  51. package/cpp/ggml-impl.h +622 -0
  52. package/cpp/ggml-metal-impl.h +688 -0
  53. package/cpp/ggml-metal.h +66 -0
  54. package/cpp/ggml-metal.m +6833 -0
  55. package/cpp/ggml-opt.cpp +1093 -0
  56. package/cpp/ggml-opt.h +256 -0
  57. package/cpp/ggml-quants.c +5324 -0
  58. package/cpp/ggml-quants.h +106 -0
  59. package/cpp/ggml-threading.cpp +12 -0
  60. package/cpp/ggml-threading.h +14 -0
  61. package/cpp/ggml.c +7108 -0
  62. package/cpp/ggml.h +2492 -0
  63. package/cpp/gguf.cpp +1358 -0
  64. package/cpp/gguf.h +202 -0
  65. package/cpp/json-partial.cpp +256 -0
  66. package/cpp/json-partial.h +38 -0
  67. package/cpp/json-schema-to-grammar.cpp +985 -0
  68. package/cpp/json-schema-to-grammar.h +21 -0
  69. package/cpp/llama-adapter.cpp +388 -0
  70. package/cpp/llama-adapter.h +76 -0
  71. package/cpp/llama-arch.cpp +2355 -0
  72. package/cpp/llama-arch.h +499 -0
  73. package/cpp/llama-batch.cpp +875 -0
  74. package/cpp/llama-batch.h +160 -0
  75. package/cpp/llama-chat.cpp +783 -0
  76. package/cpp/llama-chat.h +65 -0
  77. package/cpp/llama-context.cpp +2748 -0
  78. package/cpp/llama-context.h +306 -0
  79. package/cpp/llama-cparams.cpp +5 -0
  80. package/cpp/llama-cparams.h +41 -0
  81. package/cpp/llama-cpp.h +30 -0
  82. package/cpp/llama-grammar.cpp +1229 -0
  83. package/cpp/llama-grammar.h +173 -0
  84. package/cpp/llama-graph.cpp +1891 -0
  85. package/cpp/llama-graph.h +810 -0
  86. package/cpp/llama-hparams.cpp +180 -0
  87. package/cpp/llama-hparams.h +233 -0
  88. package/cpp/llama-impl.cpp +167 -0
  89. package/cpp/llama-impl.h +61 -0
  90. package/cpp/llama-io.cpp +15 -0
  91. package/cpp/llama-io.h +35 -0
  92. package/cpp/llama-kv-cache-iswa.cpp +318 -0
  93. package/cpp/llama-kv-cache-iswa.h +135 -0
  94. package/cpp/llama-kv-cache.cpp +2059 -0
  95. package/cpp/llama-kv-cache.h +374 -0
  96. package/cpp/llama-kv-cells.h +491 -0
  97. package/cpp/llama-memory-hybrid.cpp +258 -0
  98. package/cpp/llama-memory-hybrid.h +137 -0
  99. package/cpp/llama-memory-recurrent.cpp +1146 -0
  100. package/cpp/llama-memory-recurrent.h +179 -0
  101. package/cpp/llama-memory.cpp +59 -0
  102. package/cpp/llama-memory.h +119 -0
  103. package/cpp/llama-mmap.cpp +600 -0
  104. package/cpp/llama-mmap.h +68 -0
  105. package/cpp/llama-model-loader.cpp +1164 -0
  106. package/cpp/llama-model-loader.h +170 -0
  107. package/cpp/llama-model-saver.cpp +282 -0
  108. package/cpp/llama-model-saver.h +37 -0
  109. package/cpp/llama-model.cpp +19042 -0
  110. package/cpp/llama-model.h +491 -0
  111. package/cpp/llama-sampling.cpp +2575 -0
  112. package/cpp/llama-sampling.h +32 -0
  113. package/cpp/llama-vocab.cpp +3792 -0
  114. package/cpp/llama-vocab.h +176 -0
  115. package/cpp/llama.cpp +358 -0
  116. package/cpp/llama.h +1373 -0
  117. package/cpp/log.cpp +427 -0
  118. package/cpp/log.h +103 -0
  119. package/cpp/minja/chat-template.hpp +550 -0
  120. package/cpp/minja/minja.hpp +3009 -0
  121. package/cpp/nlohmann/json.hpp +25526 -0
  122. package/cpp/nlohmann/json_fwd.hpp +187 -0
  123. package/cpp/regex-partial.cpp +204 -0
  124. package/cpp/regex-partial.h +56 -0
  125. package/cpp/rn-completion.cpp +681 -0
  126. package/cpp/rn-completion.h +116 -0
  127. package/cpp/rn-llama.cpp +345 -0
  128. package/cpp/rn-llama.h +149 -0
  129. package/cpp/rn-mtmd.hpp +602 -0
  130. package/cpp/rn-tts.cpp +591 -0
  131. package/cpp/rn-tts.h +59 -0
  132. package/cpp/sampling.cpp +579 -0
  133. package/cpp/sampling.h +107 -0
  134. package/cpp/tools/mtmd/clip-impl.h +473 -0
  135. package/cpp/tools/mtmd/clip.cpp +4322 -0
  136. package/cpp/tools/mtmd/clip.h +106 -0
  137. package/cpp/tools/mtmd/miniaudio/miniaudio.h +93468 -0
  138. package/cpp/tools/mtmd/mtmd-audio.cpp +769 -0
  139. package/cpp/tools/mtmd/mtmd-audio.h +47 -0
  140. package/cpp/tools/mtmd/mtmd-helper.cpp +460 -0
  141. package/cpp/tools/mtmd/mtmd-helper.h +91 -0
  142. package/cpp/tools/mtmd/mtmd.cpp +1066 -0
  143. package/cpp/tools/mtmd/mtmd.h +298 -0
  144. package/cpp/tools/mtmd/stb/stb_image.h +7988 -0
  145. package/cpp/unicode-data.cpp +7034 -0
  146. package/cpp/unicode-data.h +20 -0
  147. package/cpp/unicode.cpp +1061 -0
  148. package/cpp/unicode.h +68 -0
  149. package/package.json +2 -1
@@ -0,0 +1,1066 @@
1
+ #include "clip.h"
2
+ #include "clip-impl.h"
3
+ #include "mtmd.h"
4
+ #include "mtmd-audio.h"
5
+
6
+ #include "llama.h"
7
+
8
+ #include <algorithm>
9
+ #include <cerrno>
10
+ #include <cstdio>
11
+ #include <cstdlib>
12
+ #include <cstring>
13
+ #include <limits>
14
+ #include <vector>
15
+
16
+ // represents raw image data, layout is RGBRGBRGB...
17
+ // length of data must be nx * ny * 3
18
+ struct mtmd_bitmap {
19
+ uint32_t nx;
20
+ uint32_t ny;
21
+ std::vector<unsigned char> data;
22
+ std::string id; // optional user-defined id, for ex: can be set to image hash, useful for KV cache tracking
23
+ bool is_audio = false; // true if the bitmap is audio
24
+ };
25
+
26
+ struct mtmd_image_tokens {
27
+ uint32_t nx; // number of tokens in x direction
28
+ uint32_t ny; // number of tokens in y direction
29
+ bool use_mrope_pos = false; // use M-RoPE position counting (the whole image is 1 temporal position)
30
+ uint32_t n_tokens() const { return nx * ny; }
31
+ clip_image_f32_batch batch_f32; // preprocessed image patches
32
+ std::string id; // optional user-defined ID, useful for KV cache tracking
33
+
34
+ mtmd_image_tokens clone() {
35
+ return mtmd_image_tokens{
36
+ nx,
37
+ ny,
38
+ use_mrope_pos,
39
+ batch_f32.clone(),
40
+ id
41
+ };
42
+ }
43
+ };
44
+ using mtmd_image_tokens_ptr = std::unique_ptr<mtmd_image_tokens>;
45
+
46
+ struct mtmd_audio_tokens {
47
+ uint32_t n_tokens; // number of tokens
48
+ clip_image_f32_batch batch_f32; // preprocessed image patches
49
+ std::string id; // optional user-defined ID, useful for KV cache tracking
50
+
51
+ mtmd_audio_tokens clone() {
52
+ return mtmd_audio_tokens{
53
+ n_tokens,
54
+ batch_f32.clone(),
55
+ id
56
+ };
57
+ }
58
+ };
59
+ using mtmd_audio_tokens_ptr = std::unique_ptr<mtmd_audio_tokens>;
60
+
61
+ struct mtmd_input_chunk {
62
+ mtmd_input_chunk_type type;
63
+ std::vector<llama_token> tokens_text;
64
+ mtmd_image_tokens_ptr tokens_image;
65
+ mtmd_audio_tokens_ptr tokens_audio;
66
+ };
67
+
68
+ struct mtmd_input_chunks {
69
+ std::vector<mtmd_input_chunk> entries;
70
+ };
71
+
72
+ // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
73
+ // models not having it (llava-1.6) will process embeddings without any special tokens in-between
74
+ enum mtmd_slice_tmpl {
75
+ MTMD_SLICE_TMPL_NONE,
76
+ MTMD_SLICE_TMPL_MINICPMV_2_5,
77
+ MTMD_SLICE_TMPL_MINICPMV_2_6,
78
+ MTMD_SLICE_TMPL_LLAMA4,
79
+ // TODO @ngxson : add support for idefics (SmolVLM)
80
+ };
81
+
82
+ const char * mtmd_default_marker() {
83
+ return "<__media__>";
84
+ }
85
+
86
+ mtmd_context_params mtmd_context_params_default() {
87
+ mtmd_context_params params;
88
+ params.use_gpu = true;
89
+ params.print_timings = true;
90
+ params.n_threads = 4;
91
+ params.verbosity = LM_GGML_LOG_LEVEL_INFO;
92
+ params.image_marker = MTMD_DEFAULT_IMAGE_MARKER;
93
+ params.media_marker = mtmd_default_marker();
94
+ return params;
95
+ }
96
+
97
+ struct mtmd_context {
98
+ struct clip_ctx * ctx_v; // vision
99
+ struct clip_ctx * ctx_a; // audio
100
+ const struct llama_model * text_model;
101
+ std::vector<float> image_embd_v; // image embedding vector
102
+
103
+ bool print_timings;
104
+ int n_threads;
105
+ std::string media_marker;
106
+ const int n_embd_text;
107
+
108
+ // these are not token, but strings used to mark the beginning and end of image/audio embeddings
109
+ std::string img_beg;
110
+ std::string img_end;
111
+ std::string aud_beg;
112
+ std::string aud_end;
113
+
114
+ // for llava-uhd style models, we need special tokens in-between slices
115
+ // minicpmv calls them "slices", llama 4 calls them "tiles"
116
+ mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
117
+ llama_token tok_ov_img_start = LLAMA_TOKEN_NULL; // overview image
118
+ llama_token tok_ov_img_end = LLAMA_TOKEN_NULL; // overview image
119
+ llama_token tok_slices_start = LLAMA_TOKEN_NULL; // start of all slices
120
+ llama_token tok_slices_end = LLAMA_TOKEN_NULL; // end of all slices
121
+ llama_token tok_sli_img_start = LLAMA_TOKEN_NULL; // single slice start
122
+ llama_token tok_sli_img_end = LLAMA_TOKEN_NULL; // single slice end
123
+ llama_token tok_sli_img_mid = LLAMA_TOKEN_NULL; // between 2 slices
124
+ llama_token tok_row_end = LLAMA_TOKEN_NULL; // end of row
125
+ bool tok_row_end_trail = false;
126
+ bool ov_img_first = false;
127
+
128
+ bool use_mrope = false; // for Qwen2VL, we need to use M-RoPE
129
+
130
+ // for whisper, we pre-calculate the mel filter bank
131
+ whisper_preprocessor::whisper_filters w_filters;
132
+
133
+ // TODO @ngxson : add timings
134
+
135
+ mtmd_context(const char * mmproj_fname,
136
+ const llama_model * text_model,
137
+ const mtmd_context_params & ctx_params) :
138
+ text_model (text_model),
139
+ print_timings(ctx_params.print_timings),
140
+ n_threads (ctx_params.n_threads),
141
+ media_marker (ctx_params.media_marker),
142
+ n_embd_text (llama_model_n_embd(text_model))
143
+ {
144
+ if (std::string(ctx_params.image_marker) != MTMD_DEFAULT_IMAGE_MARKER) {
145
+ throw std::runtime_error("custom image_marker is not supported anymore, use media_marker instead");
146
+ }
147
+
148
+ if (media_marker.empty()) {
149
+ throw std::runtime_error("media_marker must not be empty");
150
+ }
151
+
152
+ clip_context_params ctx_clip_params;
153
+ ctx_clip_params.use_gpu = ctx_params.use_gpu;
154
+ ctx_clip_params.verbosity = ctx_params.verbosity;
155
+ auto res = clip_init(mmproj_fname, ctx_clip_params);
156
+ ctx_v = res.ctx_v;
157
+ ctx_a = res.ctx_a;
158
+ if (!ctx_v && !ctx_a) {
159
+ throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
160
+ }
161
+
162
+ // if both vision and audio mmproj are present, we need to validate their n_embd
163
+ if (ctx_v && ctx_a) {
164
+ int n_embd_v = clip_n_mmproj_embd(ctx_v);
165
+ int n_embd_a = clip_n_mmproj_embd(ctx_a);
166
+ if (n_embd_v != n_embd_a) {
167
+ throw std::runtime_error(string_format(
168
+ "mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d)\n",
169
+ n_embd_v, n_embd_a));
170
+ }
171
+ }
172
+
173
+ // since we already validate n_embd of vision and audio mmproj,
174
+ // we can safely assume that they are the same
175
+ int n_embd_clip = clip_n_mmproj_embd(ctx_v ? ctx_v : ctx_a);
176
+ if (n_embd_text != n_embd_clip) {
177
+ throw std::runtime_error(string_format(
178
+ "mismatch between text model (n_embd = %d) and mmproj (n_embd = %d)\n"
179
+ "hint: you may be using wrong mmproj\n",
180
+ n_embd_text, n_embd_clip));
181
+ }
182
+ if (ctx_v) {
183
+ init_vision();
184
+ }
185
+ if (ctx_a) {
186
+ init_audio();
187
+ }
188
+ }
189
+
190
+ void init_vision() {
191
+ LM_GGML_ASSERT(ctx_v != nullptr);
192
+ use_mrope = clip_is_qwen2vl(ctx_v);
193
+
194
+ projector_type proj = clip_get_projector_type(ctx_v);
195
+ int minicpmv_version = clip_is_minicpmv(ctx_v);
196
+ if (minicpmv_version == 2) {
197
+ // minicpmv 2.5 format:
198
+ // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
199
+ slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
200
+ tok_ov_img_start = lookup_token("<image>");
201
+ tok_ov_img_end = lookup_token("</image>");
202
+ tok_slices_start = lookup_token("<slice>");
203
+ tok_slices_end = lookup_token("</slice>");
204
+ tok_sli_img_start = tok_ov_img_start;
205
+ tok_sli_img_end = tok_ov_img_end;
206
+ tok_row_end = lookup_token("\n");
207
+ tok_row_end_trail = false; // no trailing end-of-row token
208
+ ov_img_first = true;
209
+
210
+ } else if (minicpmv_version == 3 || minicpmv_version == 4 || minicpmv_version == 5) {
211
+ // minicpmv 2.6 format:
212
+ // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
213
+ slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
214
+ tok_ov_img_start = lookup_token("<image>");
215
+ tok_ov_img_end = lookup_token("</image>");
216
+ tok_sli_img_start = lookup_token("<slice>");
217
+ tok_sli_img_end = lookup_token("</slice>");
218
+ tok_row_end = lookup_token("\n");
219
+ tok_row_end_trail = false; // no trailing end-of-row token
220
+ ov_img_first = true;
221
+
222
+ } else if (minicpmv_version != 0) {
223
+ LM_GGML_ASSERT(false && "unsupported minicpmv version");
224
+ } else if (proj == PROJECTOR_TYPE_LLAMA4) {
225
+ // llama 4 format:
226
+ // <|image_start|>
227
+ // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
228
+ // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
229
+ // ... <|tile_y_separator|> <-- trailing end-of-row token
230
+ // <|image|> (overview) <-- overview image is last
231
+ // <|image_end|>
232
+ slice_tmpl = MTMD_SLICE_TMPL_LLAMA4;
233
+ tok_ov_img_start = lookup_token("<|image|>");
234
+ tok_sli_img_mid = lookup_token("<|tile_x_separator|>");
235
+ tok_row_end = lookup_token("<|tile_y_separator|>");
236
+ tok_row_end_trail = true; // add trailing end-of-row token
237
+ ov_img_first = false; // overview image is last
238
+ }
239
+
240
+ // set boi/eoi
241
+ if (proj == PROJECTOR_TYPE_GEMMA3) {
242
+ // <start_of_image> ... (image embeddings) ... <end_of_image>
243
+ img_beg = "<start_of_image>";
244
+ img_end = "<end_of_image>";
245
+
246
+ } else if (proj == PROJECTOR_TYPE_IDEFICS3) {
247
+ // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
248
+ img_beg = "<fake_token_around_image><global-img>";
249
+ img_end = "<fake_token_around_image>";
250
+
251
+ } else if (proj == PROJECTOR_TYPE_PIXTRAL) {
252
+ // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
253
+ img_end = "[IMG_END]";
254
+
255
+ } else if (proj == PROJECTOR_TYPE_QWEN2VL || proj == PROJECTOR_TYPE_QWEN25VL) {
256
+ // <|vision_start|> ... (image embeddings) ... <|vision_end|>
257
+ img_beg = "<|vision_start|>";
258
+ img_end = "<|vision_end|>";
259
+
260
+ } else if (proj == PROJECTOR_TYPE_LLAMA4) {
261
+ // (more details in mtmd_context constructor)
262
+ img_beg = "<|image_start|>";
263
+ img_end = "<|image_end|>";
264
+ LOG_WRN("%s: llama 4 vision is known to have degraded quality:\n"
265
+ " https://github.com/ggml-org/llama.cpp/pull/13282\n", __func__);
266
+
267
+ } else if (proj == PROJECTOR_TYPE_INTERNVL) {
268
+ // <img> ... (image embeddings) ... </img>
269
+ img_beg = "<img>";
270
+ img_end = "</img>";
271
+
272
+ }
273
+ }
274
+
275
+ void init_audio() {
276
+ LM_GGML_ASSERT(ctx_a != nullptr);
277
+ projector_type proj = clip_get_projector_type(ctx_a);
278
+
279
+ if (clip_has_whisper_encoder(ctx_a)) {
280
+ // TODO @ngxson : check if model n_mel is 128 or 80
281
+ w_filters = whisper_precalc_filters::get_128_bins();
282
+ }
283
+
284
+ LOG_WRN("%s: audio input is in experimental stage and may have reduced quality:\n"
285
+ " https://github.com/ggml-org/llama.cpp/discussions/13759\n", __func__);
286
+
287
+ if (proj == PROJECTOR_TYPE_QWEN2A) {
288
+ // <|audio_bos|> ... (embeddings) ... <|audio_eos|>
289
+ aud_beg = "<|audio_bos|>";
290
+ aud_end = "<|audio_eos|>";
291
+
292
+ } else if (proj == PROJECTOR_TYPE_ULTRAVOX) {
293
+ // [BEGIN_AUDIO] ... (embeddings) ...
294
+ aud_beg = "[BEGIN_AUDIO]";
295
+
296
+ }
297
+ }
298
+
299
+ // get clip ctx based on chunk type
300
+ clip_ctx * get_clip_ctx(const mtmd_input_chunk * chunk) const {
301
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
302
+ return ctx_v;
303
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
304
+ return ctx_a;
305
+ }
306
+ LM_GGML_ABORT("unknown chunk type");
307
+ }
308
+
309
+ projector_type proj_type_v() const {
310
+ return ctx_v ? clip_get_projector_type(ctx_v) : PROJECTOR_TYPE_UNKNOWN;
311
+ }
312
+
313
+ projector_type proj_type_a() const {
314
+ return ctx_a ? clip_get_projector_type(ctx_a) : PROJECTOR_TYPE_UNKNOWN;
315
+ }
316
+
317
+ ~mtmd_context() {
318
+ clip_free(ctx_a);
319
+ clip_free(ctx_v);
320
+ }
321
+
322
+ private:
323
+ llama_token lookup_token(const std::string & token_text) {
324
+ const llama_vocab * vocab = llama_model_get_vocab(text_model);
325
+ const int n_vocab = llama_vocab_n_tokens(vocab);
326
+ for (int i = 0; i < n_vocab; i++) {
327
+ if (token_to_piece(vocab, i, true) == token_text) {
328
+ return i;
329
+ }
330
+ }
331
+ return LLAMA_TOKEN_NULL;
332
+ }
333
+
334
+ std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
335
+ std::string piece;
336
+ piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
337
+ const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
338
+ if (n_chars < 0) {
339
+ piece.resize(-n_chars);
340
+ int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
341
+ LM_GGML_ASSERT(check == -n_chars);
342
+ } else {
343
+ piece.resize(n_chars);
344
+ }
345
+ return piece;
346
+ }
347
+ };
348
+
349
+ mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
350
+ const struct llama_model * text_model,
351
+ const struct mtmd_context_params ctx_params) {
352
+ try {
353
+ return new mtmd_context(mmproj_fname, text_model, ctx_params);
354
+ } catch (const std::exception & e) {
355
+ LOG_ERR("%s: error: %s\n", __func__, e.what());
356
+ return nullptr;
357
+ }
358
+ }
359
+
360
+ void mtmd_free(mtmd_context * ctx) {
361
+ if (ctx) {
362
+ delete ctx;
363
+ }
364
+ }
365
+
366
+ struct mtmd_tokenizer {
367
+ mtmd_context * ctx;
368
+ std::vector<const mtmd_bitmap *> bitmaps;
369
+
370
+ std::string input_text;
371
+ bool add_special;
372
+ bool parse_special;
373
+ const llama_vocab * vocab;
374
+
375
+ mtmd_input_chunks cur;
376
+
377
+ mtmd_tokenizer(mtmd_context * ctx,
378
+ const mtmd_input_text * text,
379
+ const mtmd_bitmap ** bitmaps,
380
+ size_t n_bitmaps) : ctx(ctx), bitmaps(bitmaps, bitmaps + n_bitmaps) {
381
+ add_special = text->add_special;
382
+ parse_special = text->parse_special;
383
+ input_text = text->text;
384
+ vocab = llama_model_get_vocab(ctx->text_model);
385
+
386
+ // for compatibility, we convert image marker to media marker
387
+ string_replace_all(input_text, MTMD_DEFAULT_IMAGE_MARKER, ctx->media_marker);
388
+ }
389
+
390
+ int32_t tokenize(mtmd_input_chunks * output) {
391
+ cur.entries.clear();
392
+ std::vector<std::string> parts = split_text(input_text, ctx->media_marker);
393
+ size_t i_bm = 0; // index of the current bitmap
394
+ for (auto & part : parts) {
395
+ if (part == ctx->media_marker) {
396
+ // this is a marker, we should add the next bitmap
397
+ if (i_bm >= bitmaps.size()) {
398
+ LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
399
+ __func__, bitmaps.size(), parts.size() - 1);
400
+ return 1;
401
+ }
402
+ const mtmd_bitmap * bitmap = bitmaps[i_bm++];
403
+ int32_t res = add_media(bitmap);
404
+ if (res != 0) {
405
+ return res;
406
+ }
407
+ } else {
408
+ // this is a text part, we should add it as text
409
+ add_text(part, parse_special);
410
+ }
411
+ }
412
+
413
+ if (add_special && llama_vocab_get_add_bos(vocab)) {
414
+ // if first chunk is text, we add BOS token to first text chunk
415
+ // otherwise, create a new text chunk with BOS token
416
+ if (!cur.entries.empty() && cur.entries[0].type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
417
+ // add BOS token to the beginning of first text chunk
418
+ cur.entries[0].tokens_text.insert(cur.entries[0].tokens_text.begin(), llama_vocab_bos(vocab));
419
+ } else {
420
+ // create a new text chunk with BOS token at the beginning
421
+ mtmd_input_chunk bos_chunk{
422
+ MTMD_INPUT_CHUNK_TYPE_TEXT,
423
+ {llama_vocab_bos(vocab)},
424
+ nullptr, // image tokens
425
+ nullptr, // audio tokens
426
+ };
427
+ cur.entries.insert(cur.entries.begin(), std::move(bos_chunk));
428
+ }
429
+ }
430
+
431
+ if (add_special && llama_vocab_get_add_eos(vocab)) {
432
+ // if last chunk is text, we add EOS token to it
433
+ add_text({llama_vocab_eos(vocab)});
434
+ }
435
+
436
+ if (i_bm != bitmaps.size()) {
437
+ LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
438
+ __func__, bitmaps.size(), parts.size() - 1);
439
+ return 1;
440
+ }
441
+
442
+ *output = std::move(cur);
443
+
444
+ return 0;
445
+ }
446
+
447
+ void add_text(const std::string & txt, bool parse_special) {
448
+ LOG_DBG("%s: %s\n", __func__, txt.c_str());
449
+ auto tokens = mtmd_tokenize_text_internal(vocab, txt, /* add_special */ false, parse_special);
450
+ add_text(tokens);
451
+ }
452
+
453
+ void add_text(const std::vector<llama_token> & tokens) {
454
+ if (tokens.empty()) {
455
+ return;
456
+ }
457
+ // if last entry is also a text chunk, add tokens to it instead of creating new chunk
458
+ if (!cur.entries.empty() && cur.entries.back().type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
459
+ cur.entries.back().tokens_text.insert(
460
+ cur.entries.back().tokens_text.end(),
461
+ tokens.begin(),
462
+ tokens.end());
463
+ } else {
464
+ mtmd_input_chunk chunk{
465
+ MTMD_INPUT_CHUNK_TYPE_TEXT,
466
+ tokens,
467
+ nullptr, // image tokens
468
+ nullptr, // audio tokens
469
+ };
470
+ cur.entries.emplace_back(std::move(chunk));
471
+ }
472
+ }
473
+
474
+ int32_t add_media(const mtmd_bitmap * bitmap) {
475
+ if (!bitmap->is_audio) {
476
+ // handle image
477
+
478
+ if (!ctx->ctx_v) {
479
+ LOG_ERR("%s: error: model does not support vision input\n", __func__);
480
+ return 2;
481
+ }
482
+
483
+ if (!ctx->img_beg.empty()) {
484
+ add_text(ctx->img_beg, true); // add image begin token
485
+ }
486
+
487
+ // convert mtmd_bitmap to clip_image_u8
488
+ clip_image_u8_ptr img_u8(clip_image_u8_init());
489
+ img_u8->nx = bitmap->nx;
490
+ img_u8->ny = bitmap->ny;
491
+ img_u8->buf.resize(bitmap->data.size());
492
+ std::memcpy(img_u8->buf.data(), bitmap->data.data(), img_u8->nx * img_u8->ny * 3);
493
+
494
+ // preprocess image
495
+ clip_image_f32_batch batch_f32;
496
+ bool ok = clip_image_preprocess(ctx->ctx_v, img_u8.get(), &batch_f32);
497
+ if (!ok) {
498
+ LOG_ERR("Unable to preprocess image\n");
499
+ return 2;
500
+ }
501
+
502
+ // handle llava-uhd style preprocessing
503
+ if (
504
+ ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5
505
+ || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6
506
+ || ctx->slice_tmpl == MTMD_SLICE_TMPL_LLAMA4
507
+ ) {
508
+ const int n_col = batch_f32.grid_x;
509
+ const int n_row = batch_f32.grid_y;
510
+ // split batch into chunks of single images
511
+ // NOTE: batch_f32 will be invalidated after this call
512
+ auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmap->id);
513
+ LM_GGML_ASSERT(chunks.size() > 0);
514
+
515
+ auto ov_chunk = std::move(chunks.front());
516
+ chunks.erase(chunks.begin());
517
+
518
+ // add overview image (first)
519
+ if (ctx->ov_img_first) {
520
+ if (ctx->tok_ov_img_start != LLAMA_TOKEN_NULL) {
521
+ add_text({ctx->tok_ov_img_start});
522
+ }
523
+ cur.entries.emplace_back(std::move(ov_chunk));
524
+ if (ctx->tok_ov_img_end != LLAMA_TOKEN_NULL) {
525
+ add_text({ctx->tok_ov_img_end});
526
+ }
527
+ }
528
+
529
+ // add slices (or tiles)
530
+ if (!chunks.empty()) {
531
+ LM_GGML_ASSERT((int)chunks.size() == n_row * n_col);
532
+ if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
533
+ add_text({ctx->tok_slices_start});
534
+ }
535
+ for (int y = 0; y < n_row; y++) {
536
+ for (int x = 0; x < n_col; x++) {
537
+ const bool is_last_in_row = (x == n_col - 1);
538
+ if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
539
+ add_text({ctx->tok_sli_img_start});
540
+ }
541
+ cur.entries.emplace_back(std::move(chunks[y * n_col + x]));
542
+ if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
543
+ add_text({ctx->tok_sli_img_end});
544
+ }
545
+ if (!is_last_in_row && ctx->tok_sli_img_mid != LLAMA_TOKEN_NULL) {
546
+ add_text({ctx->tok_sli_img_mid});
547
+ }
548
+ }
549
+ if ((y != n_row - 1 || ctx->tok_row_end_trail) && ctx->tok_row_end != LLAMA_TOKEN_NULL) {
550
+ add_text({ctx->tok_row_end});
551
+ }
552
+ }
553
+ if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
554
+ add_text({ctx->tok_slices_end});
555
+ }
556
+ }
557
+
558
+ // add overview image (last)
559
+ if (!ctx->ov_img_first) {
560
+ if (ctx->tok_ov_img_start != LLAMA_TOKEN_NULL) {
561
+ add_text({ctx->tok_ov_img_start});
562
+ }
563
+ cur.entries.emplace_back(std::move(ov_chunk));
564
+ if (ctx->tok_ov_img_end != LLAMA_TOKEN_NULL) {
565
+ add_text({ctx->tok_ov_img_end});
566
+ }
567
+ }
568
+
569
+ } else {
570
+ size_t n_tokens = 0;
571
+ for (const auto & entry : batch_f32.entries) {
572
+ n_tokens += clip_n_output_tokens(ctx->ctx_v, entry.get());
573
+ }
574
+
575
+ mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
576
+ if (ctx->use_mrope) {
577
+ // for Qwen2VL, we need this information for M-RoPE decoding positions
578
+ image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_v, batch_f32.entries[0].get());
579
+ image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_v, batch_f32.entries[0].get());
580
+ image_tokens->use_mrope_pos = true;
581
+ } else {
582
+ // other models, we only need the total number of tokens
583
+ image_tokens->nx = n_tokens;
584
+ image_tokens->ny = 1;
585
+ }
586
+ image_tokens->batch_f32 = std::move(batch_f32);
587
+ image_tokens->id = bitmap->id; // optional
588
+
589
+ LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
590
+ LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
591
+ LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
592
+
593
+ mtmd_input_chunk chunk{
594
+ MTMD_INPUT_CHUNK_TYPE_IMAGE,
595
+ {}, // text tokens
596
+ std::move(image_tokens),
597
+ nullptr, // audio tokens
598
+ };
599
+ cur.entries.emplace_back(std::move(chunk));
600
+ }
601
+
602
+ if (!ctx->img_end.empty()) {
603
+ add_text(ctx->img_end, true); // add image end token
604
+ }
605
+
606
+ } else {
607
+ // handle audio
608
+
609
+ if (!ctx->ctx_a) {
610
+ LOG_ERR("%s: error: model does not support audio input\n", __func__);
611
+ return 2;
612
+ }
613
+
614
+ if (bitmap->data.size() == 0) {
615
+ LOG_ERR("%s: error: empty audio data\n", __func__);
616
+ return 2;
617
+ }
618
+
619
+ if (!ctx->aud_beg.empty()) {
620
+ add_text(ctx->aud_beg, true); // add audio begin token
621
+ }
622
+
623
+ // preprocess audio
624
+ LM_GGML_ASSERT(ctx->w_filters.n_mel); // make sure we have filter preloaded
625
+ std::vector<whisper_preprocessor::whisper_mel> mel_spec_chunks;
626
+ const float * samples = (const float *)bitmap->data.data();
627
+ size_t n_samples = bitmap->data.size() / sizeof(float);
628
+ bool ok = whisper_preprocessor::preprocess_audio(samples, n_samples, ctx->w_filters, mel_spec_chunks);
629
+ if (!ok) {
630
+ LOG_ERR("Unable to preprocess audio\n");
631
+ return 2;
632
+ }
633
+
634
+ // consider each mel_spec as a separate audio chunk
635
+ // TODO: maybe support batching, but this may come with memory cost
636
+ for (auto & mel_spec : mel_spec_chunks) {
637
+ clip_image_f32_ptr mel_f32(clip_image_f32_init());
638
+ mel_f32->nx = mel_spec.n_len;
639
+ mel_f32->ny = mel_spec.n_mel;
640
+ mel_f32->buf = std::move(mel_spec.data);
641
+ size_t n_tokens = clip_n_output_tokens(ctx->ctx_a, mel_f32.get());
642
+
643
+ clip_image_f32_batch batch_f32;
644
+ batch_f32.is_audio = true;
645
+ batch_f32.entries.push_back(std::move(mel_f32));
646
+
647
+ mtmd_audio_tokens_ptr audio_tokens(new mtmd_audio_tokens);
648
+ audio_tokens->n_tokens = n_tokens;
649
+ audio_tokens->batch_f32 = std::move(batch_f32);
650
+ audio_tokens->id = bitmap->id; // optional
651
+
652
+ LOG_DBG("audio_tokens->n_tokens = %d\n", audio_tokens->n_tokens);
653
+
654
+ mtmd_input_chunk chunk{
655
+ MTMD_INPUT_CHUNK_TYPE_AUDIO,
656
+ {}, // text tokens
657
+ nullptr, // image tokens
658
+ std::move(audio_tokens),
659
+ };
660
+ cur.entries.emplace_back(std::move(chunk));
661
+ }
662
+
663
+ if (!ctx->aud_end.empty()) {
664
+ add_text(ctx->aud_end, true); // add audio end token
665
+ }
666
+ }
667
+
668
+ return 0;
669
+ }
670
+
671
+ std::vector<mtmd_input_chunk> split_batch_to_chunk(clip_image_f32_batch && batch_f32, const std::string & id) {
672
+ std::vector<mtmd_input_chunk> chunks;
673
+
674
+ for (auto & entry : batch_f32.entries) {
675
+ mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
676
+ image_tokens->nx = clip_n_output_tokens(ctx->ctx_v, entry.get());
677
+ image_tokens->ny = 1;
678
+ image_tokens->batch_f32.entries.push_back(std::move(entry));
679
+ image_tokens->id = id;
680
+
681
+ mtmd_input_chunk chunk{
682
+ MTMD_INPUT_CHUNK_TYPE_IMAGE,
683
+ {}, // text tokens
684
+ std::move(image_tokens),
685
+ nullptr, // audio tokens
686
+ };
687
+ chunks.emplace_back(std::move(chunk));
688
+ }
689
+
690
+ return chunks;
691
+ }
692
+
693
+ // for example: "a <__media__> b <__media__> c" --> "a", "<__media__>", "b", "<__media__>", "c"
694
+ static std::vector<std::string> split_text(const std::string & input, const std::string & delimiter) {
695
+ std::vector<std::string> result;
696
+ if (input.empty()) {
697
+ return result;
698
+ }
699
+ size_t start = 0;
700
+ size_t pos = 0;
701
+ while ((pos = input.find(delimiter, start)) != std::string::npos) {
702
+ if (pos > start) {
703
+ result.push_back(input.substr(start, pos - start));
704
+ }
705
+ result.push_back(delimiter);
706
+ start = pos + delimiter.length();
707
+ }
708
+ if (start < input.length()) {
709
+ result.push_back(input.substr(start));
710
+ }
711
+ return result;
712
+ }
713
+
714
+ // copied from common_tokenize
715
+ static std::vector<llama_token> mtmd_tokenize_text_internal(
716
+ const struct llama_vocab * vocab,
717
+ const std::string & text,
718
+ bool add_special,
719
+ bool parse_special) {
720
+ // upper limit for the number of tokens
721
+ int n_tokens = text.length() + 2 * add_special;
722
+ std::vector<llama_token> result(n_tokens);
723
+ n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
724
+ if (n_tokens < 0) {
725
+ result.resize(-n_tokens);
726
+ int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
727
+ LM_GGML_ASSERT(check == -n_tokens);
728
+ } else {
729
+ result.resize(n_tokens);
730
+ }
731
+ return result;
732
+ }
733
+ };
734
+
735
+ int32_t mtmd_tokenize(mtmd_context * ctx,
736
+ mtmd_input_chunks * output,
737
+ const mtmd_input_text * text,
738
+ const mtmd_bitmap ** bitmaps,
739
+ size_t n_bitmaps) {
740
+ mtmd_tokenizer tokenizer(ctx, text, bitmaps, n_bitmaps);
741
+ return tokenizer.tokenize(output);
742
+ }
743
+
744
+ int32_t mtmd_encode_chunk(mtmd_context * ctx, const mtmd_input_chunk * chunk) {
745
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
746
+ LOG_WRN("mtmd_encode_chunk has no effect for text chunks\n");
747
+ return 0;
748
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
749
+ if (!ctx->ctx_v) {
750
+ LOG_ERR("%s: model does not support vision input\n", __func__);
751
+ return 1;
752
+ }
753
+ return mtmd_encode(ctx, chunk->tokens_image.get());
754
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
755
+ if (!ctx->ctx_a) {
756
+ LOG_ERR("%s: model does not support audio input\n", __func__);
757
+ return 1;
758
+ }
759
+ int n_mmproj_embd = ctx->n_embd_text;
760
+ ctx->image_embd_v.resize(chunk->tokens_audio->n_tokens * n_mmproj_embd);
761
+ bool ok = clip_image_batch_encode(
762
+ ctx->ctx_a,
763
+ ctx->n_threads,
764
+ &chunk->tokens_audio->batch_f32,
765
+ ctx->image_embd_v.data());
766
+ return ok ? 0 : 1;
767
+ }
768
+
769
+ LOG_ERR("%s: unknown chunk type %d\n", __func__, (int)chunk->type);
770
+ return 1;
771
+ }
772
+
773
+ int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
774
+ clip_ctx * ctx_clip = ctx->ctx_v;
775
+ if (!ctx_clip) {
776
+ LOG_ERR("%s: this API does not support non-vision input, please use mtmd_encode_chunk instead\n", __func__);
777
+ return 1;
778
+ }
779
+ int n_mmproj_embd = clip_n_mmproj_embd(ctx_clip);
780
+ ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
781
+ bool ok = false;
782
+
783
+ if (clip_is_llava(ctx_clip) || clip_is_minicpmv(ctx_clip) || clip_is_glm(ctx_clip)) {
784
+ // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
785
+ const auto & entries = image_tokens->batch_f32.entries;
786
+ for (size_t i = 0; i < entries.size(); i++) {
787
+ int n_tokens_per_image = clip_n_output_tokens(ctx_clip, entries[i].get());
788
+ ok = clip_image_encode(
789
+ ctx_clip,
790
+ ctx->n_threads,
791
+ entries[i].get(),
792
+ ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
793
+ }
794
+ } else {
795
+ ok = clip_image_batch_encode(
796
+ ctx_clip,
797
+ ctx->n_threads,
798
+ &image_tokens->batch_f32,
799
+ ctx->image_embd_v.data());
800
+ }
801
+
802
+ return ok ? 0 : 1;
803
+ }
804
+
805
+ float * mtmd_get_output_embd(mtmd_context * ctx) {
806
+ return ctx->image_embd_v.data();
807
+ }
808
+
809
+ bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
810
+ if (ctx->ctx_v && clip_get_projector_type(ctx->ctx_v) == PROJECTOR_TYPE_GEMMA3) {
811
+ return true;
812
+ }
813
+ return false;
814
+ }
815
+
816
+ bool mtmd_decode_use_mrope(mtmd_context * ctx) {
817
+ return ctx->use_mrope;
818
+ }
819
+
820
+ bool mtmd_support_vision(mtmd_context * ctx) {
821
+ return ctx->ctx_v != nullptr;
822
+ }
823
+
824
+ bool mtmd_support_audio(mtmd_context * ctx) {
825
+ return ctx->ctx_a != nullptr;
826
+ }
827
+
828
+ int mtmd_get_audio_bitrate(mtmd_context * ctx) {
829
+ if (!ctx->ctx_a) {
830
+ return -1;
831
+ }
832
+ // for now, we assume that all audio models have the same bitrate
833
+ return 16000; // 16kHz
834
+ }
835
+
836
+ //
837
+ // public API functions
838
+ //
839
+
840
+ // mtmd_bitmap
841
+
842
+ mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
843
+ uint32_t ny,
844
+ const unsigned char * data) {
845
+ mtmd_bitmap * bitmap = new mtmd_bitmap;
846
+ bitmap->nx = nx;
847
+ bitmap->ny = ny;
848
+ size_t data_size = (size_t)nx * ny * 3;
849
+ bitmap->data.resize(data_size);
850
+ std::memcpy(bitmap->data.data(), data, data_size);
851
+ return bitmap;
852
+ }
853
+
854
+ mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples,
855
+ const float * data) {
856
+ mtmd_bitmap * bitmap = new mtmd_bitmap;
857
+ bitmap->nx = n_samples;
858
+ bitmap->ny = 1;
859
+ bitmap->is_audio = true;
860
+ size_t data_size = n_samples * sizeof(float);
861
+ bitmap->data.resize(data_size);
862
+ std::memcpy(bitmap->data.data(), data, data_size);
863
+ return bitmap;
864
+ }
865
+
866
+ uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
867
+ return bitmap->nx;
868
+ }
869
+
870
+ uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
871
+ return bitmap->ny;
872
+ }
873
+
874
+ const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
875
+ return bitmap->data.data();
876
+ }
877
+
878
+ size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap) {
879
+ return bitmap->data.size();
880
+ }
881
+
882
+ bool mtmd_bitmap_is_audio(const mtmd_bitmap * bitmap) {
883
+ return bitmap->is_audio;
884
+ }
885
+
886
+ const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
887
+ return bitmap->id.c_str();
888
+ }
889
+
890
+ void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
891
+ if (id) {
892
+ bitmap->id = std::string(id);
893
+ } else {
894
+ bitmap->id.clear();
895
+ }
896
+ }
897
+
898
+ void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
899
+ if (bitmap) {
900
+ delete bitmap;
901
+ }
902
+ }
903
+
904
+ // mtmd_input_chunks
905
+
906
+ mtmd_input_chunks * mtmd_input_chunks_init() {
907
+ return new mtmd_input_chunks;
908
+ }
909
+
910
+ size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
911
+ return chunks->entries.size();
912
+ }
913
+
914
+ const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
915
+ if (idx >= chunks->entries.size()) {
916
+ return nullptr;
917
+ }
918
+ return &chunks->entries[idx];
919
+ }
920
+
921
+ void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
922
+ if (chunks) {
923
+ delete chunks;
924
+ }
925
+ }
926
+
927
+ // mtmd_input_chunk
928
+
929
+ enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
930
+ return chunk->type;
931
+ }
932
+
933
+ const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
934
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
935
+ *n_tokens_output = chunk->tokens_text.size();
936
+ return chunk->tokens_text.data();
937
+ }
938
+ *n_tokens_output = 0;
939
+ return nullptr;
940
+ }
941
+
942
+ const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
943
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
944
+ return chunk->tokens_image.get();
945
+ }
946
+ return nullptr;
947
+ }
948
+
949
+ size_t mtmd_input_chunk_get_n_tokens(const mtmd_input_chunk * chunk) {
950
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
951
+ return chunk->tokens_text.size();
952
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
953
+ return mtmd_image_tokens_get_n_tokens(chunk->tokens_image.get());
954
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
955
+ return chunk->tokens_audio->n_tokens;
956
+ } else {
957
+ LM_GGML_ABORT("invalid chunk type");
958
+ }
959
+ }
960
+
961
+ llama_pos mtmd_input_chunk_get_n_pos(const mtmd_input_chunk * chunk) {
962
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
963
+ return chunk->tokens_text.size();
964
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
965
+ return mtmd_image_tokens_get_n_pos(chunk->tokens_image.get());
966
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
967
+ return chunk->tokens_audio->n_tokens;
968
+ } else {
969
+ LM_GGML_ABORT("invalid chunk type");
970
+ }
971
+ }
972
+
973
+ const char * mtmd_input_chunk_get_id(const mtmd_input_chunk * chunk) {
974
+ if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
975
+ return chunk->tokens_image->id.c_str();
976
+ } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
977
+ return chunk->tokens_audio->id.c_str();
978
+ }
979
+ return nullptr;
980
+ }
981
+
982
+ mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
983
+ mtmd_input_chunk * copy = new mtmd_input_chunk{
984
+ chunk->type,
985
+ chunk->tokens_text,
986
+ nullptr,
987
+ nullptr,
988
+ };
989
+ if (chunk->tokens_image) {
990
+ // copy the image tokens
991
+ copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
992
+ *copy->tokens_image = chunk->tokens_image->clone();
993
+ }
994
+ if (chunk->tokens_audio) {
995
+ // copy the audio tokens
996
+ copy->tokens_audio = mtmd_audio_tokens_ptr(new mtmd_audio_tokens());
997
+ *copy->tokens_audio = chunk->tokens_audio->clone();
998
+ }
999
+ return copy;
1000
+ }
1001
+
1002
+ void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
1003
+ if (chunk) {
1004
+ delete chunk;
1005
+ }
1006
+ }
1007
+
1008
+ // mtmd_image_tokens
1009
+
1010
+ size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
1011
+ return image_tokens->n_tokens();
1012
+ }
1013
+
1014
+ size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
1015
+ return image_tokens->nx;
1016
+ }
1017
+
1018
+ size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
1019
+ return image_tokens->ny;
1020
+ }
1021
+
1022
+ const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
1023
+ return image_tokens->id.c_str();
1024
+ }
1025
+
1026
+ llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
1027
+ if (image_tokens->use_mrope_pos) {
1028
+ return 1; // for M-RoPE, the whole image is 1 in temporal dimension
1029
+ }
1030
+ return image_tokens->n_tokens();
1031
+ }
1032
+
1033
+ // test function
1034
+
1035
+ mtmd_input_chunks * mtmd_test_create_input_chunks() {
1036
+ mtmd_input_chunks * chunks = mtmd_input_chunks_init();
1037
+ if (!chunks) {
1038
+ return nullptr;
1039
+ }
1040
+
1041
+ // create a text chunk
1042
+ std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
1043
+ mtmd_input_chunk chunk_text{
1044
+ MTMD_INPUT_CHUNK_TYPE_TEXT,
1045
+ std::move(tokens_text),
1046
+ nullptr, // image tokens
1047
+ nullptr, // audio tokens
1048
+ };
1049
+ chunks->entries.emplace_back(std::move(chunk_text));
1050
+
1051
+ // create an image chunk
1052
+ mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
1053
+ image_tokens->nx = 4;
1054
+ image_tokens->ny = 4;
1055
+ image_tokens->batch_f32.entries.resize(16);
1056
+ image_tokens->id = "image_1";
1057
+ mtmd_input_chunk chunk_image{
1058
+ MTMD_INPUT_CHUNK_TYPE_IMAGE,
1059
+ {}, // text tokens
1060
+ std::move(image_tokens),
1061
+ nullptr, // audio tokens
1062
+ };
1063
+ chunks->entries.emplace_back(std::move(chunk_image));
1064
+
1065
+ return chunks;
1066
+ }