mtmd.cpp 40 KB

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