mtmd.cpp 24 KB

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