mtmd.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. std::vector<std::string> parts = string_split_str(prompt_modified, ctx->image_marker);
  180. output.clear();
  181. output.reserve(parts.size());
  182. size_t i_img = 0;
  183. // utility for adding raw tokens
  184. auto add_text_chunk = [&output](std::vector<llama_token> && tokens) {
  185. mtmd_input_chunk chunk{
  186. MTMD_INPUT_CHUNK_TYPE_TEXT,
  187. std::move(tokens),
  188. {},
  189. };
  190. output.emplace_back(std::move(chunk));
  191. };
  192. // utility for splitting batch of multiple images into chunks of batch having single images
  193. auto split_batch_to_chunk = [&ctx](clip_image_f32_batch && batch_f32, const std::string & id) {
  194. std::vector<mtmd_input_chunk> chunks;
  195. for (auto & entry : batch_f32.entries) {
  196. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  197. image_tokens->nx = clip_n_patches_by_img(ctx->ctx_clip, entry.get());
  198. image_tokens->ny = 1;
  199. image_tokens->batch_f32.entries.push_back(std::move(entry));
  200. image_tokens->id = id;
  201. mtmd_input_chunk chunk{
  202. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  203. {},
  204. std::move(image_tokens),
  205. };
  206. chunks.emplace_back(std::move(chunk));
  207. }
  208. return chunks;
  209. };
  210. for (const auto & part : parts) {
  211. // printf("tokenizing part: %s\n", part.c_str());
  212. bool add_bos = &parts.front() == &part;
  213. auto tokens = mtmd_tokenize_text_internal(vocab, part, text.add_special && add_bos, text.parse_special);
  214. if (tokens.empty()) {
  215. continue;
  216. }
  217. mtmd_input_chunk chunk{
  218. MTMD_INPUT_CHUNK_TYPE_TEXT,
  219. std::move(tokens),
  220. {},
  221. };
  222. output.emplace_back(std::move(chunk));
  223. if (&parts.back() != &part) {
  224. // add image token to middle of 2 parts
  225. if (i_img >= bitmaps.size()) {
  226. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  227. return 1;
  228. }
  229. // convert mtmd_bitmap to clip_image_u8
  230. clip_image_u8_ptr img_u8(clip_image_u8_init());
  231. img_u8->nx = bitmaps[i_img].nx;
  232. img_u8->ny = bitmaps[i_img].ny;
  233. img_u8->buf.resize(bitmaps[i_img].data.size());
  234. std::memcpy(img_u8->buf.data(), bitmaps[i_img].data.data(), img_u8->nx * img_u8->ny * 3);
  235. clip_image_size img_u8_size{img_u8->nx, img_u8->ny};
  236. // preprocess image
  237. clip_image_f32_batch batch_f32;
  238. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), &batch_f32);
  239. if (!ok) {
  240. LOG_ERR("Unable to preprocess image\n");
  241. return 2;
  242. }
  243. if (ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5 || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6) {
  244. // split batch into chunks of single images
  245. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmaps[i_img].id);
  246. GGML_ASSERT(chunks.size() > 0);
  247. // add overview image
  248. add_text_chunk({ctx->tok_ov_img_start});
  249. output.emplace_back(std::move(chunks.front()));
  250. chunks.erase(chunks.begin());
  251. add_text_chunk({ctx->tok_ov_img_end});
  252. // add slices
  253. if (!chunks.empty()) {
  254. clip_add_load_image_size(ctx->ctx_clip, &img_u8_size);
  255. int n_col = clip_uhd_num_image_embeds_col(ctx->ctx_clip);
  256. int n_row = (int)chunks.size() / n_col;
  257. GGML_ASSERT(n_row * n_col == (int)chunks.size());
  258. if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
  259. add_text_chunk({ctx->tok_slices_start});
  260. }
  261. for (int y = 0; y < n_row; y++) {
  262. for (int x = 0; x < n_col; x++) {
  263. if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
  264. add_text_chunk({ctx->tok_sli_img_start});
  265. }
  266. output.emplace_back(std::move(chunks[y * n_col + x]));
  267. if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
  268. add_text_chunk({ctx->tok_sli_img_end});
  269. }
  270. }
  271. if (ctx->tok_row_end != LLAMA_TOKEN_NULL && y != n_row - 1) {
  272. add_text_chunk({ctx->tok_row_end});
  273. }
  274. }
  275. if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
  276. add_text_chunk({ctx->tok_slices_end});
  277. }
  278. }
  279. } else {
  280. size_t n_tokens = 0;
  281. for (const auto & entry : batch_f32.entries) {
  282. n_tokens += clip_n_patches_by_img(ctx->ctx_clip, entry.get());
  283. }
  284. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  285. image_tokens->nx = n_tokens;
  286. image_tokens->ny = 1; // TODO
  287. image_tokens->batch_f32 = std::move(batch_f32);
  288. image_tokens->id = bitmaps[i_img].id; // optional
  289. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  290. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  291. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  292. mtmd_input_chunk chunk{
  293. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  294. {},
  295. std::move(image_tokens),
  296. };
  297. output.emplace_back(std::move(chunk));
  298. }
  299. i_img++; // move to next image
  300. }
  301. }
  302. return 0;
  303. }
  304. void mtmd_image_tokens_free(mtmd_image_tokens * image_tokens) {
  305. if (image_tokens) {
  306. delete image_tokens;
  307. }
  308. }
  309. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  310. return image_tokens->n_tokens();
  311. }
  312. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  313. return image_tokens->nx;
  314. }
  315. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  316. return image_tokens->ny;
  317. }
  318. std::string mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  319. return image_tokens->id;
  320. }
  321. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  322. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  323. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  324. bool ok = false;
  325. // only effective for minicpmv and qwen2vl, other models will ignore load_image_size
  326. {
  327. clip_image_size slice_size{
  328. image_tokens->batch_f32.entries[0]->nx,
  329. image_tokens->batch_f32.entries[0]->ny};
  330. clip_add_load_image_size(ctx->ctx_clip, &slice_size);
  331. }
  332. if (clip_is_llava(ctx->ctx_clip) || clip_is_minicpmv(ctx->ctx_clip) || clip_is_glm(ctx->ctx_clip)) {
  333. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  334. const auto & entries = image_tokens->batch_f32.entries;
  335. for (size_t i = 0; i < entries.size(); i++) {
  336. int n_tokens_per_image = clip_n_patches_by_img(ctx->ctx_clip, entries[i].get());
  337. ok = clip_image_encode(
  338. ctx->ctx_clip,
  339. ctx->n_threads,
  340. entries[i].get(),
  341. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  342. }
  343. } else {
  344. ok = clip_image_batch_encode(
  345. ctx->ctx_clip,
  346. ctx->n_threads,
  347. &image_tokens->batch_f32,
  348. ctx->image_embd_v.data());
  349. }
  350. return ok ? 0 : 1;
  351. }
  352. float * mtmd_get_output_embd(mtmd_context * ctx) {
  353. return ctx->image_embd_v.data();
  354. }
  355. size_t mtmd_helper_get_n_tokens(mtmd_input_chunks & chunks) {
  356. size_t n_tokens = 0;
  357. for (auto & chunk : chunks) {
  358. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  359. n_tokens += chunk.tokens_text.size();
  360. } else if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  361. n_tokens += chunk.tokens_image->n_tokens();
  362. } else {
  363. GGML_ASSERT(false && "chunk type not supported");
  364. }
  365. }
  366. return n_tokens;
  367. }
  368. // helper struct to make working with embd batch easier
  369. // note: this will be removed after llama_batch_ext refactoring
  370. struct decode_embd_batch {
  371. std::vector<llama_pos> pos;
  372. std::vector<int32_t> n_seq_id;
  373. std::vector<llama_seq_id> seq_id_0;
  374. std::vector<llama_seq_id *> seq_ids;
  375. std::vector<int8_t> logits;
  376. llama_batch batch;
  377. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  378. pos .resize(n_tokens);
  379. n_seq_id.resize(n_tokens);
  380. seq_ids .resize(n_tokens + 1);
  381. logits .resize(n_tokens);
  382. seq_id_0.resize(1);
  383. seq_id_0[0] = seq_id;
  384. seq_ids [n_tokens] = nullptr;
  385. batch = {
  386. /*n_tokens =*/ n_tokens,
  387. /*tokens =*/ nullptr,
  388. /*embd =*/ embd,
  389. /*pos =*/ pos.data(),
  390. /*n_seq_id =*/ n_seq_id.data(),
  391. /*seq_id =*/ seq_ids.data(),
  392. /*logits =*/ logits.data(),
  393. };
  394. for (int i = 0; i < n_tokens; i++) {
  395. batch.pos [i] = pos_0 + i;
  396. batch.n_seq_id[i] = 1;
  397. batch.seq_id [i] = seq_id_0.data();
  398. batch.logits [i] = false;
  399. }
  400. }
  401. };
  402. int32_t mtmd_helper_eval(mtmd_context * ctx,
  403. llama_context * lctx,
  404. mtmd_input_chunks & chunks,
  405. llama_pos pos0,
  406. llama_seq_id seq_id,
  407. int32_t n_batch) {
  408. int32_t ret;
  409. llama_pos n_past = pos0;
  410. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  411. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  412. for (auto & chunk : chunks) {
  413. bool is_last = &chunk == &chunks.back();
  414. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  415. text_batch.n_tokens = chunk.tokens_text.size();
  416. size_t i = 0;
  417. while (i < chunk.tokens_text.size()) { // split into batches
  418. for (; i < chunk.tokens_text.size() && text_batch.n_tokens < n_batch; i++) {
  419. text_batch.token [i] = chunk.tokens_text[i];
  420. text_batch.pos [i] = n_past++;
  421. text_batch.n_seq_id[i] = 1;
  422. text_batch.seq_id [i][0] = seq_id;
  423. text_batch.logits [i] = false;
  424. }
  425. if (is_last) {
  426. // always get logits for last input chunk
  427. text_batch.logits[text_batch.n_tokens - 1] = true;
  428. }
  429. ret = llama_decode(lctx, text_batch);
  430. if (ret != 0) {
  431. LOG_ERR("failed to decode text\n");
  432. llama_batch_free(text_batch);
  433. return ret;
  434. }
  435. }
  436. } else if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  437. GGML_ASSERT(!is_last && "logits for last image chunk is not yet support");
  438. GGML_ASSERT(chunk.tokens_image != nullptr);
  439. int64_t t0 = ggml_time_ms();
  440. if (ctx->print_timings) {
  441. LOG_INF("encoding image or slice...\n");
  442. }
  443. ret = mtmd_encode(ctx, chunk.tokens_image.get());
  444. if (ret != 0) {
  445. LOG_ERR("failed to encode image\n");
  446. llama_batch_free(text_batch);
  447. return ret;
  448. }
  449. if (ctx->print_timings) {
  450. LOG_INF("image/slice encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  451. }
  452. int32_t n_tokens = mtmd_image_tokens_get_n_tokens(chunk.tokens_image.get());
  453. int32_t i_batch = 0;
  454. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  455. float * embd = mtmd_get_output_embd(ctx);
  456. if (mtmd_decode_use_non_causal(ctx)) {
  457. llama_set_causal_attn(lctx, false);
  458. // TODO @ngxson : need to make sure only one image is processed at a time, and n_ubatch must be enough to hold the image
  459. }
  460. while (i_batch < n_img_batches) { // split into batches
  461. int32_t pos_offset = i_batch*n_batch;
  462. int32_t n_tokens_batch = std::min(n_batch, n_tokens - pos_offset);
  463. float * embd_batch = embd + pos_offset*n_mmproj_embd;
  464. decode_embd_batch batch_img(embd_batch, n_tokens_batch, n_past, 0);
  465. printf("decoding image batch %d/%d, n_tokens_batch = %d\n", i_batch+1, n_img_batches, n_tokens_batch);
  466. int64_t t1 = ggml_time_ms();
  467. ret = llama_decode(lctx, batch_img.batch);
  468. if (ret != 0) {
  469. LOG_ERR("failed to decode image\n");
  470. llama_set_causal_attn(lctx, true); // restore causal attn
  471. llama_batch_free(text_batch);
  472. return ret;
  473. }
  474. if (ctx->print_timings) {
  475. LOG_INF("image decoded (batch %d/%d) in %" PRId64 " ms\n", i_batch+1, n_img_batches, ggml_time_ms() - t1);
  476. }
  477. i_batch++;
  478. n_past += n_tokens_batch;
  479. }
  480. if (mtmd_decode_use_non_causal(ctx)) {
  481. llama_set_causal_attn(lctx, true);
  482. }
  483. } else {
  484. GGML_ASSERT(false && "chunk type not supported");
  485. }
  486. }
  487. llama_batch_free(text_batch);
  488. return 0;
  489. }
  490. int32_t mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len, mtmd_bitmap & output) {
  491. clip_image_u8_ptr img_u8(clip_image_u8_init());
  492. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  493. if (!ok) {
  494. LOG_ERR("Unable to load image from buffer\n");
  495. return 1;
  496. }
  497. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &output.nx, &output.ny);
  498. output.data.resize(output.nx * output.ny * 3);
  499. std::memcpy(output.data.data(), data, output.nx * output.ny * 3);
  500. return 0;
  501. }
  502. int32_t mtmd_helper_bitmap_init_from_file(const char * fname, mtmd_bitmap & output) {
  503. clip_image_u8_ptr img_u8(clip_image_u8_init());
  504. bool ok = clip_image_load_from_file(fname, img_u8.get());
  505. if (!ok) {
  506. LOG_ERR("Unable to load image %s\n", fname);
  507. return 1;
  508. }
  509. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &output.nx, &output.ny);
  510. output.data.resize(output.nx * output.ny * 3);
  511. std::memcpy(output.data.data(), data, output.nx * output.ny * 3);
  512. return 0;
  513. }
  514. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  515. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  516. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  517. return true;
  518. }
  519. return false;
  520. }
  521. void mtmd_image_tokens_deleter::operator()(mtmd_image_tokens * val) {
  522. mtmd_image_tokens_free(val);
  523. }