1
0

llava.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. #include "clip.h"
  2. #include "common.h"
  3. #include "llama.h"
  4. #include "llava.h"
  5. #include "base64.hpp"
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <vector>
  9. #include <numeric>
  10. // RGB uint8 image
  11. struct clip_image_u8 {
  12. int nx;
  13. int ny;
  14. std::vector<uint8_t> buf;
  15. };
  16. // RGB float32 image (NHWC)
  17. // Memory layout: RGBRGBRGB...
  18. struct clip_image_f32 {
  19. int nx;
  20. int ny;
  21. std::vector<float> buf;
  22. };
  23. struct clip_image_grid_shape {
  24. int first;
  25. int second;
  26. };
  27. /**
  28. * Selects the best resolution from a list of possible resolutions based on the original size.
  29. *
  30. * @param original_size The original size of the image in the format (width, height).
  31. * @param possible_resolutions A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
  32. * @return The best fit resolution in the format (width, height).
  33. */
  34. static std::pair<int, int> select_best_resolution(const std::pair<int, int>& original_size, const std::vector<std::pair<int, int>>& possible_resolutions) {
  35. int original_width = original_size.first;
  36. int original_height = original_size.second;
  37. std::pair<int, int> best_fit;
  38. int max_effective_resolution = 0;
  39. int min_wasted_resolution = std::numeric_limits<int>::max();
  40. for (const auto& resolution : possible_resolutions) {
  41. int width = resolution.first;
  42. int height = resolution.second;
  43. float scale = std::min(static_cast<float>(width) / original_width, static_cast<float>(height) / original_height);
  44. int downscaled_width = static_cast<int>(original_width * scale);
  45. int downscaled_height = static_cast<int>(original_height * scale);
  46. int effective_resolution = std::min(downscaled_width * downscaled_height, original_width * original_height);
  47. int wasted_resolution = (width * height) - effective_resolution;
  48. // LOG_TEE("resolution: %d %d, scale: %f, downscaled: %d %d, effective: %d, wasted: %d\n", width, height, scale, downscaled_width, downscaled_height, effective_resolution, wasted_resolution);
  49. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_resolution < min_wasted_resolution)) {
  50. max_effective_resolution = effective_resolution;
  51. min_wasted_resolution = wasted_resolution;
  52. best_fit = resolution;
  53. }
  54. }
  55. return best_fit;
  56. }
  57. /**
  58. * @brief Get the anyres image grid shape object
  59. *
  60. * @param image_size
  61. * @param grid_pinpoints
  62. * @param image_patch_size
  63. * @return <int, int>
  64. */
  65. 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) {
  66. /**
  67. Conversion from gguf flat array to vector:
  68. std::vector<std::pair<int, int>> possible_resolutions;
  69. for (int i = 0; i < 32 && params.image_grid_pinpoints[i] != 0; i+=2) {
  70. possible_resolutions.push_back({params.image_grid_pinpoints[i], params.image_grid_pinpoints[i+1]});
  71. }
  72. */
  73. auto best_resolution = select_best_resolution(image_size, grid_pinpoints);
  74. return {best_resolution.first / image_patch_size, best_resolution.second / image_patch_size};
  75. }
  76. // Take the image segments in a grid configuration and return the embeddings and the number of embeddings into preallocated memory (image_embd_out)
  77. 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) {
  78. struct {
  79. struct ggml_context * ctx;
  80. } model;
  81. const int32_t image_size = clip_image_size(ctx_clip);
  82. const int32_t patch_size = clip_patch_size(ctx_clip);
  83. int32_t num_patches_per_side = image_size / patch_size; // 336 / 14 = 24 - used for embedding-patching boxes (24*24 = 576 patches)
  84. int num_patches_width = grid_shape.first; // grid 1-4
  85. int num_patches_height = grid_shape.second; // grid 1-4
  86. const size_t num_images = num_patches_width * num_patches_height + 1;
  87. // TODO: size calculation is not calculated - it's only tens of MB
  88. size_t ctx_size = 0;
  89. {
  90. ctx_size += clip_embd_nbytes(ctx_clip) * num_images * 8; // image_features
  91. ctx_size += 1024*1024 * ggml_type_size(GGML_TYPE_F32);
  92. }
  93. struct ggml_init_params params {
  94. /*.mem_size =*/ ctx_size,
  95. /*.mem_buffer =*/ NULL,
  96. /*.no_alloc =*/ false, // NOTE: this should be false when using the legacy API
  97. };
  98. // Python reference code for full unpad:
  99. /*
  100. base_image_feature = image_feature[0]
  101. image_feature = image_feature[1:]
  102. image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
  103. image_feature = image_feature.flatten(1, 2).flatten(2, 3)
  104. image_feature = unpad_image(image_feature, image_sizes[image_idx])
  105. image_feature = torch.cat((
  106. image_feature,
  107. self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1)
  108. ), dim=-1)
  109. image_feature = image_feature.flatten(1, 2).transpose(0, 1)
  110. image_feature = torch.cat((base_image_feature, image_feature), dim=0)
  111. */
  112. // We now have two options: unpad or no unpad. Unpad removes tokens for faster llm eval.
  113. // 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.
  114. // Without unpad we have to split the sub-image embeddings into patches of 24 features each and permute them.
  115. // Once all images are processed to prepended the base_image_features without any changes.
  116. // Pytorch reference simplified, modified for ggml compatibility - confirmed identical output in python (for a 2x2 grid image (676x676 scaling))
  117. /*
  118. image_feature = image_feature.view(2, 2, 24, 24, 4096)
  119. image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
  120. image_feature = image_feature.view(2, 24, 2, 24, 4096)
  121. image_feature = image_feature.flatten(0, 3)
  122. // Reshape to 4D tensor by merging the last two dimensions
  123. image_feature = image_feature.view(2, 2, 24, 24*4096)
  124. image_feature = image_feature.permute(0, 2, 1, 3).contiguous()
  125. image_feature = image_feature.view(-1, 4096)
  126. */
  127. model.ctx = ggml_init(params);
  128. struct ggml_tensor * image_features = ggml_new_tensor_3d(model.ctx, GGML_TYPE_F32, clip_n_mmproj_embd(ctx_clip), clip_n_patches(ctx_clip), num_images - 1); // example: 4096 x 576 x 4
  129. // ggml_tensor_printf(image_features,"image_features",__LINE__,false,false);
  130. // fill it with the image embeddings, ignoring the base
  131. for (size_t i = 1; i < num_images; i++) {
  132. size_t offset = (i-1) * clip_embd_nbytes(ctx_clip);
  133. memcpy((uint8_t *)(image_features->data) + offset, image_embd_v[i], clip_embd_nbytes(ctx_clip));
  134. }
  135. struct ggml_cgraph * gf = ggml_new_graph(model.ctx);
  136. size_t size_ele = ggml_type_size(GGML_TYPE_F32);
  137. struct ggml_tensor *image_features_patchview = ggml_view_4d(model.ctx, image_features,
  138. num_patches_per_side * clip_n_mmproj_embd(ctx_clip),
  139. num_patches_per_side,
  140. num_patches_width,
  141. num_patches_height,
  142. size_ele * num_patches_per_side * clip_n_mmproj_embd(ctx_clip),
  143. size_ele * num_patches_per_side * clip_n_mmproj_embd(ctx_clip) * num_patches_per_side,
  144. size_ele * num_patches_per_side * clip_n_mmproj_embd(ctx_clip) * num_patches_per_side * num_patches_width, 0);
  145. // ggml_tensor_printf(image_features_patchview,"image_features_patchview",__LINE__,false,false);
  146. struct ggml_tensor *permuted_cont = ggml_cont(model.ctx, ggml_permute(model.ctx, image_features_patchview, 0, 2, 1, 3));
  147. /**
  148. At the end of each row we have to add the row_end embeddings, which are the same as the newline embeddings
  149. image_feature = torch.cat((
  150. image_feature,
  151. self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)
  152. ), dim=-1)
  153. *
  154. */
  155. // ggml_tensor_printf(permuted_cont,"permuted_cont",__LINE__,false,false);
  156. 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);
  157. // ggml_tensor_printf(flatten,"flatten",__LINE__,false,false);
  158. ggml_build_forward_expand(gf, flatten);
  159. ggml_graph_compute_with_ctx(model.ctx, gf, 1);
  160. struct ggml_tensor* result = gf->nodes[gf->n_nodes - 1];
  161. memcpy(image_embd_out, image_embd_v[0], clip_embd_nbytes(ctx_clip)); // main image as global context
  162. // append without newline tokens (default behavior in llava_arch when not using unpad ):
  163. memcpy(image_embd_out + clip_n_patches(ctx_clip) * clip_n_mmproj_embd(ctx_clip), (float*)result->data, clip_embd_nbytes(ctx_clip) * (num_images-1)); // grid patches
  164. *n_img_pos_out = static_cast<int>(result->ne[1]+clip_n_patches(ctx_clip));
  165. // Debug: Test single segments
  166. // Current findings: sending base image, sending a segment embedding all works similar to python
  167. // However, permuted embeddings do not work yet (stride issue?)
  168. // memcpy(image_embd_out, image_embd_v[0], clip_embd_nbytes(ctx_clip)); // main image as context
  169. // memcpy(image_embd_out, (float*)prepared_cont->data, clip_embd_nbytes(ctx_clip)); // main image as context
  170. // *n_img_pos_out=576;
  171. ggml_free(model.ctx);
  172. return true;
  173. }
  174. 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) {
  175. // 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
  176. clip_image_f32_batch img_res_v;
  177. img_res_v.size = 0;
  178. img_res_v.data = nullptr;
  179. if (!clip_image_preprocess(ctx_clip, img, &img_res_v)) {
  180. LOG_TEE("%s: unable to preprocess image\n", __func__);
  181. delete[] img_res_v.data;
  182. return false;
  183. }
  184. const int64_t t_img_enc_start_us = ggml_time_us();
  185. const char * mm_patch_merge_type = clip_patch_merge_type(ctx_clip);
  186. if (strcmp(mm_patch_merge_type, "spatial_unpad") != 0) {
  187. // flat / default llava-1.5 type embedding
  188. *n_img_pos = clip_n_patches(ctx_clip);
  189. bool encoded = clip_image_encode(ctx_clip, n_threads, &img_res_v.data[0], image_embd); // image_embd shape is 576 x 4096
  190. delete[] img_res_v.data;
  191. if (!encoded) {
  192. LOG_TEE("Unable to encode image\n");
  193. return false;
  194. }
  195. } else {
  196. // spatial_unpad llava-1.6 type embedding
  197. // TODO: CLIP needs batching support - in HF the llm projection is separate after encoding, which might be a solution to quickly get batching working
  198. std::vector<float *> image_embd_v;
  199. image_embd_v.resize(img_res_v.size);
  200. for (size_t i = 0; i < img_res_v.size; i++) {
  201. image_embd_v[i] = (float *)malloc(clip_embd_nbytes(ctx_clip)); // 576 patches * 4096 embeddings * 4 bytes = 9437184
  202. const bool encoded = clip_image_encode(ctx_clip, n_threads, &img_res_v.data[i], image_embd_v[i]); // image data is in 3x336x336 format and will be converted to 336x336x3 inside
  203. if (!encoded) {
  204. LOG_TEE("Unable to encode image - spatial_unpad - subimage %d of %d\n", (int) i+1, (int) img_res_v.size);
  205. return false;
  206. }
  207. }
  208. const int64_t t_img_enc_batch_us = ggml_time_us();
  209. LOG_TEE("%s: %d segments encoded in %8.2f ms\n", __func__, (int)img_res_v.size, (t_img_enc_batch_us - t_img_enc_start_us) / 1000.0);
  210. const int32_t * image_grid = clip_image_grid(ctx_clip);
  211. std::vector<std::pair<int, int>> grid_pinpoints;
  212. for (int i = 0; i < 32 && image_grid[i] != 0; i += 2) {
  213. grid_pinpoints.push_back({image_grid[i], image_grid[i+1]});
  214. }
  215. // free all img_res_v - not needed anymore
  216. delete[] img_res_v.data;
  217. img_res_v.size = 0;
  218. img_res_v.data = nullptr;
  219. const int32_t image_size = clip_image_size(ctx_clip);
  220. struct clip_image_grid_shape grid_shape = get_anyres_image_grid_shape({img->nx,img->ny}, grid_pinpoints, image_size);
  221. int n_img_pos_out;
  222. clip_llava_handle_patches(ctx_clip, image_embd_v, grid_shape, image_embd, &n_img_pos_out);
  223. *n_img_pos = n_img_pos_out;
  224. for (size_t i = 0; i < image_embd_v.size(); i++) {
  225. free(image_embd_v[i]);
  226. }
  227. image_embd_v.clear();
  228. // debug image/segment/normalization content:
  229. // clip_image_u8 * tmp = clip_image_u8_init();
  230. // clip_image_convert_f32_to_u8(*image_feature, *tmp);
  231. // clip_image_save_to_bmp(*tmp, "image_feature.bmp");
  232. }
  233. LOG_TEE("%s: image embedding created: %d tokens\n", __func__, *n_img_pos);
  234. const int64_t t_img_enc_end_us = ggml_time_us();
  235. float t_img_enc_ms = (t_img_enc_end_us - t_img_enc_start_us) / 1000.0;
  236. LOG_TEE("\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);
  237. return true;
  238. }
  239. bool llava_validate_embed_size(const llama_context * ctx_llama, const clip_ctx * ctx_clip) {
  240. // make sure that the correct mmproj was used, i.e., compare apples to apples
  241. int n_llama_embd = llama_n_embd(llama_get_model(ctx_llama));
  242. auto n_image_embd = clip_n_mmproj_embd(ctx_clip);
  243. if (n_image_embd != n_llama_embd) {
  244. LOG_TEE("%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);
  245. return false;
  246. }
  247. return true;
  248. }
  249. 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) {
  250. float * image_embd = (float *)malloc(clip_embd_nbytes(ctx_clip)*6); // TODO: base on gridsize/llava model
  251. if (!image_embd) {
  252. LOG_TEE("Unable to allocate memory for image embeddings\n");
  253. return false;
  254. }
  255. int n_img_pos;
  256. if (!encode_image_with_clip(ctx_clip, n_threads, img, image_embd, &n_img_pos)) {
  257. LOG_TEE("%s: cannot encode image, aborting\n", __func__);
  258. free(image_embd);
  259. return false;
  260. }
  261. *image_embd_out = image_embd;
  262. *n_img_pos_out = n_img_pos;
  263. return true;
  264. }
  265. bool llava_eval_image_embed(llama_context * ctx_llama, const struct llava_image_embed * image_embed, int n_batch, int * n_past) {
  266. int n_embd = llama_n_embd(llama_get_model(ctx_llama));
  267. for (int i = 0; i < image_embed->n_image_pos; i += n_batch) {
  268. int n_eval = image_embed->n_image_pos - i;
  269. if (n_eval > n_batch) {
  270. n_eval = n_batch;
  271. }
  272. llama_batch batch = {int32_t(n_eval), nullptr, (image_embed->embed+i*n_embd), nullptr, nullptr, nullptr, nullptr, *n_past, 1, 0, };
  273. if (llama_decode(ctx_llama, batch)) {
  274. LOG_TEE("%s : failed to eval\n", __func__);
  275. return false;
  276. }
  277. *n_past += n_eval;
  278. }
  279. return true;
  280. }
  281. 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) {
  282. clip_image_u8 * img = clip_image_u8_init();
  283. if (!clip_image_load_from_bytes(image_bytes, image_bytes_length, img)) {
  284. clip_image_u8_free(img);
  285. LOG_TEE("%s: can't load image from bytes, is it a valid image?", __func__);
  286. return NULL;
  287. }
  288. float* image_embed = NULL;
  289. int n_image_pos = 0;
  290. bool image_embed_result = llava_image_embed_make_with_clip_img(ctx_clip, n_threads, img, &image_embed, &n_image_pos);
  291. if (!image_embed_result) {
  292. clip_image_u8_free(img);
  293. LOG_TEE("%s: coulnd't embed the image\n", __func__);
  294. return NULL;
  295. }
  296. clip_image_u8_free(img);
  297. auto result = (llava_image_embed*)malloc(sizeof(llava_image_embed));
  298. result->embed = image_embed;
  299. result->n_image_pos = n_image_pos;
  300. return result;
  301. }
  302. static bool load_file_to_bytes(const char* path, unsigned char** bytesOut, long *sizeOut) {
  303. auto file = fopen(path, "rb");
  304. if (file == NULL) {
  305. LOG_TEE("%s: can't read file %s\n", __func__, path);
  306. return false;
  307. }
  308. fseek(file, 0, SEEK_END);
  309. auto fileSize = ftell(file);
  310. fseek(file, 0, SEEK_SET);
  311. auto buffer = (unsigned char *)malloc(fileSize); // Allocate memory to hold the file data
  312. if (buffer == NULL) {
  313. LOG_TEE("%s: failed to alloc %ld bytes for file %s\n", __func__, fileSize, path);
  314. perror("Memory allocation error");
  315. fclose(file);
  316. return false;
  317. }
  318. errno = 0;
  319. size_t ret = fread(buffer, 1, fileSize, file); // Read the file into the buffer
  320. if (ferror(file)) {
  321. die_fmt("read error: %s", strerror(errno));
  322. }
  323. if (ret != (size_t) fileSize) {
  324. die("unexpectedly reached end of file");
  325. }
  326. fclose(file); // Close the file
  327. *bytesOut = buffer;
  328. *sizeOut = fileSize;
  329. return true;
  330. }
  331. struct llava_image_embed * llava_image_embed_make_with_filename(struct clip_ctx * ctx_clip, int n_threads, const char * image_path) {
  332. unsigned char* image_bytes;
  333. long image_bytes_length;
  334. auto loaded = load_file_to_bytes(image_path, &image_bytes, &image_bytes_length);
  335. if (!loaded) {
  336. LOG_TEE("%s: failed to load %s\n", __func__, image_path);
  337. return NULL;
  338. }
  339. llava_image_embed *embed = llava_image_embed_make_with_bytes(ctx_clip, n_threads, image_bytes, image_bytes_length);
  340. free(image_bytes);
  341. return embed;
  342. }
  343. void llava_image_embed_free(struct llava_image_embed * embed) {
  344. free(embed->embed);
  345. free(embed);
  346. }