mtmd.cpp 38 KB

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