1
0

llava.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. #include "clip.h"
  2. #include "llava.h"
  3. #include "llama.h"
  4. #include "ggml-cpp.h"
  5. #include <algorithm>
  6. #include <cerrno>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <limits>
  11. #include <vector>
  12. #include <memory>
  13. #if defined(LLAVA_LOG_OFF)
  14. # define LOG_INF(...)
  15. # define LOG_WRN(...)
  16. # define LOG_ERR(...)
  17. # define LOG_DBG(...)
  18. #else // defined(LLAVA_LOG_OFF)
  19. # define LOG_INF(...) do { fprintf(stdout, __VA_ARGS__); } while (0)
  20. # define LOG_WRN(...) do { fprintf(stderr, __VA_ARGS__); } while (0)
  21. # define LOG_ERR(...) do { fprintf(stderr, __VA_ARGS__); } while (0)
  22. # define LOG_DBG(...) do { fprintf(stdout, __VA_ARGS__); } while (0)
  23. #endif // defined(LLAVA_LOG_OFF)
  24. // RGB uint8 image
  25. struct clip_image_u8 {
  26. int nx;
  27. int ny;
  28. std::vector<uint8_t> buf;
  29. };
  30. // RGB float32 image (NHWC)
  31. // Memory layout: RGBRGBRGB...
  32. struct clip_image_f32 {
  33. int nx;
  34. int ny;
  35. std::vector<float> buf;
  36. };
  37. struct clip_image_grid_shape {
  38. int first;
  39. int second;
  40. };
  41. // convenience cpp wrapper
  42. struct clip_image_f32_batch_deleter {
  43. void operator()(clip_image_f32_batch * val) { clip_image_f32_batch_free(val); }
  44. };
  45. typedef std::unique_ptr<clip_image_f32_batch, clip_image_f32_batch_deleter> clip_image_f32_batch_ptr;
  46. struct clip_image_size_deleter {
  47. void operator()(clip_image_f32_batch * val) { clip_image_f32_batch_free(val); }
  48. };
  49. typedef std::unique_ptr<clip_image_size, clip_image_size_deleter> clip_image_size_ptr;
  50. /**
  51. * Selects the best resolution from a list of possible resolutions based on the original size.
  52. *
  53. * @param original_size The original size of the image in the format (width, height).
  54. * @param possible_resolutions A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
  55. * @return The best fit resolution in the format (width, height).
  56. */
  57. static std::pair<int, int> select_best_resolution(const std::pair<int, int>& original_size, const std::vector<std::pair<int, int>>& possible_resolutions) {
  58. int original_width = original_size.first;
  59. int original_height = original_size.second;
  60. std::pair<int, int> best_fit;
  61. int max_effective_resolution = 0;
  62. int min_wasted_resolution = std::numeric_limits<int>::max();
  63. for (const auto& resolution : possible_resolutions) {
  64. int width = resolution.first;
  65. int height = resolution.second;
  66. float scale = std::min(static_cast<float>(width) / original_width, static_cast<float>(height) / original_height);
  67. int downscaled_width = static_cast<int>(original_width * scale);
  68. int downscaled_height = static_cast<int>(original_height * scale);
  69. int effective_resolution = std::min(downscaled_width * downscaled_height, original_width * original_height);
  70. int wasted_resolution = (width * height) - effective_resolution;
  71. // LOG_DBG("resolution: %d %d, scale: %f, downscaled: %d %d, effective: %d, wasted: %d\n", width, height, scale, downscaled_width, downscaled_height, effective_resolution, wasted_resolution);
  72. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_resolution < min_wasted_resolution)) {
  73. max_effective_resolution = effective_resolution;
  74. min_wasted_resolution = wasted_resolution;
  75. best_fit = resolution;
  76. }
  77. }
  78. return best_fit;
  79. }
  80. /**
  81. * @brief Get the anyres image grid shape object
  82. *
  83. * @param image_size
  84. * @param grid_pinpoints
  85. * @param image_patch_size
  86. * @return <int, int>
  87. */
  88. static struct clip_image_grid_shape get_anyres_image_grid_shape(const std::pair<int, int> & image_size, const std::vector<std::pair<int, int>> & grid_pinpoints, int image_patch_size) {
  89. /**
  90. Conversion from gguf flat array to vector:
  91. std::vector<std::pair<int, int>> possible_resolutions;
  92. for (int i = 0; i < 32 && params.image_grid_pinpoints[i] != 0; i+=2) {
  93. possible_resolutions.push_back({params.image_grid_pinpoints[i], params.image_grid_pinpoints[i+1]});
  94. }
  95. */
  96. auto best_resolution = select_best_resolution(image_size, grid_pinpoints);
  97. return {best_resolution.first / image_patch_size, best_resolution.second / image_patch_size};
  98. }
  99. // Take the image segments in a grid configuration and return the embeddings and the number of embeddings into preallocated memory (image_embd_out)
  100. static bool clip_llava_handle_patches(clip_ctx * ctx_clip, std::vector<float *> & image_embd_v, struct clip_image_grid_shape grid_shape, float * image_embd_out, int * n_img_pos_out, clip_image_f32 * img_input) {
  101. struct {
  102. struct ggml_context * ctx;
  103. } model;
  104. const int32_t image_size = clip_get_image_size(ctx_clip);
  105. const int32_t patch_size = clip_get_patch_size(ctx_clip);
  106. int32_t num_patches_per_side = image_size / patch_size; // 336 / 14 = 24 - used for embedding-patching boxes (24*24 = 576 patches)
  107. int num_patches_width = grid_shape.first; // grid 1-4
  108. int num_patches_height = grid_shape.second; // grid 1-4
  109. const size_t num_images = num_patches_width * num_patches_height + 1;
  110. // TODO: size calculation is not calculated - it's only tens of MB
  111. size_t ctx_size = 0;
  112. {
  113. ctx_size += clip_embd_nbytes(ctx_clip) * num_images * 8; // image_features
  114. ctx_size += 1024*1024 * ggml_type_size(GGML_TYPE_F32);
  115. }
  116. struct ggml_init_params params {
  117. /*.mem_size =*/ ctx_size,
  118. /*.mem_buffer =*/ NULL,
  119. /*.no_alloc =*/ false, // NOTE: this should be false when using the legacy API
  120. };
  121. // Python reference code for full unpad:
  122. /*
  123. base_image_feature = image_feature[0]
  124. image_feature = image_feature[1:]
  125. image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
  126. image_feature = image_feature.flatten(1, 2).flatten(2, 3)
  127. image_feature = unpad_image(image_feature, image_sizes[image_idx])
  128. image_feature = torch.cat((
  129. image_feature,
  130. self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1)
  131. ), dim=-1)
  132. image_feature = image_feature.flatten(1, 2).transpose(0, 1)
  133. image_feature = torch.cat((base_image_feature, image_feature), dim=0)
  134. */
  135. // We now have two options: unpad or no unpad. Unpad removes tokens for faster llm eval.
  136. // In terms of result quality it appears to make no difference, so we'll start with the easier approach given 5D tensors are not supported in ggml yet.
  137. // Without unpad we have to split the sub-image embeddings into patches of 24 features each and permute them.
  138. // Once all images are processed to prepended the base_image_features without any changes.
  139. // Pytorch reference simplified, modified for ggml compatibility - confirmed identical output in python (for a 2x2 grid image (676x676 scaling))
  140. /*
  141. image_feature = image_feature.view(2, 2, 24, 24, 4096)
  142. image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
  143. image_feature = image_feature.view(2, 24, 2, 24, 4096)
  144. image_feature = image_feature.flatten(0, 3)
  145. // Reshape to 4D tensor by merging the last two dimensions
  146. image_feature = image_feature.view(2, 2, 24, 24*4096)
  147. image_feature = image_feature.permute(0, 2, 1, 3).contiguous()
  148. image_feature = image_feature.view(-1, 4096)
  149. */
  150. model.ctx = ggml_init(params);
  151. struct ggml_tensor * image_features = ggml_new_tensor_3d(model.ctx, GGML_TYPE_F32, clip_n_mmproj_embd(ctx_clip), clip_n_output_tokens(ctx_clip, img_input), num_images - 1); // example: 4096 x 576 x 4
  152. // ggml_tensor_printf(image_features,"image_features",__LINE__,false,false);
  153. // fill it with the image embeddings, ignoring the base
  154. for (size_t i = 1; i < num_images; i++) {
  155. size_t offset = (i-1) * clip_embd_nbytes(ctx_clip);
  156. memcpy((uint8_t *)(image_features->data) + offset, image_embd_v[i], clip_embd_nbytes(ctx_clip));
  157. }
  158. struct ggml_cgraph * gf = ggml_new_graph(model.ctx);
  159. size_t size_ele = ggml_type_size(GGML_TYPE_F32);
  160. struct ggml_tensor *image_features_patchview = ggml_view_4d(model.ctx, image_features,
  161. num_patches_per_side * clip_n_mmproj_embd(ctx_clip),
  162. num_patches_per_side,
  163. num_patches_width,
  164. num_patches_height,
  165. size_ele * num_patches_per_side * clip_n_mmproj_embd(ctx_clip),
  166. size_ele * num_patches_per_side * clip_n_mmproj_embd(ctx_clip) * num_patches_per_side,
  167. size_ele * num_patches_per_side * clip_n_mmproj_embd(ctx_clip) * num_patches_per_side * num_patches_width, 0);
  168. // ggml_tensor_printf(image_features_patchview,"image_features_patchview",__LINE__,false,false);
  169. struct ggml_tensor *permuted_cont = ggml_cont(model.ctx, ggml_permute(model.ctx, image_features_patchview, 0, 2, 1, 3));
  170. /**
  171. At the end of each row we have to add the row_end embeddings, which are the same as the newline embeddings
  172. image_feature = torch.cat((
  173. image_feature,
  174. self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)
  175. ), dim=-1)
  176. *
  177. */
  178. // ggml_tensor_printf(permuted_cont,"permuted_cont",__LINE__,false,false);
  179. struct ggml_tensor *flatten = ggml_view_2d(model.ctx, permuted_cont, clip_n_mmproj_embd(ctx_clip), num_patches_height * num_patches_width * num_patches_per_side * num_patches_per_side, size_ele * clip_n_mmproj_embd(ctx_clip), 0);
  180. // ggml_tensor_printf(flatten,"flatten",__LINE__,false,false);
  181. ggml_build_forward_expand(gf, flatten);
  182. ggml_backend_ptr backend { ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr) };
  183. ggml_backend_graph_compute(backend.get(), gf);
  184. struct ggml_tensor* result = ggml_graph_node(gf, -1);
  185. memcpy(image_embd_out, image_embd_v[0], clip_embd_nbytes(ctx_clip)); // main image as global context
  186. // append without newline tokens (default behavior in llava_arch when not using unpad ):
  187. memcpy(image_embd_out + clip_n_output_tokens(ctx_clip, img_input) * clip_n_mmproj_embd(ctx_clip), (float*)result->data, clip_embd_nbytes(ctx_clip) * (num_images-1)); // grid patches
  188. *n_img_pos_out = static_cast<int>(result->ne[1]+clip_n_output_tokens(ctx_clip, img_input));
  189. // Debug: Test single segments
  190. // Current findings: sending base image, sending a segment embedding all works similar to python
  191. // However, permuted embeddings do not work yet (stride issue?)
  192. // memcpy(image_embd_out, image_embd_v[0], clip_embd_nbytes(ctx_clip)); // main image as context
  193. // memcpy(image_embd_out, (float*)prepared_cont->data, clip_embd_nbytes(ctx_clip)); // main image as context
  194. // *n_img_pos_out=576;
  195. ggml_free(model.ctx);
  196. return true;
  197. }
  198. static clip_image_f32 * reshape_by_patch(clip_image_f32 * image, int patch_size) {
  199. int width = image->nx;
  200. int height = image->ny;
  201. int num_patches = (height / patch_size) * (width / patch_size);
  202. clip_image_f32 * patch = clip_image_f32_init();
  203. patch->nx = patch_size * num_patches;
  204. patch->ny = patch_size;
  205. patch->buf.resize(3 * patch->nx * patch->ny);
  206. int patch_index = 0;
  207. for (int i = 0; i < height; i += patch_size) {
  208. for (int j = 0; j < width; j += patch_size) {
  209. for (int pi = 0; pi < patch_size; ++pi) {
  210. for (int pj = 0; pj < patch_size; ++pj) {
  211. int input_index = ((i + pi) * width + (j + pj)) * 3;
  212. int output_index = (pi * patch_size * num_patches + patch_index * patch_size + pj) * 3;
  213. patch->buf[output_index] = image->buf[input_index];
  214. patch->buf[output_index+1] = image->buf[input_index+1];
  215. patch->buf[output_index+2] = image->buf[input_index+2];
  216. }
  217. }
  218. patch_index++;
  219. }
  220. }
  221. return patch;
  222. }
  223. static bool encode_image_with_clip(clip_ctx * ctx_clip, int n_threads, const clip_image_u8 * img, float * image_embd, int * n_img_pos) {
  224. // std::vector<clip_image_f32*> img_res_v; // format VectN x H x W x RGB (N x 336 x 336 x 3), so interleaved RGB - different to the python implementation which is N x 3 x 336 x 336
  225. clip_image_f32_batch_ptr img_res_v(clip_image_f32_batch_init());
  226. if (!clip_image_preprocess(ctx_clip, img, img_res_v.get())) {
  227. LOG_ERR("%s: unable to preprocess image\n", __func__);
  228. return false;
  229. }
  230. const int64_t t_img_enc_start_us = ggml_time_us();
  231. const char * mm_patch_merge_type = clip_patch_merge_type(ctx_clip);
  232. const size_t n_imgs = clip_image_f32_batch_n_images(img_res_v.get());
  233. if (clip_is_minicpmv(ctx_clip) || clip_is_qwen2vl(ctx_clip)) {
  234. std::vector<float *> image_embd_v;
  235. image_embd_v.resize(n_imgs);
  236. clip_image_size load_image_size;
  237. for (size_t i = 0; i < n_imgs; i++) {
  238. const int64_t t_img_enc_step_start_us = ggml_time_us();
  239. int nx = clip_image_f32_batch_nx(img_res_v.get(), i);
  240. int ny = clip_image_f32_batch_ny(img_res_v.get(), i);
  241. image_embd_v[i] = (float *)malloc(clip_embd_nbytes_by_img(ctx_clip, nx, ny));
  242. int patch_size = 14;
  243. load_image_size.width = nx;
  244. load_image_size.height = ny;
  245. clip_add_load_image_size(ctx_clip, &load_image_size);
  246. bool encoded = false;
  247. clip_image_f32 * img_res = clip_image_f32_get_img(img_res_v.get(), i);
  248. if (clip_is_qwen2vl(ctx_clip)) {
  249. encoded = clip_image_encode(ctx_clip, n_threads, img_res, image_embd_v[i]);
  250. }
  251. else {
  252. encoded = clip_image_encode(ctx_clip, n_threads, reshape_by_patch(img_res, patch_size), image_embd_v[i]);
  253. }
  254. if (!encoded) {
  255. LOG_ERR("Unable to encode image - spatial_unpad - subimage %d of %d\n", (int) i+1, (int) n_imgs);
  256. return false;
  257. }
  258. const int64_t t_img_enc_steop_batch_us = ggml_time_us();
  259. LOG_INF("%s: step %d of %d encoded in %8.2f ms\n", __func__, (int)i+1, (int)n_imgs, (t_img_enc_steop_batch_us - t_img_enc_step_start_us) / 1000.0);
  260. }
  261. const int64_t t_img_enc_batch_us = ggml_time_us();
  262. LOG_INF("%s: all %d segments encoded in %8.2f ms\n", __func__, (int)n_imgs, (t_img_enc_batch_us - t_img_enc_start_us) / 1000.0);
  263. int n_img_pos_out = 0;
  264. for (size_t i = 0; i < image_embd_v.size(); i++) {
  265. int nx = clip_image_f32_batch_nx(img_res_v.get(), i);
  266. int ny = clip_image_f32_batch_ny(img_res_v.get(), i);
  267. clip_image_f32 * img_res = clip_image_f32_get_img(img_res_v.get(), i);
  268. std::memcpy(
  269. image_embd + n_img_pos_out * clip_n_mmproj_embd(ctx_clip),
  270. image_embd_v[i],
  271. clip_embd_nbytes_by_img(ctx_clip, nx, ny));
  272. n_img_pos_out += clip_n_output_tokens(ctx_clip, img_res);
  273. }
  274. *n_img_pos = n_img_pos_out;
  275. for (size_t i = 0; i < image_embd_v.size(); i++) {
  276. free(image_embd_v[i]);
  277. }
  278. image_embd_v.clear();
  279. load_image_size.width = img->nx;
  280. load_image_size.height = img->ny;
  281. clip_add_load_image_size(ctx_clip, &load_image_size);
  282. LOG_INF("%s: load_image_size %d %d\n", __func__, load_image_size.width, load_image_size.height);
  283. }
  284. else if (clip_is_glm(ctx_clip)){
  285. struct clip_image_size * load_image_size = clip_image_size_init();
  286. load_image_size->width = clip_image_f32_batch_nx(img_res_v.get(), 0);
  287. load_image_size->height = clip_image_f32_batch_ny(img_res_v.get(), 0);
  288. clip_add_load_image_size(ctx_clip, load_image_size);
  289. clip_image_f32 * img_res = clip_image_f32_get_img(img_res_v.get(), 0);
  290. bool encoded = clip_image_encode(ctx_clip, n_threads, img_res, image_embd);
  291. int pos = int(load_image_size->width/clip_get_patch_size(ctx_clip)/2);
  292. *n_img_pos = (pos * pos + 2);
  293. if (!encoded){
  294. LOG_ERR("Unable to encode image \n");
  295. return false;
  296. }
  297. }
  298. else if (strcmp(mm_patch_merge_type, "spatial_unpad") != 0) {
  299. // flat / default llava-1.5 type embedding
  300. clip_image_f32 * img_res = clip_image_f32_get_img(img_res_v.get(), 0);
  301. *n_img_pos = clip_n_output_tokens(ctx_clip, img_res);
  302. bool encoded = clip_image_encode(ctx_clip, n_threads, img_res, image_embd); // image_embd shape is 576 x 4096
  303. if (!encoded) {
  304. LOG_ERR("Unable to encode image\n");
  305. return false;
  306. }
  307. }
  308. else {
  309. // spatial_unpad llava-1.6 type embedding
  310. // TODO: CLIP needs batching support - in HF the llm projection is separate after encoding, which might be a solution to quickly get batching working
  311. std::vector<float *> image_embd_v;
  312. image_embd_v.resize(n_imgs);
  313. for (size_t i = 0; i < n_imgs; i++) {
  314. clip_image_f32 * img_res = clip_image_f32_get_img(img_res_v.get(), i);
  315. image_embd_v[i] = (float *)malloc(clip_embd_nbytes(ctx_clip)); // 576 patches * 4096 embeddings * 4 bytes = 9437184
  316. const bool encoded = clip_image_encode(ctx_clip, n_threads, img_res, image_embd_v[i]); // image data is in 3x336x336 format and will be converted to 336x336x3 inside
  317. if (!encoded) {
  318. LOG_ERR("Unable to encode image - spatial_unpad - subimage %d of %d\n", (int) i+1, (int) n_imgs);
  319. return false;
  320. }
  321. }
  322. const int64_t t_img_enc_batch_us = ggml_time_us();
  323. LOG_INF("%s: %d segments encoded in %8.2f ms\n", __func__, (int)n_imgs, (t_img_enc_batch_us - t_img_enc_start_us) / 1000.0);
  324. const int32_t * image_grid = clip_image_grid(ctx_clip);
  325. const size_t num_gridpoints = get_clip_image_grid_size(ctx_clip);
  326. std::vector<std::pair<int, int>> grid_pinpoints;
  327. for (size_t i = 0; i < num_gridpoints; i += 2) {
  328. grid_pinpoints.push_back({image_grid[i], image_grid[i+1]});
  329. }
  330. const int32_t image_size = clip_get_image_size(ctx_clip);
  331. struct clip_image_grid_shape grid_shape = get_anyres_image_grid_shape({img->nx,img->ny}, grid_pinpoints, image_size);
  332. int n_img_pos_out;
  333. clip_image_f32 * img_input = clip_image_f32_get_img(img_res_v.get(), 0);
  334. clip_llava_handle_patches(ctx_clip, image_embd_v, grid_shape, image_embd, &n_img_pos_out, img_input);
  335. *n_img_pos = n_img_pos_out;
  336. for (size_t i = 0; i < image_embd_v.size(); i++) {
  337. free(image_embd_v[i]);
  338. }
  339. image_embd_v.clear();
  340. // debug image/segment/normalization content:
  341. // clip_image_u8 * tmp = clip_image_u8_init();
  342. // clip_image_convert_f32_to_u8(*image_feature, *tmp);
  343. // clip_image_save_to_bmp(*tmp, "image_feature.bmp");
  344. }
  345. LOG_INF("%s: image embedding created: %d tokens\n", __func__, *n_img_pos);
  346. const int64_t t_img_enc_end_us = ggml_time_us();
  347. float t_img_enc_ms = (t_img_enc_end_us - t_img_enc_start_us) / 1000.0;
  348. LOG_INF("\n%s: image encoded in %8.2f ms by CLIP (%8.2f ms per image patch)\n", __func__, t_img_enc_ms, t_img_enc_ms / *n_img_pos);
  349. return true;
  350. }
  351. bool llava_validate_embed_size(const llama_context * ctx_llama, const clip_ctx * ctx_clip) {
  352. // make sure that the correct mmproj was used, i.e., compare apples to apples
  353. int n_llama_embd = llama_model_n_embd(llama_get_model(ctx_llama));
  354. auto n_image_embd = clip_n_mmproj_embd(ctx_clip);
  355. if (n_image_embd != n_llama_embd) {
  356. LOG_ERR("%s: embedding dim of the multimodal projector (%d) is not equal to that of LLaMA (%d). Make sure that you use the correct mmproj file.\n", __func__, n_image_embd, n_llama_embd);
  357. return false;
  358. }
  359. return true;
  360. }
  361. bool llava_image_embed_make_with_clip_img(clip_ctx * ctx_clip, int n_threads, const clip_image_u8 * img, float ** image_embd_out, int * n_img_pos_out) {
  362. // Granite vision uses up to 10 patches + base patch
  363. int num_max_patches = 11;
  364. if (clip_is_minicpmv(ctx_clip)) {
  365. num_max_patches = 10;
  366. }
  367. if (clip_is_glm(ctx_clip)) {
  368. num_max_patches = 1;
  369. }
  370. float * image_embd;
  371. if (clip_is_qwen2vl(ctx_clip)) {
  372. // qwen2vl don't split image into chunks, so `num_max_patches` is not needed.
  373. image_embd = (float *)malloc(clip_embd_nbytes_by_img(ctx_clip, img->nx, img->ny));
  374. } else {
  375. image_embd = (float *)malloc(clip_embd_nbytes(ctx_clip)*num_max_patches); // TODO: base on gridsize/llava model
  376. }
  377. if (!image_embd) {
  378. LOG_ERR("Unable to allocate memory for image embeddings\n");
  379. return false;
  380. }
  381. int n_img_pos;
  382. if (!encode_image_with_clip(ctx_clip, n_threads, img, image_embd, &n_img_pos)) {
  383. LOG_ERR("%s: cannot encode image, aborting\n", __func__);
  384. free(image_embd);
  385. return false;
  386. }
  387. *image_embd_out = image_embd;
  388. *n_img_pos_out = n_img_pos;
  389. return true;
  390. }
  391. struct llava_embd_batch {
  392. std::vector<llama_pos> pos;
  393. std::vector<int32_t> n_seq_id;
  394. std::vector<llama_seq_id> seq_id_0;
  395. std::vector<llama_seq_id *> seq_ids;
  396. std::vector<int8_t> logits;
  397. llama_batch batch;
  398. llava_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  399. pos .resize(n_tokens);
  400. n_seq_id.resize(n_tokens);
  401. seq_ids .resize(n_tokens + 1);
  402. logits .resize(n_tokens);
  403. seq_id_0.resize(1);
  404. seq_id_0[0] = seq_id;
  405. seq_ids [n_tokens] = nullptr;
  406. batch = {
  407. /*n_tokens =*/ n_tokens,
  408. /*tokens =*/ nullptr,
  409. /*embd =*/ embd,
  410. /*pos =*/ pos.data(),
  411. /*n_seq_id =*/ n_seq_id.data(),
  412. /*seq_id =*/ seq_ids.data(),
  413. /*logits =*/ logits.data(),
  414. };
  415. for (int i = 0; i < n_tokens; i++) {
  416. batch.pos [i] = pos_0 + i;
  417. batch.n_seq_id[i] = 1;
  418. batch.seq_id [i] = seq_id_0.data();
  419. batch.logits [i] = false;
  420. }
  421. }
  422. };
  423. bool llava_eval_image_embed(llama_context * ctx_llama, const struct llava_image_embed * image_embed, int n_batch, int * n_past) {
  424. int n_embd = llama_model_n_embd(llama_get_model(ctx_llama));
  425. for (int i = 0; i < image_embed->n_image_pos; i += n_batch) {
  426. int n_eval = image_embed->n_image_pos - i;
  427. if (n_eval > n_batch) {
  428. n_eval = n_batch;
  429. }
  430. float * embd = image_embed->embed+i*n_embd;
  431. llava_embd_batch llava_batch = llava_embd_batch(embd, n_eval, *n_past, 0);
  432. if (llama_decode(ctx_llama, llava_batch.batch)) {
  433. LOG_ERR("%s : failed to eval\n", __func__);
  434. return false;
  435. }
  436. *n_past += n_eval;
  437. }
  438. return true;
  439. }
  440. struct llava_image_embed * llava_image_embed_make_with_bytes(struct clip_ctx * ctx_clip, int n_threads, const unsigned char * image_bytes, int image_bytes_length) {
  441. clip_image_u8 * img = clip_image_u8_init();
  442. if (!clip_image_load_from_bytes(image_bytes, image_bytes_length, img)) {
  443. clip_image_u8_free(img);
  444. LOG_ERR("%s: can't load image from bytes, is it a valid image?", __func__);
  445. return NULL;
  446. }
  447. float* image_embed = NULL;
  448. int n_image_pos = 0;
  449. bool image_embed_result = llava_image_embed_make_with_clip_img(ctx_clip, n_threads, img, &image_embed, &n_image_pos);
  450. if (!image_embed_result) {
  451. clip_image_u8_free(img);
  452. LOG_ERR("%s: couldn't embed the image\n", __func__);
  453. return NULL;
  454. }
  455. clip_image_u8_free(img);
  456. auto result = (llava_image_embed*)malloc(sizeof(llava_image_embed));
  457. result->embed = image_embed;
  458. result->n_image_pos = n_image_pos;
  459. return result;
  460. }
  461. static bool load_file_to_bytes(const char* path, unsigned char** bytesOut, long *sizeOut) {
  462. auto file = fopen(path, "rb");
  463. if (file == NULL) {
  464. LOG_ERR("%s: can't read file %s\n", __func__, path);
  465. return false;
  466. }
  467. fseek(file, 0, SEEK_END);
  468. auto fileSize = ftell(file);
  469. fseek(file, 0, SEEK_SET);
  470. auto buffer = (unsigned char *)malloc(fileSize); // Allocate memory to hold the file data
  471. if (buffer == NULL) {
  472. LOG_ERR("%s: failed to alloc %ld bytes for file %s\n", __func__, fileSize, path);
  473. perror("Memory allocation error");
  474. fclose(file);
  475. return false;
  476. }
  477. errno = 0;
  478. size_t ret = fread(buffer, 1, fileSize, file); // Read the file into the buffer
  479. if (ferror(file)) {
  480. LOG_ERR("read error: %s", strerror(errno));
  481. free(buffer);
  482. fclose(file);
  483. return false;
  484. }
  485. if (ret != (size_t) fileSize) {
  486. LOG_ERR("unexpectedly reached end of file");
  487. free(buffer);
  488. fclose(file);
  489. return false;
  490. }
  491. fclose(file); // Close the file
  492. *bytesOut = buffer;
  493. *sizeOut = fileSize;
  494. return true;
  495. }
  496. struct llava_image_embed * llava_image_embed_make_with_filename(struct clip_ctx * ctx_clip, int n_threads, const char * image_path) {
  497. unsigned char* image_bytes;
  498. long image_bytes_length;
  499. auto loaded = load_file_to_bytes(image_path, &image_bytes, &image_bytes_length);
  500. if (!loaded) {
  501. LOG_ERR("%s: failed to load %s\n", __func__, image_path);
  502. return NULL;
  503. }
  504. llava_image_embed *embed = llava_image_embed_make_with_bytes(ctx_clip, n_threads, image_bytes, image_bytes_length);
  505. free(image_bytes);
  506. return embed;
  507. }
  508. void llava_image_embed_free(struct llava_image_embed * embed) {
  509. free(embed->embed);
  510. free(embed);
  511. }