clip.cpp 61 KB

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