clip.cpp 59 KB

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