mtmd.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "mtmd.h"
  4. #include "llama.h"
  5. #include <algorithm>
  6. #include <cerrno>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <limits>
  11. #include <vector>
  12. // represents raw image data, layout is RGBRGBRGB...
  13. // length of data must be nx * ny * 3
  14. struct mtmd_bitmap {
  15. uint32_t nx;
  16. uint32_t ny;
  17. std::vector<unsigned char> data;
  18. std::string id; // optional user-defined id, for ex: can be set to image hash, useful for KV cache tracking
  19. };
  20. struct mtmd_image_tokens_deleter {
  21. void operator()(mtmd_image_tokens * val); // forward declaration
  22. };
  23. using mtmd_image_tokens_ptr = std::unique_ptr<mtmd_image_tokens, mtmd_image_tokens_deleter>;
  24. struct mtmd_input_chunk {
  25. mtmd_input_chunk_type type;
  26. std::vector<llama_token> tokens_text;
  27. mtmd_image_tokens_ptr tokens_image;
  28. };
  29. struct mtmd_input_chunks {
  30. std::vector<mtmd_input_chunk> entries;
  31. };
  32. // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
  33. // models not having it (llava-1.6) will process embeddings without any special tokens in-between
  34. enum mtmd_slice_tmpl {
  35. MTMD_SLICE_TMPL_NONE,
  36. MTMD_SLICE_TMPL_MINICPMV_2_5,
  37. MTMD_SLICE_TMPL_MINICPMV_2_6,
  38. MTMD_SLICE_TMPL_LLAMA4,
  39. // TODO @ngxson : add support for idefics (SmolVLM)
  40. };
  41. mtmd_context_params mtmd_context_params_default() {
  42. mtmd_context_params params;
  43. params.use_gpu = true;
  44. params.print_timings = true;
  45. params.n_threads = 4;
  46. params.verbosity = GGML_LOG_LEVEL_INFO;
  47. params.image_marker = MTMD_DEFAULT_IMAGE_MARKER;
  48. return params;
  49. }
  50. struct mtmd_context {
  51. struct clip_ctx * ctx_clip;
  52. const struct llama_model * text_model;
  53. std::vector<float> image_embd_v; // image embedding vector
  54. bool print_timings;
  55. int n_threads;
  56. std::string image_marker;
  57. // for llava-uhd style models, we need special tokens in-between slices
  58. // minicpmv calls them "slices", llama 4 calls them "tiles"
  59. mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
  60. llama_token tok_ov_img_start = LLAMA_TOKEN_NULL; // overview image
  61. llama_token tok_ov_img_end = LLAMA_TOKEN_NULL; // overview image
  62. llama_token tok_slices_start = LLAMA_TOKEN_NULL; // start of all slices
  63. llama_token tok_slices_end = LLAMA_TOKEN_NULL; // end of all slices
  64. llama_token tok_sli_img_start = LLAMA_TOKEN_NULL; // single slice start
  65. llama_token tok_sli_img_end = LLAMA_TOKEN_NULL; // single slice end
  66. llama_token tok_sli_img_mid = LLAMA_TOKEN_NULL; // between 2 slices
  67. llama_token tok_row_end = LLAMA_TOKEN_NULL; // end of row
  68. bool tok_row_end_trail = false;
  69. bool ov_img_first = false;
  70. bool use_mrope = false; // for Qwen2VL, we need to use M-RoPE
  71. // TODO @ngxson : add timings
  72. mtmd_context(const char * mmproj_fname,
  73. const llama_model * text_model,
  74. const mtmd_context_params & ctx_params) :
  75. text_model (text_model),
  76. print_timings(ctx_params.print_timings),
  77. n_threads (ctx_params.n_threads),
  78. image_marker (ctx_params.image_marker)
  79. {
  80. clip_context_params ctx_clip_params;
  81. ctx_clip_params.use_gpu = ctx_params.use_gpu;
  82. ctx_clip_params.verbosity = ctx_params.verbosity;
  83. ctx_clip = clip_init(mmproj_fname, ctx_clip_params);
  84. if (!ctx_clip) {
  85. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  86. }
  87. use_mrope = clip_is_qwen2vl(ctx_clip);
  88. projector_type proj = clip_get_projector_type(ctx_clip);
  89. int minicpmv_version = clip_is_minicpmv(ctx_clip);
  90. if (minicpmv_version == 2) {
  91. // minicpmv 2.5 format:
  92. // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
  93. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
  94. tok_ov_img_start = lookup_token("<image>");
  95. tok_ov_img_end = lookup_token("</image>");
  96. tok_slices_start = lookup_token("<slice>");
  97. tok_slices_end = lookup_token("</slice>");
  98. tok_sli_img_start = tok_ov_img_start;
  99. tok_sli_img_end = tok_ov_img_end;
  100. tok_row_end = lookup_token("\n");
  101. tok_row_end_trail = false; // no trailing end-of-row token
  102. ov_img_first = true;
  103. } else if (minicpmv_version == 3 || minicpmv_version == 4) {
  104. // minicpmv 2.6 format:
  105. // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
  106. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
  107. tok_ov_img_start = lookup_token("<image>");
  108. tok_ov_img_end = lookup_token("</image>");
  109. tok_sli_img_start = lookup_token("<slice>");
  110. tok_sli_img_end = lookup_token("</slice>");
  111. tok_row_end = lookup_token("\n");
  112. tok_row_end_trail = false; // no trailing end-of-row token
  113. ov_img_first = true;
  114. } else if (minicpmv_version != 0) {
  115. GGML_ASSERT(false && "unsupported minicpmv version");
  116. } else if (proj == PROJECTOR_TYPE_LLAMA4) {
  117. // llama 4 format:
  118. // <|image_start|>
  119. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  120. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  121. // ... <|tile_y_separator|> <-- trailing end-of-row token
  122. // <|image|> (overview) <-- overview image is last
  123. // <|image_end|>
  124. slice_tmpl = MTMD_SLICE_TMPL_LLAMA4;
  125. tok_ov_img_start = lookup_token("<|image|>");
  126. tok_sli_img_mid = lookup_token("<|tile_x_separator|>");
  127. tok_row_end = lookup_token("<|tile_y_separator|>");
  128. tok_row_end_trail = true; // add trailing end-of-row token
  129. ov_img_first = false; // overview image is last
  130. }
  131. }
  132. ~mtmd_context() {
  133. clip_free(ctx_clip);
  134. }
  135. private:
  136. llama_token lookup_token(const std::string & token_text) {
  137. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  138. const int n_vocab = llama_vocab_n_tokens(vocab);
  139. for (int i = 0; i < n_vocab; i++) {
  140. if (token_to_piece(vocab, i, true) == token_text) {
  141. return i;
  142. }
  143. }
  144. return LLAMA_TOKEN_NULL;
  145. }
  146. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  147. std::string piece;
  148. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  149. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  150. if (n_chars < 0) {
  151. piece.resize(-n_chars);
  152. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  153. GGML_ASSERT(check == -n_chars);
  154. } else {
  155. piece.resize(n_chars);
  156. }
  157. return piece;
  158. }
  159. };
  160. struct mtmd_image_tokens_data {
  161. clip_image_f32_batch batch_f32; // preprocessed image patches
  162. };
  163. struct mtmd_image_tokens {
  164. uint32_t nx; // number of tokens in x direction
  165. uint32_t ny; // number of tokens in y direction
  166. bool use_mrope_pos = false; // use M-RoPE position counting (the whole image is 1 temporal position)
  167. uint32_t n_tokens() const { return nx * ny; }
  168. clip_image_f32_batch batch_f32; // preprocessed image patches
  169. std::string id; // optional user-defined ID, useful for KV cache tracking
  170. mtmd_image_tokens clone() {
  171. return mtmd_image_tokens{
  172. nx,
  173. ny,
  174. use_mrope_pos,
  175. batch_f32.clone(),
  176. id
  177. };
  178. }
  179. };
  180. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  181. const struct llama_model * text_model,
  182. const struct mtmd_context_params ctx_params) {
  183. try {
  184. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  185. } catch (const std::exception & e) {
  186. LOG_ERR("%s: error: %s\n", __func__, e.what());
  187. return nullptr;
  188. }
  189. }
  190. void mtmd_free(mtmd_context * ctx) {
  191. if (ctx) {
  192. delete ctx;
  193. }
  194. }
  195. // copied from common_tokenize
  196. static std::vector<llama_token> mtmd_tokenize_text_internal(
  197. const struct llama_vocab * vocab,
  198. const std::string & text,
  199. bool add_special,
  200. bool parse_special) {
  201. // upper limit for the number of tokens
  202. int n_tokens = text.length() + 2 * add_special;
  203. std::vector<llama_token> result(n_tokens);
  204. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  205. if (n_tokens < 0) {
  206. result.resize(-n_tokens);
  207. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  208. GGML_ASSERT(check == -n_tokens);
  209. } else {
  210. result.resize(n_tokens);
  211. }
  212. return result;
  213. }
  214. int32_t mtmd_tokenize(mtmd_context * ctx,
  215. mtmd_input_chunks * output,
  216. const mtmd_input_text * text,
  217. const mtmd_bitmap ** bitmaps,
  218. size_t n_bitmaps) {
  219. auto vocab = llama_model_get_vocab(ctx->text_model);
  220. std::string prompt_modified(text->text);
  221. std::string marker_modified(ctx->image_marker);
  222. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  223. // a bit hacky here, but works for now
  224. // for some models, we need to add prefix and suffix to the image embeddings
  225. if (clip_is_gemma3(ctx->ctx_clip)) {
  226. // gemma 3
  227. // <start_of_image> ... (image embeddings) ... <end_of_image>
  228. marker_modified = "<start_of_image>" + ctx->image_marker + "<end_of_image>";
  229. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  230. } else if (proj_type == PROJECTOR_TYPE_IDEFICS3) {
  231. // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
  232. marker_modified = "<fake_token_around_image><global-img>" + ctx->image_marker + "<fake_token_around_image>";
  233. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  234. } else if (proj_type == PROJECTOR_TYPE_PIXTRAL) {
  235. // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
  236. marker_modified = ctx->image_marker + "[IMG_END]";
  237. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  238. } else if (proj_type == PROJECTOR_TYPE_QWEN2VL || proj_type == PROJECTOR_TYPE_QWEN25VL) {
  239. // <|vision_start|> ... (image embeddings) ... <|vision_end|>
  240. marker_modified = "<|vision_start|>" + ctx->image_marker + "<|vision_end|>";
  241. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  242. } else if (proj_type == PROJECTOR_TYPE_LLAMA4) {
  243. // (more details in mtmd_context constructor)
  244. marker_modified = "<|image_start|>" + ctx->image_marker + "<|image_end|>";
  245. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  246. } else if (proj_type == PROJECTOR_TYPE_INTERNVL) {
  247. // <img> ... (image embeddings) ... </img>
  248. marker_modified = "<img>" + ctx->image_marker + "</img>";
  249. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  250. }
  251. // llava-1.5, llava-1.6, Yi-VL, Yi-34B, granite: don't need to add prefix and suffix
  252. // for glm-edge, BOI and EOI token's embeddings are not present in the text model
  253. std::vector<std::string> parts = string_split_str(prompt_modified, ctx->image_marker);
  254. output->entries.clear();
  255. output->entries.reserve(parts.size());
  256. size_t i_img = 0;
  257. // utility for adding raw tokens
  258. auto add_text_chunk = [&output](std::vector<llama_token> && tokens) {
  259. mtmd_input_chunk chunk{
  260. MTMD_INPUT_CHUNK_TYPE_TEXT,
  261. std::move(tokens),
  262. {},
  263. };
  264. output->entries.emplace_back(std::move(chunk));
  265. };
  266. // utility for splitting batch of multiple images into chunks of batch having single images
  267. auto split_batch_to_chunk = [&ctx](clip_image_f32_batch && batch_f32, const std::string & id) {
  268. std::vector<mtmd_input_chunk> chunks;
  269. for (auto & entry : batch_f32.entries) {
  270. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  271. image_tokens->nx = clip_n_output_tokens(ctx->ctx_clip, entry.get());
  272. image_tokens->ny = 1;
  273. image_tokens->batch_f32.entries.push_back(std::move(entry));
  274. image_tokens->id = id;
  275. mtmd_input_chunk chunk{
  276. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  277. {},
  278. std::move(image_tokens),
  279. };
  280. chunks.emplace_back(std::move(chunk));
  281. }
  282. return chunks;
  283. };
  284. for (const auto & part : parts) {
  285. // printf("tokenizing part: %s\n", part.c_str());
  286. bool add_bos = &parts.front() == &part;
  287. auto tokens = mtmd_tokenize_text_internal(vocab, part, text->add_special && add_bos, text->parse_special);
  288. if (tokens.empty()) {
  289. continue;
  290. }
  291. mtmd_input_chunk chunk{
  292. MTMD_INPUT_CHUNK_TYPE_TEXT,
  293. std::move(tokens),
  294. {},
  295. };
  296. output->entries.emplace_back(std::move(chunk));
  297. if (&parts.back() != &part) {
  298. // add image token to middle of 2 parts
  299. if (i_img >= n_bitmaps) {
  300. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  301. return 1;
  302. }
  303. // convert mtmd_bitmap to clip_image_u8
  304. clip_image_u8_ptr img_u8(clip_image_u8_init());
  305. img_u8->nx = bitmaps[i_img]->nx;
  306. img_u8->ny = bitmaps[i_img]->ny;
  307. img_u8->buf.resize(bitmaps[i_img]->data.size());
  308. std::memcpy(img_u8->buf.data(), bitmaps[i_img]->data.data(), img_u8->nx * img_u8->ny * 3);
  309. // preprocess image
  310. clip_image_f32_batch batch_f32;
  311. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), &batch_f32);
  312. if (!ok) {
  313. LOG_ERR("Unable to preprocess image\n");
  314. return 2;
  315. }
  316. // handle llava-uhd style preprocessing
  317. if (
  318. ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5
  319. || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6
  320. || ctx->slice_tmpl == MTMD_SLICE_TMPL_LLAMA4
  321. ) {
  322. // split batch into chunks of single images
  323. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmaps[i_img]->id);
  324. GGML_ASSERT(chunks.size() > 0);
  325. auto ov_chunk = std::move(chunks.front());
  326. chunks.erase(chunks.begin());
  327. // add overview image (first)
  328. if (ctx->ov_img_first) {
  329. if (ctx->tok_ov_img_start != LLAMA_TOKEN_NULL) {
  330. add_text_chunk({ctx->tok_ov_img_start});
  331. }
  332. output->entries.emplace_back(std::move(ov_chunk));
  333. if (ctx->tok_ov_img_end != LLAMA_TOKEN_NULL) {
  334. add_text_chunk({ctx->tok_ov_img_end});
  335. }
  336. }
  337. // add slices (or tiles)
  338. if (!chunks.empty()) {
  339. const int n_col = batch_f32.grid_x;
  340. const int n_row = batch_f32.grid_y;
  341. if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
  342. add_text_chunk({ctx->tok_slices_start});
  343. }
  344. for (int y = 0; y < n_row; y++) {
  345. for (int x = 0; x < n_col; x++) {
  346. const bool is_last_in_row = (x == n_col - 1);
  347. if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
  348. add_text_chunk({ctx->tok_sli_img_start});
  349. }
  350. output->entries.emplace_back(std::move(chunks[y * n_col + x]));
  351. if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
  352. add_text_chunk({ctx->tok_sli_img_end});
  353. }
  354. if (!is_last_in_row && ctx->tok_sli_img_mid != LLAMA_TOKEN_NULL) {
  355. add_text_chunk({ctx->tok_sli_img_mid});
  356. }
  357. }
  358. if ((y != n_row - 1 || ctx->tok_row_end_trail) && ctx->tok_row_end != LLAMA_TOKEN_NULL) {
  359. add_text_chunk({ctx->tok_row_end});
  360. }
  361. }
  362. if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
  363. add_text_chunk({ctx->tok_slices_end});
  364. }
  365. }
  366. // add overview image (last)
  367. if (!ctx->ov_img_first) {
  368. if (ctx->tok_ov_img_start != LLAMA_TOKEN_NULL) {
  369. add_text_chunk({ctx->tok_ov_img_start});
  370. }
  371. output->entries.emplace_back(std::move(ov_chunk));
  372. if (ctx->tok_ov_img_end != LLAMA_TOKEN_NULL) {
  373. add_text_chunk({ctx->tok_ov_img_end});
  374. }
  375. }
  376. } else {
  377. size_t n_tokens = 0;
  378. for (const auto & entry : batch_f32.entries) {
  379. n_tokens += clip_n_output_tokens(ctx->ctx_clip, entry.get());
  380. }
  381. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  382. if (ctx->use_mrope) {
  383. // for Qwen2VL, we need this information for M-RoPE decoding positions
  384. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_clip, batch_f32.entries[0].get());
  385. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_clip, batch_f32.entries[0].get());
  386. image_tokens->use_mrope_pos = true;
  387. } else {
  388. // other models, we only need the total number of tokens
  389. image_tokens->nx = n_tokens;
  390. image_tokens->ny = 1;
  391. }
  392. image_tokens->batch_f32 = std::move(batch_f32);
  393. image_tokens->id = bitmaps[i_img]->id; // optional
  394. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  395. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  396. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  397. mtmd_input_chunk chunk{
  398. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  399. {},
  400. std::move(image_tokens),
  401. };
  402. output->entries.emplace_back(std::move(chunk));
  403. }
  404. i_img++; // move to next image
  405. }
  406. }
  407. return 0;
  408. }
  409. static void mtmd_image_tokens_free(mtmd_image_tokens * image_tokens) {
  410. if (image_tokens) {
  411. delete image_tokens;
  412. }
  413. }
  414. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  415. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  416. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  417. bool ok = false;
  418. if (clip_is_llava(ctx->ctx_clip) || clip_is_minicpmv(ctx->ctx_clip) || clip_is_glm(ctx->ctx_clip)) {
  419. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  420. const auto & entries = image_tokens->batch_f32.entries;
  421. for (size_t i = 0; i < entries.size(); i++) {
  422. int n_tokens_per_image = clip_n_output_tokens(ctx->ctx_clip, entries[i].get());
  423. ok = clip_image_encode(
  424. ctx->ctx_clip,
  425. ctx->n_threads,
  426. entries[i].get(),
  427. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  428. }
  429. } else {
  430. ok = clip_image_batch_encode(
  431. ctx->ctx_clip,
  432. ctx->n_threads,
  433. &image_tokens->batch_f32,
  434. ctx->image_embd_v.data());
  435. }
  436. return ok ? 0 : 1;
  437. }
  438. float * mtmd_get_output_embd(mtmd_context * ctx) {
  439. return ctx->image_embd_v.data();
  440. }
  441. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  442. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  443. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  444. return true;
  445. }
  446. return false;
  447. }
  448. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  449. return ctx->use_mrope;
  450. }
  451. void mtmd_image_tokens_deleter::operator()(mtmd_image_tokens * val) {
  452. mtmd_image_tokens_free(val);
  453. }
  454. // these 2 helpers below use internal clip_image_u8_ptr,
  455. // so unfortunately they cannot moved to mtmd-helper.h
  456. // however, in theory, user can decode image file to bitmap using
  457. // whichever library they want, and then use mtmd_bitmap_init() to create bitmap
  458. mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len) {
  459. clip_image_u8_ptr img_u8(clip_image_u8_init());
  460. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  461. if (!ok) {
  462. LOG_ERR("Unable to load image from buffer\n");
  463. return nullptr;
  464. }
  465. uint32_t nx, ny;
  466. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  467. return mtmd_bitmap_init(nx, ny, data);
  468. }
  469. mtmd_bitmap * mtmd_helper_bitmap_init_from_file(const char * fname) {
  470. clip_image_u8_ptr img_u8(clip_image_u8_init());
  471. bool ok = clip_image_load_from_file(fname, img_u8.get());
  472. if (!ok) {
  473. LOG_ERR("Unable to load image %s\n", fname);
  474. return nullptr;
  475. }
  476. uint32_t nx, ny;
  477. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  478. return mtmd_bitmap_init(nx, ny, data);
  479. }
  480. //
  481. // public API functions
  482. //
  483. // mtmd_bitmap
  484. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  485. uint32_t ny,
  486. const unsigned char * data) {
  487. mtmd_bitmap * bitmap = new mtmd_bitmap;
  488. bitmap->nx = nx;
  489. bitmap->ny = ny;
  490. size_t data_size = (size_t)nx * ny * 3;
  491. bitmap->data.resize(data_size);
  492. std::memcpy(bitmap->data.data(), data, data_size);
  493. return bitmap;
  494. }
  495. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  496. return bitmap->nx;
  497. }
  498. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  499. return bitmap->ny;
  500. }
  501. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  502. return bitmap->data.data();
  503. }
  504. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  505. return bitmap->id.c_str();
  506. }
  507. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  508. if (id) {
  509. bitmap->id = std::string(id);
  510. } else {
  511. bitmap->id.clear();
  512. }
  513. }
  514. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  515. if (bitmap) {
  516. delete bitmap;
  517. }
  518. }
  519. // mtmd_input_chunks
  520. mtmd_input_chunks * mtmd_input_chunks_init() {
  521. return new mtmd_input_chunks;
  522. }
  523. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  524. return chunks->entries.size();
  525. }
  526. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  527. if (idx >= chunks->entries.size()) {
  528. return nullptr;
  529. }
  530. return &chunks->entries[idx];
  531. }
  532. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  533. if (chunks) {
  534. delete chunks;
  535. }
  536. }
  537. // mtmd_input_chunk
  538. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  539. return chunk->type;
  540. }
  541. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  542. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  543. *n_tokens_output = chunk->tokens_text.size();
  544. return chunk->tokens_text.data();
  545. }
  546. *n_tokens_output = 0;
  547. return nullptr;
  548. }
  549. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  550. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  551. return chunk->tokens_image.get();
  552. }
  553. return nullptr;
  554. }
  555. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  556. mtmd_input_chunk * copy = new mtmd_input_chunk{
  557. chunk->type,
  558. chunk->tokens_text,
  559. mtmd_image_tokens_ptr(),
  560. };
  561. if (chunk->tokens_image) {
  562. // copy the image tokens
  563. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  564. *copy->tokens_image = chunk->tokens_image->clone();
  565. }
  566. return copy;
  567. }
  568. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  569. if (chunk) {
  570. delete chunk;
  571. }
  572. }
  573. // mtmd_image_tokens
  574. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  575. return image_tokens->n_tokens();
  576. }
  577. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  578. return image_tokens->nx;
  579. }
  580. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  581. return image_tokens->ny;
  582. }
  583. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  584. return image_tokens->id.c_str();
  585. }
  586. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  587. if (image_tokens->use_mrope_pos) {
  588. return 1; // for M-RoPE, the whole image is 1 in temporal dimension
  589. }
  590. return image_tokens->n_tokens();
  591. }
  592. // test function
  593. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  594. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  595. if (!chunks) {
  596. return nullptr;
  597. }
  598. // create a text chunk
  599. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  600. mtmd_input_chunk chunk_text{
  601. MTMD_INPUT_CHUNK_TYPE_TEXT,
  602. std::move(tokens_text),
  603. {},
  604. };
  605. chunks->entries.emplace_back(std::move(chunk_text));
  606. // create an image chunk
  607. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  608. image_tokens->nx = 4;
  609. image_tokens->ny = 4;
  610. image_tokens->batch_f32.entries.resize(16);
  611. image_tokens->id = "image_1";
  612. mtmd_input_chunk chunk_image{
  613. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  614. {},
  615. std::move(image_tokens),
  616. };
  617. chunks->entries.emplace_back(std::move(chunk_image));
  618. return chunks;
  619. }