mtmd.cpp 27 KB

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