clip.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. // NOTE: This is modified from clip.cpp only for LLaVA,
  2. // so there might be still unnecessary artifacts hanging around
  3. // I'll gradually clean and extend it
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <map>
  11. #include <regex>
  12. #include <stdexcept>
  13. #include <vector>
  14. #include "clip.h"
  15. #include "ggml.h"
  16. #include "ggml-alloc.h"
  17. #include "ggml-backend.h"
  18. #ifdef GGML_USE_CUBLAS
  19. #include "ggml-cuda.h"
  20. #endif
  21. #ifdef GGML_USE_METAL
  22. #include "ggml-metal.h"
  23. #endif
  24. #define STB_IMAGE_IMPLEMENTATION
  25. #include "stb_image.h"
  26. static std::string format(const char * fmt, ...) {
  27. va_list ap;
  28. va_list ap2;
  29. va_start(ap, fmt);
  30. va_copy(ap2, ap);
  31. int size = vsnprintf(NULL, 0, fmt, ap);
  32. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  33. std::vector<char> buf(size + 1);
  34. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  35. GGML_ASSERT(size2 == size);
  36. va_end(ap2);
  37. va_end(ap);
  38. return std::string(buf.data(), buf.size());
  39. }
  40. //
  41. // key constants
  42. //
  43. #define KEY_FTYPE "general.file_type"
  44. #define KEY_NAME "general.name"
  45. #define KEY_DESCRIPTION "general.description"
  46. #define KEY_HAS_TEXT_ENC "clip.has_text_encoder"
  47. #define KEY_HAS_VIS_ENC "clip.has_vision_encoder"
  48. #define KEY_HAS_LLAVA_PROJ "clip.has_llava_projector"
  49. #define KEY_USE_GELU "clip.use_gelu"
  50. #define KEY_N_EMBD "clip.%s.embedding_length"
  51. #define KEY_N_FF "clip.%s.feed_forward_length"
  52. #define KEY_N_BLOCK "clip.%s.block_count"
  53. #define KEY_N_HEAD "clip.%s.attention.head_count"
  54. #define KEY_LAYER_NORM_EPS "clip.%s.attention.layer_norm_epsilon"
  55. #define KEY_PROJ_DIM "clip.%s.projection_dim"
  56. #define KEY_TOKENS "tokenizer.ggml.tokens"
  57. #define KEY_N_POSITIONS "clip.text.context_length"
  58. #define KEY_IMAGE_SIZE "clip.vision.image_size"
  59. #define KEY_PATCH_SIZE "clip.vision.patch_size"
  60. #define KEY_IMAGE_MEAN "clip.vision.image_mean"
  61. #define KEY_IMAGE_STD "clip.vision.image_std"
  62. //
  63. // tensor name constants
  64. //
  65. #define TN_TOKEN_EMBD "%s.token_embd.weight"
  66. #define TN_POS_EMBD "%s.position_embd.weight"
  67. #define TN_CLASS_EMBD "v.class_embd"
  68. #define TN_PATCH_EMBD "v.patch_embd.weight"
  69. #define TN_ATTN_K "%s.blk.%d.attn_k.%s"
  70. #define TN_ATTN_Q "%s.blk.%d.attn_q.%s"
  71. #define TN_ATTN_V "%s.blk.%d.attn_v.%s"
  72. #define TN_ATTN_OUTPUT "%s.blk.%d.attn_out.%s"
  73. #define TN_FFN_DOWN "%s.blk.%d.ffn_down.%s"
  74. #define TN_FFN_UP "%s.blk.%d.ffn_up.%s"
  75. #define TN_LN_1 "%s.blk.%d.ln1.%s"
  76. #define TN_LN_2 "%s.blk.%d.ln2.%s"
  77. #define TN_LN_PRE "%s.pre_ln.%s"
  78. #define TN_LN_POST "%s.post_ln.%s"
  79. #define TN_TEXT_PROJ "text_projection.weight"
  80. #define TN_VIS_PROJ "visual_projection.weight"
  81. #define TN_LLAVA_PROJ "mm.%d.%s"
  82. //
  83. // utilities to get data from a gguf file
  84. //
  85. static int get_key_idx(const gguf_context * ctx, const char * key) {
  86. int i = gguf_find_key(ctx, key);
  87. if (i == -1) {
  88. fprintf(stderr, "key %s not found in file\n", key);
  89. throw std::runtime_error(format("Missing required key: %s", key));
  90. }
  91. return i;
  92. }
  93. static uint32_t get_u32(const gguf_context * ctx, const std::string & key) {
  94. const int i = get_key_idx(ctx, key.c_str());
  95. return gguf_get_val_u32(ctx, i);
  96. }
  97. static float get_f32(const gguf_context * ctx, const std::string & key) {
  98. const int i = get_key_idx(ctx, key.c_str());
  99. return gguf_get_val_f32(ctx, i);
  100. }
  101. static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const std::string & name) {
  102. struct ggml_tensor * cur = ggml_get_tensor(ctx, name.c_str());
  103. if (!cur) {
  104. throw std::runtime_error(format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  105. }
  106. return cur;
  107. }
  108. static std::string get_ftype(int ftype) {
  109. switch (ftype) {
  110. case 0:
  111. return "f32";
  112. case 1:
  113. return "f16";
  114. case 2:
  115. return "q4_0";
  116. case 3:
  117. return "q4_1";
  118. case 6:
  119. return "q5_0";
  120. case 7:
  121. return "q5_1";
  122. case 8:
  123. return "q8_0";
  124. default:
  125. throw std::runtime_error(format("%s: Unrecognized file type: %d\n", __func__, ftype));
  126. }
  127. }
  128. //
  129. // image data
  130. //
  131. // RGB uint8 image
  132. struct clip_image_u8 {
  133. int nx;
  134. int ny;
  135. std::vector<uint8_t> buf;
  136. };
  137. // RGB float32 image (NHWC)
  138. // Memory layout: RGBRGBRGB...
  139. struct clip_image_f32 {
  140. int nx;
  141. int ny;
  142. std::vector<float> buf;
  143. };
  144. //
  145. // clip layers
  146. //
  147. struct clip_layer {
  148. // attention
  149. struct ggml_tensor * k_w;
  150. struct ggml_tensor * k_b;
  151. struct ggml_tensor * q_w;
  152. struct ggml_tensor * q_b;
  153. struct ggml_tensor * v_w;
  154. struct ggml_tensor * v_b;
  155. struct ggml_tensor * o_w;
  156. struct ggml_tensor * o_b;
  157. // layernorm 1
  158. struct ggml_tensor * ln_1_w;
  159. struct ggml_tensor * ln_1_b;
  160. // ff
  161. struct ggml_tensor * ff_i_w;
  162. struct ggml_tensor * ff_i_b;
  163. struct ggml_tensor * ff_o_w;
  164. struct ggml_tensor * ff_o_b;
  165. // layernorm 2
  166. struct ggml_tensor * ln_2_w;
  167. struct ggml_tensor * ln_2_b;
  168. };
  169. struct clip_vision_model {
  170. struct clip_vision_hparams hparams;
  171. // embeddings
  172. struct ggml_tensor * class_embedding;
  173. struct ggml_tensor * patch_embeddings;
  174. struct ggml_tensor * position_embeddings;
  175. struct ggml_tensor * pre_ln_w;
  176. struct ggml_tensor * pre_ln_b;
  177. std::vector<clip_layer> layers;
  178. struct ggml_tensor * post_ln_w;
  179. struct ggml_tensor * post_ln_b;
  180. struct ggml_tensor * projection;
  181. // LLaVA projection
  182. struct ggml_tensor * mm_0_w;
  183. struct ggml_tensor * mm_0_b;
  184. struct ggml_tensor * mm_2_w;
  185. struct ggml_tensor * mm_2_b;
  186. };
  187. struct clip_ctx {
  188. bool has_text_encoder = false;
  189. bool has_vision_encoder = false;
  190. bool has_llava_projector = false;
  191. struct clip_vision_model vision_model;
  192. float image_mean[3];
  193. float image_std[3];
  194. bool use_gelu = false;
  195. int32_t ftype = 1;
  196. struct gguf_context * ctx_gguf;
  197. struct ggml_context * ctx_data;
  198. std::vector<uint8_t> buf_compute_meta;
  199. // memory buffers to evaluate the model
  200. ggml_backend_buffer_t params_buffer = NULL;
  201. ggml_backend_buffer_t compute_buffer = NULL;
  202. ggml_backend_t backend = NULL;
  203. ggml_allocr * compute_alloc = NULL;
  204. };
  205. static ggml_cgraph * clip_image_build_graph(clip_ctx * ctx, const clip_image_f32_batch * imgs) {
  206. if (!ctx->has_vision_encoder) {
  207. printf("This gguf file seems to have no vision encoder\n");
  208. return nullptr;
  209. }
  210. const auto & model = ctx->vision_model;
  211. const auto & hparams = model.hparams;
  212. const int image_size = hparams.image_size;
  213. const int patch_size = hparams.patch_size;
  214. const int num_patches = ((image_size / patch_size) * (image_size / patch_size));
  215. const int num_positions = num_patches + 1;
  216. const int hidden_size = hparams.hidden_size;
  217. const int n_head = hparams.n_head;
  218. const int d_head = hidden_size / n_head;
  219. const int n_layer = hparams.n_layer;
  220. //const int n_intermediate = hparams.n_intermediate;
  221. //const int projection_dim = hparams.projection_dim;
  222. const float eps = hparams.eps;
  223. int batch_size = imgs->size;
  224. if (ctx->has_llava_projector) {
  225. GGML_ASSERT(batch_size == 1);
  226. }
  227. struct ggml_init_params params = {
  228. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  229. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  230. /*.no_alloc =*/ true,
  231. };
  232. struct ggml_context * ctx0 = ggml_init(params);
  233. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  234. struct ggml_tensor * inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size, image_size, 3, batch_size);
  235. ggml_allocr_alloc(ctx->compute_alloc, inp_raw);
  236. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  237. float * data = (float *)malloc(ggml_nbytes(inp_raw));
  238. for (size_t i = 0; i < imgs->size; i++) {
  239. const int nx = imgs->data[i].nx;
  240. const int ny = imgs->data[i].ny;
  241. GGML_ASSERT(nx == image_size && ny == image_size);
  242. const int n = nx * ny;
  243. for (int b = 0; b < batch_size; b++) {
  244. for (int k = 0; k < 3; k++) {
  245. for (int y = 0; y < ny; y++) {
  246. for (int x = 0; x < nx; x++) {
  247. data[(b * 3 * n) + k * n + y * nx + x] = imgs->data[b].buf[3 * (y * nx + x) + k];
  248. }
  249. }
  250. }
  251. }
  252. }
  253. ggml_backend_tensor_set(inp_raw, data, 0, ggml_nbytes(inp_raw));
  254. free(data);
  255. }
  256. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  257. inp = ggml_reshape_3d(ctx0, inp, num_patches, hidden_size, batch_size);
  258. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 0, 2, 3));
  259. // concat class_embeddings and patch_embeddings
  260. struct ggml_tensor * embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size);
  261. ggml_allocr_alloc(ctx->compute_alloc, embeddings);
  262. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  263. void* zero_mem = malloc(ggml_nbytes(embeddings));
  264. memset(zero_mem, 0, ggml_nbytes(embeddings));
  265. ggml_backend_tensor_set(embeddings, zero_mem, 0, ggml_nbytes(embeddings));
  266. free(zero_mem);
  267. }
  268. embeddings = ggml_acc(ctx0, embeddings, model.class_embedding,
  269. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], 0);
  270. embeddings = ggml_acc(ctx0, embeddings, inp,
  271. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], model.class_embedding->nb[1]);
  272. struct ggml_tensor * positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions);
  273. ggml_allocr_alloc(ctx->compute_alloc, positions);
  274. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  275. int* positions_data = (int*)malloc(ggml_nbytes(positions));
  276. for (int i = 0; i < num_positions; i++) {
  277. positions_data[i] = i;
  278. }
  279. ggml_backend_tensor_set(positions, positions_data, 0, ggml_nbytes(positions));
  280. free(positions_data);
  281. }
  282. embeddings =
  283. ggml_add(ctx0, embeddings, ggml_get_rows(ctx0, model.position_embeddings, positions));
  284. // pre-layernorm
  285. {
  286. embeddings = ggml_norm(ctx0, embeddings, eps);
  287. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.pre_ln_w), model.pre_ln_b);
  288. }
  289. // loop over layers
  290. for (int il = 0; il < n_layer - 1; il++) {
  291. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  292. //const size_t nb_q_w = model.layers[il].q_w->nb[0];
  293. // layernorm1
  294. {
  295. cur = ggml_norm(ctx0, cur, eps);
  296. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_1_w),
  297. model.layers[il].ln_1_b);
  298. }
  299. // self-attention
  300. {
  301. struct ggml_tensor * Q =
  302. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  303. Q = ggml_scale_inplace(ctx0, Q, 1.0f / sqrt((float)d_head));
  304. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  305. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  306. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  307. struct ggml_tensor * K =
  308. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  309. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  310. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  311. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  312. struct ggml_tensor * V =
  313. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  314. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  315. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  316. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  317. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  318. KQ = ggml_soft_max_inplace(ctx0, KQ);
  319. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  320. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  321. KQV = ggml_cont(ctx0, ggml_permute(ctx0, KQV, 0, 2, 1, 3));
  322. cur = ggml_cpy(ctx0, KQV, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size));
  323. }
  324. // attention output
  325. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  326. // re-add the layer input, e.g., residual
  327. cur = ggml_add(ctx0, cur, embeddings);
  328. embeddings = cur; // embeddings = residual, cur = hidden_states
  329. // layernorm2
  330. {
  331. cur = ggml_norm(ctx0, cur, eps);
  332. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_2_w), model.layers[il].ln_2_b);
  333. }
  334. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  335. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  336. if (ctx->use_gelu) {
  337. cur = ggml_gelu_inplace(ctx0, cur);
  338. } else {
  339. cur = ggml_gelu_quick_inplace(ctx0, cur);
  340. }
  341. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  342. cur = ggml_add(ctx0, cur, model.layers[il].ff_o_b);
  343. // residual 2
  344. cur = ggml_add(ctx0, embeddings, cur);
  345. embeddings = cur;
  346. }
  347. // llava projector
  348. {
  349. embeddings = ggml_reshape_2d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1]);
  350. struct ggml_tensor * patches = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  351. ggml_allocr_alloc(ctx->compute_alloc, patches);
  352. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  353. int* patches_data = (int*)malloc(ggml_nbytes(patches));
  354. for (int i = 0; i < num_patches; i++) {
  355. patches_data[i] = i + 1;
  356. }
  357. ggml_backend_tensor_set(patches, patches_data, 0, ggml_nbytes(patches));
  358. free(patches_data);
  359. }
  360. embeddings = ggml_get_rows(ctx0, embeddings, patches);
  361. // mm projection 0
  362. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  363. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  364. embeddings = ggml_gelu(ctx0, embeddings);
  365. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  366. embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
  367. }
  368. // build the graph
  369. ggml_build_forward_expand(gf, embeddings);
  370. ggml_free(ctx0);
  371. return gf;
  372. }
  373. // read and create ggml_context containing the tensors and their data
  374. struct clip_ctx * clip_model_load(const char * fname, const int verbosity = 1) {
  375. struct ggml_context * meta = NULL;
  376. struct gguf_init_params params = {
  377. /*.no_alloc = */ true,
  378. /*.ctx = */ &meta,
  379. };
  380. struct gguf_context * ctx = gguf_init_from_file(fname, params);
  381. if (!ctx) {
  382. throw std::runtime_error(format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  383. }
  384. if (verbosity >= 1) {
  385. const int n_tensors = gguf_get_n_tensors(ctx);
  386. const int n_kv = gguf_get_n_kv(ctx);
  387. const int ftype = get_u32(ctx, KEY_FTYPE);
  388. const std::string ftype_str = get_ftype(ftype);
  389. const int idx_desc = get_key_idx(ctx, KEY_DESCRIPTION);
  390. const std::string description = gguf_get_val_str(ctx, idx_desc);
  391. const int idx_name = gguf_find_key(ctx, KEY_NAME);
  392. if (idx_name != -1) { // make name optional temporarily as some of the uploaded models missing it due to a bug
  393. const std::string name = gguf_get_val_str(ctx, idx_name);
  394. printf("%s: model name: %s\n", __func__, name.c_str());
  395. }
  396. printf("%s: description: %s\n", __func__, description.c_str());
  397. printf("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx));
  398. printf("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx));
  399. printf("%s: n_tensors: %d\n", __func__, n_tensors);
  400. printf("%s: n_kv: %d\n", __func__, n_kv);
  401. printf("%s: ftype: %s\n", __func__, ftype_str.c_str());
  402. printf("\n");
  403. }
  404. const int n_tensors = gguf_get_n_tensors(ctx);
  405. // kv
  406. if (verbosity >= 3) {
  407. const int n_kv = gguf_get_n_kv(ctx);
  408. for (int i = 0; i < n_kv; ++i) {
  409. const char * key = gguf_get_key(ctx, i);
  410. printf("%s: kv[%d]: key = %s\n", __func__, i, key);
  411. }
  412. printf("\n");
  413. }
  414. // data
  415. size_t buffer_size = 0;
  416. {
  417. for (int i = 0; i < n_tensors; ++i) {
  418. const char * name = gguf_get_tensor_name(ctx, i);
  419. const size_t offset = gguf_get_tensor_offset(ctx, i);
  420. struct ggml_tensor * cur = ggml_get_tensor(meta, name);
  421. size_t tensor_size = ggml_nbytes(cur);
  422. buffer_size += tensor_size;
  423. if (verbosity >= 3) {
  424. printf("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu\n", __func__, i,
  425. ggml_n_dims(cur), cur->name, tensor_size, offset);
  426. }
  427. }
  428. }
  429. buffer_size += n_tensors * 128 /* CLIP PADDING */;
  430. clip_ctx * new_clip = new clip_ctx;
  431. #ifdef GGML_USE_CUBLAS
  432. new_clip->backend = ggml_backend_cuda_init(0);
  433. printf("%s: CLIP using CUDA backend\n", __func__);
  434. #endif
  435. #ifdef GGML_USE_METAL
  436. new_clip->backend = ggml_backend_metal_init();
  437. printf("%s: CLIP using Metal backend\n", __func__);
  438. #endif
  439. if (!new_clip->backend) {
  440. new_clip->backend = ggml_backend_cpu_init();
  441. printf("%s: CLIP using CPU backend\n", __func__);
  442. }
  443. // model size and capabilities
  444. {
  445. int idx = get_key_idx(ctx, KEY_HAS_TEXT_ENC);
  446. new_clip->has_text_encoder = gguf_get_val_bool(ctx, idx);
  447. idx = get_key_idx(ctx, KEY_HAS_VIS_ENC);
  448. new_clip->has_vision_encoder = gguf_get_val_bool(ctx, idx);
  449. idx = gguf_find_key(ctx, KEY_HAS_LLAVA_PROJ);
  450. if (idx != -1) {
  451. new_clip->has_llava_projector = gguf_get_val_bool(ctx, idx);
  452. }
  453. GGML_ASSERT(new_clip->has_llava_projector); // see monatis/clip.cpp for image and/or text encoding for semantic search
  454. GGML_ASSERT(new_clip->has_vision_encoder);
  455. GGML_ASSERT(!new_clip->has_text_encoder);
  456. idx = get_key_idx(ctx, KEY_USE_GELU);
  457. new_clip->use_gelu = gguf_get_val_bool(ctx, idx);
  458. if (verbosity >= 1) {
  459. printf("%s: text_encoder: %d\n", __func__, new_clip->has_text_encoder);
  460. printf("%s: vision_encoder: %d\n", __func__, new_clip->has_vision_encoder);
  461. printf("%s: llava_projector: %d\n", __func__, new_clip->has_llava_projector);
  462. printf("%s: model size: %.2f MB\n", __func__, buffer_size / 1024.0 / 1024.0);
  463. printf("%s: metadata size: %.2f MB\n", __func__, ggml_get_mem_size(meta) / 1024.0 / 1024.0);
  464. }
  465. }
  466. printf("%s: params backend buffer size = % 6.2f MB (%i tensors)\n", __func__, buffer_size / (1024.0 * 1024.0), n_tensors);
  467. // load tensors
  468. {
  469. std::vector<uint8_t> read_buf;
  470. struct ggml_init_params params = {
  471. /*.mem_size =*/ (n_tensors + 1) * ggml_tensor_overhead(),
  472. /*.mem_buffer =*/ NULL,
  473. /*.no_alloc =*/ true,
  474. };
  475. new_clip->ctx_data = ggml_init(params);
  476. if (!new_clip->ctx_data) {
  477. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  478. clip_free(new_clip);
  479. return nullptr;
  480. }
  481. auto fin = std::ifstream(fname, std::ios::binary);
  482. if (!fin) {
  483. printf("cannot open model file for loading tensors\n");
  484. clip_free(new_clip);
  485. return nullptr;
  486. }
  487. // add tensors to context
  488. for (int i = 0; i < n_tensors; ++i) {
  489. const char * name = gguf_get_tensor_name(ctx, i);
  490. struct ggml_tensor * t = ggml_get_tensor(meta, name);
  491. struct ggml_tensor * cur = ggml_dup_tensor(new_clip->ctx_data, t);
  492. ggml_set_name(cur, name);
  493. }
  494. // alloc memory and offload data
  495. new_clip->params_buffer = ggml_backend_alloc_buffer(new_clip->backend, buffer_size);
  496. ggml_allocr* alloc = ggml_allocr_new_from_buffer(new_clip->params_buffer);
  497. for (int i = 0; i < n_tensors; ++i) {
  498. const char * name = gguf_get_tensor_name(ctx, i);
  499. struct ggml_tensor * cur = ggml_get_tensor(new_clip->ctx_data, name);
  500. ggml_allocr_alloc(alloc, cur);
  501. const size_t offset = gguf_get_data_offset(ctx) + gguf_get_tensor_offset(ctx, i);
  502. fin.seekg(offset, std::ios::beg);
  503. if (!fin) {
  504. printf("%s: failed to seek for tensor %s\n", __func__, name);
  505. clip_free(new_clip);
  506. return nullptr;
  507. }
  508. int num_bytes = ggml_nbytes(cur);
  509. if (ggml_backend_buffer_is_host(new_clip->params_buffer)) {
  510. // for the CPU and Metal backend, we can read directly into the tensor
  511. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  512. } else {
  513. // read into a temporary buffer first, then copy to device memory
  514. read_buf.resize(num_bytes);
  515. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  516. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  517. }
  518. }
  519. ggml_allocr_free(alloc);
  520. fin.close();
  521. }
  522. // vision model
  523. if (new_clip->has_vision_encoder) {
  524. // load vision model
  525. auto & vision_model = new_clip->vision_model;
  526. auto & hparams = vision_model.hparams;
  527. hparams.hidden_size = get_u32(ctx, format(KEY_N_EMBD, "vision"));
  528. hparams.n_head = get_u32(ctx, format(KEY_N_HEAD, "vision"));
  529. hparams.n_intermediate = get_u32(ctx, format(KEY_N_FF, "vision"));
  530. hparams.n_layer = get_u32(ctx, format(KEY_N_BLOCK, "vision"));
  531. hparams.image_size = get_u32(ctx, KEY_IMAGE_SIZE);
  532. hparams.patch_size = get_u32(ctx, KEY_PATCH_SIZE);
  533. hparams.projection_dim = get_u32(ctx, format(KEY_PROJ_DIM, "vision"));
  534. hparams.eps = get_f32(ctx, format(KEY_LAYER_NORM_EPS, "vision"));
  535. int idx_mean = get_key_idx(ctx, KEY_IMAGE_MEAN);
  536. int idx_std = get_key_idx(ctx, KEY_IMAGE_STD);
  537. for (int i = 0; i < 3; ++i) {
  538. new_clip->image_mean[i] = *((const float *)gguf_get_arr_data(ctx, idx_mean));
  539. new_clip->image_std[i] = *((const float *)gguf_get_arr_data(ctx, idx_std));
  540. }
  541. if (verbosity >= 2) {
  542. printf("\n%s: vision model hparams\n", __func__);
  543. printf("image_size %d\n", hparams.image_size);
  544. printf("patch_size %d\n", hparams.patch_size);
  545. printf("v_hidden_size %d\n", hparams.hidden_size);
  546. printf("v_n_intermediate %d\n", hparams.n_intermediate);
  547. printf("v_projection_dim %d\n", hparams.projection_dim);
  548. printf("v_n_head %d\n", hparams.n_head);
  549. printf("v_n_layer %d\n", hparams.n_layer);
  550. }
  551. vision_model.patch_embeddings = get_tensor(new_clip->ctx_data, TN_PATCH_EMBD);
  552. vision_model.class_embedding = get_tensor(new_clip->ctx_data, TN_CLASS_EMBD);
  553. vision_model.position_embeddings = get_tensor(new_clip->ctx_data, format(TN_POS_EMBD, "v"));
  554. vision_model.pre_ln_w = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "weight"));
  555. vision_model.pre_ln_b = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "bias"));
  556. vision_model.mm_0_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "weight"));
  557. vision_model.mm_0_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "bias"));
  558. vision_model.mm_2_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "weight"));
  559. vision_model.mm_2_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "bias"));
  560. vision_model.layers.resize(hparams.n_layer);
  561. for (int il = 0; il < hparams.n_layer; ++il) {
  562. auto & layer = vision_model.layers[il];
  563. layer.k_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "weight"));
  564. layer.q_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "weight"));
  565. layer.v_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "weight"));
  566. layer.o_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "weight"));
  567. layer.ln_1_w = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "weight"));
  568. layer.ln_2_w = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "weight"));
  569. layer.ff_i_w = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "weight"));
  570. layer.ff_o_w = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "weight"));
  571. layer.k_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "bias"));
  572. layer.q_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "bias"));
  573. layer.v_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "bias"));
  574. layer.o_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "bias"));
  575. layer.ln_1_b = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "bias"));
  576. layer.ln_2_b = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "bias"));
  577. layer.ff_i_b = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "bias"));
  578. layer.ff_o_b = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "bias"));
  579. }
  580. }
  581. ggml_free(meta);
  582. new_clip->ctx_gguf = ctx;
  583. // measure mem requirement and allocate
  584. {
  585. new_clip->buf_compute_meta.resize(GGML_DEFAULT_GRAPH_SIZE * ggml_tensor_overhead() + ggml_graph_overhead());
  586. new_clip->compute_alloc = ggml_allocr_new_measure_from_backend(new_clip->backend);
  587. clip_image_f32_batch batch;
  588. batch.size = 1;
  589. ggml_cgraph * gf = clip_image_build_graph(new_clip, &batch);
  590. size_t compute_memory_buffer_size = ggml_allocr_alloc_graph(new_clip->compute_alloc, gf);
  591. ggml_allocr_free(new_clip->compute_alloc);
  592. new_clip->compute_buffer = ggml_backend_alloc_buffer(new_clip->backend, compute_memory_buffer_size);
  593. new_clip->compute_alloc = ggml_allocr_new_from_buffer(new_clip->compute_buffer);
  594. printf("%s: compute allocated memory: %.2f MB\n", __func__, compute_memory_buffer_size /1024.0/1024.0);
  595. }
  596. return new_clip;
  597. }
  598. struct clip_image_u8 * clip_image_u8_init() {
  599. return new clip_image_u8();
  600. }
  601. struct clip_image_f32 * clip_image_f32_init() {
  602. return new clip_image_f32();
  603. }
  604. void clip_image_u8_free (struct clip_image_u8 * img) { delete img; }
  605. void clip_image_f32_free(struct clip_image_f32 * img) { delete img; }
  606. static void build_clip_img_from_data(const stbi_uc * data, int nx, int ny, clip_image_u8 * img) {
  607. img->nx = nx;
  608. img->ny = ny;
  609. img->buf.resize(3 * nx * ny);
  610. memcpy(img->buf.data(), data, img->buf.size());
  611. }
  612. bool clip_image_load_from_file(const char * fname, clip_image_u8 * img) {
  613. int nx, ny, nc;
  614. auto * data = stbi_load(fname, &nx, &ny, &nc, 3);
  615. if (!data) {
  616. fprintf(stderr, "%s: failed to load image '%s'\n", __func__, fname);
  617. return false;
  618. }
  619. build_clip_img_from_data(data, nx, ny, img);
  620. stbi_image_free(data);
  621. return true;
  622. }
  623. bool clip_image_load_from_bytes(const unsigned char * bytes, size_t bytes_length, struct clip_image_u8 * img) {
  624. int nx, ny, nc;
  625. auto * data = stbi_load_from_memory(bytes, bytes_length, &nx, &ny, &nc, 3);
  626. if (!data) {
  627. fprintf(stderr, "%s: failed to decode image bytes\n", __func__);
  628. return false;
  629. }
  630. build_clip_img_from_data(data, nx, ny, img);
  631. stbi_image_free(data);
  632. return true;
  633. }
  634. // normalize: x = (x - mean) / std
  635. // TODO: implement bicubic interpolation instead of linear.
  636. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, clip_image_f32 * res, const bool pad2square) {
  637. if (!ctx->has_vision_encoder) {
  638. printf("This gguf file seems to have no vision encoder\n");
  639. return false;
  640. }
  641. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  642. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  643. clip_image_u8 * temp = clip_image_u8_init(); // we will keep the input image data here temporarily
  644. if (pad2square && img->nx != img->ny) {
  645. int longer_side = std::max(img->nx, img->ny);
  646. temp->nx = longer_side;
  647. temp->ny = longer_side;
  648. temp->buf.resize(3 * longer_side * longer_side);
  649. const uint8_t bc[3] = {122, 116, 104}; // background color in RGB from LLaVA
  650. // fill with background color
  651. for (size_t i = 0; i < temp->buf.size(); i++) {
  652. temp->buf[i] = bc[i % 3];
  653. }
  654. // copy from the input image
  655. for (int y = 0; y < img->ny; y++) {
  656. for (int x = 0; x < img->nx; x++) {
  657. const int i = 3 * (y * img->nx + x);
  658. const int j = 3 * (y * temp->nx + x);
  659. temp->buf[j] = img->buf[i];
  660. temp->buf[j+1] = img->buf[i+1];
  661. temp->buf[j+2] = img->buf[i+2];
  662. }
  663. }
  664. } else {
  665. temp->nx = img->nx;
  666. temp->ny = img->ny;
  667. temp->buf.resize(img->buf.size());
  668. memcpy(temp->buf.data(), img->buf.data(), temp->buf.size());
  669. }
  670. const int nx = temp->nx;
  671. const int ny = temp->ny;
  672. const int nx2 = ctx->vision_model.hparams.image_size;
  673. const int ny2 = ctx->vision_model.hparams.image_size;
  674. res->nx = nx2;
  675. res->ny = ny2;
  676. res->buf.resize(3 * nx2 * ny2);
  677. const float scale = std::max(nx, ny) / (float)ctx->vision_model.hparams.image_size;
  678. const int nx3 = int(nx / scale + 0.5f);
  679. const int ny3 = int(ny / scale + 0.5f);
  680. const auto & m3 = ctx->image_mean; // {0.48145466f, 0.4578275f, 0.40821073f};
  681. const auto & s3 = ctx->image_std; // {0.26862954f, 0.26130258f, 0.27577711f};
  682. for (int y = 0; y < ny3; y++) {
  683. for (int x = 0; x < nx3; x++) {
  684. for (int c = 0; c < 3; c++) {
  685. // linear interpolation
  686. const float sx = (x + 0.5f) * scale - 0.5f;
  687. const float sy = (y + 0.5f) * scale - 0.5f;
  688. const int x0 = std::max(0, (int)std::floor(sx));
  689. const int y0 = std::max(0, (int)std::floor(sy));
  690. const int x1 = std::min(x0 + 1, nx - 1);
  691. const int y1 = std::min(y0 + 1, ny - 1);
  692. const float dx = sx - x0;
  693. const float dy = sy - y0;
  694. const int j00 = 3 * (y0 * nx + x0) + c;
  695. const int j01 = 3 * (y0 * nx + x1) + c;
  696. const int j10 = 3 * (y1 * nx + x0) + c;
  697. const int j11 = 3 * (y1 * nx + x1) + c;
  698. const float v00 = temp->buf[j00];
  699. const float v01 = temp->buf[j01];
  700. const float v10 = temp->buf[j10];
  701. const float v11 = temp->buf[j11];
  702. const float v0 = v00 * (1.0f - dx) + v01 * dx;
  703. const float v1 = v10 * (1.0f - dx) + v11 * dx;
  704. const float v = v0 * (1.0f - dy) + v1 * dy;
  705. const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
  706. const int i = 3 * (y * nx3 + x) + c;
  707. res->buf[i] = ((float(v2) / 255.0f) - m3[c]) / s3[c];
  708. }
  709. }
  710. }
  711. clip_image_u8_free(temp);
  712. return true;
  713. }
  714. void clip_free(clip_ctx * ctx) {
  715. ggml_free(ctx->ctx_data);
  716. gguf_free(ctx->ctx_gguf);
  717. delete ctx;
  718. }
  719. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  720. if (!ctx->has_vision_encoder) {
  721. printf("This gguf file seems to have no vision encoder\n");
  722. return false;
  723. }
  724. clip_image_f32_batch imgs{};
  725. imgs.size = 1;
  726. imgs.data = img;
  727. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  728. }
  729. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs, float * vec) {
  730. if (!ctx->has_vision_encoder) {
  731. printf("This gguf file seems to have no vision encoder\n");
  732. return false;
  733. }
  734. int batch_size = imgs->size;
  735. if(ctx->has_llava_projector) {
  736. GGML_ASSERT(batch_size == 1); // TODO: support multiple images
  737. }
  738. // reset alloc buffer to clean the memory from previous invocations
  739. ggml_allocr_reset(ctx->compute_alloc);
  740. // build the inference graph
  741. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs);
  742. ggml_allocr_alloc_graph(ctx->compute_alloc, gf);
  743. if (ggml_backend_is_cpu(ctx->backend)) {
  744. ggml_backend_cpu_set_n_threads(ctx->backend, n_threads);
  745. }
  746. #ifdef GGML_USE_METAL
  747. if (ggml_backend_is_metal(ctx->backend)) {
  748. ggml_backend_metal_set_n_cb(ctx->backend, n_threads);
  749. }
  750. #endif
  751. ggml_backend_graph_compute(ctx->backend, gf);
  752. // the last node is the embedding tensor
  753. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 1];
  754. // copy the embeddings to the location passed by the user
  755. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  756. return true;
  757. }
  758. bool clip_model_quantize(const char * fname_inp, const char * fname_out, const int itype) {
  759. ggml_type type = GGML_TYPE_Q4_1;
  760. switch (itype) {
  761. case 2:
  762. type = GGML_TYPE_Q4_0;
  763. break;
  764. case 3:
  765. type = GGML_TYPE_Q4_1;
  766. break;
  767. case 6:
  768. type = GGML_TYPE_Q5_0;
  769. break;
  770. case 7:
  771. type = GGML_TYPE_Q5_1;
  772. break;
  773. case 8:
  774. type = GGML_TYPE_Q8_0;
  775. break;
  776. default:
  777. fprintf(stderr, "%s: invalid quantization type %d\n", __func__, itype);
  778. return false;
  779. };
  780. auto * ctx_clip = clip_model_load(fname_inp, 2);
  781. const auto & ctx_src = ctx_clip->ctx_gguf;
  782. const auto & ctx_data = ctx_clip->ctx_data;
  783. auto * ctx_out = gguf_init_empty();
  784. gguf_set_kv(ctx_out, ctx_src);
  785. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  786. gguf_set_val_u32(ctx_out, "general.file_type", itype);
  787. auto fout = std::ofstream(fname_out, std::ios::binary);
  788. const int n_tensors = gguf_get_n_tensors(ctx_src);
  789. for (int i = 0; i < n_tensors; ++i) {
  790. const char * name = gguf_get_tensor_name(ctx_src, i);
  791. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name);
  792. gguf_add_tensor(ctx_out, cur);
  793. }
  794. const size_t meta_size = gguf_get_meta_size(ctx_out);
  795. for (size_t i = 0; i < meta_size; ++i) {
  796. fout.put(0);
  797. }
  798. // regexes of tensor names to be quantized
  799. const std::vector<std::string> k_names = {
  800. ".*weight",
  801. };
  802. std::vector<uint8_t> read_data(512);
  803. std::vector<uint8_t> work(512);
  804. std::vector<float> conv_buf(512);
  805. std::vector<int64_t> hist_all(1 << 4, 0);
  806. size_t total_size_org = 0;
  807. size_t total_size_new = 0;
  808. for (int i = 0; i < n_tensors; ++i) {
  809. const std::string name = gguf_get_tensor_name(ctx_src, i);
  810. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name.c_str());
  811. enum ggml_type new_type;
  812. void * new_data;
  813. size_t new_size;
  814. bool quantize = false;
  815. for (const auto & s : k_names) {
  816. if (std::regex_match(name, std::regex(s))) {
  817. quantize = true;
  818. break;
  819. }
  820. }
  821. // quantize only 2D tensors
  822. quantize &= (ggml_n_dims(cur) == 2);
  823. if (quantize) {
  824. new_type = type;
  825. const size_t n_elms = ggml_nelements(cur);
  826. float * f32_data;
  827. switch (cur->type) {
  828. case GGML_TYPE_F32:
  829. f32_data = (float *)cur->data;
  830. break;
  831. case GGML_TYPE_F16:
  832. if (conv_buf.size() < n_elms) {
  833. conv_buf.resize(n_elms);
  834. }
  835. for (size_t j = 0; j < n_elms; ++j) {
  836. conv_buf[j] = ggml_fp16_to_fp32(((ggml_fp16_t *)cur->data)[j]);
  837. }
  838. f32_data = (float *)conv_buf.data();
  839. break;
  840. default:
  841. printf("Please use an input file in f32 or f16\n");
  842. return false;
  843. }
  844. if (work.size() < n_elms * 4) {
  845. work.resize(n_elms * 4);
  846. }
  847. new_data = work.data();
  848. std::vector<int64_t> hist_cur(1 << 4, 0);
  849. switch (new_type) {
  850. case GGML_TYPE_Q4_0: {
  851. new_size = ggml_quantize_q4_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  852. } break;
  853. case GGML_TYPE_Q4_1: {
  854. new_size = ggml_quantize_q4_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  855. } break;
  856. case GGML_TYPE_Q5_0: {
  857. new_size = ggml_quantize_q5_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  858. } break;
  859. case GGML_TYPE_Q5_1: {
  860. new_size = ggml_quantize_q5_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  861. } break;
  862. case GGML_TYPE_Q8_0: {
  863. new_size = ggml_quantize_q8_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  864. } break;
  865. default: {
  866. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, new_type);
  867. return false;
  868. }
  869. }
  870. for (size_t j = 0; j < hist_cur.size(); ++j) {
  871. hist_all[j] += hist_cur[j];
  872. }
  873. } else {
  874. new_type = cur->type;
  875. new_data = cur->data;
  876. new_size = ggml_nbytes(cur);
  877. }
  878. const size_t orig_size = ggml_nbytes(cur);
  879. total_size_org += orig_size;
  880. total_size_new += new_size;
  881. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  882. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  883. fout.write((const char *)new_data, new_size);
  884. size_t pad = GGML_PAD(new_size, gguf_get_alignment(ctx_out)) - new_size;
  885. for (size_t j = 0; j < pad; ++j) {
  886. fout.put(0);
  887. }
  888. printf("%s: n_dims = %d | quantize=%d | size = %f MB -> %f MB\n", name.c_str(), ggml_n_dims(cur), quantize,
  889. orig_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  890. }
  891. // go back to beginning of file and write the updated metadata
  892. fout.seekp(0, std::ios::beg);
  893. std::vector<uint8_t> meta(meta_size);
  894. gguf_get_meta_data(ctx_out, meta.data());
  895. fout.write((const char *)meta.data(), meta_size);
  896. fout.close();
  897. clip_free(ctx_clip);
  898. gguf_free(ctx_out);
  899. {
  900. printf("%s: original size = %8.2f MB\n", __func__, total_size_org / 1024.0 / 1024.0);
  901. printf("%s: quantized size = %8.2f MB\n", __func__, total_size_new / 1024.0 / 1024.0);
  902. int64_t sum_all = 0;
  903. for (size_t i = 0; i < hist_all.size(); ++i) {
  904. sum_all += hist_all[i];
  905. }
  906. printf("%s: hist: ", __func__);
  907. for (size_t i = 0; i < hist_all.size(); ++i) {
  908. printf("%5.3f ", hist_all[i] / (float)sum_all);
  909. }
  910. printf("\n");
  911. }
  912. return true;
  913. }
  914. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  915. return ctx->vision_model.mm_2_b->ne[0];
  916. }
  917. int clip_n_patches(const struct clip_ctx * ctx) {
  918. auto & params = ctx->vision_model.hparams;
  919. return (params.image_size / params.patch_size) * (params.image_size / params.patch_size);
  920. }
  921. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  922. return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);
  923. }