clip.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  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 "clip.h"
  5. #include "ggml.h"
  6. #include "ggml-alloc.h"
  7. #include "ggml-backend.h"
  8. #ifdef GGML_USE_CUBLAS
  9. #include "ggml-cuda.h"
  10. #endif
  11. #ifdef GGML_USE_METAL
  12. #include "ggml-metal.h"
  13. #endif
  14. #define STB_IMAGE_IMPLEMENTATION
  15. #include "stb_image.h"
  16. #include <cassert>
  17. #include <cmath>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <fstream>
  21. #include <iostream>
  22. #include <map>
  23. #include <regex>
  24. #include <stdexcept>
  25. #include <vector>
  26. #include <sstream>
  27. #include <cinttypes>
  28. static std::string format(const char * fmt, ...) {
  29. va_list ap;
  30. va_list ap2;
  31. va_start(ap, fmt);
  32. va_copy(ap2, ap);
  33. int size = vsnprintf(NULL, 0, fmt, ap);
  34. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  35. std::vector<char> buf(size + 1);
  36. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  37. GGML_ASSERT(size2 == size);
  38. va_end(ap2);
  39. va_end(ap);
  40. return std::string(buf.data(), buf.size());
  41. }
  42. //
  43. // key constants
  44. //
  45. #define KEY_FTYPE "general.file_type"
  46. #define KEY_NAME "general.name"
  47. #define KEY_DESCRIPTION "general.description"
  48. #define KEY_HAS_TEXT_ENC "clip.has_text_encoder"
  49. #define KEY_HAS_VIS_ENC "clip.has_vision_encoder"
  50. #define KEY_HAS_LLAVA_PROJ "clip.has_llava_projector"
  51. #define KEY_USE_GELU "clip.use_gelu"
  52. #define KEY_N_EMBD "clip.%s.embedding_length"
  53. #define KEY_N_FF "clip.%s.feed_forward_length"
  54. #define KEY_N_BLOCK "clip.%s.block_count"
  55. #define KEY_N_HEAD "clip.%s.attention.head_count"
  56. #define KEY_LAYER_NORM_EPS "clip.%s.attention.layer_norm_epsilon"
  57. #define KEY_PROJ_DIM "clip.%s.projection_dim"
  58. #define KEY_TOKENS "tokenizer.ggml.tokens"
  59. #define KEY_N_POSITIONS "clip.text.context_length"
  60. #define KEY_IMAGE_SIZE "clip.vision.image_size"
  61. #define KEY_PATCH_SIZE "clip.vision.patch_size"
  62. #define KEY_IMAGE_MEAN "clip.vision.image_mean"
  63. #define KEY_IMAGE_STD "clip.vision.image_std"
  64. #define KEY_PROJ_TYPE "clip.projector_type"
  65. //
  66. // tensor name constants
  67. //
  68. #define TN_TOKEN_EMBD "%s.token_embd.weight"
  69. #define TN_POS_EMBD "%s.position_embd.weight"
  70. #define TN_CLASS_EMBD "v.class_embd"
  71. #define TN_PATCH_EMBD "v.patch_embd.weight"
  72. #define TN_ATTN_K "%s.blk.%d.attn_k.%s"
  73. #define TN_ATTN_Q "%s.blk.%d.attn_q.%s"
  74. #define TN_ATTN_V "%s.blk.%d.attn_v.%s"
  75. #define TN_ATTN_OUTPUT "%s.blk.%d.attn_out.%s"
  76. #define TN_FFN_DOWN "%s.blk.%d.ffn_down.%s"
  77. #define TN_FFN_UP "%s.blk.%d.ffn_up.%s"
  78. #define TN_LN_1 "%s.blk.%d.ln1.%s"
  79. #define TN_LN_2 "%s.blk.%d.ln2.%s"
  80. #define TN_LN_PRE "%s.pre_ln.%s"
  81. #define TN_LN_POST "%s.post_ln.%s"
  82. #define TN_TEXT_PROJ "text_projection.weight"
  83. #define TN_VIS_PROJ "visual_projection.weight"
  84. #define TN_LLAVA_PROJ "mm.%d.%s"
  85. #define TN_MVLM_PROJ_MLP "mm.model.mlp.%d.%s"
  86. #define TN_MVLM_PROJ_BLOCK "mm.model.mb_block.%d.block.%d.%s"
  87. enum projector_type {
  88. PROJECTOR_TYPE_MLP,
  89. PROJECTOR_TYPE_LDP,
  90. PROJECTOR_TYPE_UNKNOWN,
  91. };
  92. static std::map<projector_type, std::string> PROJECTOR_TYPE_NAMES = {
  93. { PROJECTOR_TYPE_MLP, "mlp" },
  94. { PROJECTOR_TYPE_LDP, "ldp" },
  95. };
  96. //
  97. // utilities to get data from a gguf file
  98. //
  99. static int get_key_idx(const gguf_context * ctx, const char * key) {
  100. int i = gguf_find_key(ctx, key);
  101. if (i == -1) {
  102. fprintf(stderr, "key %s not found in file\n", key);
  103. throw std::runtime_error(format("Missing required key: %s", key));
  104. }
  105. return i;
  106. }
  107. static uint32_t get_u32(const gguf_context * ctx, const std::string & key) {
  108. const int i = get_key_idx(ctx, key.c_str());
  109. return gguf_get_val_u32(ctx, i);
  110. }
  111. static float get_f32(const gguf_context * ctx, const std::string & key) {
  112. const int i = get_key_idx(ctx, key.c_str());
  113. return gguf_get_val_f32(ctx, i);
  114. }
  115. static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const std::string & name) {
  116. struct ggml_tensor * cur = ggml_get_tensor(ctx, name.c_str());
  117. if (!cur) {
  118. throw std::runtime_error(format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  119. }
  120. return cur;
  121. }
  122. static std::string get_ftype(int ftype) {
  123. return ggml_type_name(static_cast<ggml_type>(ftype));
  124. }
  125. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  126. switch (type) {
  127. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  128. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  129. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  130. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  131. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  132. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  133. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  134. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  135. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  136. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  137. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  138. default: return format("unknown type %d", type);
  139. }
  140. }
  141. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  142. std::string result;
  143. for (size_t pos = 0; ; pos += search.length()) {
  144. auto new_pos = s.find(search, pos);
  145. if (new_pos == std::string::npos) {
  146. result += s.substr(pos, s.size() - pos);
  147. break;
  148. }
  149. result += s.substr(pos, new_pos - pos) + replace;
  150. pos = new_pos;
  151. }
  152. s = std::move(result);
  153. }
  154. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  155. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  156. switch (type) {
  157. case GGUF_TYPE_STRING:
  158. return gguf_get_val_str(ctx_gguf, i);
  159. case GGUF_TYPE_ARRAY:
  160. {
  161. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  162. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  163. const void * data = gguf_get_arr_data(ctx_gguf, i);
  164. std::stringstream ss;
  165. ss << "[";
  166. for (int j = 0; j < arr_n; j++) {
  167. if (arr_type == GGUF_TYPE_STRING) {
  168. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  169. // escape quotes
  170. replace_all(val, "\\", "\\\\");
  171. replace_all(val, "\"", "\\\"");
  172. ss << '"' << val << '"';
  173. } else if (arr_type == GGUF_TYPE_ARRAY) {
  174. ss << "???";
  175. } else {
  176. ss << gguf_data_to_str(arr_type, data, j);
  177. }
  178. if (j < arr_n - 1) {
  179. ss << ", ";
  180. }
  181. }
  182. ss << "]";
  183. return ss.str();
  184. }
  185. default:
  186. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  187. }
  188. }
  189. static void print_tensor_info(const ggml_tensor* tensor, const char* prefix = "") {
  190. size_t tensor_size = ggml_nbytes(tensor);
  191. printf("%s: n_dims = %d, name = %s, tensor_size=%zu, shape:[%" PRId64 ", %" PRId64 ", %" PRId64 ", %" PRId64 "], type = %s\n",
  192. prefix, ggml_n_dims(tensor), tensor->name, tensor_size,
  193. tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], ggml_type_name(tensor->type));
  194. }
  195. static projector_type clip_projector_type_from_string(const std::string & name) {
  196. for (const auto & kv : PROJECTOR_TYPE_NAMES) { // NOLINT
  197. if (kv.second == name) {
  198. return kv.first;
  199. }
  200. }
  201. return PROJECTOR_TYPE_UNKNOWN;
  202. }
  203. //
  204. // image data
  205. //
  206. // RGB uint8 image
  207. struct clip_image_u8 {
  208. int nx;
  209. int ny;
  210. std::vector<uint8_t> buf;
  211. };
  212. // RGB float32 image (NHWC)
  213. // Memory layout: RGBRGBRGB...
  214. struct clip_image_f32 {
  215. int nx;
  216. int ny;
  217. std::vector<float> buf;
  218. };
  219. //
  220. // clip layers
  221. //
  222. struct clip_layer {
  223. // attention
  224. struct ggml_tensor * k_w;
  225. struct ggml_tensor * k_b;
  226. struct ggml_tensor * q_w;
  227. struct ggml_tensor * q_b;
  228. struct ggml_tensor * v_w;
  229. struct ggml_tensor * v_b;
  230. struct ggml_tensor * o_w;
  231. struct ggml_tensor * o_b;
  232. // layernorm 1
  233. struct ggml_tensor * ln_1_w;
  234. struct ggml_tensor * ln_1_b;
  235. // ff
  236. struct ggml_tensor * ff_i_w;
  237. struct ggml_tensor * ff_i_b;
  238. struct ggml_tensor * ff_o_w;
  239. struct ggml_tensor * ff_o_b;
  240. // layernorm 2
  241. struct ggml_tensor * ln_2_w;
  242. struct ggml_tensor * ln_2_b;
  243. };
  244. struct clip_vision_model {
  245. struct clip_vision_hparams hparams;
  246. // embeddings
  247. struct ggml_tensor * class_embedding;
  248. struct ggml_tensor * patch_embeddings;
  249. struct ggml_tensor * position_embeddings;
  250. struct ggml_tensor * pre_ln_w;
  251. struct ggml_tensor * pre_ln_b;
  252. std::vector<clip_layer> layers;
  253. struct ggml_tensor * post_ln_w;
  254. struct ggml_tensor * post_ln_b;
  255. struct ggml_tensor * projection;
  256. // LLaVA projection
  257. struct ggml_tensor * mm_0_w;
  258. struct ggml_tensor * mm_0_b;
  259. struct ggml_tensor * mm_2_w;
  260. struct ggml_tensor * mm_2_b;
  261. // MobileVLM projection
  262. struct ggml_tensor * mm_model_mlp_1_w;
  263. struct ggml_tensor * mm_model_mlp_1_b;
  264. struct ggml_tensor * mm_model_mlp_3_w;
  265. struct ggml_tensor * mm_model_mlp_3_b;
  266. struct ggml_tensor * mm_model_block_1_block_0_0_w;
  267. struct ggml_tensor * mm_model_block_1_block_0_1_w;
  268. struct ggml_tensor * mm_model_block_1_block_0_1_b;
  269. struct ggml_tensor * mm_model_block_1_block_1_fc1_w;
  270. struct ggml_tensor * mm_model_block_1_block_1_fc1_b;
  271. struct ggml_tensor * mm_model_block_1_block_1_fc2_w;
  272. struct ggml_tensor * mm_model_block_1_block_1_fc2_b;
  273. struct ggml_tensor * mm_model_block_1_block_2_0_w;
  274. struct ggml_tensor * mm_model_block_1_block_2_1_w;
  275. struct ggml_tensor * mm_model_block_1_block_2_1_b;
  276. struct ggml_tensor * mm_model_block_2_block_0_0_w;
  277. struct ggml_tensor * mm_model_block_2_block_0_1_w;
  278. struct ggml_tensor * mm_model_block_2_block_0_1_b;
  279. struct ggml_tensor * mm_model_block_2_block_1_fc1_w;
  280. struct ggml_tensor * mm_model_block_2_block_1_fc1_b;
  281. struct ggml_tensor * mm_model_block_2_block_1_fc2_w;
  282. struct ggml_tensor * mm_model_block_2_block_1_fc2_b;
  283. struct ggml_tensor * mm_model_block_2_block_2_0_w;
  284. struct ggml_tensor * mm_model_block_2_block_2_1_w;
  285. struct ggml_tensor * mm_model_block_2_block_2_1_b;
  286. };
  287. struct clip_ctx {
  288. bool has_text_encoder = false;
  289. bool has_vision_encoder = false;
  290. bool has_llava_projector = false;
  291. struct clip_vision_model vision_model;
  292. projector_type proj_type = PROJECTOR_TYPE_MLP;
  293. float image_mean[3];
  294. float image_std[3];
  295. bool use_gelu = false;
  296. int32_t ftype = 1;
  297. struct gguf_context * ctx_gguf;
  298. struct ggml_context * ctx_data;
  299. std::vector<uint8_t> buf_compute_meta;
  300. // memory buffers to evaluate the model
  301. ggml_backend_buffer_t params_buffer = NULL;
  302. ggml_backend_buffer_t compute_buffer = NULL;
  303. ggml_backend_t backend = NULL;
  304. ggml_allocr * compute_alloc = NULL;
  305. };
  306. static ggml_cgraph * clip_image_build_graph(clip_ctx * ctx, const clip_image_f32_batch * imgs) {
  307. if (!ctx->has_vision_encoder) {
  308. printf("This gguf file seems to have no vision encoder\n");
  309. return nullptr;
  310. }
  311. const auto & model = ctx->vision_model;
  312. const auto & hparams = model.hparams;
  313. const int image_size = hparams.image_size;
  314. const int patch_size = hparams.patch_size;
  315. const int num_patches = ((image_size / patch_size) * (image_size / patch_size));
  316. const int num_positions = num_patches + 1;
  317. const int hidden_size = hparams.hidden_size;
  318. const int n_head = hparams.n_head;
  319. const int d_head = hidden_size / n_head;
  320. const int n_layer = hparams.n_layer;
  321. //const int n_intermediate = hparams.n_intermediate;
  322. //const int projection_dim = hparams.projection_dim;
  323. const float eps = hparams.eps;
  324. int batch_size = imgs->size;
  325. if (ctx->has_llava_projector) {
  326. GGML_ASSERT(batch_size == 1);
  327. }
  328. struct ggml_init_params params = {
  329. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  330. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  331. /*.no_alloc =*/ true,
  332. };
  333. struct ggml_context * ctx0 = ggml_init(params);
  334. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  335. struct ggml_tensor * inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size, image_size, 3, batch_size);
  336. ggml_allocr_alloc(ctx->compute_alloc, inp_raw);
  337. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  338. float * data = (float *)malloc(ggml_nbytes(inp_raw));
  339. for (size_t i = 0; i < imgs->size; i++) {
  340. const int nx = imgs->data[i].nx;
  341. const int ny = imgs->data[i].ny;
  342. GGML_ASSERT(nx == image_size && ny == image_size);
  343. const int n = nx * ny;
  344. for (int b = 0; b < batch_size; b++) {
  345. for (int k = 0; k < 3; k++) {
  346. for (int y = 0; y < ny; y++) {
  347. for (int x = 0; x < nx; x++) {
  348. data[(b * 3 * n) + k * n + y * nx + x] = imgs->data[b].buf[3 * (y * nx + x) + k];
  349. }
  350. }
  351. }
  352. }
  353. }
  354. ggml_backend_tensor_set(inp_raw, data, 0, ggml_nbytes(inp_raw));
  355. free(data);
  356. }
  357. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  358. inp = ggml_reshape_3d(ctx0, inp, num_patches, hidden_size, batch_size);
  359. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 0, 2, 3));
  360. // concat class_embeddings and patch_embeddings
  361. struct ggml_tensor * embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size);
  362. ggml_allocr_alloc(ctx->compute_alloc, embeddings);
  363. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  364. void* zero_mem = malloc(ggml_nbytes(embeddings));
  365. memset(zero_mem, 0, ggml_nbytes(embeddings));
  366. ggml_backend_tensor_set(embeddings, zero_mem, 0, ggml_nbytes(embeddings));
  367. free(zero_mem);
  368. }
  369. embeddings = ggml_acc(ctx0, embeddings, model.class_embedding,
  370. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], 0);
  371. embeddings = ggml_acc(ctx0, embeddings, inp,
  372. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], model.class_embedding->nb[1]);
  373. struct ggml_tensor * positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions);
  374. ggml_allocr_alloc(ctx->compute_alloc, positions);
  375. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  376. int* positions_data = (int*)malloc(ggml_nbytes(positions));
  377. for (int i = 0; i < num_positions; i++) {
  378. positions_data[i] = i;
  379. }
  380. ggml_backend_tensor_set(positions, positions_data, 0, ggml_nbytes(positions));
  381. free(positions_data);
  382. }
  383. embeddings =
  384. ggml_add(ctx0, embeddings, ggml_get_rows(ctx0, model.position_embeddings, positions));
  385. // pre-layernorm
  386. {
  387. embeddings = ggml_norm(ctx0, embeddings, eps);
  388. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.pre_ln_w), model.pre_ln_b);
  389. }
  390. // loop over layers
  391. for (int il = 0; il < n_layer - 1; il++) {
  392. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  393. //const size_t nb_q_w = model.layers[il].q_w->nb[0];
  394. // layernorm1
  395. {
  396. cur = ggml_norm(ctx0, cur, eps);
  397. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_1_w),
  398. model.layers[il].ln_1_b);
  399. }
  400. // self-attention
  401. {
  402. struct ggml_tensor * Q =
  403. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  404. Q = ggml_scale_inplace(ctx0, Q, 1.0f / sqrt((float)d_head));
  405. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  406. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  407. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  408. struct ggml_tensor * K =
  409. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  410. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  411. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  412. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  413. struct ggml_tensor * V =
  414. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  415. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  416. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  417. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  418. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  419. KQ = ggml_soft_max_inplace(ctx0, KQ);
  420. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  421. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  422. KQV = ggml_cont(ctx0, ggml_permute(ctx0, KQV, 0, 2, 1, 3));
  423. cur = ggml_cpy(ctx0, KQV, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size));
  424. }
  425. // attention output
  426. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  427. // re-add the layer input, e.g., residual
  428. cur = ggml_add(ctx0, cur, embeddings);
  429. embeddings = cur; // embeddings = residual, cur = hidden_states
  430. // layernorm2
  431. {
  432. cur = ggml_norm(ctx0, cur, eps);
  433. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_2_w), model.layers[il].ln_2_b);
  434. }
  435. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  436. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  437. if (ctx->use_gelu) {
  438. cur = ggml_gelu_inplace(ctx0, cur);
  439. } else {
  440. cur = ggml_gelu_quick_inplace(ctx0, cur);
  441. }
  442. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  443. cur = ggml_add(ctx0, cur, model.layers[il].ff_o_b);
  444. // residual 2
  445. cur = ggml_add(ctx0, embeddings, cur);
  446. embeddings = cur;
  447. }
  448. // llava projector
  449. {
  450. embeddings = ggml_reshape_2d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1]);
  451. struct ggml_tensor * patches = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  452. ggml_allocr_alloc(ctx->compute_alloc, patches);
  453. if (!ggml_allocr_is_measure(ctx->compute_alloc)) {
  454. int* patches_data = (int*)malloc(ggml_nbytes(patches));
  455. for (int i = 0; i < num_patches; i++) {
  456. patches_data[i] = i + 1;
  457. }
  458. ggml_backend_tensor_set(patches, patches_data, 0, ggml_nbytes(patches));
  459. free(patches_data);
  460. }
  461. // shape [1, 576, 1024]
  462. // ne is whcn, ne = [1024, 576, 1, 1]
  463. embeddings = ggml_get_rows(ctx0, embeddings, patches);
  464. // print_tensor_info(embeddings, "embeddings");
  465. // llava projector
  466. if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  467. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  468. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  469. embeddings = ggml_gelu(ctx0, embeddings);
  470. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  471. embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
  472. }
  473. else if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  474. // MobileVLM projector
  475. int n_patch = 24;
  476. struct ggml_tensor * mlp_1 = ggml_mul_mat(ctx0, model.mm_model_mlp_1_w, embeddings);
  477. mlp_1 = ggml_add(ctx0, mlp_1, model.mm_model_mlp_1_b);
  478. mlp_1 = ggml_gelu(ctx0, mlp_1);
  479. struct ggml_tensor * mlp_3 = ggml_mul_mat(ctx0, model.mm_model_mlp_3_w, mlp_1);
  480. mlp_3 = ggml_add(ctx0, mlp_3, model.mm_model_mlp_3_b);
  481. // mlp_3 shape = [1, 576, 2048], ne = [2048, 576, 1, 1]
  482. // block 1
  483. struct ggml_tensor * block_1 = nullptr;
  484. {
  485. // transpose from [1, 576, 2048] --> [1, 2048, 576] --> [1, 2048, 24, 24]
  486. mlp_3 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_3, 1, 0, 2, 3));
  487. mlp_3 = ggml_reshape_4d(ctx0, mlp_3, n_patch, n_patch, mlp_3->ne[1], mlp_3->ne[2]);
  488. // stride = 1, padding = 1, bias is nullptr
  489. block_1 = ggml_conv_depthwise_2d(ctx0, model.mm_model_block_1_block_0_0_w, mlp_3, 1, 1, 1, 1, 1, 1);
  490. // layer norm
  491. // // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  492. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  493. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  494. block_1 = ggml_norm(ctx0, block_1, eps);
  495. block_1 = ggml_add(ctx0, ggml_mul(ctx0, block_1, model.mm_model_block_1_block_0_1_w), model.mm_model_block_1_block_0_1_b);
  496. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  497. // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  498. // hardswish
  499. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  500. block_1 = ggml_pool_2d(ctx0, block_1_hw, GGML_OP_POOL_AVG, block_1_hw->ne[0], block_1_hw->ne[1], block_1_hw->ne[0], block_1_hw->ne[1], 0, 0);
  501. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  502. // pointwise conv
  503. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  504. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc1_w, block_1);
  505. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc1_b);
  506. block_1 = ggml_relu(ctx0, block_1);
  507. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc2_w, block_1);
  508. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc2_b);
  509. block_1 = ggml_hardsigmoid(ctx0, block_1);
  510. // block_1_hw shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1], block_1 shape = [1, 2048], ne = [2048, 1, 1, 1]
  511. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  512. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  513. int w = block_1->ne[0], h = block_1->ne[1];
  514. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  515. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  516. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  517. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_2_0_w, block_1);
  518. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  519. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  520. block_1 = ggml_norm(ctx0, block_1, eps);
  521. block_1 = ggml_add(ctx0, ggml_mul(ctx0, block_1, model.mm_model_block_1_block_2_1_w), model.mm_model_block_1_block_2_1_b);
  522. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  523. // block1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  524. // residual
  525. block_1 = ggml_add(ctx0, mlp_3, block_1);
  526. }
  527. // block_2
  528. {
  529. // stride = 2
  530. block_1 = ggml_conv_depthwise_2d(ctx0, model.mm_model_block_2_block_0_0_w, block_1, 2, 2, 1, 1, 1, 1);
  531. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  532. // layer norm
  533. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  534. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  535. block_1 = ggml_norm(ctx0, block_1, eps);
  536. block_1 = ggml_add(ctx0, ggml_mul(ctx0, block_1, model.mm_model_block_2_block_0_1_w), model.mm_model_block_2_block_0_1_b);
  537. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  538. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  539. // hardswish
  540. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  541. // not sure the parameters is right for globalAvgPooling
  542. block_1 = ggml_pool_2d(ctx0, block_1_hw, GGML_OP_POOL_AVG, block_1_hw->ne[0], block_1_hw->ne[1], block_1_hw->ne[0], block_1_hw->ne[1], 0, 0);
  543. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  544. // pointwise conv
  545. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  546. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc1_w, block_1);
  547. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc1_b);
  548. block_1 = ggml_relu(ctx0, block_1);
  549. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc2_w, block_1);
  550. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc2_b);
  551. block_1 = ggml_hardsigmoid(ctx0, block_1);
  552. // block_1_hw shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1], block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  553. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  554. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  555. int w = block_1->ne[0], h = block_1->ne[1];
  556. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  557. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  558. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  559. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_2_0_w, block_1);
  560. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  561. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  562. block_1 = ggml_norm(ctx0, block_1, eps);
  563. block_1 = ggml_add(ctx0, ggml_mul(ctx0, block_1, model.mm_model_block_2_block_2_1_w), model.mm_model_block_2_block_2_1_b);
  564. block_1 = ggml_reshape_3d(ctx0, block_1, block_1->ne[0], block_1->ne[1] * block_1->ne[2], block_1->ne[3]);
  565. // block_1 shape = [1, 144, 2048], ne = [2048, 144, 1]
  566. }
  567. embeddings = block_1;
  568. }
  569. else {
  570. GGML_ASSERT(false);
  571. }
  572. }
  573. // build the graph
  574. ggml_build_forward_expand(gf, embeddings);
  575. ggml_free(ctx0);
  576. return gf;
  577. }
  578. // read and create ggml_context containing the tensors and their data
  579. struct clip_ctx * clip_model_load(const char * fname, const int verbosity = 1) {
  580. struct ggml_context * meta = NULL;
  581. struct gguf_init_params params = {
  582. /*.no_alloc = */ true,
  583. /*.ctx = */ &meta,
  584. };
  585. struct gguf_context * ctx = gguf_init_from_file(fname, params);
  586. if (!ctx) {
  587. throw std::runtime_error(format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  588. }
  589. if (verbosity >= 1) {
  590. const int n_tensors = gguf_get_n_tensors(ctx);
  591. const int n_kv = gguf_get_n_kv(ctx);
  592. const int ftype = get_u32(ctx, KEY_FTYPE);
  593. const std::string ftype_str = get_ftype(ftype);
  594. const int idx_desc = get_key_idx(ctx, KEY_DESCRIPTION);
  595. const std::string description = gguf_get_val_str(ctx, idx_desc);
  596. const int idx_name = gguf_find_key(ctx, KEY_NAME);
  597. if (idx_name != -1) { // make name optional temporarily as some of the uploaded models missing it due to a bug
  598. const std::string name = gguf_get_val_str(ctx, idx_name);
  599. printf("%s: model name: %s\n", __func__, name.c_str());
  600. }
  601. printf("%s: description: %s\n", __func__, description.c_str());
  602. printf("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx));
  603. printf("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx));
  604. printf("%s: n_tensors: %d\n", __func__, n_tensors);
  605. printf("%s: n_kv: %d\n", __func__, n_kv);
  606. printf("%s: ftype: %s\n", __func__, ftype_str.c_str());
  607. printf("\n");
  608. }
  609. const int n_tensors = gguf_get_n_tensors(ctx);
  610. // kv
  611. const int n_kv = gguf_get_n_kv(ctx);
  612. printf("%s: loaded meta data with %d key-value pairs and %d tensors from %s\n",
  613. __func__, n_kv, n_tensors, fname);
  614. {
  615. std::map<enum ggml_type, uint32_t> n_type;
  616. for (int i = 0; i < n_tensors; i++) {
  617. enum ggml_type type = gguf_get_tensor_type(ctx, i);
  618. n_type[type]++;
  619. }
  620. printf("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  621. for (int i = 0; i < n_kv; i++) {
  622. const char * name = gguf_get_key(ctx, i);
  623. const enum gguf_type type = gguf_get_kv_type(ctx, i);
  624. const std::string type_name =
  625. type == GGUF_TYPE_ARRAY
  626. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx, i)), gguf_get_arr_n(ctx, i))
  627. : gguf_type_name(type);
  628. std::string value = gguf_kv_to_str(ctx, i);
  629. const size_t MAX_VALUE_LEN = 40;
  630. if (value.size() > MAX_VALUE_LEN) {
  631. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  632. }
  633. replace_all(value, "\n", "\\n");
  634. printf("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  635. }
  636. // print type counts
  637. for (auto & kv : n_type) {
  638. if (kv.second == 0) {
  639. continue;
  640. }
  641. printf("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  642. }
  643. }
  644. // data
  645. size_t buffer_size = 0;
  646. {
  647. for (int i = 0; i < n_tensors; ++i) {
  648. const char * name = gguf_get_tensor_name(ctx, i);
  649. const size_t offset = gguf_get_tensor_offset(ctx, i);
  650. enum ggml_type type = gguf_get_tensor_type(ctx, i);
  651. struct ggml_tensor * cur = ggml_get_tensor(meta, name);
  652. size_t tensor_size = ggml_nbytes(cur);
  653. buffer_size += tensor_size;
  654. if (verbosity >= 3) {
  655. printf("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu, shape:[%" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "], type = %s\n",
  656. __func__, i, ggml_n_dims(cur), cur->name, tensor_size, offset, cur->ne[0], cur->ne[1], cur->ne[2], cur->ne[3], ggml_type_name(type));
  657. }
  658. }
  659. }
  660. buffer_size += n_tensors * 128 /* CLIP PADDING */;
  661. clip_ctx * new_clip = new clip_ctx;
  662. // update projector type
  663. {
  664. int idx = gguf_find_key(ctx, KEY_PROJ_TYPE);
  665. if (idx != -1) {
  666. const std::string proj_type = gguf_get_val_str(ctx, idx);
  667. new_clip->proj_type = clip_projector_type_from_string(proj_type);
  668. }
  669. else {
  670. new_clip->proj_type = PROJECTOR_TYPE_MLP;
  671. }
  672. }
  673. #ifdef GGML_USE_CUBLAS
  674. new_clip->backend = ggml_backend_cuda_init(0);
  675. printf("%s: CLIP using CUDA backend\n", __func__);
  676. #endif
  677. #ifdef GGML_USE_METAL
  678. new_clip->backend = ggml_backend_metal_init();
  679. printf("%s: CLIP using Metal backend\n", __func__);
  680. #endif
  681. if (!new_clip->backend) {
  682. new_clip->backend = ggml_backend_cpu_init();
  683. printf("%s: CLIP using CPU backend\n", __func__);
  684. }
  685. // model size and capabilities
  686. {
  687. int idx = get_key_idx(ctx, KEY_HAS_TEXT_ENC);
  688. new_clip->has_text_encoder = gguf_get_val_bool(ctx, idx);
  689. idx = get_key_idx(ctx, KEY_HAS_VIS_ENC);
  690. new_clip->has_vision_encoder = gguf_get_val_bool(ctx, idx);
  691. idx = gguf_find_key(ctx, KEY_HAS_LLAVA_PROJ);
  692. if (idx != -1) {
  693. new_clip->has_llava_projector = gguf_get_val_bool(ctx, idx);
  694. }
  695. GGML_ASSERT(new_clip->has_llava_projector); // see monatis/clip.cpp for image and/or text encoding for semantic search
  696. GGML_ASSERT(new_clip->has_vision_encoder);
  697. GGML_ASSERT(!new_clip->has_text_encoder);
  698. idx = get_key_idx(ctx, KEY_USE_GELU);
  699. new_clip->use_gelu = gguf_get_val_bool(ctx, idx);
  700. if (verbosity >= 1) {
  701. printf("%s: text_encoder: %d\n", __func__, new_clip->has_text_encoder);
  702. printf("%s: vision_encoder: %d\n", __func__, new_clip->has_vision_encoder);
  703. printf("%s: llava_projector: %d\n", __func__, new_clip->has_llava_projector);
  704. printf("%s: model size: %.2f MB\n", __func__, buffer_size / 1024.0 / 1024.0);
  705. printf("%s: metadata size: %.2f MB\n", __func__, ggml_get_mem_size(meta) / 1024.0 / 1024.0);
  706. }
  707. }
  708. printf("%s: params backend buffer size = % 6.2f MB (%i tensors)\n", __func__, buffer_size / (1024.0 * 1024.0), n_tensors);
  709. // load tensors
  710. {
  711. std::vector<uint8_t> read_buf;
  712. struct ggml_init_params params = {
  713. /*.mem_size =*/ (n_tensors + 1) * ggml_tensor_overhead(),
  714. /*.mem_buffer =*/ NULL,
  715. /*.no_alloc =*/ true,
  716. };
  717. new_clip->ctx_data = ggml_init(params);
  718. if (!new_clip->ctx_data) {
  719. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  720. clip_free(new_clip);
  721. return nullptr;
  722. }
  723. auto fin = std::ifstream(fname, std::ios::binary);
  724. if (!fin) {
  725. printf("cannot open model file for loading tensors\n");
  726. clip_free(new_clip);
  727. return nullptr;
  728. }
  729. // add tensors to context
  730. for (int i = 0; i < n_tensors; ++i) {
  731. const char * name = gguf_get_tensor_name(ctx, i);
  732. struct ggml_tensor * t = ggml_get_tensor(meta, name);
  733. struct ggml_tensor * cur = ggml_dup_tensor(new_clip->ctx_data, t);
  734. ggml_set_name(cur, name);
  735. }
  736. // alloc memory and offload data
  737. new_clip->params_buffer = ggml_backend_alloc_buffer(new_clip->backend, buffer_size);
  738. ggml_allocr* alloc = ggml_allocr_new_from_buffer(new_clip->params_buffer);
  739. for (int i = 0; i < n_tensors; ++i) {
  740. const char * name = gguf_get_tensor_name(ctx, i);
  741. struct ggml_tensor * cur = ggml_get_tensor(new_clip->ctx_data, name);
  742. ggml_allocr_alloc(alloc, cur);
  743. const size_t offset = gguf_get_data_offset(ctx) + gguf_get_tensor_offset(ctx, i);
  744. fin.seekg(offset, std::ios::beg);
  745. if (!fin) {
  746. printf("%s: failed to seek for tensor %s\n", __func__, name);
  747. clip_free(new_clip);
  748. return nullptr;
  749. }
  750. int num_bytes = ggml_nbytes(cur);
  751. if (ggml_backend_buffer_is_host(new_clip->params_buffer)) {
  752. // for the CPU and Metal backend, we can read directly into the tensor
  753. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  754. } else {
  755. // read into a temporary buffer first, then copy to device memory
  756. read_buf.resize(num_bytes);
  757. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  758. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  759. }
  760. }
  761. ggml_allocr_free(alloc);
  762. fin.close();
  763. }
  764. // vision model
  765. if (new_clip->has_vision_encoder) {
  766. // load vision model
  767. auto & vision_model = new_clip->vision_model;
  768. auto & hparams = vision_model.hparams;
  769. hparams.hidden_size = get_u32(ctx, format(KEY_N_EMBD, "vision"));
  770. hparams.n_head = get_u32(ctx, format(KEY_N_HEAD, "vision"));
  771. hparams.n_intermediate = get_u32(ctx, format(KEY_N_FF, "vision"));
  772. hparams.n_layer = get_u32(ctx, format(KEY_N_BLOCK, "vision"));
  773. hparams.image_size = get_u32(ctx, KEY_IMAGE_SIZE);
  774. hparams.patch_size = get_u32(ctx, KEY_PATCH_SIZE);
  775. hparams.projection_dim = get_u32(ctx, format(KEY_PROJ_DIM, "vision"));
  776. hparams.eps = get_f32(ctx, format(KEY_LAYER_NORM_EPS, "vision"));
  777. int idx_mean = get_key_idx(ctx, KEY_IMAGE_MEAN);
  778. int idx_std = get_key_idx(ctx, KEY_IMAGE_STD);
  779. for (int i = 0; i < 3; ++i) {
  780. new_clip->image_mean[i] = *((const float *)gguf_get_arr_data(ctx, idx_mean));
  781. new_clip->image_std[i] = *((const float *)gguf_get_arr_data(ctx, idx_std));
  782. }
  783. if (verbosity >= 2) {
  784. printf("\n%s: vision model hparams\n", __func__);
  785. printf("image_size %d\n", hparams.image_size);
  786. printf("patch_size %d\n", hparams.patch_size);
  787. printf("v_hidden_size %d\n", hparams.hidden_size);
  788. printf("v_n_intermediate %d\n", hparams.n_intermediate);
  789. printf("v_projection_dim %d\n", hparams.projection_dim);
  790. printf("v_n_head %d\n", hparams.n_head);
  791. printf("v_n_layer %d\n", hparams.n_layer);
  792. }
  793. vision_model.patch_embeddings = get_tensor(new_clip->ctx_data, TN_PATCH_EMBD);
  794. vision_model.class_embedding = get_tensor(new_clip->ctx_data, TN_CLASS_EMBD);
  795. vision_model.position_embeddings = get_tensor(new_clip->ctx_data, format(TN_POS_EMBD, "v"));
  796. vision_model.pre_ln_w = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "weight"));
  797. vision_model.pre_ln_b = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "bias"));
  798. // LLaVA projection
  799. if (new_clip->proj_type == PROJECTOR_TYPE_MLP) {
  800. vision_model.mm_0_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "weight"));
  801. vision_model.mm_0_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "bias"));
  802. vision_model.mm_2_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "weight"));
  803. vision_model.mm_2_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "bias"));
  804. }
  805. else if (new_clip->proj_type == PROJECTOR_TYPE_LDP) {
  806. // MobileVLM projection
  807. vision_model.mm_model_mlp_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 1, "weight"));
  808. vision_model.mm_model_mlp_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 1, "bias"));
  809. vision_model.mm_model_mlp_3_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 3, "weight"));
  810. vision_model.mm_model_mlp_3_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 3, "bias"));
  811. vision_model.mm_model_block_1_block_0_0_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 0, "0.weight"));
  812. vision_model.mm_model_block_1_block_0_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.weight"));
  813. vision_model.mm_model_block_1_block_0_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.bias"));
  814. vision_model.mm_model_block_1_block_1_fc1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.weight"));
  815. vision_model.mm_model_block_1_block_1_fc1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.bias"));
  816. vision_model.mm_model_block_1_block_1_fc2_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.weight"));
  817. vision_model.mm_model_block_1_block_1_fc2_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.bias"));
  818. vision_model.mm_model_block_1_block_2_0_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 2, "0.weight"));
  819. vision_model.mm_model_block_1_block_2_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.weight"));
  820. vision_model.mm_model_block_1_block_2_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.bias"));
  821. vision_model.mm_model_block_2_block_0_0_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 0, "0.weight"));
  822. vision_model.mm_model_block_2_block_0_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.weight"));
  823. vision_model.mm_model_block_2_block_0_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.bias"));
  824. vision_model.mm_model_block_2_block_1_fc1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.weight"));
  825. vision_model.mm_model_block_2_block_1_fc1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.bias"));
  826. vision_model.mm_model_block_2_block_1_fc2_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.weight"));
  827. vision_model.mm_model_block_2_block_1_fc2_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.bias"));
  828. vision_model.mm_model_block_2_block_2_0_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 2, "0.weight"));
  829. vision_model.mm_model_block_2_block_2_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.weight"));
  830. vision_model.mm_model_block_2_block_2_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.bias"));
  831. }
  832. else {
  833. std::string proj_type = PROJECTOR_TYPE_NAMES[new_clip->proj_type];
  834. throw std::runtime_error(format("%s: don't support projector with: %s currently\n", __func__, proj_type.c_str()));
  835. }
  836. vision_model.layers.resize(hparams.n_layer);
  837. for (int il = 0; il < hparams.n_layer; ++il) {
  838. auto & layer = vision_model.layers[il];
  839. layer.k_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "weight"));
  840. layer.q_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "weight"));
  841. layer.v_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "weight"));
  842. layer.o_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "weight"));
  843. layer.ln_1_w = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "weight"));
  844. layer.ln_2_w = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "weight"));
  845. layer.ff_i_w = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "weight"));
  846. layer.ff_o_w = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "weight"));
  847. layer.k_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "bias"));
  848. layer.q_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "bias"));
  849. layer.v_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "bias"));
  850. layer.o_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "bias"));
  851. layer.ln_1_b = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "bias"));
  852. layer.ln_2_b = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "bias"));
  853. layer.ff_i_b = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "bias"));
  854. layer.ff_o_b = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "bias"));
  855. }
  856. }
  857. ggml_free(meta);
  858. new_clip->ctx_gguf = ctx;
  859. // measure mem requirement and allocate
  860. {
  861. new_clip->buf_compute_meta.resize(GGML_DEFAULT_GRAPH_SIZE * ggml_tensor_overhead() + ggml_graph_overhead());
  862. new_clip->compute_alloc = ggml_allocr_new_measure_from_backend(new_clip->backend);
  863. clip_image_f32_batch batch;
  864. batch.size = 1;
  865. ggml_cgraph * gf = clip_image_build_graph(new_clip, &batch);
  866. size_t compute_memory_buffer_size = ggml_allocr_alloc_graph(new_clip->compute_alloc, gf);
  867. ggml_allocr_free(new_clip->compute_alloc);
  868. new_clip->compute_buffer = ggml_backend_alloc_buffer(new_clip->backend, compute_memory_buffer_size);
  869. new_clip->compute_alloc = ggml_allocr_new_from_buffer(new_clip->compute_buffer);
  870. printf("%s: compute allocated memory: %.2f MB\n", __func__, compute_memory_buffer_size /1024.0/1024.0);
  871. }
  872. return new_clip;
  873. }
  874. struct clip_image_u8 * clip_image_u8_init() {
  875. return new clip_image_u8();
  876. }
  877. struct clip_image_f32 * clip_image_f32_init() {
  878. return new clip_image_f32();
  879. }
  880. void clip_image_u8_free (struct clip_image_u8 * img) { delete img; }
  881. void clip_image_f32_free(struct clip_image_f32 * img) { delete img; }
  882. static void build_clip_img_from_data(const stbi_uc * data, int nx, int ny, clip_image_u8 * img) {
  883. img->nx = nx;
  884. img->ny = ny;
  885. img->buf.resize(3 * nx * ny);
  886. memcpy(img->buf.data(), data, img->buf.size());
  887. }
  888. bool clip_image_load_from_file(const char * fname, clip_image_u8 * img) {
  889. int nx, ny, nc;
  890. auto * data = stbi_load(fname, &nx, &ny, &nc, 3);
  891. if (!data) {
  892. fprintf(stderr, "%s: failed to load image '%s'\n", __func__, fname);
  893. return false;
  894. }
  895. build_clip_img_from_data(data, nx, ny, img);
  896. stbi_image_free(data);
  897. return true;
  898. }
  899. bool clip_image_load_from_bytes(const unsigned char * bytes, size_t bytes_length, struct clip_image_u8 * img) {
  900. int nx, ny, nc;
  901. auto * data = stbi_load_from_memory(bytes, bytes_length, &nx, &ny, &nc, 3);
  902. if (!data) {
  903. fprintf(stderr, "%s: failed to decode image bytes\n", __func__);
  904. return false;
  905. }
  906. build_clip_img_from_data(data, nx, ny, img);
  907. stbi_image_free(data);
  908. return true;
  909. }
  910. // normalize: x = (x - mean) / std
  911. // TODO: implement bicubic interpolation instead of linear.
  912. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, clip_image_f32 * res, const bool pad2square) {
  913. if (!ctx->has_vision_encoder) {
  914. printf("This gguf file seems to have no vision encoder\n");
  915. return false;
  916. }
  917. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  918. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  919. clip_image_u8 * temp = clip_image_u8_init(); // we will keep the input image data here temporarily
  920. if (pad2square && img->nx != img->ny) {
  921. int longer_side = std::max(img->nx, img->ny);
  922. temp->nx = longer_side;
  923. temp->ny = longer_side;
  924. temp->buf.resize(3 * longer_side * longer_side);
  925. const uint8_t bc[3] = {122, 116, 104}; // background color in RGB from LLaVA
  926. // fill with background color
  927. for (size_t i = 0; i < temp->buf.size(); i++) {
  928. temp->buf[i] = bc[i % 3];
  929. }
  930. // copy from the input image
  931. for (int y = 0; y < img->ny; y++) {
  932. for (int x = 0; x < img->nx; x++) {
  933. const int i = 3 * (y * img->nx + x);
  934. const int j = 3 * (y * temp->nx + x);
  935. temp->buf[j] = img->buf[i];
  936. temp->buf[j+1] = img->buf[i+1];
  937. temp->buf[j+2] = img->buf[i+2];
  938. }
  939. }
  940. } else {
  941. temp->nx = img->nx;
  942. temp->ny = img->ny;
  943. temp->buf.resize(img->buf.size());
  944. memcpy(temp->buf.data(), img->buf.data(), temp->buf.size());
  945. }
  946. const int nx = temp->nx;
  947. const int ny = temp->ny;
  948. const int nx2 = ctx->vision_model.hparams.image_size;
  949. const int ny2 = ctx->vision_model.hparams.image_size;
  950. res->nx = nx2;
  951. res->ny = ny2;
  952. res->buf.resize(3 * nx2 * ny2);
  953. const float scale = std::max(nx, ny) / (float)ctx->vision_model.hparams.image_size;
  954. const int nx3 = int(nx / scale + 0.5f);
  955. const int ny3 = int(ny / scale + 0.5f);
  956. const auto & m3 = ctx->image_mean; // {0.48145466f, 0.4578275f, 0.40821073f};
  957. const auto & s3 = ctx->image_std; // {0.26862954f, 0.26130258f, 0.27577711f};
  958. for (int y = 0; y < ny3; y++) {
  959. for (int x = 0; x < nx3; x++) {
  960. for (int c = 0; c < 3; c++) {
  961. // linear interpolation
  962. const float sx = (x + 0.5f) * scale - 0.5f;
  963. const float sy = (y + 0.5f) * scale - 0.5f;
  964. const int x0 = std::max(0, (int)std::floor(sx));
  965. const int y0 = std::max(0, (int)std::floor(sy));
  966. const int x1 = std::min(x0 + 1, nx - 1);
  967. const int y1 = std::min(y0 + 1, ny - 1);
  968. const float dx = sx - x0;
  969. const float dy = sy - y0;
  970. const int j00 = 3 * (y0 * nx + x0) + c;
  971. const int j01 = 3 * (y0 * nx + x1) + c;
  972. const int j10 = 3 * (y1 * nx + x0) + c;
  973. const int j11 = 3 * (y1 * nx + x1) + c;
  974. const float v00 = temp->buf[j00];
  975. const float v01 = temp->buf[j01];
  976. const float v10 = temp->buf[j10];
  977. const float v11 = temp->buf[j11];
  978. const float v0 = v00 * (1.0f - dx) + v01 * dx;
  979. const float v1 = v10 * (1.0f - dx) + v11 * dx;
  980. const float v = v0 * (1.0f - dy) + v1 * dy;
  981. const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
  982. const int i = 3 * (y * nx3 + x) + c;
  983. res->buf[i] = ((float(v2) / 255.0f) - m3[c]) / s3[c];
  984. }
  985. }
  986. }
  987. clip_image_u8_free(temp);
  988. return true;
  989. }
  990. void clip_free(clip_ctx * ctx) {
  991. ggml_free(ctx->ctx_data);
  992. gguf_free(ctx->ctx_gguf);
  993. delete ctx;
  994. }
  995. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  996. if (!ctx->has_vision_encoder) {
  997. printf("This gguf file seems to have no vision encoder\n");
  998. return false;
  999. }
  1000. clip_image_f32_batch imgs{};
  1001. imgs.size = 1;
  1002. imgs.data = img;
  1003. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  1004. }
  1005. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs, float * vec) {
  1006. if (!ctx->has_vision_encoder) {
  1007. printf("This gguf file seems to have no vision encoder\n");
  1008. return false;
  1009. }
  1010. int batch_size = imgs->size;
  1011. if(ctx->has_llava_projector) {
  1012. GGML_ASSERT(batch_size == 1); // TODO: support multiple images
  1013. }
  1014. // reset alloc buffer to clean the memory from previous invocations
  1015. ggml_allocr_reset(ctx->compute_alloc);
  1016. // build the inference graph
  1017. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs);
  1018. ggml_allocr_alloc_graph(ctx->compute_alloc, gf);
  1019. if (ggml_backend_is_cpu(ctx->backend)) {
  1020. ggml_backend_cpu_set_n_threads(ctx->backend, n_threads);
  1021. }
  1022. #ifdef GGML_USE_METAL
  1023. if (ggml_backend_is_metal(ctx->backend)) {
  1024. ggml_backend_metal_set_n_cb(ctx->backend, n_threads);
  1025. }
  1026. #endif
  1027. ggml_backend_graph_compute(ctx->backend, gf);
  1028. // the last node is the embedding tensor
  1029. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 1];
  1030. // copy the embeddings to the location passed by the user
  1031. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  1032. return true;
  1033. }
  1034. bool clip_model_quantize(const char * fname_inp, const char * fname_out, const int itype) {
  1035. ggml_type type = GGML_TYPE_Q4_1;
  1036. assert(itype < GGML_TYPE_COUNT);
  1037. type = static_cast<ggml_type>(itype);
  1038. auto * ctx_clip = clip_model_load(fname_inp, 2);
  1039. const auto & ctx_src = ctx_clip->ctx_gguf;
  1040. const auto & ctx_data = ctx_clip->ctx_data;
  1041. auto * ctx_out = gguf_init_empty();
  1042. gguf_set_kv(ctx_out, ctx_src);
  1043. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  1044. gguf_set_val_u32(ctx_out, "general.file_type", itype);
  1045. auto fout = std::ofstream(fname_out, std::ios::binary);
  1046. const int n_tensors = gguf_get_n_tensors(ctx_src);
  1047. for (int i = 0; i < n_tensors; ++i) {
  1048. const char * name = gguf_get_tensor_name(ctx_src, i);
  1049. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name);
  1050. gguf_add_tensor(ctx_out, cur);
  1051. }
  1052. const size_t meta_size = gguf_get_meta_size(ctx_out);
  1053. for (size_t i = 0; i < meta_size; ++i) {
  1054. fout.put(0);
  1055. }
  1056. // regexes of tensor names to be quantized
  1057. const std::vector<std::string> k_names = {
  1058. ".*weight",
  1059. };
  1060. std::vector<uint8_t> work(512);
  1061. std::vector<float> conv_buf(512);
  1062. std::vector<int64_t> hist_all(1 << 4, 0);
  1063. size_t total_size_org = 0;
  1064. size_t total_size_new = 0;
  1065. for (int i = 0; i < n_tensors; ++i) {
  1066. const std::string name = gguf_get_tensor_name(ctx_src, i);
  1067. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name.c_str());
  1068. enum ggml_type new_type;
  1069. void * new_data;
  1070. size_t new_size;
  1071. bool quantize = false;
  1072. for (const auto & s : k_names) {
  1073. if (std::regex_match(name, std::regex(s))) {
  1074. quantize = true;
  1075. break;
  1076. }
  1077. }
  1078. // quantize only 2D tensors
  1079. quantize &= (ggml_n_dims(cur) == 2);
  1080. if (quantize) {
  1081. new_type = type;
  1082. if (new_type >= GGML_TYPE_Q2_K && name.find("embd") != std::string::npos) {
  1083. new_type = GGML_TYPE_Q8_0; // ggml_get_rows needs non K type
  1084. // fprintf(stderr, "%s: quantizing %s to %s\n", __func__, name.c_str(), ggml_type_name(new_type));
  1085. }
  1086. const size_t n_elms = ggml_nelements(cur);
  1087. float * f32_data;
  1088. switch (cur->type) {
  1089. case GGML_TYPE_F32:
  1090. f32_data = (float *)cur->data;
  1091. break;
  1092. case GGML_TYPE_F16:
  1093. if (conv_buf.size() < n_elms) {
  1094. conv_buf.resize(n_elms);
  1095. }
  1096. for (size_t j = 0; j < n_elms; ++j) {
  1097. conv_buf[j] = ggml_fp16_to_fp32(((ggml_fp16_t *)cur->data)[j]);
  1098. }
  1099. f32_data = (float *)conv_buf.data();
  1100. break;
  1101. default:
  1102. printf("Please use an input file in f32 or f16\n");
  1103. return false;
  1104. }
  1105. if (work.size() < n_elms * 4) {
  1106. work.resize(n_elms * 4);
  1107. }
  1108. new_data = work.data();
  1109. std::vector<int64_t> hist_cur(1 << 4, 0);
  1110. switch (new_type) {
  1111. case GGML_TYPE_Q4_0: {
  1112. new_size = ggml_quantize_q4_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1113. } break;
  1114. case GGML_TYPE_Q4_1: {
  1115. new_size = ggml_quantize_q4_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1116. } break;
  1117. case GGML_TYPE_Q5_0: {
  1118. new_size = ggml_quantize_q5_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1119. } break;
  1120. case GGML_TYPE_Q5_1: {
  1121. new_size = ggml_quantize_q5_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1122. } break;
  1123. case GGML_TYPE_Q8_0: {
  1124. new_size = ggml_quantize_q8_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1125. } break;
  1126. case GGML_TYPE_Q2_K: {
  1127. new_size = ggml_quantize_q2_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1128. } break;
  1129. case GGML_TYPE_Q3_K: {
  1130. new_size = ggml_quantize_q3_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1131. } break;
  1132. case GGML_TYPE_Q4_K: {
  1133. new_size = ggml_quantize_q4_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1134. } break;
  1135. case GGML_TYPE_Q5_K: {
  1136. new_size = ggml_quantize_q5_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1137. } break;
  1138. case GGML_TYPE_Q6_K: {
  1139. new_size = ggml_quantize_q6_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1140. } break;
  1141. default: {
  1142. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, new_type);
  1143. return false;
  1144. }
  1145. }
  1146. for (size_t j = 0; j < hist_cur.size(); ++j) {
  1147. hist_all[j] += hist_cur[j];
  1148. }
  1149. } else {
  1150. new_type = cur->type;
  1151. new_data = cur->data;
  1152. new_size = ggml_nbytes(cur);
  1153. }
  1154. const size_t orig_size = ggml_nbytes(cur);
  1155. total_size_org += orig_size;
  1156. total_size_new += new_size;
  1157. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  1158. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  1159. fout.write((const char *)new_data, new_size);
  1160. size_t pad = GGML_PAD(new_size, gguf_get_alignment(ctx_out)) - new_size;
  1161. for (size_t j = 0; j < pad; ++j) {
  1162. fout.put(0);
  1163. }
  1164. printf("%s: n_dims = %d | quantize=%d | size = %f MB -> %f MB\n", name.c_str(), ggml_n_dims(cur), quantize,
  1165. orig_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  1166. }
  1167. // go back to beginning of file and write the updated metadata
  1168. fout.seekp(0, std::ios::beg);
  1169. std::vector<uint8_t> meta(meta_size);
  1170. gguf_get_meta_data(ctx_out, meta.data());
  1171. fout.write((const char *)meta.data(), meta_size);
  1172. fout.close();
  1173. clip_free(ctx_clip);
  1174. gguf_free(ctx_out);
  1175. {
  1176. printf("%s: original size = %8.2f MB\n", __func__, total_size_org / 1024.0 / 1024.0);
  1177. printf("%s: quantized size = %8.2f MB\n", __func__, total_size_new / 1024.0 / 1024.0);
  1178. int64_t sum_all = 0;
  1179. for (size_t i = 0; i < hist_all.size(); ++i) {
  1180. sum_all += hist_all[i];
  1181. }
  1182. printf("%s: hist: ", __func__);
  1183. for (size_t i = 0; i < hist_all.size(); ++i) {
  1184. printf("%5.3f ", hist_all[i] / (float)sum_all);
  1185. }
  1186. printf("\n");
  1187. }
  1188. return true;
  1189. }
  1190. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  1191. if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  1192. return ctx->vision_model.mm_model_block_1_block_2_1_b->ne[0];
  1193. }
  1194. else if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  1195. return ctx->vision_model.mm_2_b->ne[0];
  1196. }
  1197. else {
  1198. std::string proj_type = PROJECTOR_TYPE_NAMES[ctx->proj_type];
  1199. throw std::runtime_error(format("%s: don't support projector with: %s currently\n", __func__, proj_type.c_str()));
  1200. }
  1201. }
  1202. int clip_n_patches(const struct clip_ctx * ctx) {
  1203. auto & params = ctx->vision_model.hparams;
  1204. int n_patches = (params.image_size / params.patch_size) * (params.image_size / params.patch_size);
  1205. if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  1206. n_patches /= 4;
  1207. }
  1208. return n_patches;
  1209. }
  1210. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  1211. return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);
  1212. }