clip.cpp 59 KB

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