clip.cpp 37 KB

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