mtmd-helper.cpp 12 KB

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