1
0

mtmd.cpp 28 KB

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