mtmd.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx,
  515. struct llama_context * lctx,
  516. const mtmd_input_chunk * chunk,
  517. llama_pos n_past,
  518. llama_seq_id seq_id,
  519. int32_t n_batch,
  520. bool logits_last,
  521. llama_pos * new_n_past) {
  522. int32_t ret;
  523. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  524. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  525. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  526. int n_pos_per_embd = mtmd_decode_use_mrope(ctx) ? 4 : 1;
  527. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  528. size_t n_tokens;
  529. const auto tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  530. LOG_DBG("decoding text chunk, n_tokens = %zu\n", n_tokens);
  531. size_t i = 0;
  532. while (i < n_tokens) { // split into batches
  533. text_batch.n_tokens = 0; // clear the batch
  534. for (; i < n_tokens && text_batch.n_tokens < n_batch; i++) {
  535. text_batch.n_tokens++;
  536. text_batch.token [i] = tokens[i];
  537. text_batch.pos [i] = n_past++;
  538. text_batch.n_seq_id[i] = 1;
  539. text_batch.seq_id [i][0] = seq_id;
  540. text_batch.logits [i] = false;
  541. }
  542. bool is_last_token = (i == n_tokens);
  543. if (logits_last && is_last_token) {
  544. text_batch.logits[text_batch.n_tokens - 1] = true;
  545. }
  546. ret = llama_decode(lctx, text_batch);
  547. if (ret != 0) {
  548. LOG_ERR("failed to decode text\n");
  549. llama_batch_free(text_batch);
  550. return ret;
  551. }
  552. *new_n_past += text_batch.n_tokens;
  553. }
  554. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  555. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  556. int64_t t0 = ggml_time_ms();
  557. if (ctx->print_timings) {
  558. LOG_INF("encoding image or slice...\n");
  559. }
  560. ret = mtmd_encode(ctx, image_tokens);
  561. if (ret != 0) {
  562. LOG_ERR("failed to encode image\n");
  563. llama_batch_free(text_batch);
  564. return ret;
  565. }
  566. if (ctx->print_timings) {
  567. LOG_INF("image/slice encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  568. }
  569. int32_t n_tokens = mtmd_image_tokens_get_n_tokens(image_tokens);
  570. int32_t i_batch = 0;
  571. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  572. float * embd = mtmd_get_output_embd(ctx);
  573. decode_embd_batch batch_embd(embd, n_tokens, n_pos_per_embd, n_mmproj_embd);
  574. const int nx = mtmd_image_tokens_get_nx(image_tokens);
  575. const int ny = mtmd_image_tokens_get_ny(image_tokens);
  576. if (mtmd_decode_use_mrope(ctx)) {
  577. batch_embd.set_position_mrope(n_past, nx, ny, seq_id);
  578. } else {
  579. batch_embd.set_position_normal(n_past, seq_id);
  580. }
  581. if (mtmd_decode_use_non_causal(ctx)) {
  582. llama_set_causal_attn(lctx, false);
  583. // TODO @ngxson : need to make sure only one image is processed at a time, and n_ubatch must be enough to hold the image
  584. }
  585. while (i_batch < n_img_batches) { // split into batches
  586. int pos_offset = i_batch*n_batch;
  587. int n_tokens_batch = std::min(n_batch, n_tokens - pos_offset);
  588. llama_batch batch_embd_view = batch_embd.get_view(pos_offset, n_tokens_batch);
  589. LOG_INF("decoding image batch %d/%d, n_tokens_batch = %d\n", i_batch+1, n_img_batches, n_tokens_batch);
  590. int64_t t1 = ggml_time_ms();
  591. ret = llama_decode(lctx, batch_embd_view);
  592. if (ret != 0) {
  593. LOG_ERR("failed to decode image\n");
  594. llama_set_causal_attn(lctx, true); // restore causal attn
  595. llama_batch_free(text_batch);
  596. return ret;
  597. }
  598. if (ctx->print_timings) {
  599. LOG_INF("image decoded (batch %d/%d) in %" PRId64 " ms\n", i_batch+1, n_img_batches, ggml_time_ms() - t1);
  600. }
  601. i_batch++;
  602. }
  603. n_past += mtmd_image_tokens_get_n_pos(image_tokens);
  604. *new_n_past = n_past;
  605. if (mtmd_decode_use_non_causal(ctx)) {
  606. llama_set_causal_attn(lctx, true);
  607. }
  608. } else {
  609. GGML_ABORT("chunk type not supported");
  610. }
  611. return 0;
  612. }
  613. int32_t mtmd_helper_eval_chunks(mtmd_context * ctx,
  614. struct llama_context * lctx,
  615. const mtmd_input_chunks * chunks,
  616. llama_pos n_past,
  617. llama_seq_id seq_id,
  618. int32_t n_batch,
  619. bool logits_last,
  620. llama_pos * new_n_past) {
  621. size_t n_chunks = mtmd_input_chunks_size(chunks);
  622. if (n_chunks == 0) {
  623. LOG_WRN("no chunks to eval\n");
  624. return 0;
  625. }
  626. for (size_t i = 0; i < n_chunks; i++) {
  627. bool chunk_logits_last = (i == n_chunks - 1) && logits_last;
  628. auto chunk = mtmd_input_chunks_get(chunks, i);
  629. int32_t res = mtmd_helper_eval_chunk_single(ctx, lctx, chunk, n_past, seq_id, n_batch, chunk_logits_last, &n_past);
  630. if (res != 0) {
  631. LOG_ERR("failed to eval chunk %zu\n", i);
  632. return res;
  633. }
  634. *new_n_past = n_past;
  635. }
  636. return 0;
  637. }
  638. mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len) {
  639. clip_image_u8_ptr img_u8(clip_image_u8_init());
  640. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  641. if (!ok) {
  642. LOG_ERR("Unable to load image from buffer\n");
  643. return nullptr;
  644. }
  645. uint32_t nx, ny;
  646. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  647. return mtmd_bitmap_init(nx, ny, data);
  648. }
  649. mtmd_bitmap * mtmd_helper_bitmap_init_from_file(const char * fname) {
  650. clip_image_u8_ptr img_u8(clip_image_u8_init());
  651. bool ok = clip_image_load_from_file(fname, img_u8.get());
  652. if (!ok) {
  653. LOG_ERR("Unable to load image %s\n", fname);
  654. return nullptr;
  655. }
  656. uint32_t nx, ny;
  657. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  658. return mtmd_bitmap_init(nx, ny, data);
  659. }
  660. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  661. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  662. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  663. return true;
  664. }
  665. return false;
  666. }
  667. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  668. return ctx->use_mrope;
  669. }
  670. void mtmd_image_tokens_deleter::operator()(mtmd_image_tokens * val) {
  671. mtmd_image_tokens_free(val);
  672. }
  673. //
  674. // public API functions
  675. //
  676. // mtmd_bitmap
  677. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  678. uint32_t ny,
  679. const unsigned char * data) {
  680. mtmd_bitmap * bitmap = new mtmd_bitmap;
  681. bitmap->nx = nx;
  682. bitmap->ny = ny;
  683. size_t data_size = (size_t)nx * ny * 3;
  684. bitmap->data.resize(data_size);
  685. std::memcpy(bitmap->data.data(), data, data_size);
  686. return bitmap;
  687. }
  688. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  689. return bitmap->nx;
  690. }
  691. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  692. return bitmap->ny;
  693. }
  694. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  695. return bitmap->data.data();
  696. }
  697. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  698. return bitmap->id.c_str();
  699. }
  700. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  701. if (id) {
  702. bitmap->id = std::string(id);
  703. } else {
  704. bitmap->id.clear();
  705. }
  706. }
  707. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  708. if (bitmap) {
  709. delete bitmap;
  710. }
  711. }
  712. // mtmd_input_chunks
  713. mtmd_input_chunks * mtmd_input_chunks_init() {
  714. return new mtmd_input_chunks;
  715. }
  716. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  717. return chunks->entries.size();
  718. }
  719. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  720. if (idx >= chunks->entries.size()) {
  721. return nullptr;
  722. }
  723. return &chunks->entries[idx];
  724. }
  725. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  726. if (chunks) {
  727. delete chunks;
  728. }
  729. }
  730. // mtmd_input_chunk
  731. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  732. return chunk->type;
  733. }
  734. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  735. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  736. *n_tokens_output = chunk->tokens_text.size();
  737. return chunk->tokens_text.data();
  738. }
  739. *n_tokens_output = 0;
  740. return nullptr;
  741. }
  742. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  743. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  744. return chunk->tokens_image.get();
  745. }
  746. return nullptr;
  747. }
  748. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  749. mtmd_input_chunk * copy = new mtmd_input_chunk{
  750. chunk->type,
  751. chunk->tokens_text,
  752. mtmd_image_tokens_ptr(),
  753. };
  754. if (chunk->tokens_image) {
  755. // copy the image tokens
  756. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  757. *copy->tokens_image = chunk->tokens_image->clone();
  758. }
  759. return copy;
  760. }
  761. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  762. if (chunk) {
  763. delete chunk;
  764. }
  765. }
  766. // mtmd_image_tokens
  767. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  768. return image_tokens->n_tokens();
  769. }
  770. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  771. return image_tokens->nx;
  772. }
  773. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  774. return image_tokens->ny;
  775. }
  776. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  777. return image_tokens->id.c_str();
  778. }
  779. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  780. if (image_tokens->use_mrope_pos) {
  781. return 1; // for M-RoPE, the whole image is 1 in temporal dimension
  782. }
  783. return image_tokens->n_tokens();
  784. }
  785. // test function
  786. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  787. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  788. if (!chunks) {
  789. return nullptr;
  790. }
  791. // create a text chunk
  792. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  793. mtmd_input_chunk chunk_text{
  794. MTMD_INPUT_CHUNK_TYPE_TEXT,
  795. std::move(tokens_text),
  796. {},
  797. };
  798. chunks->entries.emplace_back(std::move(chunk_text));
  799. // create an image chunk
  800. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  801. image_tokens->nx = 4;
  802. image_tokens->ny = 4;
  803. image_tokens->batch_f32.entries.resize(16);
  804. image_tokens->id = "image_1";
  805. mtmd_input_chunk chunk_image{
  806. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  807. {},
  808. std::move(image_tokens),
  809. };
  810. chunks->entries.emplace_back(std::move(chunk_image));
  811. return chunks;
  812. }