mtmd.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. // represents raw image data, layout is RGBRGBRGB...
  13. // length of data must be nx * ny * 3
  14. struct mtmd_bitmap {
  15. uint32_t nx;
  16. uint32_t ny;
  17. std::vector<unsigned char> data;
  18. std::string id; // optional user-defined id, for ex: can be set to image hash, useful for KV cache tracking
  19. };
  20. struct mtmd_image_tokens_deleter {
  21. void operator()(mtmd_image_tokens * val); // forward declaration
  22. };
  23. using mtmd_image_tokens_ptr = std::unique_ptr<mtmd_image_tokens, mtmd_image_tokens_deleter>;
  24. struct mtmd_input_chunk {
  25. mtmd_input_chunk_type type;
  26. std::vector<llama_token> tokens_text;
  27. mtmd_image_tokens_ptr tokens_image;
  28. };
  29. struct mtmd_input_chunks {
  30. std::vector<mtmd_input_chunk> entries;
  31. };
  32. // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
  33. // models not having it (llava-1.6) will process embeddings without any special tokens in-between
  34. enum mtmd_slice_tmpl {
  35. MTMD_SLICE_TMPL_NONE,
  36. MTMD_SLICE_TMPL_MINICPMV_2_5,
  37. MTMD_SLICE_TMPL_MINICPMV_2_6,
  38. // TODO @ngxson : add support for idefics (SmolVLM)
  39. };
  40. mtmd_context_params mtmd_context_params_default() {
  41. mtmd_context_params params;
  42. params.use_gpu = true;
  43. params.print_timings = true;
  44. params.n_threads = 4;
  45. params.verbosity = GGML_LOG_LEVEL_INFO;
  46. params.image_marker = MTMD_DEFAULT_IMAGE_MARKER;
  47. return params;
  48. }
  49. struct mtmd_context {
  50. struct clip_ctx * ctx_clip;
  51. const struct llama_model * text_model;
  52. std::vector<float> image_embd_v; // image embedding vector
  53. bool print_timings;
  54. int n_threads;
  55. std::string image_marker;
  56. // for minicpmv, we need special tokens in-between slices
  57. mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
  58. llama_token tok_ov_img_start = LLAMA_TOKEN_NULL; // overview image
  59. llama_token tok_ov_img_end = LLAMA_TOKEN_NULL; // overview image
  60. llama_token tok_slices_start = LLAMA_TOKEN_NULL; // start of all slices
  61. llama_token tok_slices_end = LLAMA_TOKEN_NULL; // end of all slices
  62. llama_token tok_sli_img_start = LLAMA_TOKEN_NULL; // single slice
  63. llama_token tok_sli_img_end = LLAMA_TOKEN_NULL; // single slice
  64. llama_token tok_row_end = LLAMA_TOKEN_NULL; // end of row
  65. bool use_mrope = false; // for Qwen2VL, we need to use M-RoPE
  66. // TODO @ngxson : add timings
  67. mtmd_context(const char * mmproj_fname,
  68. const llama_model * text_model,
  69. const mtmd_context_params & ctx_params) :
  70. text_model (text_model),
  71. print_timings(ctx_params.print_timings),
  72. n_threads (ctx_params.n_threads),
  73. image_marker (ctx_params.image_marker)
  74. {
  75. clip_context_params ctx_clip_params;
  76. ctx_clip_params.use_gpu = ctx_params.use_gpu;
  77. ctx_clip_params.verbosity = ctx_params.verbosity;
  78. ctx_clip = clip_init(mmproj_fname, ctx_clip_params);
  79. if (!ctx_clip) {
  80. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  81. }
  82. use_mrope = clip_is_qwen2vl(ctx_clip);
  83. int minicpmv_version = clip_is_minicpmv(ctx_clip);
  84. if (minicpmv_version == 2) {
  85. // minicpmv 2.5 format:
  86. // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
  87. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
  88. tok_ov_img_start = lookup_token("<image>");
  89. tok_ov_img_end = lookup_token("</image>");
  90. tok_slices_start = lookup_token("<slice>");
  91. tok_slices_end = lookup_token("</slice>");
  92. tok_sli_img_start = tok_ov_img_start;
  93. tok_sli_img_end = tok_ov_img_end;
  94. tok_row_end = lookup_token("\n");
  95. } else if (minicpmv_version == 3 || minicpmv_version == 4) {
  96. // minicpmv 2.6 format:
  97. // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
  98. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
  99. tok_ov_img_start = lookup_token("<image>");
  100. tok_ov_img_end = lookup_token("</image>");
  101. tok_sli_img_start = lookup_token("<slice>");
  102. tok_sli_img_end = lookup_token("</slice>");
  103. tok_row_end = lookup_token("\n");
  104. } else if (minicpmv_version != 0) {
  105. GGML_ASSERT(false && "unsupported minicpmv version");
  106. }
  107. }
  108. ~mtmd_context() {
  109. clip_free(ctx_clip);
  110. }
  111. private:
  112. llama_token lookup_token(const std::string & token_text) {
  113. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  114. const int n_vocab = llama_vocab_n_tokens(vocab);
  115. for (int i = 0; i < n_vocab; i++) {
  116. if (token_to_piece(vocab, i, true) == token_text) {
  117. return i;
  118. }
  119. }
  120. return LLAMA_TOKEN_NULL;
  121. }
  122. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  123. std::string piece;
  124. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  125. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  126. if (n_chars < 0) {
  127. piece.resize(-n_chars);
  128. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  129. GGML_ASSERT(check == -n_chars);
  130. } else {
  131. piece.resize(n_chars);
  132. }
  133. return piece;
  134. }
  135. };
  136. struct mtmd_image_tokens_data {
  137. clip_image_f32_batch batch_f32; // preprocessed image patches
  138. };
  139. struct mtmd_image_tokens {
  140. uint32_t nx; // number of tokens in x direction
  141. uint32_t ny; // number of tokens in y direction
  142. bool use_mrope_pos = false; // use M-RoPE position counting (the whole image is 1 temporal position)
  143. uint32_t n_tokens() const { return nx * ny; }
  144. clip_image_f32_batch batch_f32; // preprocessed image patches
  145. std::string id; // optional user-defined ID, useful for KV cache tracking
  146. mtmd_image_tokens clone() {
  147. return mtmd_image_tokens{
  148. nx,
  149. ny,
  150. use_mrope_pos,
  151. batch_f32.clone(),
  152. id
  153. };
  154. }
  155. };
  156. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  157. const struct llama_model * text_model,
  158. const struct mtmd_context_params ctx_params) {
  159. try {
  160. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  161. } catch (const std::exception & e) {
  162. LOG_ERR("%s: error: %s\n", __func__, e.what());
  163. return nullptr;
  164. }
  165. }
  166. void mtmd_free(mtmd_context * ctx) {
  167. if (ctx) {
  168. delete ctx;
  169. }
  170. }
  171. // copied from common_tokenize
  172. static std::vector<llama_token> mtmd_tokenize_text_internal(
  173. const struct llama_vocab * vocab,
  174. const std::string & text,
  175. bool add_special,
  176. bool parse_special) {
  177. // upper limit for the number of tokens
  178. int n_tokens = text.length() + 2 * add_special;
  179. std::vector<llama_token> result(n_tokens);
  180. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  181. if (n_tokens < 0) {
  182. result.resize(-n_tokens);
  183. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  184. GGML_ASSERT(check == -n_tokens);
  185. } else {
  186. result.resize(n_tokens);
  187. }
  188. return result;
  189. }
  190. int32_t mtmd_tokenize(mtmd_context * ctx,
  191. mtmd_input_chunks * output,
  192. const mtmd_input_text * text,
  193. const mtmd_bitmap ** bitmaps,
  194. size_t n_bitmaps) {
  195. auto vocab = llama_model_get_vocab(ctx->text_model);
  196. std::string prompt_modified(text->text);
  197. std::string marker_modified(ctx->image_marker);
  198. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  199. // a bit hacky here, but works for now
  200. // for some models, we need to add prefix and suffix to the image embeddings
  201. if (clip_is_gemma3(ctx->ctx_clip)) {
  202. // gemma 3
  203. // <start_of_image> ... (image embeddings) ... <end_of_image>
  204. marker_modified = "<start_of_image>" + ctx->image_marker + "<end_of_image>";
  205. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  206. } else if (proj_type == PROJECTOR_TYPE_IDEFICS3) {
  207. // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
  208. marker_modified = "<fake_token_around_image><global-img>" + ctx->image_marker + "<fake_token_around_image>";
  209. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  210. } else if (proj_type == PROJECTOR_TYPE_PIXTRAL) {
  211. // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
  212. marker_modified = ctx->image_marker + "[IMG_END]";
  213. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  214. }
  215. else if (proj_type == PROJECTOR_TYPE_QWEN2VL || proj_type == PROJECTOR_TYPE_QWEN25VL) {
  216. // <|vision_start|> ... (image embeddings) ... <|vision_end|>
  217. marker_modified = "<|vision_start|>" + ctx->image_marker + "<|vision_end|>";
  218. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  219. }
  220. // llava-1.5, llava-1.6, Yi-VL, Yi-34B, granite: don't need to add prefix and suffix
  221. // for glm-edge, BOI and EOI token's embeddings are not present in the text model
  222. std::vector<std::string> parts = string_split_str(prompt_modified, ctx->image_marker);
  223. output->entries.clear();
  224. output->entries.reserve(parts.size());
  225. size_t i_img = 0;
  226. // utility for adding raw tokens
  227. auto add_text_chunk = [&output](std::vector<llama_token> && tokens) {
  228. mtmd_input_chunk chunk{
  229. MTMD_INPUT_CHUNK_TYPE_TEXT,
  230. std::move(tokens),
  231. {},
  232. };
  233. output->entries.emplace_back(std::move(chunk));
  234. };
  235. // utility for splitting batch of multiple images into chunks of batch having single images
  236. auto split_batch_to_chunk = [&ctx](clip_image_f32_batch && batch_f32, const std::string & id) {
  237. std::vector<mtmd_input_chunk> chunks;
  238. for (auto & entry : batch_f32.entries) {
  239. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  240. image_tokens->nx = clip_n_output_tokens(ctx->ctx_clip, entry.get());
  241. image_tokens->ny = 1;
  242. image_tokens->batch_f32.entries.push_back(std::move(entry));
  243. image_tokens->id = id;
  244. mtmd_input_chunk chunk{
  245. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  246. {},
  247. std::move(image_tokens),
  248. };
  249. chunks.emplace_back(std::move(chunk));
  250. }
  251. return chunks;
  252. };
  253. for (const auto & part : parts) {
  254. // printf("tokenizing part: %s\n", part.c_str());
  255. bool add_bos = &parts.front() == &part;
  256. auto tokens = mtmd_tokenize_text_internal(vocab, part, text->add_special && add_bos, text->parse_special);
  257. if (tokens.empty()) {
  258. continue;
  259. }
  260. mtmd_input_chunk chunk{
  261. MTMD_INPUT_CHUNK_TYPE_TEXT,
  262. std::move(tokens),
  263. {},
  264. };
  265. output->entries.emplace_back(std::move(chunk));
  266. if (&parts.back() != &part) {
  267. // add image token to middle of 2 parts
  268. if (i_img >= n_bitmaps) {
  269. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  270. return 1;
  271. }
  272. // convert mtmd_bitmap to clip_image_u8
  273. clip_image_u8_ptr img_u8(clip_image_u8_init());
  274. img_u8->nx = bitmaps[i_img]->nx;
  275. img_u8->ny = bitmaps[i_img]->ny;
  276. img_u8->buf.resize(bitmaps[i_img]->data.size());
  277. std::memcpy(img_u8->buf.data(), bitmaps[i_img]->data.data(), img_u8->nx * img_u8->ny * 3);
  278. clip_image_size img_u8_size{img_u8->nx, img_u8->ny};
  279. // preprocess image
  280. clip_image_f32_batch batch_f32;
  281. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), &batch_f32);
  282. if (!ok) {
  283. LOG_ERR("Unable to preprocess image\n");
  284. return 2;
  285. }
  286. if (ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5 || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6) {
  287. // split batch into chunks of single images
  288. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmaps[i_img]->id);
  289. GGML_ASSERT(chunks.size() > 0);
  290. // add overview image
  291. add_text_chunk({ctx->tok_ov_img_start});
  292. output->entries.emplace_back(std::move(chunks.front()));
  293. chunks.erase(chunks.begin());
  294. add_text_chunk({ctx->tok_ov_img_end});
  295. // add slices
  296. if (!chunks.empty()) {
  297. clip_add_load_image_size(ctx->ctx_clip, &img_u8_size);
  298. int n_col = clip_uhd_num_image_embeds_col(ctx->ctx_clip);
  299. int n_row = (int)chunks.size() / n_col;
  300. GGML_ASSERT(n_row * n_col == (int)chunks.size());
  301. if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
  302. add_text_chunk({ctx->tok_slices_start});
  303. }
  304. for (int y = 0; y < n_row; y++) {
  305. for (int x = 0; x < n_col; x++) {
  306. if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
  307. add_text_chunk({ctx->tok_sli_img_start});
  308. }
  309. output->entries.emplace_back(std::move(chunks[y * n_col + x]));
  310. if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
  311. add_text_chunk({ctx->tok_sli_img_end});
  312. }
  313. }
  314. if (ctx->tok_row_end != LLAMA_TOKEN_NULL && y != n_row - 1) {
  315. add_text_chunk({ctx->tok_row_end});
  316. }
  317. }
  318. if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
  319. add_text_chunk({ctx->tok_slices_end});
  320. }
  321. }
  322. } else {
  323. size_t n_tokens = 0;
  324. for (const auto & entry : batch_f32.entries) {
  325. n_tokens += clip_n_output_tokens(ctx->ctx_clip, entry.get());
  326. }
  327. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  328. if (ctx->use_mrope) {
  329. // for Qwen2VL, we need this information for M-RoPE decoding positions
  330. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_clip, batch_f32.entries[0].get());
  331. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_clip, batch_f32.entries[0].get());
  332. image_tokens->use_mrope_pos = true;
  333. } else {
  334. // other models, we only need the total number of tokens
  335. image_tokens->nx = n_tokens;
  336. image_tokens->ny = 1;
  337. }
  338. image_tokens->batch_f32 = std::move(batch_f32);
  339. image_tokens->id = bitmaps[i_img]->id; // optional
  340. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  341. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  342. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  343. mtmd_input_chunk chunk{
  344. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  345. {},
  346. std::move(image_tokens),
  347. };
  348. output->entries.emplace_back(std::move(chunk));
  349. }
  350. i_img++; // move to next image
  351. }
  352. }
  353. return 0;
  354. }
  355. static void mtmd_image_tokens_free(mtmd_image_tokens * image_tokens) {
  356. if (image_tokens) {
  357. delete image_tokens;
  358. }
  359. }
  360. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  361. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  362. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  363. bool ok = false;
  364. // only effective for minicpmv and qwen2vl, other models will ignore load_image_size
  365. {
  366. clip_image_size slice_size{
  367. image_tokens->batch_f32.entries[0]->nx,
  368. image_tokens->batch_f32.entries[0]->ny};
  369. clip_add_load_image_size(ctx->ctx_clip, &slice_size);
  370. }
  371. if (clip_is_llava(ctx->ctx_clip) || clip_is_minicpmv(ctx->ctx_clip) || clip_is_glm(ctx->ctx_clip)) {
  372. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  373. const auto & entries = image_tokens->batch_f32.entries;
  374. for (size_t i = 0; i < entries.size(); i++) {
  375. int n_tokens_per_image = clip_n_output_tokens(ctx->ctx_clip, entries[i].get());
  376. ok = clip_image_encode(
  377. ctx->ctx_clip,
  378. ctx->n_threads,
  379. entries[i].get(),
  380. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  381. }
  382. } else {
  383. ok = clip_image_batch_encode(
  384. ctx->ctx_clip,
  385. ctx->n_threads,
  386. &image_tokens->batch_f32,
  387. ctx->image_embd_v.data());
  388. }
  389. return ok ? 0 : 1;
  390. }
  391. float * mtmd_get_output_embd(mtmd_context * ctx) {
  392. return ctx->image_embd_v.data();
  393. }
  394. size_t mtmd_helper_get_n_tokens(const mtmd_input_chunks * chunks) {
  395. size_t n_tokens = 0;
  396. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  397. auto chunk = mtmd_input_chunks_get(chunks, i);
  398. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  399. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  400. size_t n_tokens_text;
  401. mtmd_input_chunk_get_tokens_text(chunk, &n_tokens_text);
  402. n_tokens += n_tokens_text;
  403. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  404. auto tokens_image = mtmd_input_chunk_get_tokens_image(chunk);
  405. n_tokens += mtmd_image_tokens_get_n_tokens(tokens_image);
  406. } else {
  407. GGML_ASSERT(false && "chunk type not supported");
  408. }
  409. }
  410. return n_tokens;
  411. }
  412. llama_pos mtmd_helper_get_n_pos(const mtmd_input_chunks * chunks) {
  413. llama_pos n_pos = 0;
  414. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  415. auto chunk = mtmd_input_chunks_get(chunks, i);
  416. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  417. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  418. size_t n_tokens_text;
  419. mtmd_input_chunk_get_tokens_text(chunk, &n_tokens_text);
  420. n_pos += n_tokens_text;
  421. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  422. auto tokens_image = mtmd_input_chunk_get_tokens_image(chunk);
  423. n_pos += mtmd_image_tokens_get_n_pos(tokens_image);
  424. } else {
  425. GGML_ASSERT(false && "chunk type not supported");
  426. }
  427. }
  428. return n_pos;
  429. }
  430. // helper struct to make working with embd batch easier
  431. // note: this will be removed after llama_batch_ext refactoring
  432. struct decode_embd_batch {
  433. int n_pos_per_embd;
  434. int n_mmproj_embd;
  435. std::vector<llama_pos> pos;
  436. std::vector<llama_pos> pos_view; // used by mrope
  437. std::vector<int32_t> n_seq_id;
  438. std::vector<llama_seq_id> seq_id_0;
  439. std::vector<llama_seq_id *> seq_ids;
  440. std::vector<int8_t> logits;
  441. llama_batch batch;
  442. 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) {
  443. pos .resize(n_tokens * n_pos_per_embd);
  444. n_seq_id.resize(n_tokens);
  445. seq_ids .resize(n_tokens + 1);
  446. logits .resize(n_tokens);
  447. seq_id_0.resize(1);
  448. seq_ids [n_tokens] = nullptr;
  449. batch = {
  450. /*n_tokens =*/ n_tokens,
  451. /*tokens =*/ nullptr,
  452. /*embd =*/ embd,
  453. /*pos =*/ pos.data(),
  454. /*n_seq_id =*/ n_seq_id.data(),
  455. /*seq_id =*/ seq_ids.data(),
  456. /*logits =*/ logits.data(),
  457. };
  458. }
  459. void set_position_normal(llama_pos pos_0, llama_seq_id seq_id) {
  460. seq_id_0[0] = seq_id;
  461. for (int i = 0; i < batch.n_tokens; i++) {
  462. batch.pos [i] = pos_0 + i;
  463. batch.n_seq_id[i] = 1;
  464. batch.seq_id [i] = seq_id_0.data();
  465. batch.logits [i] = false;
  466. }
  467. }
  468. void set_position_mrope(llama_pos pos_0, int nx, int ny, llama_seq_id seq_id) {
  469. GGML_ASSERT(n_pos_per_embd == 4);
  470. seq_id_0[0] = seq_id;
  471. for (int y = 0; y < ny; y++) {
  472. for (int x = 0; x < nx; x++) {
  473. int i = y * nx + x;
  474. pos[i ] = pos_0;
  475. pos[i + batch.n_tokens ] = pos_0 + y;
  476. pos[i + batch.n_tokens * 2] = pos_0 + x;
  477. pos[i + batch.n_tokens * 3] = 0; // last pos dim is unused
  478. }
  479. }
  480. for (int i = 0; i < batch.n_tokens; i++) {
  481. batch.n_seq_id[i] = 1;
  482. batch.seq_id [i] = seq_id_0.data();
  483. batch.logits [i] = false;
  484. }
  485. }
  486. llama_batch get_view(int offset, int n_tokens) {
  487. llama_pos * pos_ptr;
  488. pos_view.clear();
  489. pos_view.resize(n_tokens * n_pos_per_embd);
  490. if (n_pos_per_embd > 1) {
  491. // mrope
  492. // for example, with layout of src: 1234...1234...1234...1234...
  493. // offset 2 will give us dst: 34...34...34...34...
  494. for (int i = 0; i < n_pos_per_embd; i++) {
  495. auto src = pos.begin() + i * batch.n_tokens + offset;
  496. pos_view.insert(pos_view.end(), src, src + n_tokens);
  497. }
  498. pos_ptr = pos_view.data();
  499. } else {
  500. // normal
  501. pos_ptr = pos.data() + offset;
  502. }
  503. return {
  504. /*n_tokens =*/ n_tokens,
  505. /*tokens =*/ nullptr,
  506. /*embd =*/ batch.embd + offset * n_mmproj_embd,
  507. /*pos =*/ pos_ptr,
  508. /*n_seq_id =*/ batch.n_seq_id + offset,
  509. /*seq_id =*/ batch.seq_id + offset,
  510. /*logits =*/ batch.logits + offset,
  511. };
  512. }
  513. };
  514. // Helper function for decoding an image whose embeddings have already been calculated
  515. int32_t mtmd_helper_decode_image_chunk(
  516. mtmd_context * ctx,
  517. struct llama_context * lctx,
  518. const mtmd_input_chunk * chunk,
  519. float * encoded_embd,
  520. llama_pos n_past,
  521. llama_seq_id seq_id,
  522. int32_t n_batch,
  523. llama_pos * new_n_past) {
  524. if (mtmd_input_chunk_get_type(chunk) != MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  525. LOG_ERR("failed to decode image chunk: input chunk not of image type\n");
  526. return -1;
  527. }
  528. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  529. if (!image_tokens) {
  530. LOG_ERR("failed to decode image chunk: image tokens are null\n");
  531. return -1;
  532. }
  533. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  534. int n_pos_per_embd = mtmd_decode_use_mrope(ctx) ? 4 : 1;
  535. int32_t n_tokens = mtmd_image_tokens_get_n_tokens(image_tokens);
  536. int32_t i_batch = 0;
  537. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  538. decode_embd_batch batch_embd(encoded_embd, n_tokens, n_pos_per_embd, n_mmproj_embd);
  539. const int nx = mtmd_image_tokens_get_nx(image_tokens);
  540. const int ny = mtmd_image_tokens_get_ny(image_tokens);
  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. int32_t 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. return ret;
  561. }
  562. if (ctx->print_timings) {
  563. LOG_INF("image decoded (batch %d/%d) in %" PRId64 " ms\n", i_batch+1, n_img_batches, ggml_time_ms() - t1);
  564. }
  565. i_batch++;
  566. }
  567. n_past += mtmd_image_tokens_get_n_pos(image_tokens);
  568. *new_n_past = n_past;
  569. if (mtmd_decode_use_non_causal(ctx)) {
  570. llama_set_causal_attn(lctx, true);
  571. }
  572. return 0;
  573. }
  574. int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx,
  575. struct llama_context * lctx,
  576. const mtmd_input_chunk * chunk,
  577. llama_pos n_past,
  578. llama_seq_id seq_id,
  579. int32_t n_batch,
  580. bool logits_last,
  581. llama_pos * new_n_past) {
  582. int32_t ret;
  583. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  584. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  585. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  586. size_t n_tokens;
  587. const auto tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  588. LOG_DBG("decoding text chunk, n_tokens = %zu\n", n_tokens);
  589. size_t i = 0;
  590. while (i < n_tokens) { // split into batches
  591. text_batch.n_tokens = 0; // clear the batch
  592. for (; i < n_tokens && text_batch.n_tokens < n_batch; i++) {
  593. text_batch.n_tokens++;
  594. text_batch.token [i] = tokens[i];
  595. text_batch.pos [i] = n_past++;
  596. text_batch.n_seq_id[i] = 1;
  597. text_batch.seq_id [i][0] = seq_id;
  598. text_batch.logits [i] = false;
  599. }
  600. bool is_last_token = (i == n_tokens);
  601. if (logits_last && is_last_token) {
  602. text_batch.logits[text_batch.n_tokens - 1] = true;
  603. }
  604. ret = llama_decode(lctx, text_batch);
  605. if (ret != 0) {
  606. LOG_ERR("failed to decode text\n");
  607. llama_batch_free(text_batch);
  608. return ret;
  609. }
  610. *new_n_past += text_batch.n_tokens;
  611. }
  612. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  613. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  614. int64_t t0 = ggml_time_ms();
  615. if (ctx->print_timings) {
  616. LOG_INF("encoding image or slice...\n");
  617. }
  618. ret = mtmd_encode(ctx, image_tokens);
  619. if (ret != 0) {
  620. LOG_ERR("failed to encode image\n");
  621. llama_batch_free(text_batch);
  622. return ret;
  623. }
  624. if (ctx->print_timings) {
  625. LOG_INF("image/slice encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  626. }
  627. float * embd = mtmd_get_output_embd(ctx);
  628. ret = mtmd_helper_decode_image_chunk(ctx, lctx, chunk, embd, n_past, seq_id, n_batch, new_n_past);
  629. if (ret != 0) {
  630. LOG_ERR("failed to decode image\n");
  631. llama_batch_free(text_batch);
  632. return ret;
  633. }
  634. } else {
  635. GGML_ABORT("chunk type not supported");
  636. }
  637. return 0;
  638. }
  639. int32_t mtmd_helper_eval_chunks(mtmd_context * ctx,
  640. struct llama_context * lctx,
  641. const mtmd_input_chunks * chunks,
  642. llama_pos n_past,
  643. llama_seq_id seq_id,
  644. int32_t n_batch,
  645. bool logits_last,
  646. llama_pos * new_n_past) {
  647. size_t n_chunks = mtmd_input_chunks_size(chunks);
  648. if (n_chunks == 0) {
  649. LOG_WRN("no chunks to eval\n");
  650. return 0;
  651. }
  652. for (size_t i = 0; i < n_chunks; i++) {
  653. bool chunk_logits_last = (i == n_chunks - 1) && logits_last;
  654. auto chunk = mtmd_input_chunks_get(chunks, i);
  655. int32_t res = mtmd_helper_eval_chunk_single(ctx, lctx, chunk, n_past, seq_id, n_batch, chunk_logits_last, &n_past);
  656. if (res != 0) {
  657. LOG_ERR("failed to eval chunk %zu\n", i);
  658. return res;
  659. }
  660. *new_n_past = n_past;
  661. }
  662. return 0;
  663. }
  664. mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len) {
  665. clip_image_u8_ptr img_u8(clip_image_u8_init());
  666. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  667. if (!ok) {
  668. LOG_ERR("Unable to load image from buffer\n");
  669. return nullptr;
  670. }
  671. uint32_t nx, ny;
  672. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  673. return mtmd_bitmap_init(nx, ny, data);
  674. }
  675. mtmd_bitmap * mtmd_helper_bitmap_init_from_file(const char * fname) {
  676. clip_image_u8_ptr img_u8(clip_image_u8_init());
  677. bool ok = clip_image_load_from_file(fname, img_u8.get());
  678. if (!ok) {
  679. LOG_ERR("Unable to load image %s\n", fname);
  680. return nullptr;
  681. }
  682. uint32_t nx, ny;
  683. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  684. return mtmd_bitmap_init(nx, ny, data);
  685. }
  686. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  687. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  688. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  689. return true;
  690. }
  691. return false;
  692. }
  693. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  694. return ctx->use_mrope;
  695. }
  696. void mtmd_image_tokens_deleter::operator()(mtmd_image_tokens * val) {
  697. mtmd_image_tokens_free(val);
  698. }
  699. //
  700. // public API functions
  701. //
  702. // mtmd_bitmap
  703. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  704. uint32_t ny,
  705. const unsigned char * data) {
  706. mtmd_bitmap * bitmap = new mtmd_bitmap;
  707. bitmap->nx = nx;
  708. bitmap->ny = ny;
  709. size_t data_size = (size_t)nx * ny * 3;
  710. bitmap->data.resize(data_size);
  711. std::memcpy(bitmap->data.data(), data, data_size);
  712. return bitmap;
  713. }
  714. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  715. return bitmap->nx;
  716. }
  717. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  718. return bitmap->ny;
  719. }
  720. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  721. return bitmap->data.data();
  722. }
  723. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  724. return bitmap->id.c_str();
  725. }
  726. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  727. if (id) {
  728. bitmap->id = std::string(id);
  729. } else {
  730. bitmap->id.clear();
  731. }
  732. }
  733. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  734. if (bitmap) {
  735. delete bitmap;
  736. }
  737. }
  738. // mtmd_input_chunks
  739. mtmd_input_chunks * mtmd_input_chunks_init() {
  740. return new mtmd_input_chunks;
  741. }
  742. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  743. return chunks->entries.size();
  744. }
  745. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  746. if (idx >= chunks->entries.size()) {
  747. return nullptr;
  748. }
  749. return &chunks->entries[idx];
  750. }
  751. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  752. if (chunks) {
  753. delete chunks;
  754. }
  755. }
  756. // mtmd_input_chunk
  757. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  758. return chunk->type;
  759. }
  760. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  761. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  762. *n_tokens_output = chunk->tokens_text.size();
  763. return chunk->tokens_text.data();
  764. }
  765. *n_tokens_output = 0;
  766. return nullptr;
  767. }
  768. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  769. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  770. return chunk->tokens_image.get();
  771. }
  772. return nullptr;
  773. }
  774. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  775. mtmd_input_chunk * copy = new mtmd_input_chunk{
  776. chunk->type,
  777. chunk->tokens_text,
  778. mtmd_image_tokens_ptr(),
  779. };
  780. if (chunk->tokens_image) {
  781. // copy the image tokens
  782. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  783. *copy->tokens_image = chunk->tokens_image->clone();
  784. }
  785. return copy;
  786. }
  787. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  788. if (chunk) {
  789. delete chunk;
  790. }
  791. }
  792. // mtmd_image_tokens
  793. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  794. return image_tokens->n_tokens();
  795. }
  796. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  797. return image_tokens->nx;
  798. }
  799. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  800. return image_tokens->ny;
  801. }
  802. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  803. return image_tokens->id.c_str();
  804. }
  805. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  806. if (image_tokens->use_mrope_pos) {
  807. return 1; // for M-RoPE, the whole image is 1 in temporal dimension
  808. }
  809. return image_tokens->n_tokens();
  810. }
  811. // test function
  812. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  813. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  814. if (!chunks) {
  815. return nullptr;
  816. }
  817. // create a text chunk
  818. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  819. mtmd_input_chunk chunk_text{
  820. MTMD_INPUT_CHUNK_TYPE_TEXT,
  821. std::move(tokens_text),
  822. {},
  823. };
  824. chunks->entries.emplace_back(std::move(chunk_text));
  825. // create an image chunk
  826. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  827. image_tokens->nx = 4;
  828. image_tokens->ny = 4;
  829. image_tokens->batch_f32.entries.resize(16);
  830. image_tokens->id = "image_1";
  831. mtmd_input_chunk chunk_image{
  832. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  833. {},
  834. std::move(image_tokens),
  835. };
  836. chunks->entries.emplace_back(std::move(chunk_image));
  837. return chunks;
  838. }