mtmd-helper.cpp 11 KB

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