mtmd.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "mtmd.h"
  4. #include "llama.h"
  5. #include <algorithm>
  6. #include <cerrno>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <limits>
  11. #include <vector>
  12. struct mtmd_context {
  13. struct clip_ctx * ctx_clip;
  14. const struct llama_model * text_model;
  15. std::vector<float> image_embd_v; // image embedding vector
  16. bool print_timings;
  17. int n_threads;
  18. std::string image_marker;
  19. // TODO @ngxson : add timings
  20. mtmd_context(const char * mmproj_fname,
  21. const llama_model * text_model,
  22. const mtmd_context_params & ctx_params) : print_timings(ctx_params.print_timings), n_threads(ctx_params.n_threads), image_marker(ctx_params.image_marker) {
  23. clip_context_params ctx_clip_params;
  24. ctx_clip_params.use_gpu = ctx_params.use_gpu;
  25. ctx_clip_params.verbosity = ctx_params.verbosity;
  26. ctx_clip = clip_init(mmproj_fname, ctx_clip_params);
  27. if (!ctx_clip) {
  28. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  29. }
  30. this->text_model = text_model;
  31. }
  32. ~mtmd_context() {
  33. clip_free(ctx_clip);
  34. }
  35. };
  36. struct mtmd_image_tokens_data {
  37. clip_image_f32_batch_ptr batch_f32; // preprocessed image patches
  38. };
  39. struct mtmd_image_tokens {
  40. uint32_t nx; // number of tokens in x direction
  41. uint32_t ny; // number of tokens in y direction
  42. uint32_t n_tokens() const { return nx * ny; }
  43. clip_image_f32_batch_ptr batch_f32; // preprocessed image patches
  44. };
  45. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  46. const struct llama_model * text_model,
  47. const struct mtmd_context_params ctx_params) {
  48. try {
  49. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  50. } catch (const std::exception & e) {
  51. LOG_ERR("%s: error: %s\n", __func__, e.what());
  52. return nullptr;
  53. }
  54. }
  55. void mtmd_free(mtmd_context * ctx) {
  56. if (ctx) {
  57. delete ctx;
  58. }
  59. }
  60. // copied from common_tokenize
  61. static std::vector<llama_token> mtmd_tokenize_text_internal(
  62. const struct llama_vocab * vocab,
  63. const std::string & text,
  64. bool add_special,
  65. bool parse_special) {
  66. // upper limit for the number of tokens
  67. int n_tokens = text.length() + 2 * add_special;
  68. std::vector<llama_token> result(n_tokens);
  69. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  70. if (n_tokens < 0) {
  71. result.resize(-n_tokens);
  72. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  73. GGML_ASSERT(check == -n_tokens);
  74. } else {
  75. result.resize(n_tokens);
  76. }
  77. return result;
  78. }
  79. mtmd_input_chunks * mtmd_tokenize(mtmd_context * ctx,
  80. const mtmd_input_text & text,
  81. const std::vector<mtmd_bitmap> & bitmaps) {
  82. mtmd_input_chunks * output = new mtmd_input_chunks;
  83. auto vocab = llama_model_get_vocab(ctx->text_model);
  84. std::string prompt_modified(text.text);
  85. std::string marker_modified(ctx->image_marker);
  86. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  87. // a bit hacky here, but works for now
  88. // for some models, we need to add prefix and suffix to the image embeddings
  89. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  90. // <start_of_image> ... (image embeddings) ... <end_of_image>
  91. marker_modified = "<start_of_image>" + ctx->image_marker + "<end_of_image>";
  92. string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
  93. }
  94. std::vector<std::string> parts = string_split_str(text.text, ctx->image_marker);
  95. output->clear();
  96. output->reserve(parts.size());
  97. size_t i_img = 0;
  98. for (const auto & part : parts) {
  99. //printf("tokenizing part: %s\n", part.c_str());
  100. bool add_bos = &parts.front() == &part;
  101. auto tokens = mtmd_tokenize_text_internal(vocab, part, text.add_special && add_bos, text.parse_special);
  102. if (tokens.empty()) {
  103. continue;
  104. }
  105. mtmd_input_chunk chunk{
  106. MTMD_INPUT_CHUNK_TYPE_TEXT,
  107. std::move(tokens),
  108. {},
  109. };
  110. output->emplace_back(std::move(chunk));
  111. if (&parts.back() != &part) {
  112. // add image token to middle of 2 parts
  113. if (i_img >= bitmaps.size()) {
  114. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  115. return nullptr;
  116. }
  117. // shim layer
  118. clip_image_u8_ptr img_u8(clip_image_u8_init());
  119. img_u8->nx = bitmaps[i_img].nx;
  120. img_u8->ny = bitmaps[i_img].ny;
  121. img_u8->buf.resize(bitmaps[i_img].data.size());
  122. std::memcpy(img_u8->buf.data(), bitmaps[i_img].data.data(), img_u8->nx * img_u8->ny * 3);
  123. // preprocess image
  124. clip_image_f32_batch_ptr batch_f32(new clip_image_f32_batch);
  125. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), batch_f32.get());
  126. if (!ok) {
  127. LOG_ERR("Unable to preprocess image\n");
  128. return nullptr;
  129. }
  130. mtmd_image_tokens * image_tokens = new mtmd_image_tokens;
  131. image_tokens->nx = clip_n_patches(ctx->ctx_clip); // TODO @ngxson : use clip_n_patches_by_image
  132. image_tokens->ny = 1; // TODO
  133. image_tokens->batch_f32 = std::move(batch_f32);
  134. mtmd_input_chunk chunk{
  135. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  136. {},
  137. image_tokens,
  138. };
  139. output->emplace_back(std::move(chunk));
  140. i_img++;
  141. }
  142. }
  143. return output;
  144. }
  145. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  146. for (auto & chunk : *chunks) {
  147. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE && chunk.tokens_image) {
  148. delete chunk.tokens_image;
  149. }
  150. }
  151. delete chunks;
  152. }
  153. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  154. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  155. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  156. bool ok = clip_image_batch_encode(
  157. ctx->ctx_clip,
  158. ctx->n_threads,
  159. image_tokens->batch_f32.get(),
  160. ctx->image_embd_v.data());
  161. return ok ? 0 : 1;
  162. }
  163. float * mtmd_get_output_embd(mtmd_context * ctx) {
  164. return ctx->image_embd_v.data();
  165. }
  166. size_t mtmd_helper_get_n_tokens(mtmd_input_chunks * chunks) {
  167. size_t n_tokens = 0;
  168. for (auto & chunk : *chunks) {
  169. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  170. n_tokens += chunk.tokens_text.size();
  171. } else if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  172. n_tokens += chunk.tokens_image->n_tokens();
  173. } else {
  174. GGML_ASSERT(false && "chunk type not supported");
  175. }
  176. }
  177. return n_tokens;
  178. }
  179. // helper struct to make working with embd batch easier
  180. // note: this will be removed after llama_batch_ext refactoring
  181. struct decode_embd_batch {
  182. std::vector<llama_pos> pos;
  183. std::vector<int32_t> n_seq_id;
  184. std::vector<llama_seq_id> seq_id_0;
  185. std::vector<llama_seq_id *> seq_ids;
  186. std::vector<int8_t> logits;
  187. llama_batch batch;
  188. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  189. pos .resize(n_tokens);
  190. n_seq_id.resize(n_tokens);
  191. seq_ids .resize(n_tokens + 1);
  192. logits .resize(n_tokens);
  193. seq_id_0.resize(1);
  194. seq_id_0[0] = seq_id;
  195. seq_ids [n_tokens] = nullptr;
  196. batch = {
  197. /*n_tokens =*/ n_tokens,
  198. /*tokens =*/ nullptr,
  199. /*embd =*/ embd,
  200. /*pos =*/ pos.data(),
  201. /*n_seq_id =*/ n_seq_id.data(),
  202. /*seq_id =*/ seq_ids.data(),
  203. /*logits =*/ logits.data(),
  204. };
  205. for (int i = 0; i < n_tokens; i++) {
  206. batch.pos [i] = pos_0 + i;
  207. batch.n_seq_id[i] = 1;
  208. batch.seq_id [i] = seq_id_0.data();
  209. batch.logits [i] = false;
  210. }
  211. }
  212. };
  213. int32_t mtmd_helper_eval(mtmd_context * ctx,
  214. llama_context * lctx,
  215. mtmd_input_chunks * chunks,
  216. llama_pos pos0,
  217. llama_seq_id seq_id,
  218. int32_t n_batch) {
  219. int32_t ret;
  220. llama_pos n_past = pos0;
  221. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  222. for (auto & chunk : *chunks) {
  223. bool is_last = &chunk == &chunks->back();
  224. if (chunk.type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  225. // TODO @ngxson : may need to split into smaller batches
  226. text_batch.n_tokens = chunk.tokens_text.size();
  227. for (size_t i = 0; i < chunk.tokens_text.size(); i++) {
  228. text_batch.token [i] = chunk.tokens_text[i];
  229. text_batch.pos [i] = n_past++;
  230. text_batch.n_seq_id[i] = 1;
  231. text_batch.seq_id [i][0] = seq_id;
  232. text_batch.logits [i] = false;
  233. }
  234. if (is_last) {
  235. // always get logits for last input chunk
  236. text_batch.logits[text_batch.n_tokens - 1] = true;
  237. }
  238. ret = llama_decode(lctx, text_batch);
  239. if (ret != 0) {
  240. LOG_ERR("failed to decode text\n");
  241. llama_batch_free(text_batch);
  242. return ret;
  243. }
  244. } else if (chunk.type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  245. GGML_ASSERT(!is_last && "logits for last image chunk is not yet support");
  246. GGML_ASSERT(chunk.tokens_image != nullptr);
  247. int64_t t0 = ggml_time_ms();
  248. if (ctx->print_timings) {
  249. LOG_INF("encoding image...\n");
  250. }
  251. ret = mtmd_encode(ctx, chunk.tokens_image);
  252. if (ret != 0) {
  253. LOG_ERR("failed to encode image\n");
  254. llama_batch_free(text_batch);
  255. return ret;
  256. }
  257. if (ctx->print_timings) {
  258. LOG_INF("image encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  259. }
  260. int32_t n_tokens = chunk.tokens_image->n_tokens();
  261. float * embd = mtmd_get_output_embd(ctx);
  262. decode_embd_batch batch_img(embd, n_tokens, n_past, 0);
  263. int64_t t1 = ggml_time_ms();
  264. ret = llama_decode(lctx, batch_img.batch);
  265. if (ret != 0) {
  266. LOG_ERR("failed to decode image\n");
  267. llama_batch_free(text_batch);
  268. return ret;
  269. }
  270. if (ctx->print_timings) {
  271. LOG_INF("image decoded in %" PRId64 " ms\n", ggml_time_ms() - t1);
  272. }
  273. n_past += n_tokens;
  274. } else {
  275. GGML_ASSERT(false && "chunk type not supported");
  276. }
  277. }
  278. llama_batch_free(text_batch);
  279. return 0;
  280. }
  281. int32_t mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len, mtmd_bitmap & output) {
  282. clip_image_u8_ptr img_u8(clip_image_u8_init());
  283. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  284. if (!ok) {
  285. LOG_ERR("Unable to load image from buffer\n");
  286. return 1;
  287. }
  288. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &output.nx, &output.ny);
  289. output.data.resize(output.nx * output.ny * 3);
  290. std::memcpy(output.data.data(), data, output.nx * output.ny * 3);
  291. return 0;
  292. }
  293. int32_t mtmd_helper_bitmap_init_from_file(const char * fname, mtmd_bitmap & output) {
  294. clip_image_u8_ptr img_u8(clip_image_u8_init());
  295. bool ok = clip_image_load_from_file(fname, img_u8.get());
  296. if (!ok) {
  297. LOG_ERR("Unable to load image %s\n", fname);
  298. return 1;
  299. }
  300. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &output.nx, &output.ny);
  301. output.data.resize(output.nx * output.ny * 3);
  302. std::memcpy(output.data.data(), data, output.nx * output.ny * 3);
  303. return 0;
  304. }