mtmd.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. else if (proj_type == PROJECTOR_TYPE_INTERNVL) {
  221. // <img> ... (image embeddings) ... </img>
  222. marker_modified = "<img>" + ctx->image_marker + "</img>";
  223. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  224. }
  225. // llava-1.5, llava-1.6, Yi-VL, Yi-34B, granite: don't need to add prefix and suffix
  226. // for glm-edge, BOI and EOI token's embeddings are not present in the text model
  227. std::vector<std::string> parts = string_split_str(prompt_modified, ctx->image_marker);
  228. output->entries.clear();
  229. output->entries.reserve(parts.size());
  230. size_t i_img = 0;
  231. // utility for adding raw tokens
  232. auto add_text_chunk = [&output](std::vector<llama_token> && tokens) {
  233. mtmd_input_chunk chunk{
  234. MTMD_INPUT_CHUNK_TYPE_TEXT,
  235. std::move(tokens),
  236. {},
  237. };
  238. output->entries.emplace_back(std::move(chunk));
  239. };
  240. // utility for splitting batch of multiple images into chunks of batch having single images
  241. auto split_batch_to_chunk = [&ctx](clip_image_f32_batch && batch_f32, const std::string & id) {
  242. std::vector<mtmd_input_chunk> chunks;
  243. for (auto & entry : batch_f32.entries) {
  244. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  245. image_tokens->nx = clip_n_output_tokens(ctx->ctx_clip, entry.get());
  246. image_tokens->ny = 1;
  247. image_tokens->batch_f32.entries.push_back(std::move(entry));
  248. image_tokens->id = id;
  249. mtmd_input_chunk chunk{
  250. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  251. {},
  252. std::move(image_tokens),
  253. };
  254. chunks.emplace_back(std::move(chunk));
  255. }
  256. return chunks;
  257. };
  258. for (const auto & part : parts) {
  259. // printf("tokenizing part: %s\n", part.c_str());
  260. bool add_bos = &parts.front() == &part;
  261. auto tokens = mtmd_tokenize_text_internal(vocab, part, text->add_special && add_bos, text->parse_special);
  262. if (tokens.empty()) {
  263. continue;
  264. }
  265. mtmd_input_chunk chunk{
  266. MTMD_INPUT_CHUNK_TYPE_TEXT,
  267. std::move(tokens),
  268. {},
  269. };
  270. output->entries.emplace_back(std::move(chunk));
  271. if (&parts.back() != &part) {
  272. // add image token to middle of 2 parts
  273. if (i_img >= n_bitmaps) {
  274. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  275. return 1;
  276. }
  277. // convert mtmd_bitmap to clip_image_u8
  278. clip_image_u8_ptr img_u8(clip_image_u8_init());
  279. img_u8->nx = bitmaps[i_img]->nx;
  280. img_u8->ny = bitmaps[i_img]->ny;
  281. img_u8->buf.resize(bitmaps[i_img]->data.size());
  282. std::memcpy(img_u8->buf.data(), bitmaps[i_img]->data.data(), img_u8->nx * img_u8->ny * 3);
  283. clip_image_size img_u8_size{img_u8->nx, img_u8->ny};
  284. // preprocess image
  285. clip_image_f32_batch batch_f32;
  286. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), &batch_f32);
  287. if (!ok) {
  288. LOG_ERR("Unable to preprocess image\n");
  289. return 2;
  290. }
  291. if (ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5 || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6) {
  292. // split batch into chunks of single images
  293. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmaps[i_img]->id);
  294. GGML_ASSERT(chunks.size() > 0);
  295. // add overview image
  296. add_text_chunk({ctx->tok_ov_img_start});
  297. output->entries.emplace_back(std::move(chunks.front()));
  298. chunks.erase(chunks.begin());
  299. add_text_chunk({ctx->tok_ov_img_end});
  300. // add slices
  301. if (!chunks.empty()) {
  302. clip_add_load_image_size(ctx->ctx_clip, &img_u8_size);
  303. int n_col = clip_uhd_num_image_embeds_col(ctx->ctx_clip);
  304. int n_row = (int)chunks.size() / n_col;
  305. GGML_ASSERT(n_row * n_col == (int)chunks.size());
  306. if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
  307. add_text_chunk({ctx->tok_slices_start});
  308. }
  309. for (int y = 0; y < n_row; y++) {
  310. for (int x = 0; x < n_col; x++) {
  311. if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
  312. add_text_chunk({ctx->tok_sli_img_start});
  313. }
  314. output->entries.emplace_back(std::move(chunks[y * n_col + x]));
  315. if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
  316. add_text_chunk({ctx->tok_sli_img_end});
  317. }
  318. }
  319. if (ctx->tok_row_end != LLAMA_TOKEN_NULL && y != n_row - 1) {
  320. add_text_chunk({ctx->tok_row_end});
  321. }
  322. }
  323. if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
  324. add_text_chunk({ctx->tok_slices_end});
  325. }
  326. }
  327. } else {
  328. size_t n_tokens = 0;
  329. for (const auto & entry : batch_f32.entries) {
  330. n_tokens += clip_n_output_tokens(ctx->ctx_clip, entry.get());
  331. }
  332. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  333. if (ctx->use_mrope) {
  334. // for Qwen2VL, we need this information for M-RoPE decoding positions
  335. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_clip, batch_f32.entries[0].get());
  336. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_clip, batch_f32.entries[0].get());
  337. image_tokens->use_mrope_pos = true;
  338. } else {
  339. // other models, we only need the total number of tokens
  340. image_tokens->nx = n_tokens;
  341. image_tokens->ny = 1;
  342. }
  343. image_tokens->batch_f32 = std::move(batch_f32);
  344. image_tokens->id = bitmaps[i_img]->id; // optional
  345. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  346. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  347. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  348. mtmd_input_chunk chunk{
  349. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  350. {},
  351. std::move(image_tokens),
  352. };
  353. output->entries.emplace_back(std::move(chunk));
  354. }
  355. i_img++; // move to next image
  356. }
  357. }
  358. return 0;
  359. }
  360. static void mtmd_image_tokens_free(mtmd_image_tokens * image_tokens) {
  361. if (image_tokens) {
  362. delete image_tokens;
  363. }
  364. }
  365. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  366. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  367. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  368. bool ok = false;
  369. // only effective for minicpmv and qwen2vl, other models will ignore load_image_size
  370. {
  371. clip_image_size slice_size{
  372. image_tokens->batch_f32.entries[0]->nx,
  373. image_tokens->batch_f32.entries[0]->ny};
  374. clip_add_load_image_size(ctx->ctx_clip, &slice_size);
  375. }
  376. if (clip_is_llava(ctx->ctx_clip) || clip_is_minicpmv(ctx->ctx_clip) || clip_is_glm(ctx->ctx_clip)) {
  377. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  378. const auto & entries = image_tokens->batch_f32.entries;
  379. for (size_t i = 0; i < entries.size(); i++) {
  380. int n_tokens_per_image = clip_n_output_tokens(ctx->ctx_clip, entries[i].get());
  381. ok = clip_image_encode(
  382. ctx->ctx_clip,
  383. ctx->n_threads,
  384. entries[i].get(),
  385. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  386. }
  387. } else {
  388. ok = clip_image_batch_encode(
  389. ctx->ctx_clip,
  390. ctx->n_threads,
  391. &image_tokens->batch_f32,
  392. ctx->image_embd_v.data());
  393. }
  394. return ok ? 0 : 1;
  395. }
  396. float * mtmd_get_output_embd(mtmd_context * ctx) {
  397. return ctx->image_embd_v.data();
  398. }
  399. size_t mtmd_helper_get_n_tokens(const mtmd_input_chunks * chunks) {
  400. size_t n_tokens = 0;
  401. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  402. auto chunk = mtmd_input_chunks_get(chunks, i);
  403. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  404. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  405. size_t n_tokens_text;
  406. mtmd_input_chunk_get_tokens_text(chunk, &n_tokens_text);
  407. n_tokens += n_tokens_text;
  408. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  409. auto tokens_image = mtmd_input_chunk_get_tokens_image(chunk);
  410. n_tokens += mtmd_image_tokens_get_n_tokens(tokens_image);
  411. } else {
  412. GGML_ASSERT(false && "chunk type not supported");
  413. }
  414. }
  415. return n_tokens;
  416. }
  417. llama_pos mtmd_helper_get_n_pos(const mtmd_input_chunks * chunks) {
  418. llama_pos n_pos = 0;
  419. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  420. auto chunk = mtmd_input_chunks_get(chunks, i);
  421. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  422. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  423. size_t n_tokens_text;
  424. mtmd_input_chunk_get_tokens_text(chunk, &n_tokens_text);
  425. n_pos += n_tokens_text;
  426. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  427. auto tokens_image = mtmd_input_chunk_get_tokens_image(chunk);
  428. n_pos += mtmd_image_tokens_get_n_pos(tokens_image);
  429. } else {
  430. GGML_ASSERT(false && "chunk type not supported");
  431. }
  432. }
  433. return n_pos;
  434. }
  435. // helper struct to make working with embd batch easier
  436. // note: this will be removed after llama_batch_ext refactoring
  437. struct decode_embd_batch {
  438. int n_pos_per_embd;
  439. int n_mmproj_embd;
  440. std::vector<llama_pos> pos;
  441. std::vector<llama_pos> pos_view; // used by mrope
  442. std::vector<int32_t> n_seq_id;
  443. std::vector<llama_seq_id> seq_id_0;
  444. std::vector<llama_seq_id *> seq_ids;
  445. std::vector<int8_t> logits;
  446. llama_batch batch;
  447. 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) {
  448. pos .resize(n_tokens * n_pos_per_embd);
  449. n_seq_id.resize(n_tokens);
  450. seq_ids .resize(n_tokens + 1);
  451. logits .resize(n_tokens);
  452. seq_id_0.resize(1);
  453. seq_ids [n_tokens] = nullptr;
  454. batch = {
  455. /*n_tokens =*/ n_tokens,
  456. /*tokens =*/ nullptr,
  457. /*embd =*/ embd,
  458. /*pos =*/ pos.data(),
  459. /*n_seq_id =*/ n_seq_id.data(),
  460. /*seq_id =*/ seq_ids.data(),
  461. /*logits =*/ logits.data(),
  462. };
  463. }
  464. void set_position_normal(llama_pos pos_0, llama_seq_id seq_id) {
  465. seq_id_0[0] = seq_id;
  466. for (int i = 0; i < batch.n_tokens; i++) {
  467. batch.pos [i] = pos_0 + i;
  468. batch.n_seq_id[i] = 1;
  469. batch.seq_id [i] = seq_id_0.data();
  470. batch.logits [i] = false;
  471. }
  472. }
  473. void set_position_mrope(llama_pos pos_0, int nx, int ny, llama_seq_id seq_id) {
  474. GGML_ASSERT(n_pos_per_embd == 4);
  475. seq_id_0[0] = seq_id;
  476. for (int y = 0; y < ny; y++) {
  477. for (int x = 0; x < nx; x++) {
  478. int i = y * nx + x;
  479. pos[i ] = pos_0;
  480. pos[i + batch.n_tokens ] = pos_0 + y;
  481. pos[i + batch.n_tokens * 2] = pos_0 + x;
  482. pos[i + batch.n_tokens * 3] = 0; // last pos dim is unused
  483. }
  484. }
  485. for (int i = 0; i < batch.n_tokens; i++) {
  486. batch.n_seq_id[i] = 1;
  487. batch.seq_id [i] = seq_id_0.data();
  488. batch.logits [i] = false;
  489. }
  490. }
  491. llama_batch get_view(int offset, int n_tokens) {
  492. llama_pos * pos_ptr;
  493. pos_view.clear();
  494. pos_view.reserve(n_tokens * n_pos_per_embd);
  495. if (n_pos_per_embd > 1) {
  496. // mrope
  497. // for example, with layout of src: 1234...1234...1234...1234...
  498. // offset 2 will give us dst: 34...34...34...34...
  499. for (int i = 0; i < n_pos_per_embd; i++) {
  500. // assume n_tokens is less than or equal to batch.n_tokens
  501. // batch.n_tokens is number of **total** tokens
  502. // n_tokens is number of viewed token
  503. size_t src_idx = i * batch.n_tokens + offset;
  504. pos_view.insert(pos_view.end(),
  505. pos.data() + src_idx,
  506. pos.data() + src_idx + n_tokens);
  507. }
  508. pos_ptr = pos_view.data();
  509. } else {
  510. // normal
  511. pos_ptr = pos.data() + offset;
  512. }
  513. return {
  514. /*n_tokens =*/ n_tokens,
  515. /*tokens =*/ nullptr,
  516. /*embd =*/ batch.embd + offset * n_mmproj_embd,
  517. /*pos =*/ pos_ptr,
  518. /*n_seq_id =*/ batch.n_seq_id + offset,
  519. /*seq_id =*/ batch.seq_id + offset,
  520. /*logits =*/ batch.logits + offset,
  521. };
  522. }
  523. };
  524. // Helper function for decoding an image whose embeddings have already been calculated
  525. int32_t mtmd_helper_decode_image_chunk(
  526. mtmd_context * ctx,
  527. struct llama_context * lctx,
  528. const mtmd_input_chunk * chunk,
  529. float * encoded_embd,
  530. llama_pos n_past,
  531. llama_seq_id seq_id,
  532. int32_t n_batch,
  533. llama_pos * new_n_past) {
  534. if (mtmd_input_chunk_get_type(chunk) != MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  535. LOG_ERR("failed to decode image chunk: input chunk not of image type\n");
  536. return -1;
  537. }
  538. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  539. if (!image_tokens) {
  540. LOG_ERR("failed to decode image chunk: image tokens are null\n");
  541. return -1;
  542. }
  543. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  544. int n_pos_per_embd = mtmd_decode_use_mrope(ctx) ? 4 : 1;
  545. int32_t n_tokens = mtmd_image_tokens_get_n_tokens(image_tokens);
  546. int32_t i_batch = 0;
  547. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  548. decode_embd_batch batch_embd(encoded_embd, n_tokens, n_pos_per_embd, n_mmproj_embd);
  549. const int nx = mtmd_image_tokens_get_nx(image_tokens);
  550. const int ny = mtmd_image_tokens_get_ny(image_tokens);
  551. if (mtmd_decode_use_mrope(ctx)) {
  552. batch_embd.set_position_mrope(n_past, nx, ny, seq_id);
  553. } else {
  554. batch_embd.set_position_normal(n_past, seq_id);
  555. }
  556. if (mtmd_decode_use_non_causal(ctx)) {
  557. llama_set_causal_attn(lctx, false);
  558. // TODO @ngxson : need to make sure only one image is processed at a time, and n_ubatch must be enough to hold the image
  559. }
  560. while (i_batch < n_img_batches) { // split into batches
  561. int pos_offset = i_batch*n_batch;
  562. int n_tokens_batch = std::min(n_batch, n_tokens - pos_offset);
  563. llama_batch batch_embd_view = batch_embd.get_view(pos_offset, n_tokens_batch);
  564. LOG_INF("decoding image batch %d/%d, n_tokens_batch = %d\n", i_batch+1, n_img_batches, n_tokens_batch);
  565. int64_t t1 = ggml_time_ms();
  566. int32_t ret = llama_decode(lctx, batch_embd_view);
  567. if (ret != 0) {
  568. LOG_ERR("failed to decode image\n");
  569. llama_set_causal_attn(lctx, true); // restore causal attn
  570. return ret;
  571. }
  572. if (ctx->print_timings) {
  573. LOG_INF("image decoded (batch %d/%d) in %" PRId64 " ms\n", i_batch+1, n_img_batches, ggml_time_ms() - t1);
  574. }
  575. i_batch++;
  576. }
  577. n_past += mtmd_image_tokens_get_n_pos(image_tokens);
  578. *new_n_past = n_past;
  579. if (mtmd_decode_use_non_causal(ctx)) {
  580. llama_set_causal_attn(lctx, true);
  581. }
  582. return 0;
  583. }
  584. int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx,
  585. struct llama_context * lctx,
  586. const mtmd_input_chunk * chunk,
  587. llama_pos n_past,
  588. llama_seq_id seq_id,
  589. int32_t n_batch,
  590. bool logits_last,
  591. llama_pos * new_n_past) {
  592. int32_t ret;
  593. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  594. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  595. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  596. size_t n_tokens;
  597. const auto tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  598. LOG_DBG("decoding text chunk, n_tokens = %zu\n", n_tokens);
  599. size_t i = 0;
  600. while (i < n_tokens) { // split into batches
  601. text_batch.n_tokens = 0; // clear the batch
  602. for (; i < n_tokens && text_batch.n_tokens < n_batch; i++) {
  603. text_batch.n_tokens++;
  604. text_batch.token [i] = tokens[i];
  605. text_batch.pos [i] = n_past++;
  606. text_batch.n_seq_id[i] = 1;
  607. text_batch.seq_id [i][0] = seq_id;
  608. text_batch.logits [i] = false;
  609. }
  610. bool is_last_token = (i == n_tokens);
  611. if (logits_last && is_last_token) {
  612. text_batch.logits[text_batch.n_tokens - 1] = true;
  613. }
  614. ret = llama_decode(lctx, text_batch);
  615. if (ret != 0) {
  616. LOG_ERR("failed to decode text\n");
  617. llama_batch_free(text_batch);
  618. return ret;
  619. }
  620. *new_n_past += text_batch.n_tokens;
  621. }
  622. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  623. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  624. int64_t t0 = ggml_time_ms();
  625. if (ctx->print_timings) {
  626. LOG_INF("encoding image or slice...\n");
  627. }
  628. ret = mtmd_encode(ctx, image_tokens);
  629. if (ret != 0) {
  630. LOG_ERR("failed to encode image\n");
  631. llama_batch_free(text_batch);
  632. return ret;
  633. }
  634. if (ctx->print_timings) {
  635. LOG_INF("image/slice encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  636. }
  637. float * embd = mtmd_get_output_embd(ctx);
  638. ret = mtmd_helper_decode_image_chunk(ctx, lctx, chunk, embd, n_past, seq_id, n_batch, new_n_past);
  639. if (ret != 0) {
  640. LOG_ERR("failed to decode image\n");
  641. llama_batch_free(text_batch);
  642. return ret;
  643. }
  644. } else {
  645. GGML_ABORT("chunk type not supported");
  646. }
  647. return 0;
  648. }
  649. int32_t mtmd_helper_eval_chunks(mtmd_context * ctx,
  650. struct llama_context * lctx,
  651. const mtmd_input_chunks * chunks,
  652. llama_pos n_past,
  653. llama_seq_id seq_id,
  654. int32_t n_batch,
  655. bool logits_last,
  656. llama_pos * new_n_past) {
  657. size_t n_chunks = mtmd_input_chunks_size(chunks);
  658. if (n_chunks == 0) {
  659. LOG_WRN("no chunks to eval\n");
  660. return 0;
  661. }
  662. for (size_t i = 0; i < n_chunks; i++) {
  663. bool chunk_logits_last = (i == n_chunks - 1) && logits_last;
  664. auto chunk = mtmd_input_chunks_get(chunks, i);
  665. int32_t res = mtmd_helper_eval_chunk_single(ctx, lctx, chunk, n_past, seq_id, n_batch, chunk_logits_last, &n_past);
  666. if (res != 0) {
  667. LOG_ERR("failed to eval chunk %zu\n", i);
  668. return res;
  669. }
  670. *new_n_past = n_past;
  671. }
  672. return 0;
  673. }
  674. mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len) {
  675. clip_image_u8_ptr img_u8(clip_image_u8_init());
  676. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  677. if (!ok) {
  678. LOG_ERR("Unable to load image from buffer\n");
  679. return nullptr;
  680. }
  681. uint32_t nx, ny;
  682. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  683. return mtmd_bitmap_init(nx, ny, data);
  684. }
  685. mtmd_bitmap * mtmd_helper_bitmap_init_from_file(const char * fname) {
  686. clip_image_u8_ptr img_u8(clip_image_u8_init());
  687. bool ok = clip_image_load_from_file(fname, img_u8.get());
  688. if (!ok) {
  689. LOG_ERR("Unable to load image %s\n", fname);
  690. return nullptr;
  691. }
  692. uint32_t nx, ny;
  693. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  694. return mtmd_bitmap_init(nx, ny, data);
  695. }
  696. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  697. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  698. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  699. return true;
  700. }
  701. return false;
  702. }
  703. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  704. return ctx->use_mrope;
  705. }
  706. void mtmd_image_tokens_deleter::operator()(mtmd_image_tokens * val) {
  707. mtmd_image_tokens_free(val);
  708. }
  709. //
  710. // public API functions
  711. //
  712. // mtmd_bitmap
  713. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  714. uint32_t ny,
  715. const unsigned char * data) {
  716. mtmd_bitmap * bitmap = new mtmd_bitmap;
  717. bitmap->nx = nx;
  718. bitmap->ny = ny;
  719. size_t data_size = (size_t)nx * ny * 3;
  720. bitmap->data.resize(data_size);
  721. std::memcpy(bitmap->data.data(), data, data_size);
  722. return bitmap;
  723. }
  724. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  725. return bitmap->nx;
  726. }
  727. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  728. return bitmap->ny;
  729. }
  730. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  731. return bitmap->data.data();
  732. }
  733. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  734. return bitmap->id.c_str();
  735. }
  736. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  737. if (id) {
  738. bitmap->id = std::string(id);
  739. } else {
  740. bitmap->id.clear();
  741. }
  742. }
  743. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  744. if (bitmap) {
  745. delete bitmap;
  746. }
  747. }
  748. // mtmd_input_chunks
  749. mtmd_input_chunks * mtmd_input_chunks_init() {
  750. return new mtmd_input_chunks;
  751. }
  752. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  753. return chunks->entries.size();
  754. }
  755. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  756. if (idx >= chunks->entries.size()) {
  757. return nullptr;
  758. }
  759. return &chunks->entries[idx];
  760. }
  761. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  762. if (chunks) {
  763. delete chunks;
  764. }
  765. }
  766. // mtmd_input_chunk
  767. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  768. return chunk->type;
  769. }
  770. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  771. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  772. *n_tokens_output = chunk->tokens_text.size();
  773. return chunk->tokens_text.data();
  774. }
  775. *n_tokens_output = 0;
  776. return nullptr;
  777. }
  778. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  779. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  780. return chunk->tokens_image.get();
  781. }
  782. return nullptr;
  783. }
  784. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  785. mtmd_input_chunk * copy = new mtmd_input_chunk{
  786. chunk->type,
  787. chunk->tokens_text,
  788. mtmd_image_tokens_ptr(),
  789. };
  790. if (chunk->tokens_image) {
  791. // copy the image tokens
  792. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  793. *copy->tokens_image = chunk->tokens_image->clone();
  794. }
  795. return copy;
  796. }
  797. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  798. if (chunk) {
  799. delete chunk;
  800. }
  801. }
  802. // mtmd_image_tokens
  803. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  804. return image_tokens->n_tokens();
  805. }
  806. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  807. return image_tokens->nx;
  808. }
  809. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  810. return image_tokens->ny;
  811. }
  812. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  813. return image_tokens->id.c_str();
  814. }
  815. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  816. if (image_tokens->use_mrope_pos) {
  817. return 1; // for M-RoPE, the whole image is 1 in temporal dimension
  818. }
  819. return image_tokens->n_tokens();
  820. }
  821. // test function
  822. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  823. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  824. if (!chunks) {
  825. return nullptr;
  826. }
  827. // create a text chunk
  828. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  829. mtmd_input_chunk chunk_text{
  830. MTMD_INPUT_CHUNK_TYPE_TEXT,
  831. std::move(tokens_text),
  832. {},
  833. };
  834. chunks->entries.emplace_back(std::move(chunk_text));
  835. // create an image chunk
  836. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  837. image_tokens->nx = 4;
  838. image_tokens->ny = 4;
  839. image_tokens->batch_f32.entries.resize(16);
  840. image_tokens->id = "image_1";
  841. mtmd_input_chunk chunk_image{
  842. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  843. {},
  844. std::move(image_tokens),
  845. };
  846. chunks->entries.emplace_back(std::move(chunk_image));
  847. return chunks;
  848. }