1
0

clip.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025
  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. // Note: Even when using identical normalized image inputs (see normalize_image_u8_to_f32()) we have a significant difference in resulting embeddings compared to pytorch
  5. #include "clip.h"
  6. #include "ggml.h"
  7. #include "ggml-alloc.h"
  8. #include "ggml-backend.h"
  9. #ifdef GGML_USE_CUBLAS
  10. #include "ggml-cuda.h"
  11. #endif
  12. #ifdef GGML_USE_METAL
  13. #include "ggml-metal.h"
  14. #endif
  15. #define STB_IMAGE_IMPLEMENTATION
  16. #include "stb_image.h"
  17. #include <cassert>
  18. #include <cmath>
  19. #include <cstdlib>
  20. #include <cstring>
  21. #include <fstream>
  22. #include <iostream>
  23. #include <map>
  24. #include <regex>
  25. #include <stdexcept>
  26. #include <vector>
  27. #include <sstream>
  28. #include <cinttypes>
  29. #include <limits>
  30. //#define CLIP_DEBUG_FUNCTIONS
  31. // RGB uint8 image
  32. struct clip_image_u8 {
  33. int nx;
  34. int ny;
  35. std::vector<uint8_t> buf;
  36. };
  37. // RGB float32 image (NHWC)
  38. // Memory layout: RGBRGBRGB...
  39. struct clip_image_f32 {
  40. int nx;
  41. int ny;
  42. std::vector<float> buf;
  43. };
  44. static std::string format(const char * fmt, ...) {
  45. va_list ap;
  46. va_list ap2;
  47. va_start(ap, fmt);
  48. va_copy(ap2, ap);
  49. int size = vsnprintf(NULL, 0, fmt, ap);
  50. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  51. std::vector<char> buf(size + 1);
  52. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  53. GGML_ASSERT(size2 == size);
  54. va_end(ap2);
  55. va_end(ap);
  56. return std::string(buf.data(), buf.size());
  57. }
  58. //
  59. // key constants
  60. //
  61. #define KEY_FTYPE "general.file_type"
  62. #define KEY_NAME "general.name"
  63. #define KEY_DESCRIPTION "general.description"
  64. #define KEY_HAS_TEXT_ENC "clip.has_text_encoder"
  65. #define KEY_HAS_VIS_ENC "clip.has_vision_encoder"
  66. #define KEY_HAS_LLAVA_PROJ "clip.has_llava_projector"
  67. #define KEY_USE_GELU "clip.use_gelu"
  68. #define KEY_N_EMBD "clip.%s.embedding_length"
  69. #define KEY_N_FF "clip.%s.feed_forward_length"
  70. #define KEY_N_BLOCK "clip.%s.block_count"
  71. #define KEY_N_HEAD "clip.%s.attention.head_count"
  72. #define KEY_LAYER_NORM_EPS "clip.%s.attention.layer_norm_epsilon"
  73. #define KEY_PROJ_DIM "clip.%s.projection_dim"
  74. #define KEY_TOKENS "tokenizer.ggml.tokens"
  75. #define KEY_N_POSITIONS "clip.text.context_length"
  76. #define KEY_IMAGE_SIZE "clip.vision.image_size"
  77. #define KEY_PATCH_SIZE "clip.vision.patch_size"
  78. #define KEY_IMAGE_MEAN "clip.vision.image_mean"
  79. #define KEY_IMAGE_STD "clip.vision.image_std"
  80. #define KEY_PROJ_TYPE "clip.projector_type"
  81. #define KEY_MM_PATCH_MERGE_TYPE "clip.vision.mm_patch_merge_type"
  82. #define KEY_IMAGE_GRID_PINPOINTS "clip.vision.image_grid_pinpoints"
  83. #define KEY_IMAGE_CROP_RESOLUTION "clip.vision.image_crop_resolution"
  84. //
  85. // tensor name constants
  86. //
  87. #define TN_TOKEN_EMBD "%s.token_embd.weight"
  88. #define TN_POS_EMBD "%s.position_embd.weight"
  89. #define TN_CLASS_EMBD "v.class_embd"
  90. #define TN_PATCH_EMBD "v.patch_embd.weight"
  91. #define TN_ATTN_K "%s.blk.%d.attn_k.%s"
  92. #define TN_ATTN_Q "%s.blk.%d.attn_q.%s"
  93. #define TN_ATTN_V "%s.blk.%d.attn_v.%s"
  94. #define TN_ATTN_OUTPUT "%s.blk.%d.attn_out.%s"
  95. #define TN_FFN_DOWN "%s.blk.%d.ffn_down.%s"
  96. #define TN_FFN_UP "%s.blk.%d.ffn_up.%s"
  97. #define TN_LN_1 "%s.blk.%d.ln1.%s"
  98. #define TN_LN_2 "%s.blk.%d.ln2.%s"
  99. #define TN_LN_PRE "%s.pre_ln.%s"
  100. #define TN_LN_POST "%s.post_ln.%s"
  101. #define TN_TEXT_PROJ "text_projection.weight"
  102. #define TN_VIS_PROJ "visual_projection.weight"
  103. #define TN_LLAVA_PROJ "mm.%d.%s"
  104. #define TN_MVLM_PROJ_MLP "mm.model.mlp.%d.%s"
  105. #define TN_MVLM_PROJ_BLOCK "mm.model.mb_block.%d.block.%d.%s"
  106. #define TN_IMAGE_NEWLINE "model.image_newline"
  107. enum projector_type {
  108. PROJECTOR_TYPE_MLP,
  109. PROJECTOR_TYPE_MLP_NORM,
  110. PROJECTOR_TYPE_LDP,
  111. PROJECTOR_TYPE_UNKNOWN,
  112. };
  113. static std::map<projector_type, std::string> PROJECTOR_TYPE_NAMES = {
  114. { PROJECTOR_TYPE_MLP, "mlp" },
  115. { PROJECTOR_TYPE_LDP, "ldp" },
  116. };
  117. //
  118. // utilities to get data from a gguf file
  119. //
  120. static int get_key_idx(const gguf_context * ctx, const char * key) {
  121. int i = gguf_find_key(ctx, key);
  122. if (i == -1) {
  123. fprintf(stderr, "key %s not found in file\n", key);
  124. throw std::runtime_error(format("Missing required key: %s", key));
  125. }
  126. return i;
  127. }
  128. static uint32_t get_u32(const gguf_context * ctx, const std::string & key) {
  129. const int i = get_key_idx(ctx, key.c_str());
  130. return gguf_get_val_u32(ctx, i);
  131. }
  132. static float get_f32(const gguf_context * ctx, const std::string & key) {
  133. const int i = get_key_idx(ctx, key.c_str());
  134. return gguf_get_val_f32(ctx, i);
  135. }
  136. static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const std::string & name) {
  137. struct ggml_tensor * cur = ggml_get_tensor(ctx, name.c_str());
  138. if (!cur) {
  139. throw std::runtime_error(format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  140. }
  141. return cur;
  142. }
  143. static std::string get_ftype(int ftype) {
  144. return ggml_type_name(static_cast<ggml_type>(ftype));
  145. }
  146. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  147. switch (type) {
  148. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  149. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  150. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  151. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  152. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  153. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  154. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  155. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  156. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  157. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  158. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  159. default: return format("unknown type %d", type);
  160. }
  161. }
  162. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  163. std::string result;
  164. for (size_t pos = 0; ; pos += search.length()) {
  165. auto new_pos = s.find(search, pos);
  166. if (new_pos == std::string::npos) {
  167. result += s.substr(pos, s.size() - pos);
  168. break;
  169. }
  170. result += s.substr(pos, new_pos - pos) + replace;
  171. pos = new_pos;
  172. }
  173. s = std::move(result);
  174. }
  175. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  176. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  177. switch (type) {
  178. case GGUF_TYPE_STRING:
  179. return gguf_get_val_str(ctx_gguf, i);
  180. case GGUF_TYPE_ARRAY:
  181. {
  182. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  183. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  184. const void * data = gguf_get_arr_data(ctx_gguf, i);
  185. std::stringstream ss;
  186. ss << "[";
  187. for (int j = 0; j < arr_n; j++) {
  188. if (arr_type == GGUF_TYPE_STRING) {
  189. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  190. // escape quotes
  191. replace_all(val, "\\", "\\\\");
  192. replace_all(val, "\"", "\\\"");
  193. ss << '"' << val << '"';
  194. } else if (arr_type == GGUF_TYPE_ARRAY) {
  195. ss << "???";
  196. } else {
  197. ss << gguf_data_to_str(arr_type, data, j);
  198. }
  199. if (j < arr_n - 1) {
  200. ss << ", ";
  201. }
  202. }
  203. ss << "]";
  204. return ss.str();
  205. }
  206. default:
  207. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  208. }
  209. }
  210. static void print_tensor_info(const ggml_tensor * tensor, const char * prefix = "") {
  211. size_t tensor_size = ggml_nbytes(tensor);
  212. printf("%s: n_dims = %d, name = %s, tensor_size=%zu, shape:[%" PRId64 ", %" PRId64 ", %" PRId64 ", %" PRId64 "], type = %s\n",
  213. prefix, ggml_n_dims(tensor), tensor->name, tensor_size,
  214. tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], ggml_type_name(tensor->type));
  215. }
  216. static projector_type clip_projector_type_from_string(const std::string & name) {
  217. for (const auto & kv : PROJECTOR_TYPE_NAMES) { // NOLINT
  218. if (kv.second == name) {
  219. return kv.first;
  220. }
  221. }
  222. return PROJECTOR_TYPE_UNKNOWN;
  223. }
  224. #ifdef CLIP_DEBUG_FUNCTIONS
  225. static void clip_image_write_image_to_ppm(const clip_image_u8& img, const std::string& filename) {
  226. std::ofstream file(filename, std::ios::binary);
  227. if (!file.is_open()) {
  228. std::cerr << "Failed to open file for writing: " << filename << std::endl;
  229. return;
  230. }
  231. // PPM header: P6 format, width, height, and max color value
  232. file << "P6\n" << img.nx << " " << img.ny << "\n255\n";
  233. // Write pixel data
  234. for (size_t i = 0; i < img.buf.size(); i += 3) {
  235. // PPM expects binary data in RGB format, which matches our image buffer
  236. file.write(reinterpret_cast<const char*>(&img.buf[i]), 3);
  237. }
  238. file.close();
  239. }
  240. static void clip_image_save_to_bmp(const clip_image_u8& img, const std::string& filename) {
  241. std::ofstream file(filename, std::ios::binary);
  242. if (!file.is_open()) {
  243. std::cerr << "Failed to open file for writing: " << filename << std::endl;
  244. return;
  245. }
  246. int fileSize = 54 + 3 * img.nx * img.ny; // File header + info header + pixel data
  247. int bytesPerPixel = 3;
  248. int widthInBytes = img.nx * bytesPerPixel;
  249. int paddingAmount = (4 - (widthInBytes % 4)) % 4;
  250. int stride = widthInBytes + paddingAmount;
  251. // Bitmap file header
  252. unsigned char fileHeader[14] = {
  253. 'B','M', // Signature
  254. 0,0,0,0, // Image file size in bytes
  255. 0,0,0,0, // Reserved
  256. 54,0,0,0 // Start of pixel array
  257. };
  258. // Total file size
  259. fileSize = 54 + (stride * img.ny);
  260. fileHeader[2] = (unsigned char)(fileSize);
  261. fileHeader[3] = (unsigned char)(fileSize >> 8);
  262. fileHeader[4] = (unsigned char)(fileSize >> 16);
  263. fileHeader[5] = (unsigned char)(fileSize >> 24);
  264. // Bitmap information header (BITMAPINFOHEADER)
  265. unsigned char infoHeader[40] = {
  266. 40,0,0,0, // Size of this header (40 bytes)
  267. 0,0,0,0, // Image width
  268. 0,0,0,0, // Image height
  269. 1,0, // Number of color planes
  270. 24,0, // Bits per pixel
  271. 0,0,0,0, // No compression
  272. 0,0,0,0, // Image size (can be 0 for no compression)
  273. 0,0,0,0, // X pixels per meter (not specified)
  274. 0,0,0,0, // Y pixels per meter (not specified)
  275. 0,0,0,0, // Total colors (color table not used)
  276. 0,0,0,0 // Important colors (all are important)
  277. };
  278. // Width and height in the information header
  279. infoHeader[4] = (unsigned char)(img.nx);
  280. infoHeader[5] = (unsigned char)(img.nx >> 8);
  281. infoHeader[6] = (unsigned char)(img.nx >> 16);
  282. infoHeader[7] = (unsigned char)(img.nx >> 24);
  283. infoHeader[8] = (unsigned char)(img.ny);
  284. infoHeader[9] = (unsigned char)(img.ny >> 8);
  285. infoHeader[10] = (unsigned char)(img.ny >> 16);
  286. infoHeader[11] = (unsigned char)(img.ny >> 24);
  287. // Write file headers
  288. file.write(reinterpret_cast<char*>(fileHeader), sizeof(fileHeader));
  289. file.write(reinterpret_cast<char*>(infoHeader), sizeof(infoHeader));
  290. // Pixel data
  291. std::vector<unsigned char> padding(3, 0); // Max padding size to be added to each row
  292. for (int y = img.ny - 1; y >= 0; --y) { // BMP files are stored bottom-to-top
  293. for (int x = 0; x < img.nx; ++x) {
  294. // Each pixel
  295. size_t pixelIndex = (y * img.nx + x) * 3;
  296. unsigned char pixel[3] = {
  297. img.buf[pixelIndex + 2], // BMP stores pixels in BGR format
  298. img.buf[pixelIndex + 1],
  299. img.buf[pixelIndex]
  300. };
  301. file.write(reinterpret_cast<char*>(pixel), 3);
  302. }
  303. // Write padding for the row
  304. file.write(reinterpret_cast<char*>(padding.data()), paddingAmount);
  305. }
  306. file.close();
  307. }
  308. // debug function to convert f32 to u8
  309. static void clip_image_convert_f32_to_u8(const clip_image_f32& src, clip_image_u8& dst) {
  310. dst.nx = src.nx;
  311. dst.ny = src.ny;
  312. dst.buf.resize(3 * src.nx * src.ny);
  313. for (size_t i = 0; i < src.buf.size(); ++i) {
  314. dst.buf[i] = static_cast<uint8_t>(std::min(std::max(int(src.buf[i] * 255.0f), 0), 255));
  315. }
  316. }
  317. #endif
  318. //
  319. // clip layers
  320. //
  321. struct clip_hparams {
  322. int32_t image_size;
  323. int32_t patch_size;
  324. int32_t hidden_size;
  325. int32_t n_intermediate;
  326. int32_t projection_dim;
  327. int32_t n_head;
  328. int32_t n_layer;
  329. float eps;
  330. char mm_patch_merge_type[32] = "flat"; // spatial_unpad or flat (default)
  331. int32_t image_grid_pinpoints[32];
  332. int32_t image_crop_resolution;
  333. };
  334. struct clip_layer {
  335. // attention
  336. struct ggml_tensor * k_w;
  337. struct ggml_tensor * k_b;
  338. struct ggml_tensor * q_w;
  339. struct ggml_tensor * q_b;
  340. struct ggml_tensor * v_w;
  341. struct ggml_tensor * v_b;
  342. struct ggml_tensor * o_w;
  343. struct ggml_tensor * o_b;
  344. // layernorm 1
  345. struct ggml_tensor * ln_1_w;
  346. struct ggml_tensor * ln_1_b;
  347. // ff
  348. struct ggml_tensor * ff_i_w;
  349. struct ggml_tensor * ff_i_b;
  350. struct ggml_tensor * ff_o_w;
  351. struct ggml_tensor * ff_o_b;
  352. // layernorm 2
  353. struct ggml_tensor * ln_2_w;
  354. struct ggml_tensor * ln_2_b;
  355. };
  356. struct clip_vision_model {
  357. struct clip_hparams hparams;
  358. // embeddings
  359. struct ggml_tensor * class_embedding;
  360. struct ggml_tensor * patch_embeddings;
  361. struct ggml_tensor * position_embeddings;
  362. struct ggml_tensor * pre_ln_w;
  363. struct ggml_tensor * pre_ln_b;
  364. std::vector<clip_layer> layers;
  365. struct ggml_tensor * post_ln_w;
  366. struct ggml_tensor * post_ln_b;
  367. struct ggml_tensor * projection;
  368. // LLaVA projection
  369. struct ggml_tensor * mm_0_w = NULL;
  370. struct ggml_tensor * mm_0_b = NULL;
  371. struct ggml_tensor * mm_2_w = NULL;
  372. struct ggml_tensor * mm_2_b = NULL;
  373. struct ggml_tensor * image_newline = NULL;
  374. // Yi type models with mlp+normalization projection
  375. struct ggml_tensor * mm_1_w = NULL; // Yi type models have 0, 1, 3, 4
  376. struct ggml_tensor * mm_1_b = NULL;
  377. struct ggml_tensor * mm_3_w = NULL;
  378. struct ggml_tensor * mm_3_b = NULL;
  379. struct ggml_tensor * mm_4_w = NULL;
  380. struct ggml_tensor * mm_4_b = NULL;
  381. // MobileVLM projection
  382. struct ggml_tensor * mm_model_mlp_1_w;
  383. struct ggml_tensor * mm_model_mlp_1_b;
  384. struct ggml_tensor * mm_model_mlp_3_w;
  385. struct ggml_tensor * mm_model_mlp_3_b;
  386. struct ggml_tensor * mm_model_block_1_block_0_0_w;
  387. struct ggml_tensor * mm_model_block_1_block_0_1_w;
  388. struct ggml_tensor * mm_model_block_1_block_0_1_b;
  389. struct ggml_tensor * mm_model_block_1_block_1_fc1_w;
  390. struct ggml_tensor * mm_model_block_1_block_1_fc1_b;
  391. struct ggml_tensor * mm_model_block_1_block_1_fc2_w;
  392. struct ggml_tensor * mm_model_block_1_block_1_fc2_b;
  393. struct ggml_tensor * mm_model_block_1_block_2_0_w;
  394. struct ggml_tensor * mm_model_block_1_block_2_1_w;
  395. struct ggml_tensor * mm_model_block_1_block_2_1_b;
  396. struct ggml_tensor * mm_model_block_2_block_0_0_w;
  397. struct ggml_tensor * mm_model_block_2_block_0_1_w;
  398. struct ggml_tensor * mm_model_block_2_block_0_1_b;
  399. struct ggml_tensor * mm_model_block_2_block_1_fc1_w;
  400. struct ggml_tensor * mm_model_block_2_block_1_fc1_b;
  401. struct ggml_tensor * mm_model_block_2_block_1_fc2_w;
  402. struct ggml_tensor * mm_model_block_2_block_1_fc2_b;
  403. struct ggml_tensor * mm_model_block_2_block_2_0_w;
  404. struct ggml_tensor * mm_model_block_2_block_2_1_w;
  405. struct ggml_tensor * mm_model_block_2_block_2_1_b;
  406. };
  407. struct clip_ctx {
  408. bool has_text_encoder = false;
  409. bool has_vision_encoder = false;
  410. bool has_llava_projector = false;
  411. struct clip_vision_model vision_model;
  412. projector_type proj_type = PROJECTOR_TYPE_MLP;
  413. float image_mean[3];
  414. float image_std[3];
  415. bool use_gelu = false;
  416. int32_t ftype = 1;
  417. struct gguf_context * ctx_gguf;
  418. struct ggml_context * ctx_data;
  419. std::vector<uint8_t> buf_compute_meta;
  420. // memory buffers to evaluate the model
  421. ggml_backend_buffer_t params_buffer = NULL;
  422. ggml_backend_buffer_t compute_buffer = NULL;
  423. ggml_backend_t backend = NULL;
  424. ggml_gallocr_t compute_alloc = NULL;
  425. };
  426. static ggml_cgraph * clip_image_build_graph(clip_ctx * ctx, const clip_image_f32_batch * imgs) {
  427. if (!ctx->has_vision_encoder) {
  428. printf("This gguf file seems to have no vision encoder\n");
  429. return nullptr;
  430. }
  431. const auto & model = ctx->vision_model;
  432. const auto & hparams = model.hparams;
  433. const int image_size = hparams.image_size;
  434. const int patch_size = hparams.patch_size;
  435. const int num_patches = ((image_size / patch_size) * (image_size / patch_size));
  436. const int num_patches_per_side = image_size / patch_size; GGML_UNUSED(num_patches_per_side);
  437. const int num_positions = num_patches + 1;
  438. const int hidden_size = hparams.hidden_size;
  439. const int n_head = hparams.n_head;
  440. const int d_head = hidden_size / n_head;
  441. const int n_layer = hparams.n_layer;
  442. const float eps = hparams.eps;
  443. const int batch_size = imgs->size;
  444. if (ctx->has_llava_projector) {
  445. GGML_ASSERT(batch_size == 1);
  446. }
  447. struct ggml_init_params params = {
  448. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  449. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  450. /*.no_alloc =*/ true,
  451. };
  452. struct ggml_context * ctx0 = ggml_init(params);
  453. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  454. struct ggml_tensor * inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size, image_size, 3, batch_size);
  455. ggml_set_name(inp_raw, "inp_raw");
  456. ggml_set_input(inp_raw);
  457. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  458. inp = ggml_reshape_3d(ctx0, inp, num_patches, hidden_size, batch_size);
  459. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 0, 2, 3));
  460. // concat class_embeddings and patch_embeddings
  461. struct ggml_tensor * embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size);
  462. ggml_set_name(embeddings, "embeddings");
  463. ggml_set_input(embeddings);
  464. embeddings = ggml_acc(ctx0, embeddings, model.class_embedding,
  465. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], 0);
  466. embeddings = ggml_acc(ctx0, embeddings, inp,
  467. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], model.class_embedding->nb[1]);
  468. struct ggml_tensor * positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions);
  469. ggml_set_name(positions, "positions");
  470. ggml_set_input(positions);
  471. embeddings =
  472. ggml_add(ctx0, embeddings, ggml_get_rows(ctx0, model.position_embeddings, positions));
  473. // pre-layernorm
  474. {
  475. embeddings = ggml_norm(ctx0, embeddings, eps);
  476. ggml_set_name(embeddings, "pre_ln");
  477. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.pre_ln_w), model.pre_ln_b);
  478. }
  479. // loop over layers
  480. for (int il = 0; il < n_layer - 1; il++) {
  481. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  482. //const size_t nb_q_w = model.layers[il].q_w->nb[0];
  483. // layernorm1
  484. {
  485. cur = ggml_norm(ctx0, cur, eps);
  486. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_1_w),
  487. model.layers[il].ln_1_b);
  488. }
  489. // self-attention
  490. {
  491. struct ggml_tensor * Q =
  492. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  493. Q = ggml_scale_inplace(ctx0, Q, 1.0f / sqrt((float)d_head));
  494. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  495. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  496. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  497. struct ggml_tensor * K =
  498. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  499. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  500. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  501. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  502. struct ggml_tensor * V =
  503. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  504. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  505. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  506. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  507. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  508. KQ = ggml_soft_max_inplace(ctx0, KQ);
  509. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  510. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  511. KQV = ggml_cont(ctx0, ggml_permute(ctx0, KQV, 0, 2, 1, 3));
  512. cur = ggml_cpy(ctx0, KQV, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size));
  513. }
  514. // attention output
  515. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  516. // re-add the layer input, e.g., residual
  517. cur = ggml_add(ctx0, cur, embeddings);
  518. embeddings = cur; // embeddings = residual, cur = hidden_states
  519. // layernorm2
  520. {
  521. cur = ggml_norm(ctx0, cur, eps);
  522. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_2_w), model.layers[il].ln_2_b);
  523. }
  524. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  525. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  526. if (ctx->use_gelu) {
  527. cur = ggml_gelu_inplace(ctx0, cur);
  528. } else {
  529. cur = ggml_gelu_quick_inplace(ctx0, cur);
  530. }
  531. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  532. cur = ggml_add(ctx0, cur, model.layers[il].ff_o_b);
  533. // residual 2
  534. cur = ggml_add(ctx0, embeddings, cur);
  535. embeddings = cur;
  536. }
  537. // llava projector
  538. {
  539. embeddings = ggml_reshape_2d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1]);
  540. struct ggml_tensor * patches = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  541. ggml_set_name(patches, "patches");
  542. ggml_set_input(patches);
  543. // shape [1, 576, 1024]
  544. // ne is whcn, ne = [1024, 576, 1, 1]
  545. embeddings = ggml_get_rows(ctx0, embeddings, patches);
  546. // print_tensor_info(embeddings, "embeddings");
  547. // llava projector
  548. if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  549. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  550. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  551. embeddings = ggml_gelu(ctx0, embeddings);
  552. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  553. embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
  554. } else if (ctx->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  555. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  556. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  557. // ggml_tensor_printf(embeddings, "mm_0_w",0,true,false);
  558. // First LayerNorm
  559. embeddings = ggml_norm(ctx0, embeddings, eps);
  560. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_1_w),
  561. model.mm_1_b);
  562. // GELU activation
  563. embeddings = ggml_gelu(ctx0, embeddings);
  564. // Second linear layer
  565. embeddings = ggml_mul_mat(ctx0, model.mm_3_w, embeddings);
  566. embeddings = ggml_add(ctx0, embeddings, model.mm_3_b);
  567. // Second LayerNorm
  568. embeddings = ggml_norm(ctx0, embeddings, eps);
  569. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_4_w),
  570. model.mm_4_b);
  571. }
  572. else if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  573. // MobileVLM projector
  574. int n_patch = 24;
  575. struct ggml_tensor * mlp_1 = ggml_mul_mat(ctx0, model.mm_model_mlp_1_w, embeddings);
  576. mlp_1 = ggml_add(ctx0, mlp_1, model.mm_model_mlp_1_b);
  577. mlp_1 = ggml_gelu(ctx0, mlp_1);
  578. struct ggml_tensor * mlp_3 = ggml_mul_mat(ctx0, model.mm_model_mlp_3_w, mlp_1);
  579. mlp_3 = ggml_add(ctx0, mlp_3, model.mm_model_mlp_3_b);
  580. // mlp_3 shape = [1, 576, 2048], ne = [2048, 576, 1, 1]
  581. // block 1
  582. struct ggml_tensor * block_1 = nullptr;
  583. {
  584. // transpose from [1, 576, 2048] --> [1, 2048, 576] --> [1, 2048, 24, 24]
  585. mlp_3 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_3, 1, 0, 2, 3));
  586. mlp_3 = ggml_reshape_4d(ctx0, mlp_3, n_patch, n_patch, mlp_3->ne[1], mlp_3->ne[2]);
  587. // stride = 1, padding = 1, bias is nullptr
  588. block_1 = ggml_conv_depthwise_2d(ctx0, model.mm_model_block_1_block_0_0_w, mlp_3, 1, 1, 1, 1, 1, 1);
  589. // layer norm
  590. // // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  591. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  592. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  593. block_1 = ggml_norm(ctx0, block_1, eps);
  594. 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);
  595. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  596. // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  597. // hardswish
  598. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  599. 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);
  600. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  601. // pointwise conv
  602. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  603. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc1_w, block_1);
  604. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc1_b);
  605. block_1 = ggml_relu(ctx0, block_1);
  606. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc2_w, block_1);
  607. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc2_b);
  608. block_1 = ggml_hardsigmoid(ctx0, block_1);
  609. // block_1_hw shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1], block_1 shape = [1, 2048], ne = [2048, 1, 1, 1]
  610. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  611. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  612. int w = block_1->ne[0], h = block_1->ne[1];
  613. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  614. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  615. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  616. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_2_0_w, block_1);
  617. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  618. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  619. block_1 = ggml_norm(ctx0, block_1, eps);
  620. 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);
  621. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  622. // block1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  623. // residual
  624. block_1 = ggml_add(ctx0, mlp_3, block_1);
  625. }
  626. // block_2
  627. {
  628. // stride = 2
  629. block_1 = ggml_conv_depthwise_2d(ctx0, model.mm_model_block_2_block_0_0_w, block_1, 2, 2, 1, 1, 1, 1);
  630. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  631. // layer norm
  632. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  633. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  634. block_1 = ggml_norm(ctx0, block_1, eps);
  635. 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);
  636. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  637. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  638. // hardswish
  639. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  640. // not sure the parameters is right for globalAvgPooling
  641. 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);
  642. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  643. // pointwise conv
  644. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  645. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc1_w, block_1);
  646. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc1_b);
  647. block_1 = ggml_relu(ctx0, block_1);
  648. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc2_w, block_1);
  649. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc2_b);
  650. block_1 = ggml_hardsigmoid(ctx0, block_1);
  651. // 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]
  652. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  653. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  654. int w = block_1->ne[0], h = block_1->ne[1];
  655. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  656. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  657. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  658. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_2_0_w, block_1);
  659. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  660. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  661. block_1 = ggml_norm(ctx0, block_1, eps);
  662. 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);
  663. block_1 = ggml_reshape_3d(ctx0, block_1, block_1->ne[0], block_1->ne[1] * block_1->ne[2], block_1->ne[3]);
  664. // block_1 shape = [1, 144, 2048], ne = [2048, 144, 1]
  665. }
  666. embeddings = block_1;
  667. }
  668. else {
  669. GGML_ASSERT(false);
  670. }
  671. }
  672. // build the graph
  673. ggml_build_forward_expand(gf, embeddings);
  674. ggml_free(ctx0);
  675. return gf;
  676. }
  677. // read and create ggml_context containing the tensors and their data
  678. struct clip_ctx * clip_model_load(const char * fname, const int verbosity = 1) {
  679. struct ggml_context * meta = NULL;
  680. struct gguf_init_params params = {
  681. /*.no_alloc = */ true,
  682. /*.ctx = */ &meta,
  683. };
  684. struct gguf_context * ctx = gguf_init_from_file(fname, params);
  685. if (!ctx) {
  686. throw std::runtime_error(format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  687. }
  688. if (verbosity >= 1) {
  689. const int n_tensors = gguf_get_n_tensors(ctx);
  690. const int n_kv = gguf_get_n_kv(ctx);
  691. const int ftype = get_u32(ctx, KEY_FTYPE);
  692. const std::string ftype_str = get_ftype(ftype);
  693. const int idx_desc = get_key_idx(ctx, KEY_DESCRIPTION);
  694. const std::string description = gguf_get_val_str(ctx, idx_desc);
  695. const int idx_name = gguf_find_key(ctx, KEY_NAME);
  696. if (idx_name != -1) { // make name optional temporarily as some of the uploaded models missing it due to a bug
  697. const std::string name = gguf_get_val_str(ctx, idx_name);
  698. printf("%s: model name: %s\n", __func__, name.c_str());
  699. }
  700. printf("%s: description: %s\n", __func__, description.c_str());
  701. printf("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx));
  702. printf("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx));
  703. printf("%s: n_tensors: %d\n", __func__, n_tensors);
  704. printf("%s: n_kv: %d\n", __func__, n_kv);
  705. printf("%s: ftype: %s\n", __func__, ftype_str.c_str());
  706. printf("\n");
  707. }
  708. const int n_tensors = gguf_get_n_tensors(ctx);
  709. // kv
  710. const int n_kv = gguf_get_n_kv(ctx);
  711. printf("%s: loaded meta data with %d key-value pairs and %d tensors from %s\n",
  712. __func__, n_kv, n_tensors, fname);
  713. {
  714. std::map<enum ggml_type, uint32_t> n_type;
  715. for (int i = 0; i < n_tensors; i++) {
  716. enum ggml_type type = gguf_get_tensor_type(ctx, i);
  717. n_type[type]++;
  718. }
  719. printf("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  720. for (int i = 0; i < n_kv; i++) {
  721. const char * name = gguf_get_key(ctx, i);
  722. const enum gguf_type type = gguf_get_kv_type(ctx, i);
  723. const std::string type_name =
  724. type == GGUF_TYPE_ARRAY
  725. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx, i)), gguf_get_arr_n(ctx, i))
  726. : gguf_type_name(type);
  727. std::string value = gguf_kv_to_str(ctx, i);
  728. const size_t MAX_VALUE_LEN = 40;
  729. if (value.size() > MAX_VALUE_LEN) {
  730. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  731. }
  732. replace_all(value, "\n", "\\n");
  733. printf("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  734. }
  735. // print type counts
  736. for (auto & kv : n_type) {
  737. if (kv.second == 0) {
  738. continue;
  739. }
  740. printf("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  741. }
  742. }
  743. // data
  744. size_t model_size = 0;
  745. {
  746. for (int i = 0; i < n_tensors; ++i) {
  747. const char * name = gguf_get_tensor_name(ctx, i);
  748. const size_t offset = gguf_get_tensor_offset(ctx, i);
  749. enum ggml_type type = gguf_get_tensor_type(ctx, i);
  750. struct ggml_tensor * cur = ggml_get_tensor(meta, name);
  751. size_t tensor_size = ggml_nbytes(cur);
  752. model_size += tensor_size;
  753. if (verbosity >= 3) {
  754. printf("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu, shape:[%" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "], type = %s\n",
  755. __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));
  756. }
  757. }
  758. }
  759. clip_ctx * new_clip = new clip_ctx;
  760. // update projector type
  761. {
  762. int idx = gguf_find_key(ctx, KEY_PROJ_TYPE);
  763. if (idx != -1) {
  764. const std::string proj_type = gguf_get_val_str(ctx, idx);
  765. new_clip->proj_type = clip_projector_type_from_string(proj_type);
  766. } else {
  767. new_clip->proj_type = PROJECTOR_TYPE_MLP;
  768. }
  769. if (new_clip->proj_type == PROJECTOR_TYPE_MLP) {
  770. if (gguf_find_tensor(ctx, format(TN_LLAVA_PROJ, 3, "weight").c_str()) != -1) {
  771. new_clip->proj_type = PROJECTOR_TYPE_MLP_NORM;
  772. }
  773. }
  774. }
  775. #ifdef GGML_USE_CUBLAS
  776. new_clip->backend = ggml_backend_cuda_init(0);
  777. printf("%s: CLIP using CUDA backend\n", __func__);
  778. #endif
  779. #ifdef GGML_USE_METAL
  780. new_clip->backend = ggml_backend_metal_init();
  781. printf("%s: CLIP using Metal backend\n", __func__);
  782. #endif
  783. if (!new_clip->backend) {
  784. new_clip->backend = ggml_backend_cpu_init();
  785. printf("%s: CLIP using CPU backend\n", __func__);
  786. }
  787. // model size and capabilities
  788. {
  789. int idx = get_key_idx(ctx, KEY_HAS_TEXT_ENC);
  790. new_clip->has_text_encoder = gguf_get_val_bool(ctx, idx);
  791. idx = get_key_idx(ctx, KEY_HAS_VIS_ENC);
  792. new_clip->has_vision_encoder = gguf_get_val_bool(ctx, idx);
  793. idx = gguf_find_key(ctx, KEY_HAS_LLAVA_PROJ);
  794. if (idx != -1) {
  795. new_clip->has_llava_projector = gguf_get_val_bool(ctx, idx);
  796. }
  797. GGML_ASSERT(new_clip->has_llava_projector); // see monatis/clip.cpp for image and/or text encoding for semantic search
  798. GGML_ASSERT(new_clip->has_vision_encoder);
  799. GGML_ASSERT(!new_clip->has_text_encoder);
  800. idx = get_key_idx(ctx, KEY_USE_GELU);
  801. new_clip->use_gelu = gguf_get_val_bool(ctx, idx);
  802. if (verbosity >= 1) {
  803. printf("%s: text_encoder: %d\n", __func__, new_clip->has_text_encoder);
  804. printf("%s: vision_encoder: %d\n", __func__, new_clip->has_vision_encoder);
  805. printf("%s: llava_projector: %d\n", __func__, new_clip->has_llava_projector);
  806. printf("%s: model size: %.2f MB\n", __func__, model_size / 1024.0 / 1024.0);
  807. printf("%s: metadata size: %.2f MB\n", __func__, ggml_get_mem_size(meta) / 1024.0 / 1024.0);
  808. }
  809. }
  810. printf("%s: params backend buffer size = % 6.2f MB (%i tensors)\n", __func__, model_size / (1024.0 * 1024.0), n_tensors);
  811. // load tensors
  812. {
  813. std::vector<uint8_t> read_buf;
  814. struct ggml_init_params params = {
  815. /*.mem_size =*/ (n_tensors + 1) * ggml_tensor_overhead(),
  816. /*.mem_buffer =*/ NULL,
  817. /*.no_alloc =*/ true,
  818. };
  819. new_clip->ctx_data = ggml_init(params);
  820. if (!new_clip->ctx_data) {
  821. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  822. clip_free(new_clip);
  823. return nullptr;
  824. }
  825. auto fin = std::ifstream(fname, std::ios::binary);
  826. if (!fin) {
  827. printf("cannot open model file for loading tensors\n");
  828. clip_free(new_clip);
  829. return nullptr;
  830. }
  831. // add tensors to context
  832. for (int i = 0; i < n_tensors; ++i) {
  833. const char * name = gguf_get_tensor_name(ctx, i);
  834. struct ggml_tensor * t = ggml_get_tensor(meta, name);
  835. struct ggml_tensor * cur = ggml_dup_tensor(new_clip->ctx_data, t);
  836. ggml_set_name(cur, name);
  837. }
  838. // alloc memory and offload data
  839. new_clip->params_buffer = ggml_backend_alloc_ctx_tensors(new_clip->ctx_data, new_clip->backend);
  840. for (int i = 0; i < n_tensors; ++i) {
  841. const char * name = gguf_get_tensor_name(ctx, i);
  842. struct ggml_tensor * cur = ggml_get_tensor(new_clip->ctx_data, name);
  843. const size_t offset = gguf_get_data_offset(ctx) + gguf_get_tensor_offset(ctx, i);
  844. fin.seekg(offset, std::ios::beg);
  845. if (!fin) {
  846. printf("%s: failed to seek for tensor %s\n", __func__, name);
  847. clip_free(new_clip);
  848. return nullptr;
  849. }
  850. int num_bytes = ggml_nbytes(cur);
  851. if (ggml_backend_buffer_is_host(new_clip->params_buffer)) {
  852. // for the CPU and Metal backend, we can read directly into the tensor
  853. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  854. } else {
  855. // read into a temporary buffer first, then copy to device memory
  856. read_buf.resize(num_bytes);
  857. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  858. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  859. }
  860. }
  861. fin.close();
  862. }
  863. // vision model
  864. if (new_clip->has_vision_encoder) {
  865. // load vision model
  866. auto & vision_model = new_clip->vision_model;
  867. auto & hparams = vision_model.hparams;
  868. hparams.hidden_size = get_u32(ctx, format(KEY_N_EMBD, "vision"));
  869. hparams.n_head = get_u32(ctx, format(KEY_N_HEAD, "vision"));
  870. hparams.n_intermediate = get_u32(ctx, format(KEY_N_FF, "vision"));
  871. hparams.n_layer = get_u32(ctx, format(KEY_N_BLOCK, "vision"));
  872. hparams.image_size = get_u32(ctx, KEY_IMAGE_SIZE);
  873. hparams.patch_size = get_u32(ctx, KEY_PATCH_SIZE);
  874. hparams.projection_dim = get_u32(ctx, format(KEY_PROJ_DIM, "vision"));
  875. hparams.eps = get_f32(ctx, format(KEY_LAYER_NORM_EPS, "vision"));
  876. try {
  877. int idx = get_key_idx(ctx, KEY_IMAGE_GRID_PINPOINTS);
  878. int n = gguf_get_arr_n(ctx, idx);
  879. const int32_t * pinpoints = (const int32_t *)gguf_get_arr_data(ctx, idx);
  880. for (int i = 0; i < 32 && i < n && pinpoints[i] != 0; ++i) {
  881. hparams.image_grid_pinpoints[i] = pinpoints[i];
  882. }
  883. if (n < 32)
  884. hparams.image_grid_pinpoints[n] = 0;
  885. } catch (std::runtime_error & e) {
  886. hparams.image_grid_pinpoints[0]=0;
  887. }
  888. try {
  889. int idx = get_key_idx(ctx, KEY_MM_PATCH_MERGE_TYPE);
  890. strcpy(hparams.mm_patch_merge_type, gguf_get_val_str(ctx, idx));
  891. } catch (std::runtime_error & e) {
  892. strcpy(hparams.mm_patch_merge_type, "flat");
  893. }
  894. try {
  895. hparams.image_crop_resolution = get_u32(ctx, KEY_IMAGE_CROP_RESOLUTION); // llava-1.6
  896. } catch(const std::exception& e) {
  897. hparams.image_crop_resolution = hparams.image_size;
  898. }
  899. int idx_mean = get_key_idx(ctx, KEY_IMAGE_MEAN);
  900. int idx_std = get_key_idx(ctx, KEY_IMAGE_STD);
  901. const float * mean_data = (const float *)gguf_get_arr_data(ctx, idx_mean);
  902. const float * std_data = (const float *)gguf_get_arr_data(ctx, idx_std);
  903. for (int i = 0; i < 3; ++i) {
  904. new_clip->image_mean[i] = mean_data[i];
  905. new_clip->image_std[i] = std_data[i];
  906. }
  907. if (verbosity >= 2) {
  908. printf("\n%s: vision model hparams\n", __func__);
  909. printf("image_size %d\n", hparams.image_size);
  910. printf("patch_size %d\n", hparams.patch_size);
  911. printf("v_hidden_size %d\n", hparams.hidden_size);
  912. printf("v_n_intermediate %d\n", hparams.n_intermediate);
  913. printf("v_projection_dim %d\n", hparams.projection_dim);
  914. printf("v_n_head %d\n", hparams.n_head);
  915. printf("v_n_layer %d\n", hparams.n_layer);
  916. printf("v_eps %f\n", hparams.eps);
  917. printf("v_image_mean %f %f %f\n", new_clip->image_mean[0], new_clip->image_mean[1], new_clip->image_mean[2]);
  918. printf("v_image_std %f %f %f\n", new_clip->image_std[0], new_clip->image_std[1], new_clip->image_std[2]);
  919. printf("v_image_grid_pinpoints: ");
  920. for (int i = 0; i < 32 && (hparams.image_grid_pinpoints[i] != 0); ++i) {
  921. printf("%d ", hparams.image_grid_pinpoints[i]);
  922. }
  923. printf("\n");
  924. printf("v_mm_patch_merge_type: %s\n", hparams.mm_patch_merge_type);
  925. }
  926. try {
  927. vision_model.patch_embeddings = get_tensor(new_clip->ctx_data, TN_PATCH_EMBD);
  928. vision_model.class_embedding = get_tensor(new_clip->ctx_data, TN_CLASS_EMBD);
  929. vision_model.position_embeddings = get_tensor(new_clip->ctx_data, format(TN_POS_EMBD, "v"));
  930. vision_model.pre_ln_w = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "weight"));
  931. vision_model.pre_ln_b = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "bias"));
  932. } catch(const std::exception& e) {
  933. fprintf(stderr, "%s: failed to load vision model tensors\n", __func__);
  934. }
  935. // LLaVA projection
  936. if (new_clip->proj_type == PROJECTOR_TYPE_MLP || new_clip->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  937. vision_model.mm_0_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "weight"));
  938. vision_model.mm_0_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "bias"));
  939. try {
  940. // Yi-type llava
  941. vision_model.mm_1_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 1, "weight"));
  942. vision_model.mm_1_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 1, "bias"));
  943. } catch (std::runtime_error & e) { }
  944. try {
  945. // missing in Yi-type llava
  946. vision_model.mm_2_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "weight"));
  947. vision_model.mm_2_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "bias"));
  948. } catch (std::runtime_error & e) { }
  949. try {
  950. // Yi-type llava
  951. vision_model.mm_3_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 3, "weight"));
  952. vision_model.mm_3_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 3, "bias"));
  953. } catch (std::runtime_error & e) { }
  954. try {
  955. // Yi-type llava
  956. vision_model.mm_4_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 4, "weight"));
  957. vision_model.mm_4_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 4, "bias"));
  958. } catch (std::runtime_error & e) { }
  959. try {
  960. vision_model.image_newline = get_tensor(new_clip->ctx_data, TN_IMAGE_NEWLINE);
  961. // fprintf(stderr, "%s: image_newline tensor (llava-1.6) found\n", __func__);
  962. } catch (std::runtime_error & e) { }
  963. } else if (new_clip->proj_type == PROJECTOR_TYPE_LDP) {
  964. // MobileVLM projection
  965. vision_model.mm_model_mlp_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 1, "weight"));
  966. vision_model.mm_model_mlp_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 1, "bias"));
  967. vision_model.mm_model_mlp_3_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 3, "weight"));
  968. vision_model.mm_model_mlp_3_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 3, "bias"));
  969. 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"));
  970. 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"));
  971. 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"));
  972. 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"));
  973. 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"));
  974. 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"));
  975. 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"));
  976. 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"));
  977. 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"));
  978. 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"));
  979. 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"));
  980. 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"));
  981. 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"));
  982. 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"));
  983. 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"));
  984. 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"));
  985. 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"));
  986. 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"));
  987. 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"));
  988. 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"));
  989. } else {
  990. std::string proj_type = PROJECTOR_TYPE_NAMES[new_clip->proj_type];
  991. throw std::runtime_error(format("%s: don't support projector with: %s currently\n", __func__, proj_type.c_str()));
  992. }
  993. vision_model.layers.resize(hparams.n_layer);
  994. for (int il = 0; il < hparams.n_layer; ++il) {
  995. auto & layer = vision_model.layers[il];
  996. layer.k_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "weight"));
  997. layer.q_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "weight"));
  998. layer.v_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "weight"));
  999. layer.o_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "weight"));
  1000. layer.ln_1_w = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "weight"));
  1001. layer.ln_2_w = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "weight"));
  1002. layer.ff_i_w = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "weight"));
  1003. layer.ff_o_w = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "weight"));
  1004. layer.k_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "bias"));
  1005. layer.q_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "bias"));
  1006. layer.v_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "bias"));
  1007. layer.o_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "bias"));
  1008. layer.ln_1_b = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "bias"));
  1009. layer.ln_2_b = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "bias"));
  1010. layer.ff_i_b = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "bias"));
  1011. layer.ff_o_b = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "bias"));
  1012. }
  1013. }
  1014. ggml_free(meta);
  1015. new_clip->ctx_gguf = ctx;
  1016. // measure mem requirement and allocate
  1017. {
  1018. new_clip->buf_compute_meta.resize(GGML_DEFAULT_GRAPH_SIZE * ggml_tensor_overhead() + ggml_graph_overhead());
  1019. new_clip->compute_alloc = ggml_gallocr_new(ggml_backend_get_default_buffer_type(new_clip->backend));
  1020. clip_image_f32_batch batch;
  1021. batch.size = 1;
  1022. ggml_cgraph * gf = clip_image_build_graph(new_clip, &batch);
  1023. ggml_gallocr_reserve(new_clip->compute_alloc, gf);
  1024. size_t compute_memory_buffer_size = ggml_gallocr_get_buffer_size(new_clip->compute_alloc, 0);
  1025. printf("%s: compute allocated memory: %.2f MB\n", __func__, compute_memory_buffer_size /1024.0/1024.0);
  1026. }
  1027. return new_clip;
  1028. }
  1029. struct clip_image_u8 * clip_image_u8_init() {
  1030. return new clip_image_u8();
  1031. }
  1032. struct clip_image_f32 * clip_image_f32_init() {
  1033. return new clip_image_f32();
  1034. }
  1035. void clip_image_u8_free(struct clip_image_u8 * img) { delete img; }
  1036. void clip_image_f32_free(struct clip_image_f32 * img) { delete img; }
  1037. void clip_image_u8_batch_free(struct clip_image_u8_batch & batch) {
  1038. if (batch.size > 0) {
  1039. delete[] batch.data;
  1040. batch.size = 0;
  1041. }
  1042. }
  1043. void clip_image_f32_batch_free(struct clip_image_f32_batch & batch) {
  1044. if (batch.size > 0) {
  1045. delete[] batch.data;
  1046. batch.size = 0;
  1047. }
  1048. }
  1049. static void build_clip_img_from_data(const stbi_uc * data, int nx, int ny, clip_image_u8 * img) {
  1050. img->nx = nx;
  1051. img->ny = ny;
  1052. img->buf.resize(3 * nx * ny);
  1053. memcpy(img->buf.data(), data, img->buf.size());
  1054. }
  1055. bool clip_image_load_from_file(const char * fname, clip_image_u8 * img) {
  1056. int nx, ny, nc;
  1057. auto * data = stbi_load(fname, &nx, &ny, &nc, 3);
  1058. if (!data) {
  1059. fprintf(stderr, "%s: failed to load image '%s'\n", __func__, fname);
  1060. return false;
  1061. }
  1062. build_clip_img_from_data(data, nx, ny, img);
  1063. stbi_image_free(data);
  1064. return true;
  1065. }
  1066. bool clip_image_load_from_bytes(const unsigned char * bytes, size_t bytes_length, struct clip_image_u8 * img) {
  1067. int nx, ny, nc;
  1068. auto * data = stbi_load_from_memory(bytes, bytes_length, &nx, &ny, &nc, 3);
  1069. if (!data) {
  1070. fprintf(stderr, "%s: failed to decode image bytes\n", __func__);
  1071. return false;
  1072. }
  1073. build_clip_img_from_data(data, nx, ny, img);
  1074. stbi_image_free(data);
  1075. return true;
  1076. }
  1077. // Linear interpolation between two points
  1078. inline float lerp(float s, float e, float t) {
  1079. return s + (e - s) * t;
  1080. }
  1081. // Bilinear resize function
  1082. static void bilinear_resize(const clip_image_u8& src, clip_image_u8& dst, int target_width, int target_height) {
  1083. dst.nx = target_width;
  1084. dst.ny = target_height;
  1085. dst.buf.resize(3 * target_width * target_height);
  1086. float x_ratio = static_cast<float>(src.nx - 1) / target_width;
  1087. float y_ratio = static_cast<float>(src.ny - 1) / target_height;
  1088. for (int y = 0; y < target_height; y++) {
  1089. for (int x = 0; x < target_width; x++) {
  1090. float px = x_ratio * x;
  1091. float py = y_ratio * y;
  1092. int x_floor = static_cast<int>(px);
  1093. int y_floor = static_cast<int>(py);
  1094. float x_lerp = px - x_floor;
  1095. float y_lerp = py - y_floor;
  1096. for (int c = 0; c < 3; c++) {
  1097. float top = lerp(
  1098. static_cast<float>(src.buf[3 * (y_floor * src.nx + x_floor) + c]),
  1099. static_cast<float>(src.buf[3 * (y_floor * src.nx + (x_floor + 1)) + c]),
  1100. x_lerp
  1101. );
  1102. float bottom = lerp(
  1103. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + x_floor) + c]),
  1104. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + (x_floor + 1)) + c]),
  1105. x_lerp
  1106. );
  1107. dst.buf[3 * (y * target_width + x) + c] = static_cast<uint8_t>(lerp(top, bottom, y_lerp));
  1108. }
  1109. }
  1110. }
  1111. }
  1112. // Normalize image to float32 - careful with pytorch .to(model.device, dtype=torch.float16) - this sometimes reduces precision (32>16>32), sometimes not
  1113. static void normalize_image_u8_to_f32(const clip_image_u8* src, clip_image_f32* dst, const float mean[3], const float std[3]) {
  1114. dst->nx = src->nx;
  1115. dst->ny = src->ny;
  1116. dst->buf.resize(src->buf.size());
  1117. for (size_t i = 0; i < src->buf.size(); ++i) {
  1118. int c = i % 3; // rgb
  1119. dst->buf[i] = (static_cast<float>(src->buf[i]) / 255.0f - mean[c]) / std[c];
  1120. }
  1121. }
  1122. inline float clip(float x, float lower, float upper) {
  1123. return std::max(lower, std::min(x, upper));
  1124. }
  1125. static bool bicubic_resize(const clip_image_u8 &img, clip_image_u8 &dst, int target_width, int target_height) {
  1126. const int nx = img.nx;
  1127. const int ny = img.ny;
  1128. dst.nx = target_width;
  1129. dst.ny = target_height;
  1130. dst.buf.resize(3 * target_width * target_height);
  1131. float Cc;
  1132. float C[5];
  1133. float d0, d2, d3, a0, a1, a2, a3;
  1134. int i, j, k, jj;
  1135. int x, y;
  1136. float dx, dy;
  1137. float tx, ty;
  1138. tx = (float)nx / (float)target_width;
  1139. ty = (float)ny / (float)target_height;
  1140. // Bicubic interpolation; adapted from ViT.cpp, inspired from :
  1141. // -> https://github.com/yglukhov/bicubic-interpolation-image-processing/blob/master/libimage.c#L36
  1142. // -> https://en.wikipedia.org/wiki/Bicubic_interpolation
  1143. for (i = 0; i < target_height; i++) {
  1144. for (j = 0; j < target_width; j++) {
  1145. x = (int)(tx * j);
  1146. y = (int)(ty * i);
  1147. dx = tx * j - x;
  1148. dy = ty * i - y;
  1149. for (k = 0; k < 3; k++) {
  1150. for (jj = 0; jj <= 3; jj++) {
  1151. d0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x - 1, 0, nx - 1)) * 3 + k] - img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  1152. d2 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x + 1, 0, nx - 1)) * 3 + k] - img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  1153. d3 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x + 2, 0, nx - 1)) * 3 + k] - img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  1154. a0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  1155. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  1156. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  1157. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  1158. C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx;
  1159. d0 = C[0] - C[1];
  1160. d2 = C[2] - C[1];
  1161. d3 = C[3] - C[1];
  1162. a0 = C[1];
  1163. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  1164. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  1165. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  1166. Cc = a0 + a1 * dy + a2 * dy * dy + a3 * dy * dy * dy;
  1167. const uint8_t Cc2 = std::min(std::max(std::round(Cc), 0.0f), 255.0f);
  1168. dst.buf[(i * target_width + j) * 3 + k] = float(Cc2);
  1169. }
  1170. }
  1171. }
  1172. }
  1173. return true;
  1174. }
  1175. // llava-1.6 type of resize_and_pad (black)
  1176. static void resize_and_pad_image(const clip_image_u8& image, clip_image_u8 &image_output, const std::pair<int, int>& target_resolution) {
  1177. int target_width = target_resolution.first;
  1178. int target_height = target_resolution.second;
  1179. float scale_w = static_cast<float>(target_width) / image.nx;
  1180. float scale_h = static_cast<float>(target_height) / image.ny;
  1181. int new_width, new_height;
  1182. if (scale_w < scale_h) {
  1183. new_width = target_width;
  1184. new_height = std::min(static_cast<int>(std::ceil(image.ny * scale_w)), target_height);
  1185. } else {
  1186. new_height = target_height;
  1187. new_width = std::min(static_cast<int>(std::ceil(image.nx * scale_h)), target_width);
  1188. }
  1189. clip_image_u8 resized_image;
  1190. // bilinear_resize(image, resized_image, new_width, new_height);
  1191. bicubic_resize(image, resized_image, new_width, new_height);
  1192. clip_image_u8 padded_image;
  1193. padded_image.nx = target_width;
  1194. padded_image.ny = target_height;
  1195. padded_image.buf.resize(3 * target_width * target_height, 0); // Initialize with black
  1196. // Calculate padding offsets
  1197. int pad_x = (target_width - new_width) / 2;
  1198. int pad_y = (target_height - new_height) / 2;
  1199. // Copy the resized image into the center of the padded buffer
  1200. for (int y = 0; y < new_height; ++y) {
  1201. for (int x = 0; x < new_width; ++x) {
  1202. for (int c = 0; c < 3; ++c) {
  1203. padded_image.buf[3 * ((y + pad_y) * target_width + (x + pad_x)) + c] = resized_image.buf[3 * (y * new_width + x) + c];
  1204. }
  1205. }
  1206. }
  1207. image_output = std::move(padded_image);
  1208. }
  1209. /**
  1210. * Selects the best resolution from a list of possible resolutions based on the original size.
  1211. *
  1212. * @param original_size The original size of the image in the format (width, height).
  1213. * @param possible_resolutions A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
  1214. * @return The best fit resolution in the format (width, height).
  1215. */
  1216. static std::pair<int, int> select_best_resolution(const std::pair<int, int> & original_size, const std::vector<std::pair<int, int>> & possible_resolutions) {
  1217. int original_width = original_size.first;
  1218. int original_height = original_size.second;
  1219. std::pair<int, int> best_fit;
  1220. int max_effective_resolution = 0;
  1221. int min_wasted_resolution = std::numeric_limits<int>::max();
  1222. for (const auto& resolution : possible_resolutions) {
  1223. int width = resolution.first;
  1224. int height = resolution.second;
  1225. float scale = std::min(static_cast<float>(width) / original_width, static_cast<float>(height) / original_height);
  1226. int downscaled_width = static_cast<int>(original_width * scale);
  1227. int downscaled_height = static_cast<int>(original_height * scale);
  1228. int effective_resolution = std::min(downscaled_width * downscaled_height, original_width * original_height);
  1229. int wasted_resolution = (width * height) - effective_resolution;
  1230. // fprintf(stderr, "resolution: %d %d, scale: %f, downscaled: %d %d, effective: %d, wasted: %d\n", width, height, scale, downscaled_width, downscaled_height, effective_resolution, wasted_resolution);
  1231. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_resolution < min_wasted_resolution)) {
  1232. max_effective_resolution = effective_resolution;
  1233. min_wasted_resolution = wasted_resolution;
  1234. best_fit = resolution;
  1235. }
  1236. }
  1237. return best_fit;
  1238. }
  1239. static std::vector<clip_image_u8*> divide_to_patches_u8(const clip_image_u8 & image, int patch_size) {
  1240. std::vector<clip_image_u8*> patches;
  1241. int width = image.nx;
  1242. int height = image.ny;
  1243. for (int i = 0; i < height; i += patch_size) {
  1244. for (int j = 0; j < width; j += patch_size) {
  1245. clip_image_u8 *patch = clip_image_u8_init();
  1246. patch->nx = std::min(patch_size, width - j);
  1247. patch->ny = std::min(patch_size, height - i);
  1248. patch->buf.resize(3 * patch->nx * patch->ny);
  1249. for (int y = 0; y < patch->ny; ++y) {
  1250. for (int x = 0; x < patch->nx; ++x) {
  1251. for (int c = 0; c < 3; ++c) {
  1252. patch->buf[3 * (y * patch->nx + x) + c] = image.buf[3 * ((i + y) * width + (j + x)) + c];
  1253. }
  1254. }
  1255. }
  1256. patches.push_back(patch);
  1257. }
  1258. }
  1259. return patches;
  1260. }
  1261. // returns the normalized float tensor for llava-1.5, for spatial_unpad with anyres processing for llava-1.6 it returns the normalized image patch tensors as a vector
  1262. // res_imgs memory is being allocated here, previous allocations will be freed if found
  1263. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, clip_image_f32_batch & res_imgs) {
  1264. bool pad_to_square = true;
  1265. if (!ctx->has_vision_encoder) {
  1266. printf("This gguf file seems to have no vision encoder\n");
  1267. return false;
  1268. }
  1269. auto & params = ctx->vision_model.hparams;
  1270. // The model config actually contains all we need to decide on how to preprocess, here we automatically switch to the new llava-1.6 preprocessing
  1271. if (strcmp(params.mm_patch_merge_type, "spatial_unpad") == 0) {
  1272. pad_to_square = false;
  1273. }
  1274. // free the previous res_imgs if any set
  1275. if (res_imgs.size > 0) {
  1276. clip_image_f32_batch_free(res_imgs);
  1277. }
  1278. res_imgs.data = nullptr;
  1279. res_imgs.size = 0;
  1280. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  1281. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  1282. clip_image_u8 * temp = clip_image_u8_init(); // we will keep the input image data here temporarily
  1283. if (pad_to_square && img->nx != img->ny) {
  1284. int longer_side = std::max(img->nx, img->ny);
  1285. temp->nx = longer_side;
  1286. temp->ny = longer_side;
  1287. temp->buf.resize(3 * longer_side * longer_side);
  1288. const uint8_t bc[3] = {122, 116, 104}; // background color in RGB from LLaVA (this is the mean rgb color * 255)
  1289. // fill with background color
  1290. for (size_t i = 0; i < temp->buf.size(); i++) {
  1291. temp->buf[i] = bc[i % 3];
  1292. }
  1293. // copy from the input image
  1294. for (int y = 0; y < img->ny; y++) {
  1295. for (int x = 0; x < img->nx; x++) {
  1296. const int i = 3 * (y * img->nx + x);
  1297. const int j = 3 * (y * temp->nx + x);
  1298. temp->buf[j] = img->buf[i];
  1299. temp->buf[j+1] = img->buf[i+1];
  1300. temp->buf[j+2] = img->buf[i+2];
  1301. }
  1302. }
  1303. } else {
  1304. if (params.image_grid_pinpoints[0] != 0) {
  1305. // "spatial_unpad" with "anyres" processing for llava-1.6
  1306. std::vector<std::pair<int, int>> possible_resolutions;
  1307. for (int i = 0; i < 32 && params.image_grid_pinpoints[i] != 0; i+=2) {
  1308. possible_resolutions.push_back({params.image_grid_pinpoints[i], params.image_grid_pinpoints[i+1]});
  1309. }
  1310. std::pair<int, int> best_resolution = select_best_resolution({img->nx, img->ny}, possible_resolutions);
  1311. // clip_image_save_to_bmp(*img, "input.bmp");
  1312. resize_and_pad_image(*img, *temp, best_resolution); // we do not pad with mean-bg color anymore in llava-1.6
  1313. // clip_image_save_to_bmp(*temp, "resized.bmp");
  1314. // visually verify normalized image:
  1315. // normalize_image_u8_to_f32(*temp, *res, ctx->image_mean, ctx->image_std);
  1316. // {
  1317. // clip_image_u8 * temp2 = clip_image_u8_init();
  1318. // clip_image_convert_f32_to_u8(*res, *temp2);
  1319. // clip_image_save_to_bmp(*temp2, "resized_normalized_f32.bmp");
  1320. // clip_image_u8_free(temp2);
  1321. // }
  1322. std::vector<clip_image_u8 *> patches = divide_to_patches_u8(*temp, params.image_size); // prepare spatial sorted main patches of image_size each (336 in llava-1.6)
  1323. clip_image_u8 *image_original_resize = clip_image_u8_init();
  1324. // bilinear_resize(*img, *image_original_resize, params.image_size, params.image_size); // in python this is "shortest_edge", but all CLIP are square
  1325. bicubic_resize(*img, *image_original_resize, params.image_size, params.image_size); // in python this is "shortest_edge", but all CLIP are square
  1326. patches.insert(patches.begin(), image_original_resize);
  1327. // clip_image_f32_batch_init(patches.size());
  1328. res_imgs.size = patches.size();
  1329. res_imgs.data = new clip_image_f32[res_imgs.size];
  1330. int num=0;
  1331. for (auto& patch : patches) {
  1332. normalize_image_u8_to_f32(patch, &res_imgs.data[num], ctx->image_mean, ctx->image_std);
  1333. num++;
  1334. }
  1335. for (size_t i = 0; i < patches.size(); i++) {
  1336. // printf("patch %d: %d %d\n", i, patches[i]->nx, patches[i]->ny);
  1337. clip_image_u8_free(patches[i]);
  1338. }
  1339. clip_image_u8_free(temp);
  1340. return true;
  1341. } else {
  1342. temp->nx = img->nx;
  1343. temp->ny = img->ny;
  1344. temp->buf.resize(img->buf.size());
  1345. memcpy(temp->buf.data(), img->buf.data(), temp->buf.size());
  1346. }
  1347. }
  1348. const int nx = temp->nx;
  1349. const int ny = temp->ny;
  1350. // clip_image_save_to_bmp(*temp, "resized_vanilla.bmp");
  1351. const int nx2 = ctx->vision_model.hparams.image_size;
  1352. const int ny2 = ctx->vision_model.hparams.image_size;
  1353. clip_image_f32 * res = clip_image_f32_init();
  1354. res->nx = nx2;
  1355. res->ny = ny2;
  1356. res->buf.resize(3 * nx2 * ny2);
  1357. const float scale = std::max(nx, ny) / (float)ctx->vision_model.hparams.image_size;
  1358. const int nx3 = int(nx / scale + 0.5f);
  1359. const int ny3 = int(ny / scale + 0.5f);
  1360. const auto & m3 = ctx->image_mean; // {0.48145466f, 0.4578275f, 0.40821073f};
  1361. const auto & s3 = ctx->image_std; // {0.26862954f, 0.26130258f, 0.27577711f};
  1362. for (int y = 0; y < ny3; y++) {
  1363. for (int x = 0; x < nx3; x++) {
  1364. for (int c = 0; c < 3; c++) {
  1365. // linear interpolation
  1366. const float sx = (x + 0.5f) * scale - 0.5f;
  1367. const float sy = (y + 0.5f) * scale - 0.5f;
  1368. const int x0 = std::max(0, (int)std::floor(sx));
  1369. const int y0 = std::max(0, (int)std::floor(sy));
  1370. const int x1 = std::min(x0 + 1, nx - 1);
  1371. const int y1 = std::min(y0 + 1, ny - 1);
  1372. const float dx = sx - x0;
  1373. const float dy = sy - y0;
  1374. const int j00 = 3 * (y0 * nx + x0) + c;
  1375. const int j01 = 3 * (y0 * nx + x1) + c;
  1376. const int j10 = 3 * (y1 * nx + x0) + c;
  1377. const int j11 = 3 * (y1 * nx + x1) + c;
  1378. const float v00 = temp->buf[j00];
  1379. const float v01 = temp->buf[j01];
  1380. const float v10 = temp->buf[j10];
  1381. const float v11 = temp->buf[j11];
  1382. const float v0 = v00 * (1.0f - dx) + v01 * dx;
  1383. const float v1 = v10 * (1.0f - dx) + v11 * dx;
  1384. const float v = v0 * (1.0f - dy) + v1 * dy;
  1385. const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
  1386. const int i = 3 * (y * nx3 + x) + c;
  1387. res->buf[i] = ((float(v2) / 255.0f) - m3[c]) / s3[c];
  1388. }
  1389. }
  1390. }
  1391. clip_image_u8_free(temp);
  1392. // {
  1393. // clip_image_u8 * temp2 = clip_image_u8_init();
  1394. // clip_image_convert_f32_to_u8(*res, *temp2);
  1395. // clip_image_save_to_bmp(*temp2, "resized_normalized_f32_vanilla.bmp");
  1396. // clip_image_u8_free(temp2);
  1397. // }
  1398. // res_imgs.push_back(res);
  1399. res_imgs.size = 1;
  1400. res_imgs.data = new clip_image_f32[res_imgs.size];
  1401. res_imgs.data[0] = *res;
  1402. clip_image_f32_free(res);
  1403. return true;
  1404. }
  1405. ggml_tensor * clip_get_newline_tensor(const struct clip_ctx * ctx) {
  1406. return ctx->vision_model.image_newline;
  1407. }
  1408. void clip_free(clip_ctx * ctx) {
  1409. ggml_free(ctx->ctx_data);
  1410. gguf_free(ctx->ctx_gguf);
  1411. delete ctx;
  1412. }
  1413. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  1414. return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);
  1415. }
  1416. int32_t clip_image_size(const struct clip_ctx * ctx) {
  1417. return ctx->vision_model.hparams.image_size;
  1418. }
  1419. int32_t clip_patch_size(const struct clip_ctx * ctx) {
  1420. return ctx->vision_model.hparams.patch_size;
  1421. }
  1422. int32_t clip_hidden_size(const struct clip_ctx * ctx) {
  1423. return ctx->vision_model.hparams.hidden_size;
  1424. }
  1425. const char * clip_patch_merge_type(const struct clip_ctx * ctx) {
  1426. return ctx->vision_model.hparams.mm_patch_merge_type;
  1427. }
  1428. const int32_t * clip_image_grid(const struct clip_ctx * ctx) {
  1429. return ctx->vision_model.hparams.image_grid_pinpoints;
  1430. }
  1431. int clip_n_patches(const struct clip_ctx * ctx) {
  1432. const auto & params = ctx->vision_model.hparams;
  1433. int n_patches = (params.image_size / params.patch_size) * (params.image_size / params.patch_size);
  1434. if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  1435. n_patches /= 4;
  1436. }
  1437. return n_patches;
  1438. }
  1439. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  1440. if (!ctx->has_vision_encoder) {
  1441. printf("This gguf file seems to have no vision encoder\n");
  1442. return false;
  1443. }
  1444. clip_image_f32_batch imgs{};
  1445. imgs.size = 1;
  1446. imgs.data = img;
  1447. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  1448. }
  1449. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs, float * vec) {
  1450. if (!ctx->has_vision_encoder) {
  1451. printf("This gguf file seems to have no vision encoder\n");
  1452. return false;
  1453. }
  1454. int batch_size = imgs->size;
  1455. if (ctx->has_llava_projector) {
  1456. GGML_ASSERT(batch_size == 1); // TODO: support multiple images
  1457. }
  1458. // build the inference graph
  1459. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs);
  1460. ggml_gallocr_alloc_graph(ctx->compute_alloc, gf);
  1461. // set inputs
  1462. const auto & model = ctx->vision_model;
  1463. const auto & hparams = model.hparams;
  1464. const int image_size = hparams.image_size;
  1465. const int patch_size = hparams.patch_size;
  1466. const int num_patches = ((image_size / patch_size) * (image_size / patch_size));
  1467. const int num_positions = num_patches + 1;
  1468. {
  1469. struct ggml_tensor * inp_raw = ggml_graph_get_tensor(gf, "inp_raw");
  1470. float * data = (float *)malloc(ggml_nbytes(inp_raw));
  1471. for (size_t i = 0; i < imgs->size; i++) {
  1472. const int nx = imgs->data[i].nx;
  1473. const int ny = imgs->data[i].ny;
  1474. GGML_ASSERT(nx == image_size && ny == image_size);
  1475. const int n = nx * ny;
  1476. for (int b = 0; b < batch_size; b++) {
  1477. for (int k = 0; k < 3; k++) {
  1478. for (int y = 0; y < ny; y++) {
  1479. for (int x = 0; x < nx; x++) {
  1480. data[(b * 3 * n) + k * n + y * nx + x] = imgs->data[b].buf[3 * (y * nx + x) + k];
  1481. }
  1482. }
  1483. }
  1484. }
  1485. }
  1486. ggml_backend_tensor_set(inp_raw, data, 0, ggml_nbytes(inp_raw));
  1487. free(data);
  1488. }
  1489. {
  1490. struct ggml_tensor * embeddings = ggml_graph_get_tensor(gf, "embeddings");
  1491. void* zero_mem = malloc(ggml_nbytes(embeddings));
  1492. memset(zero_mem, 0, ggml_nbytes(embeddings));
  1493. ggml_backend_tensor_set(embeddings, zero_mem, 0, ggml_nbytes(embeddings));
  1494. free(zero_mem);
  1495. }
  1496. {
  1497. struct ggml_tensor * positions = ggml_graph_get_tensor(gf, "positions");
  1498. int* positions_data = (int*)malloc(ggml_nbytes(positions));
  1499. for (int i = 0; i < num_positions; i++) {
  1500. positions_data[i] = i;
  1501. }
  1502. ggml_backend_tensor_set(positions, positions_data, 0, ggml_nbytes(positions));
  1503. free(positions_data);
  1504. }
  1505. {
  1506. struct ggml_tensor * patches = ggml_graph_get_tensor(gf, "patches");
  1507. int* patches_data = (int*)malloc(ggml_nbytes(patches));
  1508. for (int i = 0; i < num_patches; i++) {
  1509. patches_data[i] = i + 1;
  1510. }
  1511. ggml_backend_tensor_set(patches, patches_data, 0, ggml_nbytes(patches));
  1512. free(patches_data);
  1513. }
  1514. if (ggml_backend_is_cpu(ctx->backend)) {
  1515. ggml_backend_cpu_set_n_threads(ctx->backend, n_threads);
  1516. }
  1517. #ifdef GGML_USE_METAL
  1518. if (ggml_backend_is_metal(ctx->backend)) {
  1519. ggml_backend_metal_set_n_cb(ctx->backend, n_threads);
  1520. }
  1521. #endif
  1522. ggml_backend_graph_compute(ctx->backend, gf);
  1523. // the last node is the embedding tensor
  1524. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 1];
  1525. // copy the embeddings to the location passed by the user
  1526. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  1527. return true;
  1528. }
  1529. bool clip_model_quantize(const char * fname_inp, const char * fname_out, const int itype) {
  1530. ggml_type type = GGML_TYPE_Q4_1;
  1531. assert(itype < GGML_TYPE_COUNT);
  1532. type = static_cast<ggml_type>(itype);
  1533. auto * ctx_clip = clip_model_load(fname_inp, 2);
  1534. const auto & ctx_src = ctx_clip->ctx_gguf;
  1535. const auto & ctx_data = ctx_clip->ctx_data;
  1536. auto * ctx_out = gguf_init_empty();
  1537. gguf_set_kv(ctx_out, ctx_src);
  1538. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  1539. gguf_set_val_u32(ctx_out, "general.file_type", itype);
  1540. auto fout = std::ofstream(fname_out, std::ios::binary);
  1541. const int n_tensors = gguf_get_n_tensors(ctx_src);
  1542. for (int i = 0; i < n_tensors; ++i) {
  1543. const char * name = gguf_get_tensor_name(ctx_src, i);
  1544. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name);
  1545. gguf_add_tensor(ctx_out, cur);
  1546. }
  1547. const size_t meta_size = gguf_get_meta_size(ctx_out);
  1548. for (size_t i = 0; i < meta_size; ++i) {
  1549. fout.put(0);
  1550. }
  1551. // regexes of tensor names to be quantized
  1552. const std::vector<std::string> k_names = {
  1553. ".*weight",
  1554. };
  1555. std::vector<uint8_t> work(512);
  1556. std::vector<float> conv_buf(512);
  1557. std::vector<int64_t> hist_all(1 << 4, 0);
  1558. size_t total_size_org = 0;
  1559. size_t total_size_new = 0;
  1560. for (int i = 0; i < n_tensors; ++i) {
  1561. const std::string name = gguf_get_tensor_name(ctx_src, i);
  1562. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name.c_str());
  1563. enum ggml_type new_type;
  1564. void * new_data;
  1565. size_t new_size;
  1566. bool quantize = false;
  1567. for (const auto & s : k_names) {
  1568. if (std::regex_match(name, std::regex(s))) {
  1569. quantize = true;
  1570. break;
  1571. }
  1572. }
  1573. // quantize only 2D tensors
  1574. quantize &= (ggml_n_dims(cur) == 2);
  1575. if (quantize) {
  1576. new_type = type;
  1577. if (new_type >= GGML_TYPE_Q2_K && name.find("embd") != std::string::npos) {
  1578. new_type = GGML_TYPE_Q8_0; // ggml_get_rows needs non K type
  1579. // fprintf(stderr, "%s: quantizing %s to %s\n", __func__, name.c_str(), ggml_type_name(new_type));
  1580. }
  1581. const size_t n_elms = ggml_nelements(cur);
  1582. float * f32_data;
  1583. switch (cur->type) {
  1584. case GGML_TYPE_F32:
  1585. f32_data = (float *)cur->data;
  1586. break;
  1587. case GGML_TYPE_F16:
  1588. if (conv_buf.size() < n_elms) {
  1589. conv_buf.resize(n_elms);
  1590. }
  1591. for (size_t j = 0; j < n_elms; ++j) {
  1592. conv_buf[j] = ggml_fp16_to_fp32(((ggml_fp16_t *)cur->data)[j]);
  1593. }
  1594. f32_data = (float *)conv_buf.data();
  1595. break;
  1596. default:
  1597. printf("Please use an input file in f32 or f16\n");
  1598. return false;
  1599. }
  1600. if (work.size() < n_elms * 4) {
  1601. work.resize(n_elms * 4);
  1602. }
  1603. new_data = work.data();
  1604. std::vector<int64_t> hist_cur(1 << 4, 0);
  1605. switch (new_type) {
  1606. case GGML_TYPE_Q4_0: {
  1607. new_size = ggml_quantize_q4_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1608. } break;
  1609. case GGML_TYPE_Q4_1: {
  1610. new_size = ggml_quantize_q4_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1611. } break;
  1612. case GGML_TYPE_Q5_0: {
  1613. new_size = ggml_quantize_q5_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1614. } break;
  1615. case GGML_TYPE_Q5_1: {
  1616. new_size = ggml_quantize_q5_1(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1617. } break;
  1618. case GGML_TYPE_Q8_0: {
  1619. new_size = ggml_quantize_q8_0(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1620. } break;
  1621. case GGML_TYPE_Q2_K: {
  1622. new_size = ggml_quantize_q2_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1623. } break;
  1624. case GGML_TYPE_Q3_K: {
  1625. new_size = ggml_quantize_q3_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1626. } break;
  1627. case GGML_TYPE_Q4_K: {
  1628. new_size = ggml_quantize_q4_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1629. } break;
  1630. case GGML_TYPE_Q5_K: {
  1631. new_size = ggml_quantize_q5_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1632. } break;
  1633. case GGML_TYPE_Q6_K: {
  1634. new_size = ggml_quantize_q6_K(f32_data, new_data, n_elms, cur->ne[0], hist_cur.data());
  1635. } break;
  1636. default: {
  1637. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, new_type);
  1638. return false;
  1639. }
  1640. }
  1641. for (size_t j = 0; j < hist_cur.size(); ++j) {
  1642. hist_all[j] += hist_cur[j];
  1643. }
  1644. } else {
  1645. new_type = cur->type;
  1646. new_data = cur->data;
  1647. new_size = ggml_nbytes(cur);
  1648. }
  1649. const size_t orig_size = ggml_nbytes(cur);
  1650. total_size_org += orig_size;
  1651. total_size_new += new_size;
  1652. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  1653. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  1654. fout.write((const char *)new_data, new_size);
  1655. size_t pad = GGML_PAD(new_size, gguf_get_alignment(ctx_out)) - new_size;
  1656. for (size_t j = 0; j < pad; ++j) {
  1657. fout.put(0);
  1658. }
  1659. printf("%s: n_dims = %d | quantize=%d | size = %f MB -> %f MB\n", name.c_str(), ggml_n_dims(cur), quantize,
  1660. orig_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  1661. }
  1662. // go back to beginning of file and write the updated metadata
  1663. fout.seekp(0, std::ios::beg);
  1664. std::vector<uint8_t> meta(meta_size);
  1665. gguf_get_meta_data(ctx_out, meta.data());
  1666. fout.write((const char *)meta.data(), meta_size);
  1667. fout.close();
  1668. clip_free(ctx_clip);
  1669. gguf_free(ctx_out);
  1670. {
  1671. printf("%s: original size = %8.2f MB\n", __func__, total_size_org / 1024.0 / 1024.0);
  1672. printf("%s: quantized size = %8.2f MB\n", __func__, total_size_new / 1024.0 / 1024.0);
  1673. int64_t sum_all = 0;
  1674. for (size_t i = 0; i < hist_all.size(); ++i) {
  1675. sum_all += hist_all[i];
  1676. }
  1677. printf("%s: hist: ", __func__);
  1678. for (size_t i = 0; i < hist_all.size(); ++i) {
  1679. printf("%5.3f ", hist_all[i] / (float)sum_all);
  1680. }
  1681. printf("\n");
  1682. }
  1683. return true;
  1684. }
  1685. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  1686. if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  1687. return ctx->vision_model.mm_model_block_1_block_2_1_b->ne[0];
  1688. }
  1689. if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  1690. return ctx->vision_model.mm_2_b->ne[0];
  1691. }
  1692. if (ctx->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  1693. return ctx->vision_model.mm_3_b->ne[0];
  1694. }
  1695. std::string proj_type = PROJECTOR_TYPE_NAMES[ctx->proj_type];
  1696. throw std::runtime_error(format("%s: don't support projector with: %s currently\n", __func__, proj_type.c_str()));
  1697. }