mtmd-helper.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. // fix problem with std::min and std::max
  2. #if defined(_WIN32)
  3. #define WIN32_LEAN_AND_MEAN
  4. #ifndef NOMINMAX
  5. # define NOMINMAX
  6. #endif
  7. #include <windows.h>
  8. #endif
  9. #include "mtmd.h"
  10. #include "mtmd-helper.h"
  11. #include "llama.h"
  12. #include <algorithm>
  13. #include <cinttypes>
  14. #include <vector>
  15. //#define MTMD_AUDIO_DEBUG
  16. #define MINIAUDIO_IMPLEMENTATION
  17. #ifndef MTMD_AUDIO_DEBUG
  18. # define MA_NO_ENCODING
  19. #endif
  20. #define MA_NO_DEVICE_IO
  21. #define MA_NO_RESOURCE_MANAGER
  22. #define MA_NO_NODE_GRAPH
  23. #define MA_NO_ENGINE
  24. #define MA_NO_GENERATION
  25. #define MA_API static
  26. #include "miniaudio/miniaudio.h"
  27. #define STB_IMAGE_IMPLEMENTATION
  28. #include "stb/stb_image.h"
  29. #define LOG_INF(...) fprintf(stdout, __VA_ARGS__)
  30. #define LOG_ERR(...) fprintf(stderr, __VA_ARGS__)
  31. size_t mtmd_helper_get_n_tokens(const mtmd_input_chunks * chunks) {
  32. size_t n_tokens = 0;
  33. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  34. auto chunk = mtmd_input_chunks_get(chunks, i);
  35. n_tokens += mtmd_input_chunk_get_n_tokens(chunk);
  36. }
  37. return n_tokens;
  38. }
  39. llama_pos mtmd_helper_get_n_pos(const mtmd_input_chunks * chunks) {
  40. llama_pos n_pos = 0;
  41. for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
  42. auto chunk = mtmd_input_chunks_get(chunks, i);
  43. n_pos += mtmd_input_chunk_get_n_pos(chunk);
  44. }
  45. return n_pos;
  46. }
  47. // helper struct to make working with embd batch easier
  48. // note: this will be removed after llama_batch_ext refactoring
  49. struct decode_embd_batch {
  50. int n_pos_per_embd;
  51. int n_mmproj_embd;
  52. std::vector<llama_pos> pos;
  53. std::vector<llama_pos> pos_view; // used by mrope
  54. std::vector<int32_t> n_seq_id;
  55. std::vector<llama_seq_id> seq_id_0;
  56. std::vector<llama_seq_id *> seq_ids;
  57. std::vector<int8_t> logits;
  58. llama_batch batch;
  59. 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) {
  60. pos .resize(n_tokens * n_pos_per_embd);
  61. n_seq_id.resize(n_tokens);
  62. seq_ids .resize(n_tokens + 1);
  63. logits .resize(n_tokens);
  64. seq_id_0.resize(1);
  65. seq_ids [n_tokens] = nullptr;
  66. batch = {
  67. /*n_tokens =*/ n_tokens,
  68. /*tokens =*/ nullptr,
  69. /*embd =*/ embd,
  70. /*pos =*/ pos.data(),
  71. /*n_seq_id =*/ n_seq_id.data(),
  72. /*seq_id =*/ seq_ids.data(),
  73. /*logits =*/ logits.data(),
  74. };
  75. }
  76. void set_position_normal(llama_pos pos_0, llama_seq_id seq_id) {
  77. seq_id_0[0] = seq_id;
  78. for (int i = 0; i < batch.n_tokens; i++) {
  79. batch.pos [i] = pos_0 + i;
  80. batch.n_seq_id[i] = 1;
  81. batch.seq_id [i] = seq_id_0.data();
  82. batch.logits [i] = false;
  83. }
  84. }
  85. // M-RoPE for image
  86. void set_position_mrope_2d(llama_pos pos_0, int nx, int ny, llama_seq_id seq_id) {
  87. GGML_ASSERT(n_pos_per_embd == 4);
  88. seq_id_0[0] = seq_id;
  89. for (int y = 0; y < ny; y++) {
  90. for (int x = 0; x < nx; x++) {
  91. int i = y * nx + x;
  92. pos[i ] = pos_0;
  93. pos[i + batch.n_tokens ] = pos_0 + y;
  94. pos[i + batch.n_tokens * 2] = pos_0 + x;
  95. pos[i + batch.n_tokens * 3] = 0; // last pos dim is unused
  96. }
  97. }
  98. for (int i = 0; i < batch.n_tokens; i++) {
  99. batch.n_seq_id[i] = 1;
  100. batch.seq_id [i] = seq_id_0.data();
  101. batch.logits [i] = false;
  102. }
  103. }
  104. // M-RoPE for audio
  105. void set_position_mrope_1d(llama_pos pos_0, llama_seq_id seq_id) {
  106. GGML_ASSERT(n_pos_per_embd == 4);
  107. seq_id_0[0] = seq_id;
  108. for (int i = 0; i < batch.n_tokens; i++) {
  109. pos[i ] = pos_0 + i;
  110. pos[i + batch.n_tokens ] = pos_0 + i;
  111. pos[i + batch.n_tokens * 2] = pos_0 + i;
  112. pos[i + batch.n_tokens * 3] = 0; // last pos dim is unused
  113. }
  114. for (int i = 0; i < batch.n_tokens; i++) {
  115. batch.n_seq_id[i] = 1;
  116. batch.seq_id [i] = seq_id_0.data();
  117. batch.logits [i] = false;
  118. }
  119. }
  120. llama_batch get_view(int offset, int n_tokens) {
  121. llama_pos * pos_ptr;
  122. pos_view.clear();
  123. pos_view.reserve(n_tokens * n_pos_per_embd);
  124. if (n_pos_per_embd > 1) {
  125. // mrope
  126. // for example, with layout of src: 1234...1234...1234...1234...
  127. // offset 2 will give us dst: 34...34...34...34...
  128. for (int i = 0; i < n_pos_per_embd; i++) {
  129. // assume n_tokens is less than or equal to batch.n_tokens
  130. // batch.n_tokens is number of **total** tokens
  131. // n_tokens is number of viewed token
  132. size_t src_idx = i * batch.n_tokens + offset;
  133. pos_view.insert(pos_view.end(),
  134. pos.data() + src_idx,
  135. pos.data() + src_idx + n_tokens);
  136. }
  137. pos_ptr = pos_view.data();
  138. } else {
  139. // normal
  140. pos_ptr = pos.data() + offset;
  141. }
  142. return {
  143. /*n_tokens =*/ n_tokens,
  144. /*tokens =*/ nullptr,
  145. /*embd =*/ batch.embd + offset * n_mmproj_embd,
  146. /*pos =*/ pos_ptr,
  147. /*n_seq_id =*/ batch.n_seq_id + offset,
  148. /*seq_id =*/ batch.seq_id + offset,
  149. /*logits =*/ batch.logits + offset,
  150. };
  151. }
  152. };
  153. // Helper function for decoding an image whose embeddings have already been calculated
  154. int32_t mtmd_helper_decode_image_chunk(
  155. mtmd_context * ctx,
  156. struct llama_context * lctx,
  157. const mtmd_input_chunk * chunk,
  158. float * encoded_embd,
  159. llama_pos n_past,
  160. llama_seq_id seq_id,
  161. int32_t n_batch,
  162. llama_pos * new_n_past) {
  163. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  164. const char * name = chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE ? "image" : "audio";
  165. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  166. LOG_ERR("failed to decode chunk: input chunk not of image/audio type\n");
  167. return -1;
  168. }
  169. const llama_model * model = llama_get_model(lctx);
  170. int n_mmproj_embd = llama_model_n_embd_inp(model);
  171. int n_pos_per_embd = mtmd_decode_use_mrope(ctx) ? 4 : 1;
  172. int32_t n_tokens = mtmd_input_chunk_get_n_tokens(chunk);
  173. int32_t i_batch = 0;
  174. int32_t n_img_batches = GGML_PAD(n_tokens, n_batch) / n_batch;
  175. decode_embd_batch batch_embd(encoded_embd, n_tokens, n_pos_per_embd, n_mmproj_embd);
  176. if (mtmd_decode_use_mrope(ctx)) {
  177. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  178. const auto image_tokens = mtmd_input_chunk_get_tokens_image(chunk);
  179. if (!image_tokens) {
  180. LOG_ERR("failed to decode chunk: image tokens are null\n");
  181. return -1;
  182. }
  183. const int nx = mtmd_image_tokens_get_nx(image_tokens);
  184. const int ny = mtmd_image_tokens_get_ny(image_tokens);
  185. batch_embd.set_position_mrope_2d(n_past, nx, ny, seq_id);
  186. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  187. batch_embd.set_position_mrope_1d(n_past, seq_id);
  188. } else {
  189. GGML_ABORT("invalid chunk type for M-RoPE");
  190. }
  191. } else {
  192. batch_embd.set_position_normal(n_past, seq_id);
  193. }
  194. if (mtmd_decode_use_non_causal(ctx)) {
  195. llama_set_causal_attn(lctx, false);
  196. // TODO @ngxson : need to make sure only one image is processed at a time, and n_ubatch must be enough to hold the image
  197. }
  198. while (i_batch < n_img_batches) { // split into batches
  199. int pos_offset = i_batch*n_batch;
  200. int n_tokens_batch = std::min(n_batch, n_tokens - pos_offset);
  201. llama_batch batch_embd_view = batch_embd.get_view(pos_offset, n_tokens_batch);
  202. LOG_INF("decoding %s batch %d/%d, n_tokens_batch = %d\n", name, i_batch+1, n_img_batches, n_tokens_batch);
  203. int64_t t1 = ggml_time_ms();
  204. int32_t ret = llama_decode(lctx, batch_embd_view);
  205. if (ret != 0) {
  206. LOG_ERR("failed to decode %s\n", name);
  207. llama_set_causal_attn(lctx, true); // restore causal attn
  208. return ret;
  209. }
  210. LOG_INF("%s decoded (batch %d/%d) in %" PRId64 " ms\n", name, i_batch+1, n_img_batches, ggml_time_ms() - t1);
  211. i_batch++;
  212. }
  213. n_past += mtmd_input_chunk_get_n_pos(chunk);
  214. *new_n_past = n_past;
  215. if (mtmd_decode_use_non_causal(ctx)) {
  216. llama_set_causal_attn(lctx, true);
  217. }
  218. return 0;
  219. }
  220. int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx,
  221. struct llama_context * lctx,
  222. const mtmd_input_chunk * chunk,
  223. llama_pos n_past,
  224. llama_seq_id seq_id,
  225. int32_t n_batch,
  226. bool logits_last,
  227. llama_pos * new_n_past) {
  228. int32_t ret;
  229. llama_batch text_batch = llama_batch_init(n_batch, 0, 1);
  230. auto chunk_type = mtmd_input_chunk_get_type(chunk);
  231. if (chunk_type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  232. size_t n_tokens;
  233. const auto tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  234. // LOG_INF("decoding text chunk, n_tokens = %zu\n", n_tokens);
  235. size_t i = 0;
  236. while (i < n_tokens) { // split into batches
  237. text_batch.n_tokens = 0; // clear the batch
  238. for (; i < n_tokens && text_batch.n_tokens < n_batch; i++) {
  239. int32_t j = text_batch.n_tokens;
  240. text_batch.token [j] = tokens[i];
  241. text_batch.pos [j] = n_past++;
  242. text_batch.n_seq_id[j] = 1;
  243. text_batch.seq_id [j][0] = seq_id;
  244. text_batch.logits [j] = false;
  245. text_batch.n_tokens++;
  246. }
  247. bool is_last_token = (i == n_tokens);
  248. if (logits_last && is_last_token) {
  249. text_batch.logits[text_batch.n_tokens - 1] = true;
  250. }
  251. ret = llama_decode(lctx, text_batch);
  252. if (ret != 0) {
  253. LOG_ERR("failed to decode text\n");
  254. llama_batch_free(text_batch);
  255. return ret;
  256. }
  257. *new_n_past += text_batch.n_tokens;
  258. }
  259. } else if (chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE || chunk_type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  260. const char * name = chunk_type == MTMD_INPUT_CHUNK_TYPE_IMAGE ? "image" : "audio";
  261. int64_t t0 = ggml_time_ms();
  262. LOG_INF("encoding %s slice...\n", name);
  263. ret = mtmd_encode_chunk(ctx, chunk);
  264. if (ret != 0) {
  265. LOG_ERR("failed to encode %s slice\n", name);
  266. llama_batch_free(text_batch);
  267. return ret;
  268. }
  269. LOG_INF("%s slice encoded in %" PRId64 " ms\n", name, ggml_time_ms() - t0);
  270. float * embd = mtmd_get_output_embd(ctx);
  271. ret = mtmd_helper_decode_image_chunk(ctx, lctx, chunk, embd, n_past, seq_id, n_batch, new_n_past);
  272. if (ret != 0) {
  273. LOG_ERR("failed to decode %s\n", name);
  274. llama_batch_free(text_batch);
  275. return ret;
  276. }
  277. } else {
  278. GGML_ABORT("chunk type not supported");
  279. }
  280. llama_batch_free(text_batch);
  281. return 0;
  282. }
  283. int32_t mtmd_helper_eval_chunks(mtmd_context * ctx,
  284. struct llama_context * lctx,
  285. const mtmd_input_chunks * chunks,
  286. llama_pos n_past,
  287. llama_seq_id seq_id,
  288. int32_t n_batch,
  289. bool logits_last,
  290. llama_pos * new_n_past) {
  291. size_t n_chunks = mtmd_input_chunks_size(chunks);
  292. if (n_chunks == 0) {
  293. LOG_ERR("no chunks to eval\n");
  294. return 0;
  295. }
  296. for (size_t i = 0; i < n_chunks; i++) {
  297. bool chunk_logits_last = (i == n_chunks - 1) && logits_last;
  298. auto chunk = mtmd_input_chunks_get(chunks, i);
  299. int32_t res = mtmd_helper_eval_chunk_single(ctx, lctx, chunk, n_past, seq_id, n_batch, chunk_logits_last, &n_past);
  300. if (res != 0) {
  301. LOG_ERR("failed to eval chunk %zu\n", i);
  302. return res;
  303. }
  304. *new_n_past = n_past;
  305. }
  306. return 0;
  307. }
  308. namespace audio_helpers {
  309. static bool is_audio_file(const char * buf, size_t len) {
  310. if (len < 12) {
  311. return false;
  312. }
  313. // RIFF ref: https://en.wikipedia.org/wiki/Resource_Interchange_File_Format
  314. // WAV ref: https://www.mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  315. bool is_wav = memcmp(buf, "RIFF", 4) == 0 && memcmp(buf + 8, "WAVE", 4) == 0;
  316. bool is_mp3 = len >= 3 && (
  317. memcmp(buf, "ID3", 3) == 0 ||
  318. // Check for MPEG sync word (simplified check)
  319. ((unsigned char)buf[0] == 0xFF && ((unsigned char)buf[1] & 0xE0) == 0xE0)
  320. );
  321. bool is_flac = memcmp(buf, "fLaC", 4) == 0;
  322. return is_wav || is_mp3 || is_flac;
  323. }
  324. // returns true if the buffer is a valid audio file
  325. static bool decode_audio_from_buf(const unsigned char * buf_in, size_t len, int target_sampler_rate, std::vector<float> & pcmf32_mono) {
  326. ma_result result;
  327. const int channels = 1;
  328. ma_decoder_config decoder_config = ma_decoder_config_init(ma_format_f32, channels, target_sampler_rate);
  329. ma_decoder decoder;
  330. result = ma_decoder_init_memory(buf_in, len, &decoder_config, &decoder);
  331. if (result != MA_SUCCESS) {
  332. return false;
  333. }
  334. ma_uint64 frame_count;
  335. ma_uint64 frames_read;
  336. result = ma_decoder_get_length_in_pcm_frames(&decoder, &frame_count);
  337. if (result != MA_SUCCESS) {
  338. ma_decoder_uninit(&decoder);
  339. return false;
  340. }
  341. pcmf32_mono.resize(frame_count);
  342. result = ma_decoder_read_pcm_frames(&decoder, pcmf32_mono.data(), frame_count, &frames_read);
  343. if (result != MA_SUCCESS) {
  344. ma_decoder_uninit(&decoder);
  345. return false;
  346. }
  347. #ifdef MTMD_AUDIO_DEBUG
  348. // save audio to wav file
  349. ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, ma_format_f32, 1, target_sampler_rate);
  350. ma_encoder encoder;
  351. ma_encoder_init_file("output.wav", &config, &encoder);
  352. ma_encoder_write_pcm_frames(&encoder, pcmf32_mono.data(), pcmf32_mono.size(), &frames_read);
  353. ma_encoder_uninit(&encoder);
  354. #endif
  355. ma_decoder_uninit(&decoder);
  356. return true;
  357. }
  358. } // namespace audio_helpers
  359. mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(mtmd_context * ctx, const unsigned char * buf, size_t len) {
  360. if (audio_helpers::is_audio_file((const char *)buf, len)) {
  361. std::vector<float> pcmf32;
  362. int bitrate = mtmd_get_audio_bitrate(ctx);
  363. if (bitrate < 0) {
  364. LOG_ERR("This model does not support audio input\n");
  365. return nullptr;
  366. }
  367. if (!audio_helpers::decode_audio_from_buf(buf, len, bitrate, pcmf32)) {
  368. LOG_ERR("Unable to read WAV audio file from buffer\n");
  369. return nullptr;
  370. }
  371. return mtmd_bitmap_init_from_audio(pcmf32.size(), pcmf32.data());
  372. }
  373. // otherwise, we assume it's an image
  374. mtmd_bitmap * result = nullptr;
  375. {
  376. int nx, ny, nc;
  377. auto * data = stbi_load_from_memory(buf, len, &nx, &ny, &nc, 3);
  378. if (!data) {
  379. LOG_ERR("%s: failed to decode image bytes\n", __func__);
  380. return nullptr;
  381. }
  382. result = mtmd_bitmap_init(nx, ny, data);
  383. stbi_image_free(data);
  384. }
  385. return result;
  386. }
  387. mtmd_bitmap * mtmd_helper_bitmap_init_from_file(mtmd_context * ctx, const char * fname) {
  388. std::vector<unsigned char> buf;
  389. FILE * f = fopen(fname, "rb");
  390. if (!f) {
  391. LOG_ERR("Unable to open file %s: %s\n", fname, strerror(errno));
  392. return nullptr;
  393. }
  394. fseek(f, 0, SEEK_END);
  395. long file_size = ftell(f);
  396. fseek(f, 0, SEEK_SET);
  397. buf.resize(file_size);
  398. size_t n_read = fread(buf.data(), 1, file_size, f);
  399. fclose(f);
  400. if (n_read != (size_t)file_size) {
  401. LOG_ERR("Failed to read entire file %s", fname);
  402. return nullptr;
  403. }
  404. return mtmd_helper_bitmap_init_from_buf(ctx, buf.data(), buf.size());
  405. }