mtmd.cpp 40 KB

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