mtmd-helper.cpp 18 KB

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