mtmd.cpp 39 KB

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