clip.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. // loop over layers
  274. for (int il = 0; il < n_layer - 1; il++) {
  275. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  276. //const size_t nb_q_w = model.layers[il].q_w->nb[0];
  277. // layernorm1
  278. {
  279. cur = ggml_norm(ctx0, cur, eps);
  280. cur = ggml_add(ctx0, ggml_mul(ctx0, ggml_repeat(ctx0, model.layers[il].ln_1_w, cur), cur),
  281. ggml_repeat(ctx0, model.layers[il].ln_1_b, cur));
  282. }
  283. // self-attention
  284. {
  285. struct ggml_tensor * Q =
  286. ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].q_b, cur), ggml_mul_mat(ctx0, model.layers[il].q_w, cur));
  287. Q = ggml_scale_inplace(ctx0, Q, 1.0f / sqrt((float)d_head));
  288. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  289. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  290. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  291. struct ggml_tensor * K =
  292. ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].k_b, cur), ggml_mul_mat(ctx0, model.layers[il].k_w, cur));
  293. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  294. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  295. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  296. struct ggml_tensor * V =
  297. ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].v_b, cur), ggml_mul_mat(ctx0, model.layers[il].v_w, cur));
  298. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  299. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  300. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  301. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  302. KQ = ggml_soft_max_inplace(ctx0, KQ);
  303. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  304. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  305. KQV = ggml_cont(ctx0, ggml_permute(ctx0, KQV, 0, 2, 1, 3));
  306. cur = ggml_cpy(ctx0, KQV, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size));
  307. }
  308. // attention output
  309. cur = ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].o_b, cur), ggml_mul_mat(ctx0, model.layers[il].o_w, cur));
  310. // re-add the layer input, e.g., residual
  311. cur = ggml_add(ctx0, cur, embeddings);
  312. embeddings = cur; // embeddings = residual, cur = hidden_states
  313. // layernorm2
  314. {
  315. cur = ggml_norm(ctx0, cur, eps);
  316. cur = ggml_add(ctx0, ggml_mul(ctx0, ggml_repeat(ctx0, model.layers[il].ln_2_w, cur), cur),
  317. ggml_repeat(ctx0, model.layers[il].ln_2_b, cur));
  318. }
  319. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  320. cur = ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].ff_i_b, cur), cur);
  321. if (ctx->use_gelu) {
  322. cur = ggml_gelu_inplace(ctx0, cur);
  323. } else {
  324. cur = ggml_gelu_quick_inplace(ctx0, cur);
  325. }
  326. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  327. cur = ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].ff_o_b, cur), cur);
  328. // residual 2
  329. cur = ggml_add(ctx0, embeddings, cur);
  330. embeddings = cur;
  331. }
  332. // llava projector
  333. {
  334. embeddings = ggml_reshape_2d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1]);
  335. struct ggml_tensor * patches = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  336. ggml_allocr_alloc(ctx->alloc, patches);
  337. if (!ggml_allocr_is_measure(ctx->alloc)) {
  338. for (int i = 0; i < num_patches; ++i) {
  339. ggml_set_i32_1d(patches, i, i+1);
  340. }
  341. }
  342. embeddings = ggml_get_rows(ctx0, embeddings, patches);
  343. // mm projection 0
  344. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  345. embeddings = ggml_add(ctx0, ggml_repeat(ctx0, model.mm_0_b, embeddings), embeddings);
  346. embeddings = ggml_gelu(ctx0, embeddings);
  347. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  348. embeddings = ggml_add(ctx0, ggml_repeat(ctx0, model.mm_2_b, embeddings), embeddings);
  349. }
  350. // build the graph
  351. ggml_build_forward_expand(gf, embeddings);
  352. ggml_free(ctx0);
  353. return gf;
  354. }
  355. // read and create ggml_context containing the tensors and their data
  356. struct clip_ctx * clip_model_load(const char * fname, const int verbosity = 1) {
  357. struct ggml_context * meta = NULL;
  358. struct gguf_init_params params = {
  359. /*.no_alloc = */ true,
  360. /*.ctx = */ &meta,
  361. };
  362. struct gguf_context * ctx = gguf_init_from_file(fname, params);
  363. if (!ctx) {
  364. throw std::runtime_error(format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  365. }
  366. if (verbosity >= 1) {
  367. const int n_tensors = gguf_get_n_tensors(ctx);
  368. const int n_kv = gguf_get_n_kv(ctx);
  369. const int ftype = get_u32(ctx, KEY_FTYPE);
  370. const std::string ftype_str = get_ftype(ftype);
  371. const int idx_desc = get_key_idx(ctx, KEY_DESCRIPTION);
  372. const std::string description = gguf_get_val_str(ctx, idx_desc);
  373. const int idx_name = gguf_find_key(ctx, KEY_NAME);
  374. if (idx_name != -1) { // make name optional temporarily as some of the uploaded models missing it due to a bug
  375. const std::string name = gguf_get_val_str(ctx, idx_name);
  376. printf("%s: model name: %s\n", __func__, name.c_str());
  377. }
  378. printf("%s: description: %s\n", __func__, description.c_str());
  379. printf("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx));
  380. printf("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx));
  381. printf("%s: n_tensors: %d\n", __func__, n_tensors);
  382. printf("%s: n_kv: %d\n", __func__, n_kv);
  383. printf("%s: ftype: %s\n", __func__, ftype_str.c_str());
  384. printf("\n");
  385. }
  386. // kv
  387. if (verbosity >= 3) {
  388. const int n_kv = gguf_get_n_kv(ctx);
  389. for (int i = 0; i < n_kv; ++i) {
  390. const char * key = gguf_get_key(ctx, i);
  391. printf("%s: kv[%d]: key = %s\n", __func__, i, key);
  392. }
  393. printf("\n");
  394. }
  395. // data
  396. size_t ctx_size = 0;
  397. {
  398. const int n_tensors = gguf_get_n_tensors(ctx);
  399. for (int i = 0; i < n_tensors; ++i) {
  400. const char * name = gguf_get_tensor_name(ctx, i);
  401. const size_t offset = gguf_get_tensor_offset(ctx, i);
  402. struct ggml_tensor * cur = ggml_get_tensor(meta, name);
  403. ctx_size += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  404. size_t tensor_size = ggml_nbytes(cur);
  405. size_t padded_size = ggml_nbytes_pad(cur);
  406. ctx_size += padded_size;
  407. if (verbosity >= 3) {
  408. printf("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, padded_size=%zu, offset=%zu\n", __func__, i,
  409. ggml_n_dims(cur), cur->name, tensor_size, padded_size, offset);
  410. }
  411. }
  412. }
  413. clip_ctx * new_clip = new clip_ctx;
  414. // model size and capabilities
  415. {
  416. int idx = get_key_idx(ctx, KEY_HAS_TEXT_ENC);
  417. new_clip->has_text_encoder = gguf_get_val_bool(ctx, idx);
  418. idx = get_key_idx(ctx, KEY_HAS_VIS_ENC);
  419. new_clip->has_vision_encoder = gguf_get_val_bool(ctx, idx);
  420. idx = gguf_find_key(ctx, KEY_HAS_LLAVA_PROJ);
  421. if (idx != -1) {
  422. new_clip->has_llava_projector = gguf_get_val_bool(ctx, idx);
  423. }
  424. GGML_ASSERT(new_clip->has_llava_projector); // see monatis/clip.cpp for image and/or text encoding for semantic search
  425. GGML_ASSERT(new_clip->has_vision_encoder);
  426. GGML_ASSERT(!new_clip->has_text_encoder);
  427. idx = get_key_idx(ctx, KEY_USE_GELU);
  428. new_clip->use_gelu = gguf_get_val_bool(ctx, idx);
  429. if (verbosity >= 1) {
  430. printf("%s: text_encoder: %d\n", __func__, new_clip->has_text_encoder);
  431. printf("%s: vision_encoder: %d\n", __func__, new_clip->has_vision_encoder);
  432. printf("%s: llava_projector: %d\n", __func__, new_clip->has_llava_projector);
  433. printf("%s: model size: %.2f MB\n", __func__, (ctx_size / 1024.0 / 1024.0));
  434. printf("%s: metadata size: %.2f MB\n", __func__, ggml_get_mem_size(meta) / 1024.0 / 1024.0);
  435. }
  436. }
  437. // load tensors
  438. {
  439. struct ggml_init_params params = {
  440. /*.mem_size =*/ ctx_size,
  441. /*.mem_buffer =*/ NULL,
  442. /*.no_alloc =*/ false,
  443. };
  444. new_clip->ctx = ggml_init(params);
  445. if (!new_clip->ctx) {
  446. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  447. clip_free(new_clip);
  448. return nullptr;
  449. }
  450. auto fin = std::ifstream(fname, std::ios::binary);
  451. if (!fin) {
  452. printf("cannot open model file for loading tensors\n");
  453. clip_free(new_clip);
  454. return nullptr;
  455. }
  456. const int n_tensors = gguf_get_n_tensors(ctx);
  457. for (int i = 0; i < n_tensors; ++i) {
  458. const char * name = gguf_get_tensor_name(ctx, i);
  459. struct ggml_tensor * t = ggml_get_tensor(meta, name);
  460. struct ggml_tensor * cur = ggml_dup_tensor(new_clip->ctx, t);
  461. ggml_set_name(cur, name);
  462. const size_t offset = gguf_get_data_offset(ctx) + gguf_get_tensor_offset(ctx, i);
  463. fin.seekg(offset, std::ios::beg);
  464. if (!fin) {
  465. printf("%s: failed to seek for tensor %s\n", __func__, name);
  466. clip_free(new_clip);
  467. return nullptr;
  468. }
  469. fin.read(reinterpret_cast<char *>(cur->data), ggml_nbytes(t));
  470. }
  471. fin.close();
  472. }
  473. // vision model
  474. if (new_clip->has_vision_encoder) {
  475. // load vision model
  476. auto & vision_model = new_clip->vision_model;
  477. auto & hparams = vision_model.hparams;
  478. hparams.hidden_size = get_u32(ctx, format(KEY_N_EMBD, "vision"));
  479. hparams.n_head = get_u32(ctx, format(KEY_N_HEAD, "vision"));
  480. hparams.n_intermediate = get_u32(ctx, format(KEY_N_FF, "vision"));
  481. hparams.n_layer = get_u32(ctx, format(KEY_N_BLOCK, "vision"));
  482. hparams.image_size = get_u32(ctx, KEY_IMAGE_SIZE);
  483. hparams.patch_size = get_u32(ctx, KEY_PATCH_SIZE);
  484. hparams.projection_dim = get_u32(ctx, format(KEY_PROJ_DIM, "vision"));
  485. hparams.eps = get_f32(ctx, format(KEY_LAYER_NORM_EPS, "vision"));
  486. int idx_mean = get_key_idx(ctx, KEY_IMAGE_MEAN);
  487. int idx_std = get_key_idx(ctx, KEY_IMAGE_STD);
  488. for (int i = 0; i < 3; ++i) {
  489. new_clip->image_mean[i] = *((const float *)gguf_get_arr_data(ctx, idx_mean));
  490. new_clip->image_std[i] = *((const float *)gguf_get_arr_data(ctx, idx_std));
  491. }
  492. if (verbosity >= 2) {
  493. printf("\n%s: vision model hparams\n", __func__);
  494. printf("image_size %d\n", hparams.image_size);
  495. printf("patch_size %d\n", hparams.patch_size);
  496. printf("v_hidden_size %d\n", hparams.hidden_size);
  497. printf("v_n_intermediate %d\n", hparams.n_intermediate);
  498. printf("v_projection_dim %d\n", hparams.projection_dim);
  499. printf("v_n_head %d\n", hparams.n_head);
  500. printf("v_n_layer %d\n", hparams.n_layer);
  501. }
  502. vision_model.patch_embeddings = get_tensor(new_clip->ctx, TN_PATCH_EMBD);
  503. vision_model.class_embedding = get_tensor(new_clip->ctx, TN_CLASS_EMBD);
  504. vision_model.position_embeddings = get_tensor(new_clip->ctx, format(TN_POS_EMBD, "v"));
  505. vision_model.pre_ln_w = get_tensor(new_clip->ctx, format(TN_LN_PRE, "v", "weight"));
  506. vision_model.pre_ln_b = get_tensor(new_clip->ctx, format(TN_LN_PRE, "v", "bias"));
  507. vision_model.mm_0_w = get_tensor(new_clip->ctx, format(TN_LLAVA_PROJ, 0, "weight"));
  508. vision_model.mm_0_b = get_tensor(new_clip->ctx, format(TN_LLAVA_PROJ, 0, "bias"));
  509. vision_model.mm_2_w = get_tensor(new_clip->ctx, format(TN_LLAVA_PROJ, 2, "weight"));
  510. vision_model.mm_2_b = get_tensor(new_clip->ctx, format(TN_LLAVA_PROJ, 2, "bias"));
  511. vision_model.layers.resize(hparams.n_layer);
  512. for (int il = 0; il < hparams.n_layer; ++il) {
  513. auto & layer = vision_model.layers[il];
  514. layer.k_w = get_tensor(new_clip->ctx, format(TN_ATTN_K, "v", il, "weight"));
  515. layer.q_w = get_tensor(new_clip->ctx, format(TN_ATTN_Q, "v", il, "weight"));
  516. layer.v_w = get_tensor(new_clip->ctx, format(TN_ATTN_V, "v", il, "weight"));
  517. layer.o_w = get_tensor(new_clip->ctx, format(TN_ATTN_OUTPUT, "v", il, "weight"));
  518. layer.ln_1_w = get_tensor(new_clip->ctx, format(TN_LN_1, "v", il, "weight"));
  519. layer.ln_2_w = get_tensor(new_clip->ctx, format(TN_LN_2, "v", il, "weight"));
  520. layer.ff_i_w = get_tensor(new_clip->ctx, format(TN_FFN_DOWN, "v", il, "weight"));
  521. layer.ff_o_w = get_tensor(new_clip->ctx, format(TN_FFN_UP, "v", il, "weight"));
  522. layer.k_b = get_tensor(new_clip->ctx, format(TN_ATTN_K, "v", il, "bias"));
  523. layer.q_b = get_tensor(new_clip->ctx, format(TN_ATTN_Q, "v", il, "bias"));
  524. layer.v_b = get_tensor(new_clip->ctx, format(TN_ATTN_V, "v", il, "bias"));
  525. layer.o_b = get_tensor(new_clip->ctx, format(TN_ATTN_OUTPUT, "v", il, "bias"));
  526. layer.ln_1_b = get_tensor(new_clip->ctx, format(TN_LN_1, "v", il, "bias"));
  527. layer.ln_2_b = get_tensor(new_clip->ctx, format(TN_LN_2, "v", il, "bias"));
  528. layer.ff_i_b = get_tensor(new_clip->ctx, format(TN_FFN_DOWN, "v", il, "bias"));
  529. layer.ff_o_b = get_tensor(new_clip->ctx, format(TN_FFN_UP, "v", il, "bias"));
  530. }
  531. }
  532. ggml_free(meta);
  533. new_clip->ctx_gguf = ctx;
  534. // measure mem requirement and allocate
  535. {
  536. static const size_t tensor_alignment = 32;
  537. new_clip->buf_compute.resize(ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead());
  538. new_clip->alloc = ggml_allocr_new_measure(tensor_alignment);
  539. clip_image_f32_batch batch;
  540. batch.size = 1;
  541. ggml_cgraph * gf = clip_image_build_graph(new_clip, &batch);
  542. size_t alloc_size = ggml_allocr_alloc_graph(new_clip->alloc, gf) + tensor_alignment;
  543. ggml_allocr_free(new_clip->alloc);
  544. new_clip->buf_alloc.resize(alloc_size);
  545. new_clip->alloc = ggml_allocr_new(new_clip->buf_alloc.data, new_clip->buf_alloc.size, tensor_alignment);
  546. printf("%s: total allocated memory: %.2f MB\n", __func__, (new_clip->buf_compute.size + alloc_size)/1024.0/1024.0);
  547. }
  548. return new_clip;
  549. }
  550. clip_image_u8 * make_clip_image_u8() {
  551. auto img = new clip_image_u8();
  552. return img;
  553. }
  554. clip_image_f32 * make_clip_image_f32() { return new clip_image_f32(); }
  555. void clip_image_u8_free(clip_image_u8 * img) { if (img->data) { delete[] img->data; } delete img; }
  556. void clip_image_f32_free(clip_image_f32 * img) { if (img->data) { delete[] img->data; } delete img; }
  557. static void build_clip_img_from_data(const stbi_uc * data, int nx, int ny, clip_image_u8 * img) {
  558. img->nx = nx;
  559. img->ny = ny;
  560. img->size = nx * ny * 3;
  561. img->data = new uint8_t[img->size]();
  562. memcpy(img->data, data, img->size);
  563. }
  564. bool clip_image_load_from_file(const char * fname, clip_image_u8 * img) {
  565. int nx, ny, nc;
  566. auto data = stbi_load(fname, &nx, &ny, &nc, 3);
  567. if (!data) {
  568. fprintf(stderr, "%s: failed to load image '%s'\n", __func__, fname);
  569. return false;
  570. }
  571. build_clip_img_from_data(data, nx, ny, img);
  572. stbi_image_free(data);
  573. return true;
  574. }
  575. bool clip_image_load_from_bytes(const unsigned char * bytes, size_t bytes_length, struct clip_image_u8 * img) {
  576. int nx, ny, nc;
  577. auto data = stbi_load_from_memory(bytes, bytes_length, &nx, &ny, &nc, 3);
  578. if (!data) {
  579. fprintf(stderr, "%s: failed to decode image bytes\n", __func__);
  580. return false;
  581. }
  582. build_clip_img_from_data(data, nx, ny, img);
  583. stbi_image_free(data);
  584. return true;
  585. }
  586. // normalize: x = (x - mean) / std
  587. // TODO: implement bicubic interpolation instead of linear.
  588. bool clip_image_preprocess(const clip_ctx * ctx, const clip_image_u8 * img, clip_image_f32 * res, const bool pad2square) {
  589. if (!ctx->has_vision_encoder) {
  590. printf("This gguf file seems to have no vision encoder\n");
  591. return false;
  592. }
  593. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  594. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  595. clip_image_u8 * temp = make_clip_image_u8(); // we will keep the input image data here temporarily
  596. if (pad2square && img->nx != img->ny) {
  597. int longer_side = std::max(img->nx, img->ny);
  598. temp->nx = longer_side;
  599. temp->ny = longer_side;
  600. temp->size = 3 * longer_side * longer_side;
  601. temp->data = new uint8_t[temp->size]();
  602. uint8_t bc[3] = {122, 116, 104}; // background color in RGB from LLaVA
  603. // fill with background color
  604. for (size_t i = 0; i < temp->size; i++) {
  605. temp->data[i] = bc[i % 3];
  606. }
  607. // copy from the input image
  608. for (int y = 0; y < img->ny; y++) {
  609. for (int x = 0; x < img->nx; x++) {
  610. const int i = 3 * (y * img->nx + x);
  611. const int j = 3 * (y * temp->nx + x);
  612. temp->data[j] = img->data[i];
  613. temp->data[j+1] = img->data[i+1];
  614. temp->data[j+2] = img->data[i+2];
  615. }
  616. }
  617. } else {
  618. temp->nx = img->nx;
  619. temp->ny = img->ny;
  620. temp->size = img->size;
  621. temp->data = new uint8_t[temp->size]();
  622. memcpy(&temp->data[0], &img->data[0], temp->size); // copy
  623. }
  624. const int nx = temp->nx;
  625. const int ny = temp->ny;
  626. const int nx2 = ctx->vision_model.hparams.image_size;
  627. const int ny2 = ctx->vision_model.hparams.image_size;
  628. res->nx = nx2;
  629. res->ny = ny2;
  630. res->size = 3 * nx2 * ny2;
  631. res->data = new float[res->size]();
  632. const float scale = std::max(nx, ny) / (float)ctx->vision_model.hparams.image_size;
  633. const int nx3 = int(nx / scale + 0.5f);
  634. const int ny3 = int(ny / scale + 0.5f);
  635. const auto & m3 = ctx->image_mean; // {0.48145466f, 0.4578275f, 0.40821073f};
  636. const auto & s3 = ctx->image_std; // {0.26862954f, 0.26130258f, 0.27577711f};
  637. for (int y = 0; y < ny3; y++) {
  638. for (int x = 0; x < nx3; x++) {
  639. for (int c = 0; c < 3; c++) {
  640. // linear interpolation
  641. const float sx = (x + 0.5f) * scale - 0.5f;
  642. const float sy = (y + 0.5f) * scale - 0.5f;
  643. const int x0 = std::max(0, (int)std::floor(sx));
  644. const int y0 = std::max(0, (int)std::floor(sy));
  645. const int x1 = std::min(x0 + 1, nx - 1);
  646. const int y1 = std::min(y0 + 1, ny - 1);
  647. const float dx = sx - x0;
  648. const float dy = sy - y0;
  649. const int j00 = 3 * (y0 * nx + x0) + c;
  650. const int j01 = 3 * (y0 * nx + x1) + c;
  651. const int j10 = 3 * (y1 * nx + x0) + c;
  652. const int j11 = 3 * (y1 * nx + x1) + c;
  653. const float v00 = temp->data[j00];
  654. const float v01 = temp->data[j01];
  655. const float v10 = temp->data[j10];
  656. const float v11 = temp->data[j11];
  657. const float v0 = v00 * (1.0f - dx) + v01 * dx;
  658. const float v1 = v10 * (1.0f - dx) + v11 * dx;
  659. const float v = v0 * (1.0f - dy) + v1 * dy;
  660. const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
  661. const int i = 3 * (y * nx3 + x) + c;
  662. res->data[i] = ((float(v2) / 255.0f) - m3[c]) / s3[c];
  663. }
  664. }
  665. }
  666. clip_image_u8_free(temp);
  667. return true;
  668. }
  669. void clip_free(clip_ctx * ctx) {
  670. ggml_free(ctx->ctx);
  671. gguf_free(ctx->ctx_gguf);
  672. delete ctx;
  673. }
  674. bool clip_image_encode(const clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  675. if (!ctx->has_vision_encoder) {
  676. printf("This gguf file seems to have no vision encoder\n");
  677. return false;
  678. }
  679. clip_image_f32_batch imgs{};
  680. imgs.size = 1;
  681. imgs.data = img;
  682. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  683. }
  684. bool clip_image_batch_encode(const clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs, float * vec) {
  685. if (!ctx->has_vision_encoder) {
  686. printf("This gguf file seems to have no vision encoder\n");
  687. return false;
  688. }
  689. int batch_size = imgs->size;
  690. if(ctx->has_llava_projector) {
  691. GGML_ASSERT(batch_size == 1); // TODO: support multiple images
  692. }
  693. // reset alloc buffer to clean the memory from previous invocations
  694. ggml_allocr_reset(ctx->alloc);
  695. // build the inference graph
  696. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs);
  697. ggml_allocr_alloc_graph(ctx->alloc, gf);
  698. struct ggml_cplan plan = ggml_graph_plan(gf, n_threads);
  699. if (plan.work_size > 0) {
  700. plan.work_data = (uint8_t *)malloc(plan.work_size);
  701. }
  702. ggml_graph_compute(gf, &plan);
  703. // the last node is the embedding tensor
  704. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 1];
  705. // copy the embeddings to the location passed by the user
  706. memcpy(vec, ggml_get_data_f32(embeddings), ggml_nbytes(embeddings));
  707. if (plan.work_size > 0) {
  708. free(plan.work_data);
  709. }
  710. return true;
  711. }
  712. bool clip_model_quantize(const char * fname_inp, const char * fname_out, const int itype) {
  713. ggml_type type = GGML_TYPE_Q4_1;
  714. switch (itype) {
  715. case 2:
  716. type = GGML_TYPE_Q4_0;
  717. break;
  718. case 3:
  719. type = GGML_TYPE_Q4_1;
  720. break;
  721. case 6:
  722. type = GGML_TYPE_Q5_0;
  723. break;
  724. case 7:
  725. type = GGML_TYPE_Q5_1;
  726. break;
  727. case 8:
  728. type = GGML_TYPE_Q8_0;
  729. break;
  730. default:
  731. fprintf(stderr, "%s: invalid quantization type %d\n", __func__, itype);
  732. return false;
  733. };
  734. auto ctx_clip = clip_model_load(fname_inp, 2);
  735. const auto & ctx_src = ctx_clip->ctx_gguf;
  736. const auto & ctx_data = ctx_clip->ctx;
  737. auto ctx_out = gguf_init_empty();
  738. gguf_set_kv(ctx_out, ctx_src);
  739. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  740. gguf_set_val_u32(ctx_out, "general.file_type", itype);
  741. auto fout = std::ofstream(fname_out, std::ios::binary);
  742. const int n_tensors = gguf_get_n_tensors(ctx_src);
  743. for (int i = 0; i < n_tensors; ++i) {
  744. const char * name = gguf_get_tensor_name(ctx_src, i);
  745. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name);
  746. gguf_add_tensor(ctx_out, cur);
  747. }
  748. const size_t meta_size = gguf_get_meta_size(ctx_out);
  749. for (size_t i = 0; i < meta_size; ++i) {
  750. fout.put(0);
  751. }
  752. // regexes of tensor names to be quantized
  753. const std::vector<std::string> k_names = {
  754. ".*weight",
  755. };
  756. std::vector<uint8_t> read_data(512);
  757. std::vector<uint8_t> work(512);
  758. std::vector<float> conv_buf(512);
  759. std::vector<int64_t> hist_all(1 << 4, 0);
  760. size_t total_size_org = 0;
  761. size_t total_size_new = 0;
  762. for (int i = 0; i < n_tensors; ++i) {
  763. const std::string name = gguf_get_tensor_name(ctx_src, i);
  764. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name.c_str());
  765. enum ggml_type new_type;
  766. void * new_data;
  767. size_t new_size;
  768. bool quantize = false;
  769. for (const auto & s : k_names) {
  770. if (std::regex_match(name, std::regex(s))) {
  771. quantize = true;
  772. break;
  773. }
  774. }
  775. // quantize only 2D tensors
  776. quantize &= (ggml_n_dims(cur) == 2);
  777. if (quantize) {
  778. new_type = type;
  779. const size_t n_elms = ggml_nelements(cur);
  780. float * f32_data;
  781. switch (cur->type) {
  782. case GGML_TYPE_F32:
  783. f32_data = (float *)cur->data;
  784. break;
  785. case GGML_TYPE_F16:
  786. if (conv_buf.size() < n_elms) {
  787. conv_buf.resize(n_elms);
  788. }
  789. for (size_t j = 0; j < n_elms; ++j) {
  790. conv_buf[j] = ggml_fp16_to_fp32(((ggml_fp16_t *)cur->data)[j]);
  791. }
  792. f32_data = (float *)conv_buf.data();
  793. break;
  794. default:
  795. printf("Please use an input file in f32 or f16\n");
  796. return false;
  797. }
  798. if (work.size() < n_elms * 4) {
  799. work.resize(n_elms * 4);
  800. }
  801. new_data = work.data();
  802. std::vector<int64_t> hist_cur(1 << 4, 0);
  803. switch (new_type) {
  804. case GGML_TYPE_Q4_0: {
  805. new_size = ggml_quantize_q4_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  806. } break;
  807. case GGML_TYPE_Q4_1: {
  808. new_size = ggml_quantize_q4_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  809. } break;
  810. case GGML_TYPE_Q5_0: {
  811. new_size = ggml_quantize_q5_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  812. } break;
  813. case GGML_TYPE_Q5_1: {
  814. new_size = ggml_quantize_q5_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  815. } break;
  816. case GGML_TYPE_Q8_0: {
  817. new_size = ggml_quantize_q8_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  818. } break;
  819. default: {
  820. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, new_type);
  821. return false;
  822. }
  823. }
  824. for (size_t j = 0; j < hist_cur.size(); ++j) {
  825. hist_all[j] += hist_cur[j];
  826. }
  827. } else {
  828. new_type = cur->type;
  829. new_data = cur->data;
  830. new_size = ggml_nbytes(cur);
  831. }
  832. const size_t orig_size = ggml_nbytes(cur);
  833. total_size_org += orig_size;
  834. total_size_new += new_size;
  835. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  836. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  837. fout.write((const char *)new_data, new_size);
  838. size_t pad = GGML_PAD(new_size, gguf_get_alignment(ctx_out)) - new_size;
  839. for (size_t j = 0; j < pad; ++j) {
  840. fout.put(0);
  841. }
  842. printf("%s: n_dims = %d | quantize=%d | size = %f MB -> %f MB\n", name.c_str(), ggml_n_dims(cur), quantize,
  843. orig_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  844. }
  845. // go back to beginning of file and write the updated metadata
  846. fout.seekp(0, std::ios::beg);
  847. std::vector<uint8_t> meta(meta_size);
  848. gguf_get_meta_data(ctx_out, meta.data());
  849. fout.write((const char *)meta.data(), meta_size);
  850. fout.close();
  851. clip_free(ctx_clip);
  852. gguf_free(ctx_out);
  853. {
  854. printf("%s: original size = %8.2f MB\n", __func__, total_size_org / 1024.0 / 1024.0);
  855. printf("%s: quantized size = %8.2f MB\n", __func__, total_size_new / 1024.0 / 1024.0);
  856. int64_t sum_all = 0;
  857. for (size_t i = 0; i < hist_all.size(); ++i) {
  858. sum_all += hist_all[i];
  859. }
  860. printf("%s: hist: ", __func__);
  861. for (size_t i = 0; i < hist_all.size(); ++i) {
  862. printf("%5.3f ", hist_all[i] / (float)sum_all);
  863. }
  864. printf("\n");
  865. }
  866. return true;
  867. }
  868. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  869. return ctx->vision_model.mm_2_b->ne[0];
  870. }
  871. int clip_n_patches(const struct clip_ctx * ctx) {
  872. auto & params = ctx->vision_model.hparams;
  873. return (params.image_size / params.patch_size) * (params.image_size / params.patch_size);
  874. }
  875. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  876. return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);
  877. }