mtmd.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "mtmd.h"
  4. #include "mtmd-audio.h"
  5. #include "llama.h"
  6. #include <algorithm>
  7. #include <cerrno>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <limits>
  12. #include <vector>
  13. // represents raw image data, layout is RGBRGBRGB...
  14. // length of data must be nx * ny * 3
  15. struct mtmd_bitmap {
  16. uint32_t nx;
  17. uint32_t ny;
  18. std::vector<unsigned char> data;
  19. std::string id; // optional user-defined id, for ex: can be set to image hash, useful for KV cache tracking
  20. bool is_audio = false; // true if the bitmap is audio
  21. };
  22. struct mtmd_image_tokens {
  23. uint32_t nx; // number of tokens in x direction
  24. uint32_t ny; // number of tokens in y direction
  25. bool use_mrope_pos = false; // use M-RoPE position counting (the whole image is 1 temporal position)
  26. uint32_t n_tokens() const { return nx * ny; }
  27. clip_image_f32_batch batch_f32; // preprocessed image patches
  28. std::string id; // optional user-defined ID, useful for KV cache tracking
  29. mtmd_image_tokens clone() {
  30. return mtmd_image_tokens{
  31. nx,
  32. ny,
  33. use_mrope_pos,
  34. batch_f32.clone(),
  35. id
  36. };
  37. }
  38. };
  39. using mtmd_image_tokens_ptr = std::unique_ptr<mtmd_image_tokens>;
  40. struct mtmd_audio_tokens {
  41. uint32_t n_tokens; // number of tokens
  42. clip_image_f32_batch batch_f32; // preprocessed image patches
  43. std::string id; // optional user-defined ID, useful for KV cache tracking
  44. mtmd_audio_tokens clone() {
  45. return mtmd_audio_tokens{
  46. n_tokens,
  47. batch_f32.clone(),
  48. id
  49. };
  50. }
  51. };
  52. using mtmd_audio_tokens_ptr = std::unique_ptr<mtmd_audio_tokens>;
  53. struct mtmd_input_chunk {
  54. mtmd_input_chunk_type type;
  55. std::vector<llama_token> tokens_text;
  56. mtmd_image_tokens_ptr tokens_image;
  57. mtmd_audio_tokens_ptr tokens_audio;
  58. };
  59. struct mtmd_input_chunks {
  60. std::vector<mtmd_input_chunk> entries;
  61. };
  62. // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
  63. // models not having it (llava-1.6) will process embeddings without any special tokens in-between
  64. enum mtmd_slice_tmpl {
  65. MTMD_SLICE_TMPL_NONE,
  66. MTMD_SLICE_TMPL_MINICPMV_2_5,
  67. MTMD_SLICE_TMPL_MINICPMV_2_6,
  68. MTMD_SLICE_TMPL_LLAMA4,
  69. MTMD_SLICE_TMPL_IDEFICS3,
  70. };
  71. const char * mtmd_default_marker() {
  72. return "<__media__>";
  73. }
  74. mtmd_context_params mtmd_context_params_default() {
  75. mtmd_context_params params;
  76. params.use_gpu = true;
  77. params.print_timings = true;
  78. params.n_threads = 4;
  79. params.verbosity = GGML_LOG_LEVEL_INFO;
  80. params.image_marker = MTMD_DEFAULT_IMAGE_MARKER;
  81. params.media_marker = mtmd_default_marker();
  82. return params;
  83. }
  84. struct mtmd_context {
  85. struct clip_ctx * ctx_v; // vision
  86. struct clip_ctx * ctx_a; // audio
  87. const struct llama_model * text_model;
  88. std::vector<float> image_embd_v; // image embedding vector
  89. bool print_timings;
  90. int n_threads;
  91. std::string media_marker;
  92. const int n_embd_text;
  93. // these are not token, but strings used to mark the beginning and end of image/audio embeddings
  94. std::string img_beg;
  95. std::string img_end;
  96. std::string aud_beg;
  97. std::string aud_end;
  98. // for llava-uhd style models, we need special tokens in-between slices
  99. // minicpmv calls them "slices", llama 4 calls them "tiles"
  100. mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
  101. std::vector<llama_token> tok_ov_img_start; // overview image
  102. std::vector<llama_token> tok_ov_img_end; // overview image
  103. std::vector<llama_token> tok_slices_start; // start of all slices
  104. std::vector<llama_token> tok_slices_end; // end of all slices
  105. std::vector<llama_token> tok_sli_img_start; // single slice start
  106. std::vector<llama_token> tok_sli_img_end; // single slice end
  107. std::vector<llama_token> tok_sli_img_mid; // between 2 slices
  108. std::vector<llama_token> tok_row_end; // end of row
  109. bool tok_row_end_trail = false;
  110. bool ov_img_first = false;
  111. bool use_mrope = false; // for Qwen2VL, we need to use M-RoPE
  112. // string template for slice image delimiters with row/col (idefics3)
  113. std::string sli_img_start_tmpl;
  114. // for whisper, we pre-calculate the mel filter bank
  115. whisper_preprocessor::whisper_filters w_filters;
  116. // TODO @ngxson : add timings
  117. mtmd_context(const char * mmproj_fname,
  118. const llama_model * text_model,
  119. const mtmd_context_params & ctx_params) :
  120. text_model (text_model),
  121. print_timings(ctx_params.print_timings),
  122. n_threads (ctx_params.n_threads),
  123. media_marker (ctx_params.media_marker),
  124. n_embd_text (llama_model_n_embd(text_model))
  125. {
  126. if (std::string(ctx_params.image_marker) != MTMD_DEFAULT_IMAGE_MARKER) {
  127. throw std::runtime_error("custom image_marker is not supported anymore, use media_marker instead");
  128. }
  129. if (media_marker.empty()) {
  130. throw std::runtime_error("media_marker must not be empty");
  131. }
  132. clip_context_params ctx_clip_params;
  133. ctx_clip_params.use_gpu = ctx_params.use_gpu;
  134. ctx_clip_params.verbosity = ctx_params.verbosity;
  135. auto res = clip_init(mmproj_fname, ctx_clip_params);
  136. ctx_v = res.ctx_v;
  137. ctx_a = res.ctx_a;
  138. if (!ctx_v && !ctx_a) {
  139. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  140. }
  141. // if both vision and audio mmproj are present, we need to validate their n_embd
  142. if (ctx_v && ctx_a) {
  143. int n_embd_v = clip_n_mmproj_embd(ctx_v);
  144. int n_embd_a = clip_n_mmproj_embd(ctx_a);
  145. if (n_embd_v != n_embd_a) {
  146. throw std::runtime_error(string_format(
  147. "mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d)\n",
  148. n_embd_v, n_embd_a));
  149. }
  150. }
  151. // since we already validate n_embd of vision and audio mmproj,
  152. // we can safely assume that they are the same
  153. int n_embd_clip = clip_n_mmproj_embd(ctx_v ? ctx_v : ctx_a);
  154. if (n_embd_text != n_embd_clip) {
  155. throw std::runtime_error(string_format(
  156. "mismatch between text model (n_embd = %d) and mmproj (n_embd = %d)\n"
  157. "hint: you may be using wrong mmproj\n",
  158. n_embd_text, n_embd_clip));
  159. }
  160. if (ctx_v) {
  161. init_vision();
  162. }
  163. if (ctx_a) {
  164. init_audio();
  165. }
  166. }
  167. void init_vision() {
  168. GGML_ASSERT(ctx_v != nullptr);
  169. use_mrope = clip_is_qwen2vl(ctx_v);
  170. projector_type proj = clip_get_projector_type(ctx_v);
  171. int minicpmv_version = clip_is_minicpmv(ctx_v);
  172. if (minicpmv_version == 2) {
  173. // minicpmv 2.5 format:
  174. // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
  175. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
  176. tok_ov_img_start = {lookup_token("<image>")};
  177. tok_ov_img_end = {lookup_token("</image>")};
  178. tok_slices_start = {lookup_token("<slice>")};
  179. tok_slices_end = {lookup_token("</slice>")};
  180. tok_sli_img_start = tok_ov_img_start;
  181. tok_sli_img_end = tok_ov_img_end;
  182. tok_row_end = {lookup_token("\n")};
  183. tok_row_end_trail = false; // no trailing end-of-row token
  184. ov_img_first = true;
  185. } else if (minicpmv_version == 3 || minicpmv_version == 4 || minicpmv_version == 5 || minicpmv_version == 6) {
  186. // minicpmv 2.6 format:
  187. // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
  188. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
  189. tok_ov_img_start = {lookup_token("<image>")};
  190. tok_ov_img_end = {lookup_token("</image>")};
  191. tok_sli_img_start = {lookup_token("<slice>")};
  192. tok_sli_img_end = {lookup_token("</slice>")};
  193. tok_row_end = {lookup_token("\n")};
  194. tok_row_end_trail = false; // no trailing end-of-row token
  195. ov_img_first = true;
  196. } else if (minicpmv_version != 0) {
  197. GGML_ASSERT(false && "unsupported minicpmv version");
  198. } else if (proj == PROJECTOR_TYPE_LLAMA4) {
  199. // llama 4 format:
  200. // <|image_start|>
  201. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  202. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  203. // ... <|tile_y_separator|> <-- trailing end-of-row token
  204. // <|image|> (overview) <-- overview image is last
  205. // <|image_end|>
  206. slice_tmpl = MTMD_SLICE_TMPL_LLAMA4;
  207. tok_ov_img_start = {lookup_token("<|image|>")};
  208. tok_sli_img_mid = {lookup_token("<|tile_x_separator|>")};
  209. tok_row_end = {lookup_token("<|tile_y_separator|>")};
  210. tok_row_end_trail = true; // add trailing end-of-row token
  211. ov_img_first = false; // overview image is last
  212. }
  213. // set boi/eoi
  214. if (proj == PROJECTOR_TYPE_GEMMA3) {
  215. // <start_of_image> ... (image embeddings) ... <end_of_image>
  216. img_beg = "<start_of_image>";
  217. img_end = "<end_of_image>";
  218. } else if (proj == PROJECTOR_TYPE_IDEFICS3) {
  219. // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
  220. slice_tmpl = MTMD_SLICE_TMPL_IDEFICS3;
  221. tok_ov_img_start = {lookup_token("\n"), lookup_token("<fake_token_around_image>"), lookup_token("<global-img>")};
  222. tok_ov_img_end = {lookup_token("<fake_token_around_image>")};
  223. tok_row_end = {lookup_token("\n")};
  224. img_beg = "<fake_token_around_image>";
  225. sli_img_start_tmpl = "<fake_token_around_image><row_%d_col_%d>";
  226. } else if (proj == PROJECTOR_TYPE_PIXTRAL) {
  227. // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
  228. img_end = "[IMG_END]";
  229. } else if (proj == PROJECTOR_TYPE_QWEN2VL || proj == PROJECTOR_TYPE_QWEN25VL) {
  230. // <|vision_start|> ... (image embeddings) ... <|vision_end|>
  231. img_beg = "<|vision_start|>";
  232. img_end = "<|vision_end|>";
  233. } else if (proj == PROJECTOR_TYPE_LLAMA4) {
  234. // (more details in mtmd_context constructor)
  235. img_beg = "<|image_start|>";
  236. img_end = "<|image_end|>";
  237. LOG_WRN("%s: llama 4 vision is known to have degraded quality:\n"
  238. " https://github.com/ggml-org/llama.cpp/pull/13282\n", __func__);
  239. } else if (proj == PROJECTOR_TYPE_INTERNVL) {
  240. // <img> ... (image embeddings) ... </img>
  241. img_beg = "<img>";
  242. img_end = "</img>";
  243. }
  244. }
  245. void init_audio() {
  246. GGML_ASSERT(ctx_a != nullptr);
  247. projector_type proj = clip_get_projector_type(ctx_a);
  248. if (clip_has_whisper_encoder(ctx_a)) {
  249. // TODO @ngxson : check if model n_mel is 128 or 80
  250. w_filters = whisper_precalc_filters::get_128_bins();
  251. }
  252. LOG_WRN("%s: audio input is in experimental stage and may have reduced quality:\n"
  253. " https://github.com/ggml-org/llama.cpp/discussions/13759\n", __func__);
  254. if (proj == PROJECTOR_TYPE_QWEN2A) {
  255. // <|audio_bos|> ... (embeddings) ... <|audio_eos|>
  256. aud_beg = "<|audio_bos|>";
  257. aud_end = "<|audio_eos|>";
  258. } else if (proj == PROJECTOR_TYPE_ULTRAVOX) {
  259. // [BEGIN_AUDIO] ... (embeddings) ...
  260. aud_beg = "[BEGIN_AUDIO]";
  261. }
  262. }
  263. // get clip ctx based on chunk type
  264. clip_ctx * get_clip_ctx(const mtmd_input_chunk * chunk) const {
  265. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  266. return ctx_v;
  267. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  268. return ctx_a;
  269. }
  270. GGML_ABORT("unknown chunk type");
  271. }
  272. projector_type proj_type_v() const {
  273. return ctx_v ? clip_get_projector_type(ctx_v) : PROJECTOR_TYPE_UNKNOWN;
  274. }
  275. projector_type proj_type_a() const {
  276. return ctx_a ? clip_get_projector_type(ctx_a) : PROJECTOR_TYPE_UNKNOWN;
  277. }
  278. ~mtmd_context() {
  279. clip_free(ctx_a);
  280. clip_free(ctx_v);
  281. }
  282. private:
  283. llama_token lookup_token(const std::string & token_text) {
  284. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  285. const int n_vocab = llama_vocab_n_tokens(vocab);
  286. for (int i = 0; i < n_vocab; i++) {
  287. if (token_to_piece(vocab, i, true) == token_text) {
  288. return i;
  289. }
  290. }
  291. return LLAMA_TOKEN_NULL;
  292. }
  293. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  294. std::string piece;
  295. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  296. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  297. if (n_chars < 0) {
  298. piece.resize(-n_chars);
  299. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  300. GGML_ASSERT(check == -n_chars);
  301. } else {
  302. piece.resize(n_chars);
  303. }
  304. return piece;
  305. }
  306. };
  307. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  308. const struct llama_model * text_model,
  309. const struct mtmd_context_params ctx_params) {
  310. try {
  311. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  312. } catch (const std::exception & e) {
  313. LOG_ERR("%s: error: %s\n", __func__, e.what());
  314. return nullptr;
  315. }
  316. }
  317. void mtmd_free(mtmd_context * ctx) {
  318. if (ctx) {
  319. delete ctx;
  320. }
  321. }
  322. struct mtmd_tokenizer {
  323. mtmd_context * ctx;
  324. std::vector<const mtmd_bitmap *> bitmaps;
  325. std::string input_text;
  326. bool add_special;
  327. bool parse_special;
  328. const llama_vocab * vocab;
  329. mtmd_input_chunks cur;
  330. mtmd_tokenizer(mtmd_context * ctx,
  331. const mtmd_input_text * text,
  332. const mtmd_bitmap ** bitmaps,
  333. size_t n_bitmaps) : ctx(ctx), bitmaps(bitmaps, bitmaps + n_bitmaps) {
  334. add_special = text->add_special;
  335. parse_special = text->parse_special;
  336. input_text = text->text;
  337. vocab = llama_model_get_vocab(ctx->text_model);
  338. // for compatibility, we convert image marker to media marker
  339. string_replace_all(input_text, MTMD_DEFAULT_IMAGE_MARKER, ctx->media_marker);
  340. }
  341. int32_t tokenize(mtmd_input_chunks * output) {
  342. cur.entries.clear();
  343. std::vector<std::string> parts = split_text(input_text, ctx->media_marker);
  344. size_t i_bm = 0; // index of the current bitmap
  345. for (auto & part : parts) {
  346. if (part == ctx->media_marker) {
  347. // this is a marker, we should add the next bitmap
  348. if (i_bm >= bitmaps.size()) {
  349. LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
  350. __func__, bitmaps.size(), parts.size() - 1);
  351. return 1;
  352. }
  353. const mtmd_bitmap * bitmap = bitmaps[i_bm++];
  354. int32_t res = add_media(bitmap);
  355. if (res != 0) {
  356. return res;
  357. }
  358. } else {
  359. // this is a text part, we should add it as text
  360. add_text(part, parse_special);
  361. }
  362. }
  363. if (add_special && llama_vocab_get_add_bos(vocab)) {
  364. // if first chunk is text, we add BOS token to first text chunk
  365. // otherwise, create a new text chunk with BOS token
  366. if (!cur.entries.empty() && cur.entries[0].type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  367. // add BOS token to the beginning of first text chunk
  368. cur.entries[0].tokens_text.insert(cur.entries[0].tokens_text.begin(), llama_vocab_bos(vocab));
  369. } else {
  370. // create a new text chunk with BOS token at the beginning
  371. mtmd_input_chunk bos_chunk{
  372. MTMD_INPUT_CHUNK_TYPE_TEXT,
  373. {llama_vocab_bos(vocab)},
  374. nullptr, // image tokens
  375. nullptr, // audio tokens
  376. };
  377. cur.entries.insert(cur.entries.begin(), std::move(bos_chunk));
  378. }
  379. }
  380. if (add_special && llama_vocab_get_add_eos(vocab)) {
  381. // if last chunk is text, we add EOS token to it
  382. add_text({llama_vocab_eos(vocab)});
  383. }
  384. if (i_bm != bitmaps.size()) {
  385. LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
  386. __func__, bitmaps.size(), parts.size() - 1);
  387. return 1;
  388. }
  389. *output = std::move(cur);
  390. return 0;
  391. }
  392. void add_text(const std::string & txt, bool parse_special) {
  393. LOG_DBG("%s: %s\n", __func__, txt.c_str());
  394. auto tokens = mtmd_tokenize_text_internal(vocab, txt, /* add_special */ false, parse_special);
  395. add_text(tokens);
  396. }
  397. void add_text(const std::vector<llama_token> & tokens) {
  398. if (tokens.empty()) {
  399. return;
  400. }
  401. // if last entry is also a text chunk, add tokens to it instead of creating new chunk
  402. if (!cur.entries.empty() && cur.entries.back().type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  403. cur.entries.back().tokens_text.insert(
  404. cur.entries.back().tokens_text.end(),
  405. tokens.begin(),
  406. tokens.end());
  407. } else {
  408. mtmd_input_chunk chunk{
  409. MTMD_INPUT_CHUNK_TYPE_TEXT,
  410. tokens,
  411. nullptr, // image tokens
  412. nullptr, // audio tokens
  413. };
  414. cur.entries.emplace_back(std::move(chunk));
  415. }
  416. }
  417. int32_t add_media(const mtmd_bitmap * bitmap) {
  418. if (!bitmap->is_audio) {
  419. // handle image
  420. if (!ctx->ctx_v) {
  421. LOG_ERR("%s: error: model does not support vision input\n", __func__);
  422. return 2;
  423. }
  424. if (!ctx->img_beg.empty()) {
  425. add_text(ctx->img_beg, true); // add image begin token
  426. }
  427. // convert mtmd_bitmap to clip_image_u8
  428. clip_image_u8_ptr img_u8(clip_image_u8_init());
  429. img_u8->nx = bitmap->nx;
  430. img_u8->ny = bitmap->ny;
  431. img_u8->buf.resize(bitmap->data.size());
  432. std::memcpy(img_u8->buf.data(), bitmap->data.data(), img_u8->nx * img_u8->ny * 3);
  433. // preprocess image
  434. clip_image_f32_batch batch_f32;
  435. bool ok = clip_image_preprocess(ctx->ctx_v, img_u8.get(), &batch_f32);
  436. if (!ok) {
  437. LOG_ERR("Unable to preprocess image\n");
  438. return 2;
  439. }
  440. // handle llava-uhd style preprocessing
  441. if (
  442. ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5
  443. || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6
  444. || ctx->slice_tmpl == MTMD_SLICE_TMPL_LLAMA4
  445. || ctx->slice_tmpl == MTMD_SLICE_TMPL_IDEFICS3
  446. ) {
  447. const int n_col = batch_f32.grid_x;
  448. const int n_row = batch_f32.grid_y;
  449. // split batch into chunks of single images
  450. // NOTE: batch_f32 will be invalidated after this call
  451. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmap->id);
  452. GGML_ASSERT(chunks.size() > 0);
  453. auto ov_chunk = std::move(chunks.front());
  454. chunks.erase(chunks.begin());
  455. // add overview image (first)
  456. if (ctx->ov_img_first) {
  457. add_text(ctx->tok_ov_img_start);
  458. cur.entries.emplace_back(std::move(ov_chunk));
  459. add_text(ctx->tok_ov_img_end);
  460. }
  461. // add slices (or tiles)
  462. if (!chunks.empty()) {
  463. GGML_ASSERT((int)chunks.size() == n_row * n_col);
  464. add_text(ctx->tok_slices_start);
  465. for (int y = 0; y < n_row; y++) {
  466. for (int x = 0; x < n_col; x++) {
  467. const bool is_last_in_row = (x == n_col - 1);
  468. if (!ctx->tok_sli_img_start.empty()) {
  469. add_text(ctx->tok_sli_img_start);
  470. } else if (!ctx->sli_img_start_tmpl.empty()) {
  471. // If using a template to preceed a slice image
  472. const size_t sz = std::snprintf(nullptr, 0, ctx->sli_img_start_tmpl.c_str(), y+1, x+1) + 1;
  473. std::unique_ptr<char[]> buf(new char[sz]);
  474. std::snprintf(buf.get(), sz, ctx->sli_img_start_tmpl.c_str(), y+1, x+1);
  475. add_text(std::string(buf.get(), buf.get() + sz - 1), true);
  476. }
  477. cur.entries.emplace_back(std::move(chunks[y * n_col + x]));
  478. add_text(ctx->tok_sli_img_end);
  479. if (!is_last_in_row) {
  480. add_text(ctx->tok_sli_img_mid);
  481. }
  482. }
  483. if ((y != n_row - 1 || ctx->tok_row_end_trail)) {
  484. add_text(ctx->tok_row_end);
  485. }
  486. }
  487. add_text(ctx->tok_slices_end);
  488. }
  489. // add overview image (last)
  490. if (!ctx->ov_img_first) {
  491. add_text(ctx->tok_ov_img_start);
  492. cur.entries.emplace_back(std::move(ov_chunk));
  493. add_text(ctx->tok_ov_img_end);
  494. }
  495. } else {
  496. size_t n_tokens = 0;
  497. for (const auto & entry : batch_f32.entries) {
  498. n_tokens += clip_n_output_tokens(ctx->ctx_v, entry.get());
  499. }
  500. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  501. if (ctx->use_mrope) {
  502. // for Qwen2VL, we need this information for M-RoPE decoding positions
  503. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_v, batch_f32.entries[0].get());
  504. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_v, batch_f32.entries[0].get());
  505. image_tokens->use_mrope_pos = true;
  506. } else {
  507. // other models, we only need the total number of tokens
  508. image_tokens->nx = n_tokens;
  509. image_tokens->ny = 1;
  510. }
  511. image_tokens->batch_f32 = std::move(batch_f32);
  512. image_tokens->id = bitmap->id; // optional
  513. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  514. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  515. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  516. mtmd_input_chunk chunk{
  517. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  518. {}, // text tokens
  519. std::move(image_tokens),
  520. nullptr, // audio tokens
  521. };
  522. cur.entries.emplace_back(std::move(chunk));
  523. }
  524. if (!ctx->img_end.empty()) {
  525. add_text(ctx->img_end, true); // add image end token
  526. }
  527. } else {
  528. // handle audio
  529. if (!ctx->ctx_a) {
  530. LOG_ERR("%s: error: model does not support audio input\n", __func__);
  531. return 2;
  532. }
  533. if (bitmap->data.size() == 0) {
  534. LOG_ERR("%s: error: empty audio data\n", __func__);
  535. return 2;
  536. }
  537. if (!ctx->aud_beg.empty()) {
  538. add_text(ctx->aud_beg, true); // add audio begin token
  539. }
  540. // preprocess audio
  541. GGML_ASSERT(ctx->w_filters.n_mel); // make sure we have filter preloaded
  542. std::vector<whisper_preprocessor::whisper_mel> mel_spec_chunks;
  543. const float * samples = (const float *)bitmap->data.data();
  544. size_t n_samples = bitmap->data.size() / sizeof(float);
  545. bool ok = whisper_preprocessor::preprocess_audio(samples, n_samples, ctx->w_filters, mel_spec_chunks);
  546. if (!ok) {
  547. LOG_ERR("Unable to preprocess audio\n");
  548. return 2;
  549. }
  550. // consider each mel_spec as a separate audio chunk
  551. // TODO: maybe support batching, but this may come with memory cost
  552. for (auto & mel_spec : mel_spec_chunks) {
  553. clip_image_f32_ptr mel_f32(clip_image_f32_init());
  554. mel_f32->nx = mel_spec.n_len;
  555. mel_f32->ny = mel_spec.n_mel;
  556. mel_f32->buf = std::move(mel_spec.data);
  557. size_t n_tokens = clip_n_output_tokens(ctx->ctx_a, mel_f32.get());
  558. clip_image_f32_batch batch_f32;
  559. batch_f32.is_audio = true;
  560. batch_f32.entries.push_back(std::move(mel_f32));
  561. mtmd_audio_tokens_ptr audio_tokens(new mtmd_audio_tokens);
  562. audio_tokens->n_tokens = n_tokens;
  563. audio_tokens->batch_f32 = std::move(batch_f32);
  564. audio_tokens->id = bitmap->id; // optional
  565. LOG_DBG("audio_tokens->n_tokens = %d\n", audio_tokens->n_tokens);
  566. mtmd_input_chunk chunk{
  567. MTMD_INPUT_CHUNK_TYPE_AUDIO,
  568. {}, // text tokens
  569. nullptr, // image tokens
  570. std::move(audio_tokens),
  571. };
  572. cur.entries.emplace_back(std::move(chunk));
  573. }
  574. if (!ctx->aud_end.empty()) {
  575. add_text(ctx->aud_end, true); // add audio end token
  576. }
  577. }
  578. return 0;
  579. }
  580. std::vector<mtmd_input_chunk> split_batch_to_chunk(clip_image_f32_batch && batch_f32, const std::string & id) {
  581. std::vector<mtmd_input_chunk> chunks;
  582. for (auto & entry : batch_f32.entries) {
  583. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  584. image_tokens->nx = clip_n_output_tokens(ctx->ctx_v, entry.get());
  585. image_tokens->ny = 1;
  586. image_tokens->batch_f32.entries.push_back(std::move(entry));
  587. image_tokens->id = id;
  588. mtmd_input_chunk chunk{
  589. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  590. {}, // text tokens
  591. std::move(image_tokens),
  592. nullptr, // audio tokens
  593. };
  594. chunks.emplace_back(std::move(chunk));
  595. }
  596. return chunks;
  597. }
  598. // for example: "a <__media__> b <__media__> c" --> "a", "<__media__>", "b", "<__media__>", "c"
  599. static std::vector<std::string> split_text(const std::string & input, const std::string & delimiter) {
  600. std::vector<std::string> result;
  601. if (input.empty()) {
  602. return result;
  603. }
  604. size_t start = 0;
  605. size_t pos = 0;
  606. while ((pos = input.find(delimiter, start)) != std::string::npos) {
  607. if (pos > start) {
  608. result.push_back(input.substr(start, pos - start));
  609. }
  610. result.push_back(delimiter);
  611. start = pos + delimiter.length();
  612. }
  613. if (start < input.length()) {
  614. result.push_back(input.substr(start));
  615. }
  616. return result;
  617. }
  618. // copied from common_tokenize
  619. static std::vector<llama_token> mtmd_tokenize_text_internal(
  620. const struct llama_vocab * vocab,
  621. const std::string & text,
  622. bool add_special,
  623. bool parse_special) {
  624. // upper limit for the number of tokens
  625. int n_tokens = text.length() + 2 * add_special;
  626. std::vector<llama_token> result(n_tokens);
  627. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  628. if (n_tokens < 0) {
  629. result.resize(-n_tokens);
  630. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  631. GGML_ASSERT(check == -n_tokens);
  632. } else {
  633. result.resize(n_tokens);
  634. }
  635. return result;
  636. }
  637. };
  638. int32_t mtmd_tokenize(mtmd_context * ctx,
  639. mtmd_input_chunks * output,
  640. const mtmd_input_text * text,
  641. const mtmd_bitmap ** bitmaps,
  642. size_t n_bitmaps) {
  643. mtmd_tokenizer tokenizer(ctx, text, bitmaps, n_bitmaps);
  644. return tokenizer.tokenize(output);
  645. }
  646. int32_t mtmd_encode_chunk(mtmd_context * ctx, const mtmd_input_chunk * chunk) {
  647. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  648. LOG_WRN("mtmd_encode_chunk has no effect for text chunks\n");
  649. return 0;
  650. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  651. if (!ctx->ctx_v) {
  652. LOG_ERR("%s: model does not support vision input\n", __func__);
  653. return 1;
  654. }
  655. return mtmd_encode(ctx, chunk->tokens_image.get());
  656. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  657. if (!ctx->ctx_a) {
  658. LOG_ERR("%s: model does not support audio input\n", __func__);
  659. return 1;
  660. }
  661. int n_mmproj_embd = ctx->n_embd_text;
  662. ctx->image_embd_v.resize(chunk->tokens_audio->n_tokens * n_mmproj_embd);
  663. bool ok = clip_image_batch_encode(
  664. ctx->ctx_a,
  665. ctx->n_threads,
  666. &chunk->tokens_audio->batch_f32,
  667. ctx->image_embd_v.data());
  668. return ok ? 0 : 1;
  669. }
  670. LOG_ERR("%s: unknown chunk type %d\n", __func__, (int)chunk->type);
  671. return 1;
  672. }
  673. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  674. clip_ctx * ctx_clip = ctx->ctx_v;
  675. if (!ctx_clip) {
  676. LOG_ERR("%s: this API does not support non-vision input, please use mtmd_encode_chunk instead\n", __func__);
  677. return 1;
  678. }
  679. int n_mmproj_embd = clip_n_mmproj_embd(ctx_clip);
  680. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  681. bool ok = false;
  682. if (clip_is_llava(ctx_clip)
  683. || clip_is_minicpmv(ctx_clip)
  684. || clip_is_glm(ctx_clip)) {
  685. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  686. const auto & entries = image_tokens->batch_f32.entries;
  687. for (size_t i = 0; i < entries.size(); i++) {
  688. int n_tokens_per_image = clip_n_output_tokens(ctx_clip, entries[i].get());
  689. ok = clip_image_encode(
  690. ctx_clip,
  691. ctx->n_threads,
  692. entries[i].get(),
  693. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  694. }
  695. } else {
  696. ok = clip_image_batch_encode(
  697. ctx_clip,
  698. ctx->n_threads,
  699. &image_tokens->batch_f32,
  700. ctx->image_embd_v.data());
  701. }
  702. return ok ? 0 : 1;
  703. }
  704. float * mtmd_get_output_embd(mtmd_context * ctx) {
  705. return ctx->image_embd_v.data();
  706. }
  707. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  708. if (ctx->ctx_v && clip_get_projector_type(ctx->ctx_v) == PROJECTOR_TYPE_GEMMA3) {
  709. return true;
  710. }
  711. return false;
  712. }
  713. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  714. return ctx->use_mrope;
  715. }
  716. bool mtmd_support_vision(mtmd_context * ctx) {
  717. return ctx->ctx_v != nullptr;
  718. }
  719. bool mtmd_support_audio(mtmd_context * ctx) {
  720. return ctx->ctx_a != nullptr;
  721. }
  722. int mtmd_get_audio_bitrate(mtmd_context * ctx) {
  723. if (!ctx->ctx_a) {
  724. return -1;
  725. }
  726. // for now, we assume that all audio models have the same bitrate
  727. return 16000; // 16kHz
  728. }
  729. //
  730. // public API functions
  731. //
  732. // mtmd_bitmap
  733. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  734. uint32_t ny,
  735. const unsigned char * data) {
  736. mtmd_bitmap * bitmap = new mtmd_bitmap;
  737. bitmap->nx = nx;
  738. bitmap->ny = ny;
  739. size_t data_size = (size_t)nx * ny * 3;
  740. bitmap->data.resize(data_size);
  741. std::memcpy(bitmap->data.data(), data, data_size);
  742. return bitmap;
  743. }
  744. mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples,
  745. const float * data) {
  746. mtmd_bitmap * bitmap = new mtmd_bitmap;
  747. bitmap->nx = n_samples;
  748. bitmap->ny = 1;
  749. bitmap->is_audio = true;
  750. size_t data_size = n_samples * sizeof(float);
  751. bitmap->data.resize(data_size);
  752. std::memcpy(bitmap->data.data(), data, data_size);
  753. return bitmap;
  754. }
  755. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  756. return bitmap->nx;
  757. }
  758. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  759. return bitmap->ny;
  760. }
  761. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  762. return bitmap->data.data();
  763. }
  764. size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap) {
  765. return bitmap->data.size();
  766. }
  767. bool mtmd_bitmap_is_audio(const mtmd_bitmap * bitmap) {
  768. return bitmap->is_audio;
  769. }
  770. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  771. return bitmap->id.c_str();
  772. }
  773. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  774. if (id) {
  775. bitmap->id = std::string(id);
  776. } else {
  777. bitmap->id.clear();
  778. }
  779. }
  780. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  781. if (bitmap) {
  782. delete bitmap;
  783. }
  784. }
  785. // mtmd_input_chunks
  786. mtmd_input_chunks * mtmd_input_chunks_init() {
  787. return new mtmd_input_chunks;
  788. }
  789. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  790. return chunks->entries.size();
  791. }
  792. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  793. if (idx >= chunks->entries.size()) {
  794. return nullptr;
  795. }
  796. return &chunks->entries[idx];
  797. }
  798. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  799. if (chunks) {
  800. delete chunks;
  801. }
  802. }
  803. // mtmd_input_chunk
  804. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  805. return chunk->type;
  806. }
  807. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  808. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  809. *n_tokens_output = chunk->tokens_text.size();
  810. return chunk->tokens_text.data();
  811. }
  812. *n_tokens_output = 0;
  813. return nullptr;
  814. }
  815. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  816. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  817. return chunk->tokens_image.get();
  818. }
  819. return nullptr;
  820. }
  821. size_t mtmd_input_chunk_get_n_tokens(const mtmd_input_chunk * chunk) {
  822. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  823. return chunk->tokens_text.size();
  824. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  825. return mtmd_image_tokens_get_n_tokens(chunk->tokens_image.get());
  826. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  827. return chunk->tokens_audio->n_tokens;
  828. } else {
  829. GGML_ABORT("invalid chunk type");
  830. }
  831. }
  832. llama_pos mtmd_input_chunk_get_n_pos(const mtmd_input_chunk * chunk) {
  833. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  834. return chunk->tokens_text.size();
  835. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  836. return mtmd_image_tokens_get_n_pos(chunk->tokens_image.get());
  837. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  838. return chunk->tokens_audio->n_tokens;
  839. } else {
  840. GGML_ABORT("invalid chunk type");
  841. }
  842. }
  843. const char * mtmd_input_chunk_get_id(const mtmd_input_chunk * chunk) {
  844. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  845. return chunk->tokens_image->id.c_str();
  846. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  847. return chunk->tokens_audio->id.c_str();
  848. }
  849. return nullptr;
  850. }
  851. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  852. mtmd_input_chunk * copy = new mtmd_input_chunk{
  853. chunk->type,
  854. chunk->tokens_text,
  855. nullptr,
  856. nullptr,
  857. };
  858. if (chunk->tokens_image) {
  859. // copy the image tokens
  860. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  861. *copy->tokens_image = chunk->tokens_image->clone();
  862. }
  863. if (chunk->tokens_audio) {
  864. // copy the audio tokens
  865. copy->tokens_audio = mtmd_audio_tokens_ptr(new mtmd_audio_tokens());
  866. *copy->tokens_audio = chunk->tokens_audio->clone();
  867. }
  868. return copy;
  869. }
  870. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  871. if (chunk) {
  872. delete chunk;
  873. }
  874. }
  875. // mtmd_image_tokens
  876. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  877. return image_tokens->n_tokens();
  878. }
  879. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  880. return image_tokens->nx;
  881. }
  882. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  883. return image_tokens->ny;
  884. }
  885. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  886. return image_tokens->id.c_str();
  887. }
  888. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  889. if (image_tokens->use_mrope_pos) {
  890. return 1; // for M-RoPE, the whole image is 1 in temporal dimension
  891. }
  892. return image_tokens->n_tokens();
  893. }
  894. // test function
  895. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  896. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  897. if (!chunks) {
  898. return nullptr;
  899. }
  900. // create a text chunk
  901. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  902. mtmd_input_chunk chunk_text{
  903. MTMD_INPUT_CHUNK_TYPE_TEXT,
  904. std::move(tokens_text),
  905. nullptr, // image tokens
  906. nullptr, // audio tokens
  907. };
  908. chunks->entries.emplace_back(std::move(chunk_text));
  909. // create an image chunk
  910. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  911. image_tokens->nx = 4;
  912. image_tokens->ny = 4;
  913. image_tokens->batch_f32.entries.resize(16);
  914. image_tokens->id = "image_1";
  915. mtmd_input_chunk chunk_image{
  916. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  917. {}, // text tokens
  918. std::move(image_tokens),
  919. nullptr, // audio tokens
  920. };
  921. chunks->entries.emplace_back(std::move(chunk_image));
  922. return chunks;
  923. }