mtmd.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. #ifndef MTMD_H
  2. #define MTMD_H
  3. #include "ggml.h"
  4. #include "llama.h"
  5. #include "clip.h"
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <stdbool.h>
  9. #ifdef __cplusplus
  10. #include <string>
  11. #include <vector>
  12. #include <cinttypes>
  13. #include <memory>
  14. #endif
  15. /**
  16. * libmtmd: A library for multimodal support in llama.cpp.
  17. *
  18. * WARNING: This API is experimental and subject to many BREAKING CHANGES.
  19. * Issues related to API usage may receive lower priority support.
  20. *
  21. * For the usage, see an example in mtmd-cli.cpp
  22. */
  23. #ifdef LLAMA_SHARED
  24. # if defined(_WIN32) && !defined(__MINGW32__)
  25. # ifdef LLAMA_BUILD
  26. # define MTMD_API __declspec(dllexport)
  27. # else
  28. # define MTMD_API __declspec(dllimport)
  29. # endif
  30. # else
  31. # define MTMD_API __attribute__ ((visibility ("default")))
  32. # endif
  33. #else
  34. # define MTMD_API
  35. #endif
  36. #define MTMD_DEFAULT_IMAGE_MARKER "<__image__>"
  37. #ifdef __cplusplus
  38. extern "C" {
  39. #endif
  40. enum mtmd_input_chunk_type {
  41. MTMD_INPUT_CHUNK_TYPE_TEXT,
  42. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  43. };
  44. // opaque types
  45. struct mtmd_context;
  46. struct mtmd_bitmap;
  47. struct mtmd_image_tokens;
  48. struct mtmd_input_chunk;
  49. struct mtmd_input_chunks;
  50. struct mtmd_input_text {
  51. const char * text;
  52. bool add_special;
  53. bool parse_special;
  54. };
  55. //
  56. // C API
  57. //
  58. typedef struct mtmd_context mtmd_context;
  59. typedef struct mtmd_bitmap mtmd_bitmap;
  60. typedef struct mtmd_image_tokens mtmd_image_tokens;
  61. typedef struct mtmd_input_chunk mtmd_input_chunk;
  62. typedef struct mtmd_input_chunks mtmd_input_chunks;
  63. typedef struct mtmd_input_text mtmd_input_text;
  64. struct mtmd_context_params {
  65. bool use_gpu;
  66. bool print_timings;
  67. int n_threads;
  68. enum ggml_log_level verbosity;
  69. const char * image_marker;
  70. };
  71. MTMD_API struct mtmd_context_params mtmd_context_params_default(void);
  72. // initialize the mtmd context
  73. // return nullptr on failure
  74. MTMD_API mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  75. const struct llama_model * text_model,
  76. const struct mtmd_context_params ctx_params);
  77. MTMD_API void mtmd_free(mtmd_context * ctx);
  78. // whether we need to set non-causal mask before llama_decode
  79. MTMD_API bool mtmd_decode_use_non_causal(mtmd_context * ctx);
  80. // whether the current model use M-RoPE for llama_decode
  81. MTMD_API bool mtmd_decode_use_mrope(mtmd_context * ctx);
  82. // mtmd_bitmap
  83. //
  84. // length of data must be nx * ny * 3
  85. // the data is in RGBRGBRGB... format
  86. MTMD_API mtmd_bitmap * mtmd_bitmap_init (uint32_t nx,
  87. uint32_t ny,
  88. const unsigned char * data);
  89. MTMD_API uint32_t mtmd_bitmap_get_nx (const mtmd_bitmap * bitmap);
  90. MTMD_API uint32_t mtmd_bitmap_get_ny (const mtmd_bitmap * bitmap);
  91. MTMD_API const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap);
  92. MTMD_API void mtmd_bitmap_free (mtmd_bitmap * bitmap);
  93. // bitmap ID is optional, but useful for KV cache tracking
  94. // these getters/setters are dedicated functions, so you can for example calculate the hash of the image based on mtmd_bitmap_get_data()
  95. MTMD_API const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap);
  96. MTMD_API void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id);
  97. // mtmd_input_chunks
  98. //
  99. // this is simply a list of mtmd_input_chunk
  100. // the elements can only be populated via mtmd_tokenize()
  101. MTMD_API mtmd_input_chunks * mtmd_input_chunks_init(void);
  102. MTMD_API size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks);
  103. MTMD_API const mtmd_input_chunk * mtmd_input_chunks_get (const mtmd_input_chunks * chunks, size_t idx);
  104. MTMD_API void mtmd_input_chunks_free(mtmd_input_chunks * chunks);
  105. // mtmd_input_chunk
  106. //
  107. // the instance will be constructed via mtmd_tokenize()
  108. // it will be freed along with mtmd_input_chunks
  109. MTMD_API enum mtmd_input_chunk_type mtmd_input_chunk_get_type (const mtmd_input_chunk * chunk);
  110. MTMD_API const llama_token * mtmd_input_chunk_get_tokens_text (const mtmd_input_chunk * chunk, size_t * n_tokens_output);
  111. MTMD_API const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk);
  112. // in case you want to use custom logic to handle the chunk (i.e. KV cache management)
  113. // you can move the chunk ownership to your own code by copying it
  114. // remember to free the chunk when you are done with it
  115. MTMD_API mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk);
  116. MTMD_API void mtmd_input_chunk_free(mtmd_input_chunk * chunk);
  117. // mtmd_image_tokens
  118. //
  119. // the instance will be constructed via mtmd_tokenize()
  120. // it will be freed along with mtmd_input_chunk
  121. MTMD_API size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens);
  122. MTMD_API size_t mtmd_image_tokens_get_nx (const mtmd_image_tokens * image_tokens);
  123. MTMD_API size_t mtmd_image_tokens_get_ny (const mtmd_image_tokens * image_tokens);
  124. MTMD_API const char * mtmd_image_tokens_get_id (const mtmd_image_tokens * image_tokens);
  125. // number of temporal positions (always 1 for M-RoPE, n_tokens otherwise)
  126. MTMD_API llama_pos mtmd_image_tokens_get_n_pos (const mtmd_image_tokens * image_tokens);
  127. // tokenize an input text prompt and an image
  128. // the prompt must have the input image marker (default: "<__image__>") in it
  129. // the marker will be replaced with the image tokens
  130. // for example:
  131. // "here is an image: <__image__>\ndescribe it in detail."
  132. // this will gives 3 chunks:
  133. // 1. "here is an image: <start_of_image>"
  134. // 2. (image tokens)
  135. // 3. "<end_of_image>\ndescribe it in detail."
  136. // number of bitmaps must be equal to the number of image markers in the prompt
  137. // this function is thread-safe (shared ctx)
  138. // return values:
  139. // 0 on success
  140. // 1 on number of images not matching the number of markers
  141. // 2 on image preprocessing error
  142. MTMD_API int32_t mtmd_tokenize(mtmd_context * ctx,
  143. mtmd_input_chunks * output,
  144. const mtmd_input_text * text,
  145. const mtmd_bitmap ** bitmaps,
  146. size_t n_bitmaps);
  147. // returns 0 on success
  148. MTMD_API int32_t mtmd_encode(mtmd_context * ctx,
  149. const mtmd_image_tokens * image_tokens);
  150. // get output embeddings from the last encode pass
  151. MTMD_API float * mtmd_get_output_embd(mtmd_context * ctx);
  152. /////////////////////////////////////////
  153. //
  154. // Helper functions (can be implemented based on other functions)
  155. //
  156. // Please note that these helpers are not guaranteed to be stable.
  157. // BREAKING CHANGES are expected.
  158. //
  159. // helper function to construct a mtmd_bitmap from a file
  160. // returns nullptr on failure
  161. // this function is thread-safe
  162. MTMD_API mtmd_bitmap * mtmd_helper_bitmap_init_from_file(const char * fname);
  163. // helper function to construct a mtmd_bitmap from a buffer containing a file
  164. // the file content must be an image in format supported by stb_image (jpg, png, bmp, gif, etc.)
  165. // returns nullptr on failure
  166. // this function is thread-safe
  167. MTMD_API mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len);
  168. // helper to count the total number of tokens from a list of chunks, useful to keep track of KV cache
  169. MTMD_API size_t mtmd_helper_get_n_tokens(const mtmd_input_chunks * chunks);
  170. // helper to count the total position of tokens from a list of chunks, useful to keep track of n_past
  171. // normally, n_pos is equal to n_tokens, but for M-RoPE it is different
  172. MTMD_API llama_pos mtmd_helper_get_n_pos(const mtmd_input_chunks * chunks);
  173. // helper function that automatically:
  174. // 1. run llama_decode() on text chunks
  175. // 2. run mtmd_encode() on image chunks, then mtmd_get_output_embd() and then llama_decode()
  176. // if any of the mtmd_encode() or llama_decode() calls return non-zero, stop and forward the error
  177. // otherwise, returns 0 on success
  178. // this function is NOT thread-safe
  179. MTMD_API int32_t mtmd_helper_eval_chunks(mtmd_context * ctx,
  180. struct llama_context * lctx,
  181. const mtmd_input_chunks * chunks,
  182. llama_pos n_past,
  183. llama_seq_id seq_id,
  184. int32_t n_batch,
  185. bool logits_last,
  186. llama_pos * new_n_past);
  187. // works like mtmd_helper_eval_chunks(), but only for a single chunk
  188. // this function is NOT thread-safe
  189. MTMD_API int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx,
  190. struct llama_context * lctx,
  191. const mtmd_input_chunk * chunk,
  192. llama_pos n_past,
  193. llama_seq_id seq_id,
  194. int32_t n_batch,
  195. bool logits_last,
  196. llama_pos * new_n_past);
  197. // helper function to decode an image whose embeddings have already been calculated
  198. // this helper will handle batching and pre/post decoding setup (for ex. gemma 3 requires non-causal attention)
  199. // ret 0 on success, -1 on chunk not being a valid image chunk, 1 on decode failure
  200. MTMD_API int32_t mtmd_helper_decode_image_chunk(mtmd_context * ctx,
  201. struct llama_context * lctx,
  202. const mtmd_input_chunk * chunk,
  203. float * encoded_embd,
  204. llama_pos n_past,
  205. llama_seq_id seq_id,
  206. int32_t n_batch,
  207. llama_pos * new_n_past);
  208. /////////////////////////////////////////
  209. // test function, to be used in test-mtmd-c-api.c
  210. MTMD_API mtmd_input_chunks * mtmd_test_create_input_chunks(void);
  211. #ifdef __cplusplus
  212. } // extern "C"
  213. #endif
  214. //
  215. // C++ wrappers
  216. //
  217. #ifdef __cplusplus
  218. namespace mtmd {
  219. struct mtmd_context_deleter {
  220. void operator()(mtmd_context * val) { mtmd_free(val); }
  221. };
  222. using context_ptr = std::unique_ptr<mtmd_context, mtmd_context_deleter>;
  223. struct mtmd_bitmap_deleter {
  224. void operator()(mtmd_bitmap * val) { mtmd_bitmap_free(val); }
  225. };
  226. using bitmap_ptr = std::unique_ptr<mtmd_bitmap, mtmd_bitmap_deleter>;
  227. struct mtmd_input_chunks_deleter {
  228. void operator()(mtmd_input_chunks * val) { mtmd_input_chunks_free(val); }
  229. };
  230. using input_chunks_ptr = std::unique_ptr<mtmd_input_chunks, mtmd_input_chunks_deleter>;
  231. struct mtmd_input_chunk_deleter {
  232. void operator()(mtmd_input_chunk * val) { mtmd_input_chunk_free(val); }
  233. };
  234. using input_chunk_ptr = std::unique_ptr<mtmd_input_chunk, mtmd_input_chunk_deleter>;
  235. struct bitmap {
  236. bitmap_ptr ptr;
  237. bitmap() : ptr(nullptr) {}
  238. bitmap(mtmd_bitmap * bitmap) : ptr(bitmap) {}
  239. bitmap(bitmap && other) noexcept : ptr(std::move(other.ptr)) {}
  240. bitmap(uint32_t nx, uint32_t ny, const unsigned char * data) {
  241. ptr.reset(mtmd_bitmap_init(nx, ny, data));
  242. }
  243. ~bitmap() = default;
  244. uint32_t nx() { return mtmd_bitmap_get_nx(ptr.get()); }
  245. uint32_t ny() { return mtmd_bitmap_get_ny(ptr.get()); }
  246. const unsigned char * data() { return mtmd_bitmap_get_data(ptr.get()); }
  247. std::string id() { return mtmd_bitmap_get_id(ptr.get()); }
  248. void set_id(const char * id) { mtmd_bitmap_set_id(ptr.get(), id); }
  249. };
  250. struct bitmaps {
  251. std::vector<bitmap> entries;
  252. ~bitmaps() = default;
  253. // return list of pointers to mtmd_bitmap
  254. // example:
  255. // auto bitmaps_c_ptr = bitmaps.c_ptr();
  256. // int32_t res = mtmd_tokenize(... bitmaps_c_ptr.data(), bitmaps_c_ptr.size());
  257. std::vector<const mtmd_bitmap *> c_ptr() {
  258. std::vector<const mtmd_bitmap *> res(entries.size());
  259. for (size_t i = 0; i < entries.size(); i++) {
  260. res[i] = entries[i].ptr.get();
  261. }
  262. return res;
  263. }
  264. };
  265. struct input_chunks {
  266. input_chunks_ptr ptr;
  267. input_chunks() = default;
  268. input_chunks(mtmd_input_chunks * chunks) : ptr(chunks) {}
  269. ~input_chunks() = default;
  270. size_t size() { return mtmd_input_chunks_size(ptr.get()); }
  271. const mtmd_input_chunk * operator[](size_t idx) {
  272. return mtmd_input_chunks_get(ptr.get(), idx);
  273. }
  274. };
  275. } // namespace mtmd
  276. #endif
  277. #endif