mtmd-helper.cpp 18 KB

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