mtmd.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
  13. // models not having it (llava-1.6) will process embeddings without any special tokens in-between
  14. enum mtmd_slice_tmpl {
  15. MTMD_SLICE_TMPL_NONE,
  16. MTMD_SLICE_TMPL_MINICPMV_2_5,
  17. MTMD_SLICE_TMPL_MINICPMV_2_6,
  18. // TODO @ngxson : add support for idefics (SmolVLM)
  19. };
  20. struct mtmd_context {
  21. struct clip_ctx * ctx_clip;
  22. const struct llama_model * text_model;
  23. std::vector<float> image_embd_v; // image embedding vector
  24. bool print_timings;
  25. int n_threads;
  26. std::string image_marker;
  27. // for minicpmv, we need special tokens in-between slices
  28. mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
  29. llama_token tok_ov_img_start = LLAMA_TOKEN_NULL; // overview image
  30. llama_token tok_ov_img_end = LLAMA_TOKEN_NULL; // overview image
  31. llama_token tok_slices_start = LLAMA_TOKEN_NULL; // start of all slices
  32. llama_token tok_slices_end = LLAMA_TOKEN_NULL; // end of all slices
  33. llama_token tok_sli_img_start = LLAMA_TOKEN_NULL; // single slice
  34. llama_token tok_sli_img_end = LLAMA_TOKEN_NULL; // single slice
  35. llama_token tok_row_end = LLAMA_TOKEN_NULL; // end of row
  36. // TODO @ngxson : add timings
  37. mtmd_context(const char * mmproj_fname,
  38. const llama_model * text_model,
  39. const mtmd_context_params & ctx_params) :
  40. print_timings(ctx_params.print_timings),
  41. n_threads (ctx_params.n_threads),
  42. image_marker (ctx_params.image_marker)
  43. {
  44. clip_context_params ctx_clip_params;
  45. ctx_clip_params.use_gpu = ctx_params.use_gpu;
  46. ctx_clip_params.verbosity = ctx_params.verbosity;
  47. ctx_clip = clip_init(mmproj_fname, ctx_clip_params);
  48. if (!ctx_clip) {
  49. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  50. }
  51. this->text_model = text_model;
  52. GGML_ASSERT(!clip_is_qwen2vl(ctx_clip) && "Qwen2VL model is not supported yet, use llama-qwen2vl-cli instead");
  53. int minicpmv_version = clip_is_minicpmv(ctx_clip);
  54. if (minicpmv_version == 2) {
  55. // minicpmv 2.5 format:
  56. // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
  57. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
  58. tok_ov_img_start = lookup_token("<image>");
  59. tok_ov_img_end = lookup_token("</image>");
  60. tok_slices_start = lookup_token("<slice>");
  61. tok_slices_end = lookup_token("</slice>");
  62. tok_sli_img_start = tok_ov_img_start;
  63. tok_sli_img_end = tok_ov_img_end;
  64. tok_row_end = lookup_token("\n");
  65. } else if (minicpmv_version == 3 || minicpmv_version == 4) {
  66. // minicpmv 2.6 format:
  67. // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
  68. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
  69. tok_ov_img_start = lookup_token("<image>");
  70. tok_ov_img_end = lookup_token("</image>");
  71. tok_sli_img_start = lookup_token("<slice>");
  72. tok_sli_img_end = lookup_token("</slice>");
  73. tok_row_end = lookup_token("\n");
  74. } else if (minicpmv_version != 0) {
  75. GGML_ASSERT(false && "unsupported minicpmv version");
  76. }
  77. }
  78. ~mtmd_context() {
  79. clip_free(ctx_clip);
  80. }
  81. private:
  82. llama_token lookup_token(const std::string & token_text) {
  83. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  84. const int n_vocab = llama_vocab_n_tokens(vocab);
  85. for (int i = 0; i < n_vocab; i++) {
  86. if (token_to_piece(vocab, i, true) == token_text) {
  87. return i;
  88. }
  89. }
  90. return LLAMA_TOKEN_NULL;
  91. }
  92. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  93. std::string piece;
  94. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  95. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  96. if (n_chars < 0) {
  97. piece.resize(-n_chars);
  98. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  99. GGML_ASSERT(check == -n_chars);
  100. } else {
  101. piece.resize(n_chars);
  102. }
  103. return piece;
  104. }
  105. };
  106. struct mtmd_image_tokens_data {
  107. clip_image_f32_batch batch_f32; // preprocessed image patches
  108. };
  109. struct mtmd_image_tokens {
  110. uint32_t nx; // number of tokens in x direction
  111. uint32_t ny; // number of tokens in y direction
  112. uint32_t n_tokens() const { return nx * ny; }
  113. clip_image_f32_batch batch_f32; // preprocessed image patches
  114. std::string id; // optional user-defined ID, useful for KV cache tracking
  115. };
  116. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  117. const struct llama_model * text_model,
  118. const struct mtmd_context_params ctx_params) {
  119. try {
  120. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  121. } catch (const std::exception & e) {
  122. LOG_ERR("%s: error: %s\n", __func__, e.what());
  123. return nullptr;
  124. }
  125. }
  126. void mtmd_free(mtmd_context * ctx) {
  127. if (ctx) {
  128. delete ctx;
  129. }
  130. }
  131. // copied from common_tokenize
  132. static std::vector<llama_token> mtmd_tokenize_text_internal(
  133. const struct llama_vocab * vocab,
  134. const std::string & text,
  135. bool add_special,
  136. bool parse_special) {
  137. // upper limit for the number of tokens
  138. int n_tokens = text.length() + 2 * add_special;
  139. std::vector<llama_token> result(n_tokens);
  140. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  141. if (n_tokens < 0) {
  142. result.resize(-n_tokens);
  143. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  144. GGML_ASSERT(check == -n_tokens);
  145. } else {
  146. result.resize(n_tokens);
  147. }
  148. return result;
  149. }
  150. int32_t mtmd_tokenize(mtmd_context * ctx,
  151. std::vector<mtmd_input_chunk> & output,
  152. const mtmd_input_text & text,
  153. const std::vector<mtmd_bitmap> & bitmaps) {
  154. auto vocab = llama_model_get_vocab(ctx->text_model);
  155. std::string prompt_modified(text.text);
  156. std::string marker_modified(ctx->image_marker);
  157. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  158. // a bit hacky here, but works for now
  159. // for some models, we need to add prefix and suffix to the image embeddings
  160. if (clip_is_gemma3(ctx->ctx_clip)) {
  161. // gemma 3
  162. // <start_of_image> ... (image embeddings) ... <end_of_image>
  163. marker_modified = "<start_of_image>" + ctx->image_marker + "<end_of_image>";
  164. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  165. } else if (proj_type == PROJECTOR_TYPE_GLM_EDGE) {
  166. // <|begin_of_image|> ... (image embeddings) ... <|end_of_image|>
  167. marker_modified = "<|begin_of_image|>" + ctx->image_marker + "<|end_of_image|>";
  168. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  169. } else if (proj_type == PROJECTOR_TYPE_IDEFICS3) {
  170. // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
  171. marker_modified = "<fake_token_around_image><global-img>" + ctx->image_marker + "<fake_token_around_image>";
  172. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  173. } else if (proj_type == PROJECTOR_TYPE_PIXTRAL) {
  174. // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
  175. marker_modified = ctx->image_marker + "[IMG_END]";
  176. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  177. }
  178. // llava-1.5, llava-1.6, Yi-VL, Yi-34B, granite: don't need to add prefix and suffix
  179. // for glm-edge, we don't need to add because the tokens are already in the returned embeddings
  180. // TODO @ngxson : glm-edge : remove BOI / EOI tokens embeddings, decode them as normal tokens
  181. std::vector<std::string> parts = string_split_str(prompt_modified, ctx->image_marker);
  182. output.clear();
  183. output.reserve(parts.size());
  184. size_t i_img = 0;
  185. // utility for adding raw tokens
  186. auto add_text_chunk = [&output](std::vector<llama_token> && tokens) {
  187. mtmd_input_chunk chunk{
  188. MTMD_INPUT_CHUNK_TYPE_TEXT,
  189. std::move(tokens),
  190. {},
  191. };
  192. output.emplace_back(std::move(chunk));
  193. };
  194. // utility for splitting batch of multiple images into chunks of batch having single images
  195. auto split_batch_to_chunk = [&ctx](clip_image_f32_batch && batch_f32, const std::string & id) {
  196. std::vector<mtmd_input_chunk> chunks;
  197. for (auto & entry : batch_f32.entries) {
  198. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  199. image_tokens->nx = clip_n_patches_by_img(ctx->ctx_clip, entry.get());
  200. image_tokens->ny = 1;
  201. image_tokens->batch_f32.entries.push_back(std::move(entry));
  202. image_tokens->id = id;
  203. mtmd_input_chunk chunk{
  204. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  205. {},
  206. std::move(image_tokens),
  207. };
  208. chunks.emplace_back(std::move(chunk));
  209. }
  210. return chunks;
  211. };
  212. for (const auto & part : parts) {
  213. //printf("tokenizing part: %s\n", part.c_str());
  214. bool add_bos = &parts.front() == &part;
  215. auto tokens = mtmd_tokenize_text_internal(vocab, part, text.add_special && add_bos, text.parse_special);
  216. if (tokens.empty()) {
  217. continue;
  218. }
  219. mtmd_input_chunk chunk{
  220. MTMD_INPUT_CHUNK_TYPE_TEXT,
  221. std::move(tokens),
  222. {},
  223. };
  224. output.emplace_back(std::move(chunk));
  225. if (&parts.back() != &part) {
  226. // add image token to middle of 2 parts
  227. if (i_img >= bitmaps.size()) {
  228. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  229. return 1;
  230. }
  231. // convert mtmd_bitmap to clip_image_u8
  232. clip_image_u8_ptr img_u8(clip_image_u8_init());
  233. img_u8->nx = bitmaps[i_img].nx;
  234. img_u8->ny = bitmaps[i_img].ny;
  235. img_u8->buf.resize(bitmaps[i_img].data.size());
  236. std::memcpy(img_u8->buf.data(), bitmaps[i_img].data.data(), img_u8->nx * img_u8->ny * 3);
  237. clip_image_size img_u8_size{img_u8->nx, img_u8->ny};
  238. // preprocess image
  239. clip_image_f32_batch batch_f32;
  240. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), &batch_f32);
  241. if (!ok) {
  242. LOG_ERR("Unable to preprocess image\n");
  243. return 2;
  244. }
  245. if (ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5 || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6) {
  246. // split batch into chunks of single images
  247. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmaps[i_img].id);
  248. GGML_ASSERT(chunks.size() > 0);
  249. // add overview image
  250. add_text_chunk({ctx->tok_ov_img_start});
  251. output.emplace_back(std::move(chunks.front()));
  252. chunks.erase(chunks.begin());
  253. add_text_chunk({ctx->tok_ov_img_end});
  254. // add slices
  255. if (!chunks.empty()) {
  256. clip_add_load_image_size(ctx->ctx_clip, &img_u8_size);
  257. int n_col = clip_uhd_num_image_embeds_col(ctx->ctx_clip);
  258. int n_row = (int)chunks.size() / n_col;
  259. GGML_ASSERT(n_row * n_col == (int)chunks.size());
  260. if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
  261. add_text_chunk({ctx->tok_slices_start});
  262. }
  263. for (int y = 0; y < n_row; y++) {
  264. for (int x = 0; x < n_col; x++) {
  265. if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
  266. add_text_chunk({ctx->tok_sli_img_start});
  267. }
  268. output.emplace_back(std::move(chunks[y * n_col + x]));
  269. if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
  270. add_text_chunk({ctx->tok_sli_img_end});
  271. }
  272. }
  273. if (ctx->tok_row_end != LLAMA_TOKEN_NULL && y != n_row - 1) {
  274. add_text_chunk({ctx->tok_row_end});
  275. }
  276. }
  277. if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
  278. add_text_chunk({ctx->tok_slices_end});
  279. }
  280. }
  281. } else {
  282. size_t n_tokens = 0;
  283. for (const auto & entry : batch_f32.entries) {
  284. n_tokens += clip_n_patches_by_img(ctx->ctx_clip, entry.get());
  285. }
  286. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  287. image_tokens->nx = n_tokens;
  288. image_tokens->ny = 1; // TODO
  289. image_tokens->batch_f32 = std::move(batch_f32);
  290. image_tokens->id = bitmaps[i_img].id; // optional
  291. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  292. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  293. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  294. if (clip_is_glm(ctx->ctx_clip)) {
  295. // glm-edge
  296. image_tokens->nx += 2; // add 2 for the begin_of_image and end_of_image token embeddings
  297. }
  298. mtmd_input_chunk chunk{
  299. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  300. {},
  301. std::move(image_tokens),
  302. };
  303. output.emplace_back(std::move(chunk));
  304. }
  305. i_img++; // move to next image
  306. }
  307. }
  308. return 0;
  309. }
  310. void mtmd_image_tokens_free(mtmd_image_tokens * image_tokens) {
  311. if (image_tokens) {
  312. delete image_tokens;
  313. }
  314. }
  315. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  316. return image_tokens->n_tokens();
  317. }
  318. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  319. return image_tokens->nx;
  320. }
  321. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  322. return image_tokens->ny;
  323. }
  324. std::string mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  325. return image_tokens->id;
  326. }
  327. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  328. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  329. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  330. bool ok = false;
  331. // only effective for minicpmv and qwen2vl, other models will ignore load_image_size
  332. {
  333. clip_image_size slice_size{
  334. image_tokens->batch_f32.entries[0]->nx,
  335. image_tokens->batch_f32.entries[0]->ny};
  336. clip_add_load_image_size(ctx->ctx_clip, &slice_size);
  337. }
  338. if (clip_is_llava(ctx->ctx_clip) || clip_is_minicpmv(ctx->ctx_clip) || clip_is_glm(ctx->ctx_clip)) {
  339. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  340. const auto & entries = image_tokens->batch_f32.entries;
  341. for (size_t i = 0; i < entries.size(); i++) {
  342. int n_tokens_per_image = clip_n_patches_by_img(ctx->ctx_clip, entries[i].get());
  343. ok = clip_image_encode(
  344. ctx->ctx_clip,
  345. ctx->n_threads,
  346. entries[i].get(),
  347. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  348. }
  349. } else {
  350. ok = clip_image_batch_encode(
  351. ctx->ctx_clip,
  352. ctx->n_threads,
  353. &image_tokens->batch_f32,
  354. ctx->image_embd_v.data());
  355. }
  356. return ok ? 0 : 1;
  357. }
  358. float * mtmd_get_output_embd(mtmd_context * ctx) {
  359. return ctx->image_embd_v.data();
  360. }
  361. size_t mtmd_helper_get_n_tokens(mtmd_input_chunks & chunks) {
  362. size_t n_tokens = 0;
  363. for (auto & chunk : chunks) {
  364. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  365. n_tokens += chunk.tokens_text.size();
  366. } else if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  367. n_tokens += chunk.tokens_image->n_tokens();
  368. } else {
  369. GGML_ASSERT(false && "chunk type not supported");
  370. }
  371. }
  372. return n_tokens;
  373. }
  374. // helper struct to make working with embd batch easier
  375. // note: this will be removed after llama_batch_ext refactoring
  376. struct decode_embd_batch {
  377. std::vector<llama_pos> pos;
  378. std::vector<int32_t> n_seq_id;
  379. std::vector<llama_seq_id> seq_id_0;
  380. std::vector<llama_seq_id *> seq_ids;
  381. std::vector<int8_t> logits;
  382. llama_batch batch;
  383. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  384. pos .resize(n_tokens);
  385. n_seq_id.resize(n_tokens);
  386. seq_ids .resize(n_tokens + 1);
  387. logits .resize(n_tokens);
  388. seq_id_0.resize(1);
  389. seq_id_0[0] = seq_id;
  390. seq_ids [n_tokens] = nullptr;
  391. batch = {
  392. /*n_tokens =*/ n_tokens,
  393. /*tokens =*/ nullptr,
  394. /*embd =*/ embd,
  395. /*pos =*/ pos.data(),
  396. /*n_seq_id =*/ n_seq_id.data(),
  397. /*seq_id =*/ seq_ids.data(),
  398. /*logits =*/ logits.data(),
  399. };
  400. for (int i = 0; i < n_tokens; i++) {
  401. batch.pos [i] = pos_0 + i;
  402. batch.n_seq_id[i] = 1;
  403. batch.seq_id [i] = seq_id_0.data();
  404. batch.logits [i] = false;
  405. }
  406. }
  407. };
  408. int32_t mtmd_helper_eval(mtmd_context * ctx,
  409. llama_context * lctx,
  410. mtmd_input_chunks & chunks,
  411. llama_pos pos0,
  412. llama_seq_id seq_id,
  413. int32_t n_batch) {
  414. int32_t ret;
  415. llama_pos n_past = pos0;
  416. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  417. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  418. for (auto & chunk : chunks) {
  419. bool is_last = &chunk == &chunks.back();
  420. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  421. text_batch.n_tokens = chunk.tokens_text.size();
  422. size_t i = 0;
  423. while (i < chunk.tokens_text.size()) { // split into batches
  424. for (; i < chunk.tokens_text.size() && text_batch.n_tokens < n_batch; i++) {
  425. text_batch.token [i] = chunk.tokens_text[i];
  426. text_batch.pos [i] = n_past++;
  427. text_batch.n_seq_id[i] = 1;
  428. text_batch.seq_id [i][0] = seq_id;
  429. text_batch.logits [i] = false;
  430. }
  431. if (is_last) {
  432. // always get logits for last input chunk
  433. text_batch.logits[text_batch.n_tokens - 1] = true;
  434. }
  435. ret = llama_decode(lctx, text_batch);
  436. if (ret != 0) {
  437. LOG_ERR("failed to decode text\n");
  438. llama_batch_free(text_batch);
  439. return ret;
  440. }
  441. }
  442. } else if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  443. GGML_ASSERT(!is_last && "logits for last image chunk is not yet support");
  444. GGML_ASSERT(chunk.tokens_image != nullptr);
  445. int64_t t0 = ggml_time_ms();
  446. if (ctx->print_timings) {
  447. LOG_INF("encoding image or slice...\n");
  448. }
  449. ret = mtmd_encode(ctx, chunk.tokens_image.get());
  450. if (ret != 0) {
  451. LOG_ERR("failed to encode image\n");
  452. llama_batch_free(text_batch);
  453. return ret;
  454. }
  455. if (ctx->print_timings) {
  456. LOG_INF("image/slice encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  457. }
  458. int32_t n_tokens = mtmd_image_tokens_get_n_tokens(chunk.tokens_image.get());
  459. int32_t i_batch = 0;
  460. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  461. float * embd = mtmd_get_output_embd(ctx);
  462. if (mtmd_decode_use_non_causal(ctx)) {
  463. llama_set_causal_attn(lctx, false);
  464. // TODO @ngxson : need to make sure only one image is processed at a time, and n_ubatch must be enough to hold the image
  465. }
  466. while (i_batch < n_img_batches) { // split into batches
  467. int32_t pos_offset = i_batch*n_batch;
  468. int32_t n_tokens_batch = std::min(n_batch, n_tokens - pos_offset);
  469. float * embd_batch = embd + pos_offset*n_mmproj_embd;
  470. decode_embd_batch batch_img(embd_batch, n_tokens_batch, n_past, 0);
  471. printf("decoding image batch %d/%d, n_tokens_batch = %d\n", i_batch+1, n_img_batches, n_tokens_batch);
  472. int64_t t1 = ggml_time_ms();
  473. ret = llama_decode(lctx, batch_img.batch);
  474. if (ret != 0) {
  475. LOG_ERR("failed to decode image\n");
  476. llama_set_causal_attn(lctx, true); // restore causal attn
  477. llama_batch_free(text_batch);
  478. return ret;
  479. }
  480. if (ctx->print_timings) {
  481. LOG_INF("image decoded (batch %d/%d) in %" PRId64 " ms\n", i_batch+1, n_img_batches, ggml_time_ms() - t1);
  482. }
  483. i_batch++;
  484. n_past += n_tokens_batch;
  485. }
  486. if (mtmd_decode_use_non_causal(ctx)) {
  487. llama_set_causal_attn(lctx, true);
  488. }
  489. } else {
  490. GGML_ASSERT(false && "chunk type not supported");
  491. }
  492. }
  493. llama_batch_free(text_batch);
  494. return 0;
  495. }
  496. int32_t mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len, mtmd_bitmap & output) {
  497. clip_image_u8_ptr img_u8(clip_image_u8_init());
  498. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  499. if (!ok) {
  500. LOG_ERR("Unable to load image from buffer\n");
  501. return 1;
  502. }
  503. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &output.nx, &output.ny);
  504. output.data.resize(output.nx * output.ny * 3);
  505. std::memcpy(output.data.data(), data, output.nx * output.ny * 3);
  506. return 0;
  507. }
  508. int32_t mtmd_helper_bitmap_init_from_file(const char * fname, mtmd_bitmap & output) {
  509. clip_image_u8_ptr img_u8(clip_image_u8_init());
  510. bool ok = clip_image_load_from_file(fname, img_u8.get());
  511. if (!ok) {
  512. LOG_ERR("Unable to load image %s\n", fname);
  513. return 1;
  514. }
  515. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &output.nx, &output.ny);
  516. output.data.resize(output.nx * output.ny * 3);
  517. std::memcpy(output.data.data(), data, output.nx * output.ny * 3);
  518. return 0;
  519. }
  520. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  521. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  522. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  523. return true;
  524. }
  525. return false;
  526. }
  527. void mtmd_image_tokens_deleter::operator()(mtmd_image_tokens * val) {
  528. mtmd_image_tokens_free(val);
  529. }