mtmd-helper.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #include "mtmd.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <cinttypes>
  5. #include <vector>
  6. #define LOG_INF(...) fprintf(stdout, __VA_ARGS__)
  7. #define LOG_ERR(...) fprintf(stderr, __VA_ARGS__)
  8. size_t mtmd_helper_get_n_tokens(const mtmd_input_chunks * chunks) {
  9. size_t n_tokens = 0;
  10. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  11. auto chunk = mtmd_input_chunks_get(chunks, i);
  12. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  13. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  14. size_t n_tokens_text;
  15. mtmd_input_chunk_get_tokens_text(chunk, &n_tokens_text);
  16. n_tokens += n_tokens_text;
  17. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  18. auto tokens_image = mtmd_input_chunk_get_tokens_image(chunk);
  19. n_tokens += mtmd_image_tokens_get_n_tokens(tokens_image);
  20. } else {
  21. GGML_ASSERT(false && "chunk type not supported");
  22. }
  23. }
  24. return n_tokens;
  25. }
  26. llama_pos mtmd_helper_get_n_pos(const mtmd_input_chunks * chunks) {
  27. llama_pos n_pos = 0;
  28. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  29. auto chunk = mtmd_input_chunks_get(chunks, i);
  30. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  31. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  32. size_t n_tokens_text;
  33. mtmd_input_chunk_get_tokens_text(chunk, &n_tokens_text);
  34. n_pos += n_tokens_text;
  35. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  36. auto tokens_image = mtmd_input_chunk_get_tokens_image(chunk);
  37. n_pos += mtmd_image_tokens_get_n_pos(tokens_image);
  38. } else {
  39. GGML_ASSERT(false && "chunk type not supported");
  40. }
  41. }
  42. return n_pos;
  43. }
  44. // helper struct to make working with embd batch easier
  45. // note: this will be removed after llama_batch_ext refactoring
  46. struct decode_embd_batch {
  47. int n_pos_per_embd;
  48. int n_mmproj_embd;
  49. std::vector<llama_pos> pos;
  50. std::vector<llama_pos> pos_view; // used by mrope
  51. std::vector<int32_t> n_seq_id;
  52. std::vector<llama_seq_id> seq_id_0;
  53. std::vector<llama_seq_id *> seq_ids;
  54. std::vector<int8_t> logits;
  55. llama_batch batch;
  56. decode_embd_batch(float * embd, int32_t n_tokens, int n_pos_per_embd, int n_mmproj_embd) : n_pos_per_embd(n_pos_per_embd), n_mmproj_embd(n_mmproj_embd) {
  57. pos .resize(n_tokens * n_pos_per_embd);
  58. n_seq_id.resize(n_tokens);
  59. seq_ids .resize(n_tokens + 1);
  60. logits .resize(n_tokens);
  61. seq_id_0.resize(1);
  62. seq_ids [n_tokens] = nullptr;
  63. batch = {
  64. /*n_tokens =*/ n_tokens,
  65. /*tokens =*/ nullptr,
  66. /*embd =*/ embd,
  67. /*pos =*/ pos.data(),
  68. /*n_seq_id =*/ n_seq_id.data(),
  69. /*seq_id =*/ seq_ids.data(),
  70. /*logits =*/ logits.data(),
  71. };
  72. }
  73. void set_position_normal(llama_pos pos_0, llama_seq_id seq_id) {
  74. seq_id_0[0] = seq_id;
  75. for (int i = 0; i < batch.n_tokens; i++) {
  76. batch.pos [i] = pos_0 + i;
  77. batch.n_seq_id[i] = 1;
  78. batch.seq_id [i] = seq_id_0.data();
  79. batch.logits [i] = false;
  80. }
  81. }
  82. void set_position_mrope(llama_pos pos_0, int nx, int ny, llama_seq_id seq_id) {
  83. GGML_ASSERT(n_pos_per_embd == 4);
  84. seq_id_0[0] = seq_id;
  85. for (int y = 0; y < ny; y++) {
  86. for (int x = 0; x < nx; x++) {
  87. int i = y * nx + x;
  88. pos[i ] = pos_0;
  89. pos[i + batch.n_tokens ] = pos_0 + y;
  90. pos[i + batch.n_tokens * 2] = pos_0 + x;
  91. pos[i + batch.n_tokens * 3] = 0; // last pos dim is unused
  92. }
  93. }
  94. for (int i = 0; i < batch.n_tokens; i++) {
  95. batch.n_seq_id[i] = 1;
  96. batch.seq_id [i] = seq_id_0.data();
  97. batch.logits [i] = false;
  98. }
  99. }
  100. llama_batch get_view(int offset, int n_tokens) {
  101. llama_pos * pos_ptr;
  102. pos_view.clear();
  103. pos_view.reserve(n_tokens * n_pos_per_embd);
  104. if (n_pos_per_embd > 1) {
  105. // mrope
  106. // for example, with layout of src: 1234...1234...1234...1234...
  107. // offset 2 will give us dst: 34...34...34...34...
  108. for (int i = 0; i < n_pos_per_embd; i++) {
  109. // assume n_tokens is less than or equal to batch.n_tokens
  110. // batch.n_tokens is number of **total** tokens
  111. // n_tokens is number of viewed token
  112. size_t src_idx = i * batch.n_tokens + offset;
  113. pos_view.insert(pos_view.end(),
  114. pos.data() + src_idx,
  115. pos.data() + src_idx + n_tokens);
  116. }
  117. pos_ptr = pos_view.data();
  118. } else {
  119. // normal
  120. pos_ptr = pos.data() + offset;
  121. }
  122. return {
  123. /*n_tokens =*/ n_tokens,
  124. /*tokens =*/ nullptr,
  125. /*embd =*/ batch.embd + offset * n_mmproj_embd,
  126. /*pos =*/ pos_ptr,
  127. /*n_seq_id =*/ batch.n_seq_id + offset,
  128. /*seq_id =*/ batch.seq_id + offset,
  129. /*logits =*/ batch.logits + offset,
  130. };
  131. }
  132. };
  133. // Helper function for decoding an image whose embeddings have already been calculated
  134. int32_t mtmd_helper_decode_image_chunk(
  135. mtmd_context * ctx,
  136. struct llama_context * lctx,
  137. const mtmd_input_chunk * chunk,
  138. float * encoded_embd,
  139. llama_pos n_past,
  140. llama_seq_id seq_id,
  141. int32_t n_batch,
  142. llama_pos * new_n_past) {
  143. if (mtmd_input_chunk_get_type(chunk) != MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  144. LOG_ERR("failed to decode image chunk: input chunk not of image type\n");
  145. return -1;
  146. }
  147. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  148. if (!image_tokens) {
  149. LOG_ERR("failed to decode image chunk: image tokens are null\n");
  150. return -1;
  151. }
  152. const llama_model * model = llama_get_model(lctx);
  153. int n_mmproj_embd = llama_model_n_embd(model);
  154. int n_pos_per_embd = mtmd_decode_use_mrope(ctx) ? 4 : 1;
  155. int32_t n_tokens = mtmd_image_tokens_get_n_tokens(image_tokens);
  156. int32_t i_batch = 0;
  157. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  158. decode_embd_batch batch_embd(encoded_embd, n_tokens, n_pos_per_embd, n_mmproj_embd);
  159. const int nx = mtmd_image_tokens_get_nx(image_tokens);
  160. const int ny = mtmd_image_tokens_get_ny(image_tokens);
  161. if (mtmd_decode_use_mrope(ctx)) {
  162. batch_embd.set_position_mrope(n_past, nx, ny, seq_id);
  163. } else {
  164. batch_embd.set_position_normal(n_past, seq_id);
  165. }
  166. if (mtmd_decode_use_non_causal(ctx)) {
  167. llama_set_causal_attn(lctx, false);
  168. // TODO @ngxson : need to make sure only one image is processed at a time, and n_ubatch must be enough to hold the image
  169. }
  170. while (i_batch < n_img_batches) { // split into batches
  171. int pos_offset = i_batch*n_batch;
  172. int n_tokens_batch = std::min(n_batch, n_tokens - pos_offset);
  173. llama_batch batch_embd_view = batch_embd.get_view(pos_offset, n_tokens_batch);
  174. LOG_INF("decoding image batch %d/%d, n_tokens_batch = %d\n", i_batch+1, n_img_batches, n_tokens_batch);
  175. int64_t t1 = ggml_time_ms();
  176. int32_t ret = llama_decode(lctx, batch_embd_view);
  177. if (ret != 0) {
  178. LOG_ERR("failed to decode image\n");
  179. llama_set_causal_attn(lctx, true); // restore causal attn
  180. return ret;
  181. }
  182. LOG_INF("image decoded (batch %d/%d) in %" PRId64 " ms\n", i_batch+1, n_img_batches, ggml_time_ms() - t1);
  183. i_batch++;
  184. }
  185. n_past += mtmd_image_tokens_get_n_pos(image_tokens);
  186. *new_n_past = n_past;
  187. if (mtmd_decode_use_non_causal(ctx)) {
  188. llama_set_causal_attn(lctx, true);
  189. }
  190. return 0;
  191. }
  192. int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx,
  193. struct llama_context * lctx,
  194. const mtmd_input_chunk * chunk,
  195. llama_pos n_past,
  196. llama_seq_id seq_id,
  197. int32_t n_batch,
  198. bool logits_last,
  199. llama_pos * new_n_past) {
  200. int32_t ret;
  201. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  202. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  203. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  204. size_t n_tokens;
  205. const auto tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  206. // LOG_INF("decoding text chunk, n_tokens = %zu\n", n_tokens);
  207. size_t i = 0;
  208. while (i < n_tokens) { // split into batches
  209. text_batch.n_tokens = 0; // clear the batch
  210. for (; i < n_tokens && text_batch.n_tokens < n_batch; i++) {
  211. text_batch.n_tokens++;
  212. text_batch.token [i] = tokens[i];
  213. text_batch.pos [i] = n_past++;
  214. text_batch.n_seq_id[i] = 1;
  215. text_batch.seq_id [i][0] = seq_id;
  216. text_batch.logits [i] = false;
  217. }
  218. bool is_last_token = (i == n_tokens);
  219. if (logits_last && is_last_token) {
  220. text_batch.logits[text_batch.n_tokens - 1] = true;
  221. }
  222. ret = llama_decode(lctx, text_batch);
  223. if (ret != 0) {
  224. LOG_ERR("failed to decode text\n");
  225. llama_batch_free(text_batch);
  226. return ret;
  227. }
  228. *new_n_past += text_batch.n_tokens;
  229. }
  230. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  231. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  232. int64_t t0 = ggml_time_ms();
  233. LOG_INF("encoding image or slice...\n");
  234. ret = mtmd_encode(ctx, image_tokens);
  235. if (ret != 0) {
  236. LOG_ERR("failed to encode image\n");
  237. llama_batch_free(text_batch);
  238. return ret;
  239. }
  240. LOG_INF("image/slice encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  241. float * embd = mtmd_get_output_embd(ctx);
  242. ret = mtmd_helper_decode_image_chunk(ctx, lctx, chunk, embd, n_past, seq_id, n_batch, new_n_past);
  243. if (ret != 0) {
  244. LOG_ERR("failed to decode image\n");
  245. llama_batch_free(text_batch);
  246. return ret;
  247. }
  248. } else {
  249. GGML_ABORT("chunk type not supported");
  250. }
  251. return 0;
  252. }
  253. int32_t mtmd_helper_eval_chunks(mtmd_context * ctx,
  254. struct llama_context * lctx,
  255. const mtmd_input_chunks * chunks,
  256. llama_pos n_past,
  257. llama_seq_id seq_id,
  258. int32_t n_batch,
  259. bool logits_last,
  260. llama_pos * new_n_past) {
  261. size_t n_chunks = mtmd_input_chunks_size(chunks);
  262. if (n_chunks == 0) {
  263. LOG_ERR("no chunks to eval\n");
  264. return 0;
  265. }
  266. for (size_t i = 0; i < n_chunks; i++) {
  267. bool chunk_logits_last = (i == n_chunks - 1) && logits_last;
  268. auto chunk = mtmd_input_chunks_get(chunks, i);
  269. int32_t res = mtmd_helper_eval_chunk_single(ctx, lctx, chunk, n_past, seq_id, n_batch, chunk_logits_last, &n_past);
  270. if (res != 0) {
  271. LOG_ERR("failed to eval chunk %zu\n", i);
  272. return res;
  273. }
  274. *new_n_past = n_past;
  275. }
  276. return 0;
  277. }