clip.cpp 40 KB

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