mtmd.cpp 40 KB

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