mtmd.cpp 23 KB

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