clip.cpp 38 KB

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