1
0

mtmd.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #ifndef MTMD_H
  2. #define MTMD_H
  3. #include "ggml.h"
  4. #include "llama.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <stdbool.h>
  8. #ifdef __cplusplus
  9. #include <string>
  10. #include <vector>
  11. #include <cinttypes>
  12. #include <memory>
  13. #endif
  14. /**
  15. * libmtmd: A library for multimodal support in llama.cpp.
  16. *
  17. * WARNING: This API is experimental and subject to many BREAKING CHANGES.
  18. * Issues related to API usage may receive lower priority support.
  19. *
  20. * For the usage, see an example in mtmd-cli.cpp
  21. *
  22. * For contributors:
  23. * - Make sure the C API is aligned with the libllama C API (as in llama.h)
  24. * - Do not include model name (e.g., qwen, gemma) in the API, use generic terms instead
  25. * - Keep the API minimal, do not expose internal details unless necessary
  26. */
  27. #ifdef LLAMA_SHARED
  28. # if defined(_WIN32) && !defined(__MINGW32__)
  29. # ifdef LLAMA_BUILD
  30. # define MTMD_API __declspec(dllexport)
  31. # else
  32. # define MTMD_API __declspec(dllimport)
  33. # endif
  34. # else
  35. # define MTMD_API __attribute__ ((visibility ("default")))
  36. # endif
  37. #else
  38. # define MTMD_API
  39. #endif
  40. // deprecated marker, use mtmd_default_marker() instead
  41. #define MTMD_DEFAULT_IMAGE_MARKER "<__image__>"
  42. #ifdef __cplusplus
  43. extern "C" {
  44. #endif
  45. enum mtmd_input_chunk_type {
  46. MTMD_INPUT_CHUNK_TYPE_TEXT,
  47. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  48. MTMD_INPUT_CHUNK_TYPE_AUDIO,
  49. };
  50. // opaque types
  51. struct mtmd_context;
  52. struct mtmd_bitmap;
  53. struct mtmd_image_tokens;
  54. struct mtmd_input_chunk;
  55. struct mtmd_input_chunks;
  56. struct mtmd_input_text {
  57. const char * text;
  58. bool add_special;
  59. bool parse_special;
  60. };
  61. //
  62. // C API
  63. //
  64. typedef struct mtmd_context mtmd_context;
  65. typedef struct mtmd_bitmap mtmd_bitmap;
  66. typedef struct mtmd_image_tokens mtmd_image_tokens;
  67. typedef struct mtmd_input_chunk mtmd_input_chunk;
  68. typedef struct mtmd_input_chunks mtmd_input_chunks;
  69. typedef struct mtmd_input_text mtmd_input_text;
  70. struct mtmd_context_params {
  71. bool use_gpu;
  72. bool print_timings;
  73. int n_threads;
  74. const char * image_marker; // deprecated, use media_marker instead
  75. const char * media_marker;
  76. enum llama_flash_attn_type flash_attn_type;
  77. bool warmup; // whether to run a warmup encode pass after initialization
  78. // limit number of image tokens, only for vision models with dynamic resolution
  79. int image_min_tokens; // minimum number of tokens for image input (default: read from metadata)
  80. int image_max_tokens; // maximum number of tokens for image input (default: read from metadata)
  81. };
  82. MTMD_API const char * mtmd_default_marker(void);
  83. MTMD_API struct mtmd_context_params mtmd_context_params_default(void);
  84. // initialize the mtmd context
  85. // return nullptr on failure
  86. MTMD_API mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  87. const struct llama_model * text_model,
  88. const struct mtmd_context_params ctx_params);
  89. MTMD_API void mtmd_free(mtmd_context * ctx);
  90. // whether we need to set non-causal mask before llama_decode
  91. MTMD_API bool mtmd_decode_use_non_causal(mtmd_context * ctx);
  92. // whether the current model use M-RoPE for llama_decode
  93. MTMD_API bool mtmd_decode_use_mrope(mtmd_context * ctx);
  94. // whether the current model supports vision input
  95. MTMD_API bool mtmd_support_vision(mtmd_context * ctx);
  96. // whether the current model supports audio input
  97. MTMD_API bool mtmd_support_audio(mtmd_context * ctx);
  98. // get audio bitrate in Hz, for example 16000 for Whisper
  99. // return -1 if audio is not supported
  100. MTMD_API int mtmd_get_audio_bitrate(mtmd_context * ctx);
  101. // mtmd_bitmap
  102. //
  103. // if bitmap is image:
  104. // length of data must be nx * ny * 3
  105. // the data is in RGBRGBRGB... format
  106. // if bitmap is audio:
  107. // length of data must be n_samples * sizeof(float)
  108. // the data is in float format (PCM F32)
  109. MTMD_API mtmd_bitmap * mtmd_bitmap_init (uint32_t nx, uint32_t ny, const unsigned char * data);
  110. MTMD_API mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples, const float * data);
  111. MTMD_API uint32_t mtmd_bitmap_get_nx (const mtmd_bitmap * bitmap);
  112. MTMD_API uint32_t mtmd_bitmap_get_ny (const mtmd_bitmap * bitmap);
  113. MTMD_API const unsigned char * mtmd_bitmap_get_data (const mtmd_bitmap * bitmap);
  114. MTMD_API size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap);
  115. MTMD_API bool mtmd_bitmap_is_audio (const mtmd_bitmap * bitmap);
  116. MTMD_API void mtmd_bitmap_free (mtmd_bitmap * bitmap);
  117. // bitmap ID is optional, but useful for KV cache tracking
  118. // these getters/setters are dedicated functions, so you can for example calculate the hash of the image based on mtmd_bitmap_get_data()
  119. MTMD_API const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap);
  120. MTMD_API void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id);
  121. // mtmd_input_chunks
  122. //
  123. // this is simply a list of mtmd_input_chunk
  124. // the elements can only be populated via mtmd_tokenize()
  125. MTMD_API mtmd_input_chunks * mtmd_input_chunks_init(void);
  126. MTMD_API size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks);
  127. MTMD_API const mtmd_input_chunk * mtmd_input_chunks_get (const mtmd_input_chunks * chunks, size_t idx);
  128. MTMD_API void mtmd_input_chunks_free(mtmd_input_chunks * chunks);
  129. // mtmd_input_chunk
  130. //
  131. // the instance will be constructed via mtmd_tokenize()
  132. // it will be freed along with mtmd_input_chunks
  133. MTMD_API enum mtmd_input_chunk_type mtmd_input_chunk_get_type (const mtmd_input_chunk * chunk);
  134. MTMD_API const llama_token * mtmd_input_chunk_get_tokens_text (const mtmd_input_chunk * chunk, size_t * n_tokens_output);
  135. MTMD_API const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk);
  136. MTMD_API size_t mtmd_input_chunk_get_n_tokens (const mtmd_input_chunk * chunk);
  137. // returns nullptr for ID on text chunk
  138. MTMD_API const char * mtmd_input_chunk_get_id (const mtmd_input_chunk * chunk);
  139. // number of temporal positions (equals to max(t,h,w) for M-RoPE; equals to n_tokens otherwise)
  140. MTMD_API llama_pos mtmd_input_chunk_get_n_pos (const mtmd_input_chunk * chunk);
  141. // in case you want to use custom logic to handle the chunk (i.e. KV cache management)
  142. // you can move the chunk ownership to your own code by copying it
  143. // remember to free the chunk when you are done with it
  144. MTMD_API mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk);
  145. MTMD_API void mtmd_input_chunk_free(mtmd_input_chunk * chunk);
  146. // mtmd_image_tokens
  147. //
  148. // the instance will be constructed via mtmd_tokenize()
  149. // it will be freed along with mtmd_input_chunk
  150. MTMD_API size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens); // TODO: deprecate
  151. MTMD_API size_t mtmd_image_tokens_get_nx (const mtmd_image_tokens * image_tokens);
  152. MTMD_API size_t mtmd_image_tokens_get_ny (const mtmd_image_tokens * image_tokens);
  153. MTMD_API const char * mtmd_image_tokens_get_id (const mtmd_image_tokens * image_tokens); // TODO: deprecate
  154. // number of temporal positions (equals to max(t,h,w) for M-RoPE; equals to n_tokens otherwise)
  155. MTMD_API llama_pos mtmd_image_tokens_get_n_pos (const mtmd_image_tokens * image_tokens); // TODO: deprecate
  156. // tokenize an input text prompt and a list of bitmaps (images/audio)
  157. // the prompt must have the input image marker (default: "<__media__>") in it
  158. // the default marker is defined by mtmd_default_marker()
  159. // the marker will be replaced with the image/audio chunk
  160. // for example:
  161. // "here is an image: <__media__>\ndescribe it in detail."
  162. // this will gives 3 chunks:
  163. // 1. "here is an image: <start_of_image>"
  164. // 2. (image/audio tokens)
  165. // 3. "<end_of_image>\ndescribe it in detail."
  166. // number of bitmaps must be equal to the number of markers in the prompt
  167. // this function is thread-safe (shared ctx)
  168. // return values:
  169. // 0 on success
  170. // 1 on number of bitmaps not matching the number of markers
  171. // 2 on image preprocessing error
  172. MTMD_API int32_t mtmd_tokenize(mtmd_context * ctx,
  173. mtmd_input_chunks * output,
  174. const mtmd_input_text * text,
  175. const mtmd_bitmap ** bitmaps,
  176. size_t n_bitmaps);
  177. // returns 0 on success
  178. // TODO: deprecate
  179. MTMD_API int32_t mtmd_encode(mtmd_context * ctx,
  180. const mtmd_image_tokens * image_tokens);
  181. // returns 0 on success
  182. MTMD_API int32_t mtmd_encode_chunk(mtmd_context * ctx,
  183. const mtmd_input_chunk * chunk);
  184. // get output embeddings from the last encode pass
  185. // the reading size (in bytes) is equal to:
  186. // llama_model_n_embd(model) * mtmd_input_chunk_get_n_tokens(chunk) * sizeof(float)
  187. MTMD_API float * mtmd_get_output_embd(mtmd_context * ctx);
  188. // Set callback for all future logging events.
  189. // If this is not called, or NULL is supplied, everything is output on stderr.
  190. MTMD_API void mtmd_log_set(ggml_log_callback log_callback, void * user_data);
  191. /////////////////////////////////////////
  192. // test function, to be used in test-mtmd-c-api.c
  193. MTMD_API mtmd_input_chunks * mtmd_test_create_input_chunks(void);
  194. #ifdef __cplusplus
  195. } // extern "C"
  196. #endif
  197. //
  198. // C++ wrappers
  199. //
  200. #ifdef __cplusplus
  201. namespace mtmd {
  202. struct mtmd_context_deleter {
  203. void operator()(mtmd_context * val) { mtmd_free(val); }
  204. };
  205. using context_ptr = std::unique_ptr<mtmd_context, mtmd_context_deleter>;
  206. struct mtmd_bitmap_deleter {
  207. void operator()(mtmd_bitmap * val) { mtmd_bitmap_free(val); }
  208. };
  209. using bitmap_ptr = std::unique_ptr<mtmd_bitmap, mtmd_bitmap_deleter>;
  210. struct mtmd_input_chunks_deleter {
  211. void operator()(mtmd_input_chunks * val) { mtmd_input_chunks_free(val); }
  212. };
  213. using input_chunks_ptr = std::unique_ptr<mtmd_input_chunks, mtmd_input_chunks_deleter>;
  214. struct mtmd_input_chunk_deleter {
  215. void operator()(mtmd_input_chunk * val) { mtmd_input_chunk_free(val); }
  216. };
  217. using input_chunk_ptr = std::unique_ptr<mtmd_input_chunk, mtmd_input_chunk_deleter>;
  218. struct bitmap {
  219. bitmap_ptr ptr;
  220. bitmap() : ptr(nullptr) {}
  221. bitmap(mtmd_bitmap * bitmap) : ptr(bitmap) {}
  222. bitmap(bitmap && other) noexcept : ptr(std::move(other.ptr)) {}
  223. bitmap(uint32_t nx, uint32_t ny, const unsigned char * data) {
  224. ptr.reset(mtmd_bitmap_init(nx, ny, data));
  225. }
  226. ~bitmap() = default;
  227. uint32_t nx() { return mtmd_bitmap_get_nx(ptr.get()); }
  228. uint32_t ny() { return mtmd_bitmap_get_ny(ptr.get()); }
  229. const unsigned char * data() { return mtmd_bitmap_get_data(ptr.get()); }
  230. size_t n_bytes() { return mtmd_bitmap_get_n_bytes(ptr.get()); }
  231. std::string id() { return mtmd_bitmap_get_id(ptr.get()); }
  232. void set_id(const char * id) { mtmd_bitmap_set_id(ptr.get(), id); }
  233. };
  234. struct bitmaps {
  235. std::vector<bitmap> entries;
  236. ~bitmaps() = default;
  237. // return list of pointers to mtmd_bitmap
  238. // example:
  239. // auto bitmaps_c_ptr = bitmaps.c_ptr();
  240. // int32_t res = mtmd_tokenize(... bitmaps_c_ptr.data(), bitmaps_c_ptr.size());
  241. std::vector<const mtmd_bitmap *> c_ptr() {
  242. std::vector<const mtmd_bitmap *> res(entries.size());
  243. for (size_t i = 0; i < entries.size(); i++) {
  244. res[i] = entries[i].ptr.get();
  245. }
  246. return res;
  247. }
  248. };
  249. struct input_chunks {
  250. input_chunks_ptr ptr;
  251. input_chunks() = default;
  252. input_chunks(mtmd_input_chunks * chunks) : ptr(chunks) {}
  253. ~input_chunks() = default;
  254. size_t size() { return mtmd_input_chunks_size(ptr.get()); }
  255. const mtmd_input_chunk * operator[](size_t idx) {
  256. return mtmd_input_chunks_get(ptr.get(), idx);
  257. }
  258. };
  259. } // namespace mtmd
  260. #endif
  261. #endif