mtmd.cpp 23 KB

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