clip.cpp 61 KB

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