mtmd.h 12 KB

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