clip.cpp 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628
  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 "log.h"
  7. #include "ggml.h"
  8. #include "ggml-alloc.h"
  9. #include "ggml-backend.h"
  10. #ifdef GGML_USE_CUDA
  11. #include "ggml-cuda.h"
  12. #endif
  13. #ifdef GGML_USE_METAL
  14. #include "ggml-metal.h"
  15. #endif
  16. #ifdef GGML_USE_CANN
  17. #include "ggml-cann.h"
  18. #endif
  19. #ifdef GGML_USE_VULKAN
  20. #include "ggml-vulkan.h"
  21. #endif
  22. #define STB_IMAGE_IMPLEMENTATION
  23. #include "stb_image.h"
  24. #include <cassert>
  25. #include <cmath>
  26. #include <cstdlib>
  27. #include <cstring>
  28. #include <fstream>
  29. #include <map>
  30. #include <regex>
  31. #include <stdexcept>
  32. #include <vector>
  33. #include <sstream>
  34. #include <cinttypes>
  35. #include <limits>
  36. //#define CLIP_DEBUG_FUNCTIONS
  37. // RGB uint8 image
  38. struct clip_image_u8 {
  39. int nx;
  40. int ny;
  41. std::vector<uint8_t> buf;
  42. };
  43. // RGB float32 image (NHWC)
  44. // Memory layout: RGBRGBRGB...
  45. struct clip_image_f32 {
  46. int nx;
  47. int ny;
  48. std::vector<float> buf;
  49. };
  50. static std::string format(const char * fmt, ...) {
  51. va_list ap;
  52. va_list ap2;
  53. va_start(ap, fmt);
  54. va_copy(ap2, ap);
  55. int size = vsnprintf(NULL, 0, fmt, ap);
  56. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  57. std::vector<char> buf(size + 1);
  58. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  59. GGML_ASSERT(size2 == size);
  60. va_end(ap2);
  61. va_end(ap);
  62. return std::string(buf.data(), buf.size());
  63. }
  64. //
  65. // key constants
  66. //
  67. #define KEY_FTYPE "general.file_type"
  68. #define KEY_NAME "general.name"
  69. #define KEY_DESCRIPTION "general.description"
  70. #define KEY_HAS_TEXT_ENC "clip.has_text_encoder"
  71. #define KEY_HAS_VIS_ENC "clip.has_vision_encoder"
  72. #define KEY_HAS_LLAVA_PROJ "clip.has_llava_projector"
  73. #define KEY_HAS_MINICPMV_PROJ "clip.has_minicpmv_projector"
  74. #define KEY_MINICPMV_VERSION "clip.minicpmv_version"
  75. #define KEY_USE_GELU "clip.use_gelu"
  76. #define KEY_N_EMBD "clip.%s.embedding_length"
  77. #define KEY_N_FF "clip.%s.feed_forward_length"
  78. #define KEY_N_BLOCK "clip.%s.block_count"
  79. #define KEY_N_HEAD "clip.%s.attention.head_count"
  80. #define KEY_LAYER_NORM_EPS "clip.%s.attention.layer_norm_epsilon"
  81. #define KEY_PROJ_DIM "clip.%s.projection_dim"
  82. #define KEY_TOKENS "tokenizer.ggml.tokens"
  83. #define KEY_N_POSITIONS "clip.text.context_length"
  84. #define KEY_IMAGE_SIZE "clip.vision.image_size"
  85. #define KEY_PATCH_SIZE "clip.vision.patch_size"
  86. #define KEY_IMAGE_MEAN "clip.vision.image_mean"
  87. #define KEY_IMAGE_STD "clip.vision.image_std"
  88. #define KEY_PROJ_TYPE "clip.projector_type"
  89. #define KEY_MM_PATCH_MERGE_TYPE "clip.vision.mm_patch_merge_type"
  90. #define KEY_IMAGE_GRID_PINPOINTS "clip.vision.image_grid_pinpoints"
  91. #define KEY_IMAGE_CROP_RESOLUTION "clip.vision.image_crop_resolution"
  92. //
  93. // tensor name constants
  94. //
  95. #define TN_TOKEN_EMBD "%s.token_embd.weight"
  96. #define TN_POS_EMBD "%s.position_embd.weight"
  97. #define TN_CLASS_EMBD "v.class_embd"
  98. #define TN_PATCH_EMBD "v.patch_embd.weight"
  99. #define TN_PATCH_BIAS "v.patch_embd.bias"
  100. #define TN_ATTN_K "%s.blk.%d.attn_k.%s"
  101. #define TN_ATTN_Q "%s.blk.%d.attn_q.%s"
  102. #define TN_ATTN_V "%s.blk.%d.attn_v.%s"
  103. #define TN_ATTN_OUTPUT "%s.blk.%d.attn_out.%s"
  104. #define TN_FFN_DOWN "%s.blk.%d.ffn_down.%s"
  105. #define TN_FFN_UP "%s.blk.%d.ffn_up.%s"
  106. #define TN_LN_1 "%s.blk.%d.ln1.%s"
  107. #define TN_LN_2 "%s.blk.%d.ln2.%s"
  108. #define TN_LN_PRE "%s.pre_ln.%s"
  109. #define TN_LN_POST "%s.post_ln.%s"
  110. #define TN_TEXT_PROJ "text_projection.weight"
  111. #define TN_VIS_PROJ "visual_projection.weight"
  112. #define TN_LLAVA_PROJ "mm.%d.%s"
  113. #define TN_MVLM_PROJ_MLP "mm.model.mlp.%d.%s"
  114. #define TN_MVLM_PROJ_BLOCK "mm.model.mb_block.%d.block.%d.%s"
  115. #define TN_MVLM_PROJ_PEG "mm.model.peg.%d.%s"
  116. #define TN_IMAGE_NEWLINE "model.image_newline"
  117. #define TN_MINICPMV_POS_EMBD_K "resampler.pos_embed_k"
  118. #define TN_MINICPMV_QUERY "resampler.query"
  119. #define TN_MINICPMV_PROJ "resampler.proj.weight"
  120. #define TN_MINICPMV_KV_PROJ "resampler.kv.weight"
  121. #define TN_MINICPMV_ATTN "resampler.attn.%s.%s"
  122. #define TN_MINICPMV_LN "resampler.ln_%s.%s"
  123. enum projector_type {
  124. PROJECTOR_TYPE_MLP,
  125. PROJECTOR_TYPE_MLP_NORM,
  126. PROJECTOR_TYPE_LDP,
  127. PROJECTOR_TYPE_LDPV2,
  128. PROJECTOR_TYPE_RESAMPLER,
  129. PROJECTOR_TYPE_UNKNOWN,
  130. };
  131. static std::map<projector_type, std::string> PROJECTOR_TYPE_NAMES = {
  132. { PROJECTOR_TYPE_MLP, "mlp" },
  133. { PROJECTOR_TYPE_LDP, "ldp" },
  134. { PROJECTOR_TYPE_LDPV2, "ldpv2"},
  135. { PROJECTOR_TYPE_RESAMPLER, "resampler"},
  136. };
  137. //
  138. // utilities to get data from a gguf file
  139. //
  140. static int get_key_idx(const gguf_context * ctx, const char * key) {
  141. int i = gguf_find_key(ctx, key);
  142. if (i == -1) {
  143. LOG_TEE("key %s not found in file\n", key);
  144. throw std::runtime_error(format("Missing required key: %s", key));
  145. }
  146. return i;
  147. }
  148. static uint32_t get_u32(const gguf_context * ctx, const std::string & key) {
  149. const int i = get_key_idx(ctx, key.c_str());
  150. return gguf_get_val_u32(ctx, i);
  151. }
  152. static float get_f32(const gguf_context * ctx, const std::string & key) {
  153. const int i = get_key_idx(ctx, key.c_str());
  154. return gguf_get_val_f32(ctx, i);
  155. }
  156. static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const std::string & name) {
  157. struct ggml_tensor * cur = ggml_get_tensor(ctx, name.c_str());
  158. if (!cur) {
  159. throw std::runtime_error(format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  160. }
  161. return cur;
  162. }
  163. static std::string get_ftype(int ftype) {
  164. return ggml_type_name(static_cast<ggml_type>(ftype));
  165. }
  166. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  167. switch (type) {
  168. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  169. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  170. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  171. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  172. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  173. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  174. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  175. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  176. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  177. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  178. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  179. default: return format("unknown type %d", type);
  180. }
  181. }
  182. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  183. if (search.empty()) {
  184. return;
  185. }
  186. std::string builder;
  187. builder.reserve(s.length());
  188. size_t pos = 0;
  189. size_t last_pos = 0;
  190. while ((pos = s.find(search, last_pos)) != std::string::npos) {
  191. builder.append(s, last_pos, pos - last_pos);
  192. builder.append(replace);
  193. last_pos = pos + search.length();
  194. }
  195. builder.append(s, last_pos, std::string::npos);
  196. s = std::move(builder);
  197. }
  198. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  199. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  200. switch (type) {
  201. case GGUF_TYPE_STRING:
  202. return gguf_get_val_str(ctx_gguf, i);
  203. case GGUF_TYPE_ARRAY:
  204. {
  205. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  206. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  207. const void * data = gguf_get_arr_data(ctx_gguf, i);
  208. std::stringstream ss;
  209. ss << "[";
  210. for (int j = 0; j < arr_n; j++) {
  211. if (arr_type == GGUF_TYPE_STRING) {
  212. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  213. // escape quotes
  214. replace_all(val, "\\", "\\\\");
  215. replace_all(val, "\"", "\\\"");
  216. ss << '"' << val << '"';
  217. } else if (arr_type == GGUF_TYPE_ARRAY) {
  218. ss << "???";
  219. } else {
  220. ss << gguf_data_to_str(arr_type, data, j);
  221. }
  222. if (j < arr_n - 1) {
  223. ss << ", ";
  224. }
  225. }
  226. ss << "]";
  227. return ss.str();
  228. }
  229. default:
  230. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  231. }
  232. }
  233. static void print_tensor_info(const ggml_tensor * tensor, const char * prefix = "") {
  234. size_t tensor_size = ggml_nbytes(tensor);
  235. LOG_TEE("%s: n_dims = %d, name = %s, tensor_size=%zu, shape:[%" PRId64 ", %" PRId64 ", %" PRId64 ", %" PRId64 "], type = %s\n",
  236. prefix, ggml_n_dims(tensor), tensor->name, tensor_size,
  237. tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], ggml_type_name(tensor->type));
  238. }
  239. static projector_type clip_projector_type_from_string(const std::string & name) {
  240. for (const auto & kv : PROJECTOR_TYPE_NAMES) { // NOLINT
  241. if (kv.second == name) {
  242. return kv.first;
  243. }
  244. }
  245. return PROJECTOR_TYPE_UNKNOWN;
  246. }
  247. #ifdef CLIP_DEBUG_FUNCTIONS
  248. static void clip_image_write_image_to_ppm(const clip_image_u8& img, const std::string& filename) {
  249. std::ofstream file(filename, std::ios::binary);
  250. if (!file.is_open()) {
  251. LOG_TEE("Failed to open file for writing: %s\n", filename.c_str());
  252. return;
  253. }
  254. // PPM header: P6 format, width, height, and max color value
  255. file << "P6\n" << img.nx << " " << img.ny << "\n255\n";
  256. // Write pixel data
  257. for (size_t i = 0; i < img.buf.size(); i += 3) {
  258. // PPM expects binary data in RGB format, which matches our image buffer
  259. file.write(reinterpret_cast<const char*>(&img.buf[i]), 3);
  260. }
  261. file.close();
  262. }
  263. static void clip_image_save_to_bmp(const clip_image_u8& img, const std::string& filename) {
  264. std::ofstream file(filename, std::ios::binary);
  265. if (!file.is_open()) {
  266. LOG_TEE("Failed to open file for writing: %s\n", filename.c_str());
  267. return;
  268. }
  269. int fileSize = 54 + 3 * img.nx * img.ny; // File header + info header + pixel data
  270. int bytesPerPixel = 3;
  271. int widthInBytes = img.nx * bytesPerPixel;
  272. int paddingAmount = (4 - (widthInBytes % 4)) % 4;
  273. int stride = widthInBytes + paddingAmount;
  274. // Bitmap file header
  275. unsigned char fileHeader[14] = {
  276. 'B','M', // Signature
  277. 0,0,0,0, // Image file size in bytes
  278. 0,0,0,0, // Reserved
  279. 54,0,0,0 // Start of pixel array
  280. };
  281. // Total file size
  282. fileSize = 54 + (stride * img.ny);
  283. fileHeader[2] = (unsigned char)(fileSize);
  284. fileHeader[3] = (unsigned char)(fileSize >> 8);
  285. fileHeader[4] = (unsigned char)(fileSize >> 16);
  286. fileHeader[5] = (unsigned char)(fileSize >> 24);
  287. // Bitmap information header (BITMAPINFOHEADER)
  288. unsigned char infoHeader[40] = {
  289. 40,0,0,0, // Size of this header (40 bytes)
  290. 0,0,0,0, // Image width
  291. 0,0,0,0, // Image height
  292. 1,0, // Number of color planes
  293. 24,0, // Bits per pixel
  294. 0,0,0,0, // No compression
  295. 0,0,0,0, // Image size (can be 0 for no compression)
  296. 0,0,0,0, // X pixels per meter (not specified)
  297. 0,0,0,0, // Y pixels per meter (not specified)
  298. 0,0,0,0, // Total colors (color table not used)
  299. 0,0,0,0 // Important colors (all are important)
  300. };
  301. // Width and height in the information header
  302. infoHeader[4] = (unsigned char)(img.nx);
  303. infoHeader[5] = (unsigned char)(img.nx >> 8);
  304. infoHeader[6] = (unsigned char)(img.nx >> 16);
  305. infoHeader[7] = (unsigned char)(img.nx >> 24);
  306. infoHeader[8] = (unsigned char)(img.ny);
  307. infoHeader[9] = (unsigned char)(img.ny >> 8);
  308. infoHeader[10] = (unsigned char)(img.ny >> 16);
  309. infoHeader[11] = (unsigned char)(img.ny >> 24);
  310. // Write file headers
  311. file.write(reinterpret_cast<char*>(fileHeader), sizeof(fileHeader));
  312. file.write(reinterpret_cast<char*>(infoHeader), sizeof(infoHeader));
  313. // Pixel data
  314. std::vector<unsigned char> padding(3, 0); // Max padding size to be added to each row
  315. for (int y = img.ny - 1; y >= 0; --y) { // BMP files are stored bottom-to-top
  316. for (int x = 0; x < img.nx; ++x) {
  317. // Each pixel
  318. size_t pixelIndex = (y * img.nx + x) * 3;
  319. unsigned char pixel[3] = {
  320. img.buf[pixelIndex + 2], // BMP stores pixels in BGR format
  321. img.buf[pixelIndex + 1],
  322. img.buf[pixelIndex]
  323. };
  324. file.write(reinterpret_cast<char*>(pixel), 3);
  325. }
  326. // Write padding for the row
  327. file.write(reinterpret_cast<char*>(padding.data()), paddingAmount);
  328. }
  329. file.close();
  330. }
  331. // debug function to convert f32 to u8
  332. static void clip_image_convert_f32_to_u8(const clip_image_f32& src, clip_image_u8& dst) {
  333. dst.nx = src.nx;
  334. dst.ny = src.ny;
  335. dst.buf.resize(3 * src.nx * src.ny);
  336. for (size_t i = 0; i < src.buf.size(); ++i) {
  337. dst.buf[i] = static_cast<uint8_t>(std::min(std::max(int(src.buf[i] * 255.0f), 0), 255));
  338. }
  339. }
  340. #endif
  341. //
  342. // clip layers
  343. //
  344. struct clip_hparams {
  345. int32_t image_size;
  346. int32_t patch_size;
  347. int32_t hidden_size;
  348. int32_t n_intermediate;
  349. int32_t projection_dim;
  350. int32_t n_head;
  351. int32_t n_layer;
  352. float eps;
  353. char mm_patch_merge_type[32] = "flat"; // spatial_unpad or flat (default)
  354. int32_t image_grid_pinpoints[32];
  355. int32_t image_crop_resolution;
  356. };
  357. struct clip_layer {
  358. // attention
  359. struct ggml_tensor * k_w;
  360. struct ggml_tensor * k_b;
  361. struct ggml_tensor * q_w;
  362. struct ggml_tensor * q_b;
  363. struct ggml_tensor * v_w;
  364. struct ggml_tensor * v_b;
  365. struct ggml_tensor * o_w;
  366. struct ggml_tensor * o_b;
  367. // layernorm 1
  368. struct ggml_tensor * ln_1_w;
  369. struct ggml_tensor * ln_1_b;
  370. // ff
  371. struct ggml_tensor * ff_i_w;
  372. struct ggml_tensor * ff_i_b;
  373. struct ggml_tensor * ff_o_w;
  374. struct ggml_tensor * ff_o_b;
  375. // layernorm 2
  376. struct ggml_tensor * ln_2_w;
  377. struct ggml_tensor * ln_2_b;
  378. };
  379. struct clip_vision_model {
  380. struct clip_hparams hparams;
  381. // embeddings
  382. struct ggml_tensor * class_embedding;
  383. struct ggml_tensor * patch_embeddings;
  384. struct ggml_tensor * patch_bias;
  385. struct ggml_tensor * position_embeddings;
  386. struct ggml_tensor * pre_ln_w;
  387. struct ggml_tensor * pre_ln_b;
  388. std::vector<clip_layer> layers;
  389. struct ggml_tensor * post_ln_w;
  390. struct ggml_tensor * post_ln_b;
  391. struct ggml_tensor * projection;
  392. // LLaVA projection
  393. struct ggml_tensor * mm_0_w = NULL;
  394. struct ggml_tensor * mm_0_b = NULL;
  395. struct ggml_tensor * mm_2_w = NULL;
  396. struct ggml_tensor * mm_2_b = NULL;
  397. struct ggml_tensor * image_newline = NULL;
  398. // Yi type models with mlp+normalization projection
  399. struct ggml_tensor * mm_1_w = NULL; // Yi type models have 0, 1, 3, 4
  400. struct ggml_tensor * mm_1_b = NULL;
  401. struct ggml_tensor * mm_3_w = NULL;
  402. struct ggml_tensor * mm_3_b = NULL;
  403. struct ggml_tensor * mm_4_w = NULL;
  404. struct ggml_tensor * mm_4_b = NULL;
  405. // MobileVLM projection
  406. struct ggml_tensor * mm_model_mlp_1_w;
  407. struct ggml_tensor * mm_model_mlp_1_b;
  408. struct ggml_tensor * mm_model_mlp_3_w;
  409. struct ggml_tensor * mm_model_mlp_3_b;
  410. struct ggml_tensor * mm_model_block_1_block_0_0_w;
  411. struct ggml_tensor * mm_model_block_1_block_0_1_w;
  412. struct ggml_tensor * mm_model_block_1_block_0_1_b;
  413. struct ggml_tensor * mm_model_block_1_block_1_fc1_w;
  414. struct ggml_tensor * mm_model_block_1_block_1_fc1_b;
  415. struct ggml_tensor * mm_model_block_1_block_1_fc2_w;
  416. struct ggml_tensor * mm_model_block_1_block_1_fc2_b;
  417. struct ggml_tensor * mm_model_block_1_block_2_0_w;
  418. struct ggml_tensor * mm_model_block_1_block_2_1_w;
  419. struct ggml_tensor * mm_model_block_1_block_2_1_b;
  420. struct ggml_tensor * mm_model_block_2_block_0_0_w;
  421. struct ggml_tensor * mm_model_block_2_block_0_1_w;
  422. struct ggml_tensor * mm_model_block_2_block_0_1_b;
  423. struct ggml_tensor * mm_model_block_2_block_1_fc1_w;
  424. struct ggml_tensor * mm_model_block_2_block_1_fc1_b;
  425. struct ggml_tensor * mm_model_block_2_block_1_fc2_w;
  426. struct ggml_tensor * mm_model_block_2_block_1_fc2_b;
  427. struct ggml_tensor * mm_model_block_2_block_2_0_w;
  428. struct ggml_tensor * mm_model_block_2_block_2_1_w;
  429. struct ggml_tensor * mm_model_block_2_block_2_1_b;
  430. // MobileVLM_V2 projection
  431. struct ggml_tensor * mm_model_mlp_0_w;
  432. struct ggml_tensor * mm_model_mlp_0_b;
  433. struct ggml_tensor * mm_model_mlp_2_w;
  434. struct ggml_tensor * mm_model_mlp_2_b;
  435. struct ggml_tensor * mm_model_peg_0_w;
  436. struct ggml_tensor * mm_model_peg_0_b;
  437. // MINICPMV projection
  438. struct ggml_tensor * mm_model_pos_embed_k;
  439. struct ggml_tensor * mm_model_query;
  440. struct ggml_tensor * mm_model_proj;
  441. struct ggml_tensor * mm_model_kv_proj;
  442. struct ggml_tensor * mm_model_attn_q_w;
  443. struct ggml_tensor * mm_model_attn_q_b;
  444. struct ggml_tensor * mm_model_attn_k_w;
  445. struct ggml_tensor * mm_model_attn_k_b;
  446. struct ggml_tensor * mm_model_attn_v_w;
  447. struct ggml_tensor * mm_model_attn_v_b;
  448. struct ggml_tensor * mm_model_attn_o_w;
  449. struct ggml_tensor * mm_model_attn_o_b;
  450. struct ggml_tensor * mm_model_ln_q_w;
  451. struct ggml_tensor * mm_model_ln_q_b;
  452. struct ggml_tensor * mm_model_ln_kv_w;
  453. struct ggml_tensor * mm_model_ln_kv_b;
  454. struct ggml_tensor * mm_model_ln_post_w;
  455. struct ggml_tensor * mm_model_ln_post_b;
  456. };
  457. struct clip_ctx {
  458. bool has_text_encoder = false;
  459. bool has_vision_encoder = false;
  460. bool has_llava_projector = false;
  461. bool has_minicpmv_projector = false;
  462. int minicpmv_version = 2;
  463. struct clip_vision_model vision_model;
  464. projector_type proj_type = PROJECTOR_TYPE_MLP;
  465. float image_mean[3];
  466. float image_std[3];
  467. bool use_gelu = false;
  468. int32_t ftype = 1;
  469. bool has_class_embedding = true;
  470. bool has_pre_norm = true;
  471. bool has_post_norm = false;
  472. bool has_patch_bias = false;
  473. struct gguf_context * ctx_gguf;
  474. struct ggml_context * ctx_data;
  475. std::vector<uint8_t> buf_compute_meta;
  476. // memory buffers to evaluate the model
  477. ggml_backend_buffer_t params_buffer = NULL;
  478. ggml_backend_t backend = NULL;
  479. ggml_gallocr_t compute_alloc = NULL;
  480. struct clip_image_size * load_image_size;
  481. };
  482. static ggml_cgraph * clip_image_build_graph(clip_ctx * ctx, const clip_image_f32_batch * imgs, struct clip_image_size * load_image_size, bool is_inf = false) {
  483. if (!ctx->has_vision_encoder) {
  484. LOG_TEE("This gguf file seems to have no vision encoder\n");
  485. return nullptr;
  486. }
  487. const auto & model = ctx->vision_model;
  488. const auto & hparams = model.hparams;
  489. const int image_size = hparams.image_size;
  490. int image_size_width = image_size;
  491. int image_size_height = image_size;
  492. if (ctx->has_minicpmv_projector) {
  493. if (load_image_size == nullptr) {
  494. load_image_size = clip_image_size_init();
  495. }
  496. LOG_TEE("%s: %d %d\n", __func__, load_image_size->width, load_image_size->height);
  497. image_size_width = load_image_size->width;
  498. image_size_height = load_image_size->height;
  499. if (is_inf) {
  500. image_size_width = imgs->data->nx;
  501. image_size_height = imgs->data->ny;
  502. }
  503. }
  504. const int patch_size = hparams.patch_size;
  505. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  506. const int num_positions = num_patches + (ctx->has_class_embedding ? 1 : 0);
  507. const int hidden_size = hparams.hidden_size;
  508. const int n_head = hparams.n_head;
  509. const int d_head = hidden_size / n_head;
  510. int n_layer = hparams.n_layer;
  511. const float eps = hparams.eps;
  512. const int batch_size = imgs->size;
  513. if (ctx->has_llava_projector || ctx->has_minicpmv_projector) {
  514. GGML_ASSERT(batch_size == 1);
  515. }
  516. struct ggml_init_params params = {
  517. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  518. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  519. /*.no_alloc =*/ true,
  520. };
  521. struct ggml_context * ctx0 = ggml_init(params);
  522. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  523. struct ggml_tensor * inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size_width, image_size_height, 3, batch_size);
  524. ggml_set_name(inp_raw, "inp_raw");
  525. ggml_set_input(inp_raw);
  526. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  527. inp = ggml_reshape_3d(ctx0, inp, num_patches, hidden_size, batch_size);
  528. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 0, 2, 3));
  529. if (ctx->has_patch_bias) {
  530. // inp = ggml_add(ctx0, inp, ggml_repeat(ctx0, model.patch_bias, inp));
  531. inp = ggml_add(ctx0, inp, model.patch_bias);
  532. }
  533. struct ggml_tensor * embeddings = inp;
  534. struct ggml_tensor * pos_embed = nullptr;
  535. if (ctx->has_llava_projector) {
  536. // concat class_embeddings and patch_embeddings
  537. if (ctx->has_class_embedding) {
  538. embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size);
  539. ggml_set_name(embeddings, "embeddings");
  540. ggml_set_input(embeddings);
  541. embeddings = ggml_acc(ctx0, embeddings, model.class_embedding,
  542. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], 0);
  543. embeddings = ggml_acc(ctx0, embeddings, inp,
  544. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], model.class_embedding->nb[1]);
  545. }
  546. }
  547. struct ggml_tensor * positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions);
  548. ggml_set_name(positions, "positions");
  549. ggml_set_input(positions);
  550. embeddings =
  551. ggml_add(ctx0, embeddings, ggml_get_rows(ctx0, model.position_embeddings, positions));
  552. if (ctx->has_minicpmv_projector) {
  553. int pos_w = image_size_width/patch_size;
  554. int pos_h = image_size_height/patch_size;
  555. if (ctx->minicpmv_version == 2) {
  556. pos_embed = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 4096, pos_w * pos_h, 1);
  557. }
  558. else if (ctx->minicpmv_version == 3) {
  559. pos_embed = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 3584, pos_w * pos_h, 1);
  560. }
  561. ggml_set_name(pos_embed, "pos_embed");
  562. ggml_set_input(pos_embed);
  563. }
  564. // pre-layernorm
  565. if (ctx->has_pre_norm) {
  566. embeddings = ggml_norm(ctx0, embeddings, eps);
  567. ggml_set_name(embeddings, "pre_ln");
  568. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.pre_ln_w), model.pre_ln_b);
  569. }
  570. // loop over layers
  571. if (ctx->has_minicpmv_projector) {
  572. n_layer += 1;
  573. }
  574. for (int il = 0; il < n_layer - 1; il++) {
  575. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  576. //const size_t nb_q_w = model.layers[il].q_w->nb[0];
  577. // layernorm1
  578. {
  579. cur = ggml_norm(ctx0, cur, eps);
  580. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_1_w),
  581. model.layers[il].ln_1_b);
  582. }
  583. // self-attention
  584. {
  585. struct ggml_tensor * Q =
  586. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  587. Q = ggml_scale_inplace(ctx0, Q, 1.0f / sqrt((float)d_head));
  588. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  589. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  590. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  591. struct ggml_tensor * K =
  592. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  593. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  594. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  595. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  596. struct ggml_tensor * V =
  597. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  598. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  599. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  600. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  601. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  602. KQ = ggml_soft_max_inplace(ctx0, KQ);
  603. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  604. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  605. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  606. cur = ggml_cont_3d(ctx0, KQV, hidden_size, num_positions, batch_size);
  607. }
  608. // attention output
  609. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  610. // re-add the layer input, e.g., residual
  611. cur = ggml_add(ctx0, cur, embeddings);
  612. embeddings = cur; // embeddings = residual, cur = hidden_states
  613. // layernorm2
  614. {
  615. cur = ggml_norm(ctx0, cur, eps);
  616. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_2_w), model.layers[il].ln_2_b);
  617. }
  618. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  619. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  620. if (ctx->use_gelu) {
  621. cur = ggml_gelu_inplace(ctx0, cur);
  622. } else {
  623. cur = ggml_gelu_quick_inplace(ctx0, cur);
  624. }
  625. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  626. cur = ggml_add(ctx0, cur, model.layers[il].ff_o_b);
  627. // residual 2
  628. cur = ggml_add(ctx0, embeddings, cur);
  629. embeddings = cur;
  630. }
  631. // post-layernorm
  632. if (ctx->has_post_norm) {
  633. embeddings = ggml_norm(ctx0, embeddings, eps);
  634. ggml_set_name(embeddings, "post_ln");
  635. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.post_ln_w), model.post_ln_b);
  636. }
  637. // llava projector
  638. if (ctx->has_llava_projector) {
  639. embeddings = ggml_reshape_2d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1]);
  640. struct ggml_tensor * patches = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  641. ggml_set_name(patches, "patches");
  642. ggml_set_input(patches);
  643. // shape [1, 576, 1024]
  644. // ne is whcn, ne = [1024, 576, 1, 1]
  645. embeddings = ggml_get_rows(ctx0, embeddings, patches);
  646. // print_tensor_info(embeddings, "embeddings");
  647. // llava projector
  648. if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  649. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  650. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  651. embeddings = ggml_gelu(ctx0, embeddings);
  652. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  653. embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
  654. }
  655. else if (ctx->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  656. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  657. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  658. // ggml_tensor_printf(embeddings, "mm_0_w",0,true,false);
  659. // First LayerNorm
  660. embeddings = ggml_norm(ctx0, embeddings, eps);
  661. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_1_w),
  662. model.mm_1_b);
  663. // GELU activation
  664. embeddings = ggml_gelu(ctx0, embeddings);
  665. // Second linear layer
  666. embeddings = ggml_mul_mat(ctx0, model.mm_3_w, embeddings);
  667. embeddings = ggml_add(ctx0, embeddings, model.mm_3_b);
  668. // Second LayerNorm
  669. embeddings = ggml_norm(ctx0, embeddings, eps);
  670. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_4_w),
  671. model.mm_4_b);
  672. }
  673. else if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  674. // MobileVLM projector
  675. int n_patch = 24;
  676. struct ggml_tensor * mlp_1 = ggml_mul_mat(ctx0, model.mm_model_mlp_1_w, embeddings);
  677. mlp_1 = ggml_add(ctx0, mlp_1, model.mm_model_mlp_1_b);
  678. mlp_1 = ggml_gelu(ctx0, mlp_1);
  679. struct ggml_tensor * mlp_3 = ggml_mul_mat(ctx0, model.mm_model_mlp_3_w, mlp_1);
  680. mlp_3 = ggml_add(ctx0, mlp_3, model.mm_model_mlp_3_b);
  681. // mlp_3 shape = [1, 576, 2048], ne = [2048, 576, 1, 1]
  682. // block 1
  683. struct ggml_tensor * block_1 = nullptr;
  684. {
  685. // transpose from [1, 576, 2048] --> [1, 2048, 576] --> [1, 2048, 24, 24]
  686. mlp_3 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_3, 1, 0, 2, 3));
  687. mlp_3 = ggml_reshape_4d(ctx0, mlp_3, n_patch, n_patch, mlp_3->ne[1], mlp_3->ne[2]);
  688. // stride = 1, padding = 1, bias is nullptr
  689. block_1 = ggml_conv_depthwise_2d(ctx0, model.mm_model_block_1_block_0_0_w, mlp_3, 1, 1, 1, 1, 1, 1);
  690. // layer norm
  691. // // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  692. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  693. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  694. block_1 = ggml_norm(ctx0, block_1, eps);
  695. 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);
  696. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  697. // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  698. // hardswish
  699. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  700. 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);
  701. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  702. // pointwise conv
  703. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  704. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc1_w, block_1);
  705. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc1_b);
  706. block_1 = ggml_relu(ctx0, block_1);
  707. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc2_w, block_1);
  708. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc2_b);
  709. block_1 = ggml_hardsigmoid(ctx0, block_1);
  710. // block_1_hw shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1], block_1 shape = [1, 2048], ne = [2048, 1, 1, 1]
  711. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  712. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  713. int w = block_1->ne[0], h = block_1->ne[1];
  714. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  715. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  716. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  717. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_2_0_w, block_1);
  718. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  719. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  720. block_1 = ggml_norm(ctx0, block_1, eps);
  721. 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);
  722. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  723. // block1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  724. // residual
  725. block_1 = ggml_add(ctx0, mlp_3, block_1);
  726. }
  727. // block_2
  728. {
  729. // stride = 2
  730. block_1 = ggml_conv_depthwise_2d(ctx0, model.mm_model_block_2_block_0_0_w, block_1, 2, 2, 1, 1, 1, 1);
  731. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  732. // layer norm
  733. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  734. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  735. block_1 = ggml_norm(ctx0, block_1, eps);
  736. 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);
  737. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  738. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  739. // hardswish
  740. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  741. // not sure the parameters is right for globalAvgPooling
  742. 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);
  743. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  744. // pointwise conv
  745. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  746. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc1_w, block_1);
  747. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc1_b);
  748. block_1 = ggml_relu(ctx0, block_1);
  749. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc2_w, block_1);
  750. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc2_b);
  751. block_1 = ggml_hardsigmoid(ctx0, block_1);
  752. // 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]
  753. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  754. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  755. int w = block_1->ne[0], h = block_1->ne[1];
  756. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  757. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  758. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  759. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_2_0_w, block_1);
  760. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  761. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  762. block_1 = ggml_norm(ctx0, block_1, eps);
  763. 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);
  764. block_1 = ggml_reshape_3d(ctx0, block_1, block_1->ne[0], block_1->ne[1] * block_1->ne[2], block_1->ne[3]);
  765. // block_1 shape = [1, 144, 2048], ne = [2048, 144, 1]
  766. }
  767. embeddings = block_1;
  768. }
  769. else if (ctx->proj_type == PROJECTOR_TYPE_LDPV2)
  770. {
  771. int n_patch = 24;
  772. struct ggml_tensor * mlp_0 = ggml_mul_mat(ctx0, model.mm_model_mlp_0_w, embeddings);
  773. mlp_0 = ggml_add(ctx0, mlp_0, model.mm_model_mlp_0_b);
  774. mlp_0 = ggml_gelu(ctx0, mlp_0);
  775. struct ggml_tensor * mlp_2 = ggml_mul_mat(ctx0, model.mm_model_mlp_2_w, mlp_0);
  776. mlp_2 = ggml_add(ctx0, mlp_2, model.mm_model_mlp_2_b);
  777. // mlp_2 ne = [2048, 576, 1, 1]
  778. // // AVG Pool Layer 2*2, strides = 2
  779. mlp_2 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_2, 1, 0, 2, 3));
  780. // mlp_2 ne = [576, 2048, 1, 1]
  781. mlp_2 = ggml_reshape_4d(ctx0, mlp_2, n_patch, n_patch, mlp_2->ne[1], mlp_2->ne[2]);
  782. // mlp_2 ne [24, 24, 2048, 1]
  783. mlp_2 = ggml_pool_2d(ctx0, mlp_2, GGML_OP_POOL_AVG, 2, 2, 2, 2, 0, 0);
  784. // weight ne = [3, 3, 2048, 1]
  785. struct ggml_tensor * peg_0 = ggml_conv_depthwise_2d(ctx0, model.mm_model_peg_0_w, mlp_2, 1, 1, 1, 1, 1, 1);
  786. peg_0 = ggml_cont(ctx0, ggml_permute(ctx0, peg_0, 1, 2, 0, 3));
  787. peg_0 = ggml_add(ctx0, peg_0, model.mm_model_peg_0_b);
  788. mlp_2 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_2, 1, 2, 0, 3));
  789. peg_0 = ggml_add(ctx0, peg_0, mlp_2);
  790. peg_0 = ggml_reshape_3d(ctx0, peg_0, peg_0->ne[0], peg_0->ne[1] * peg_0->ne[2], peg_0->ne[3]);
  791. embeddings = peg_0;
  792. }
  793. else {
  794. GGML_ABORT("fatal error");
  795. }
  796. }
  797. // minicpmv projector
  798. else if (ctx->has_minicpmv_projector)
  799. {
  800. if (ctx->proj_type == PROJECTOR_TYPE_RESAMPLER) {
  801. struct ggml_tensor * q = model.mm_model_query;
  802. { // layernorm
  803. q = ggml_norm(ctx0, q, eps);
  804. q = ggml_add(ctx0, ggml_mul(ctx0, q, model.mm_model_ln_q_w), model.mm_model_ln_q_b);
  805. }
  806. struct ggml_tensor * v = ggml_mul_mat(ctx0, model.mm_model_kv_proj, embeddings);
  807. { // layernorm
  808. v = ggml_norm(ctx0, v, eps);
  809. v = ggml_add(ctx0, ggml_mul(ctx0, v, model.mm_model_ln_kv_w), model.mm_model_ln_kv_b);
  810. }
  811. struct ggml_tensor * k;
  812. { // position
  813. // q = ggml_add(ctx0, q, model.mm_model_pos_embed);
  814. k = ggml_add(ctx0, v, pos_embed);
  815. }
  816. { // attention
  817. int hidden_size = 4096;
  818. const int d_head = 128;
  819. int n_head = hidden_size/d_head;
  820. int num_query = 96;
  821. if (ctx->minicpmv_version == 2) {
  822. hidden_size = 4096;
  823. n_head = hidden_size/d_head;
  824. num_query = 96;
  825. }
  826. else if (ctx->minicpmv_version == 3) {
  827. hidden_size = 3584;
  828. n_head = hidden_size/d_head;
  829. num_query = 64;
  830. }
  831. struct ggml_tensor * Q = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_q_w, q), model.mm_model_attn_q_b);
  832. Q = ggml_scale_inplace(ctx0, Q, 1.0f / sqrt((float)d_head));
  833. struct ggml_tensor * K = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_k_w, k), model.mm_model_attn_k_b);
  834. struct ggml_tensor * V = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_v_w, v), model.mm_model_attn_v_b);
  835. // permute
  836. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_query, batch_size);
  837. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  838. Q = ggml_reshape_3d(ctx0, Q, d_head, num_query, n_head * batch_size);
  839. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  840. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  841. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  842. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  843. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  844. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  845. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  846. KQ = ggml_soft_max_inplace(ctx0, KQ);
  847. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  848. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_query, n_head, batch_size);
  849. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  850. KQV = ggml_cont_3d(ctx0, KQV, hidden_size, num_query, batch_size);
  851. embeddings = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_o_w, KQV), model.mm_model_attn_o_b);
  852. }
  853. { // layernorm
  854. embeddings = ggml_norm(ctx0, embeddings, eps);
  855. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_model_ln_post_w), model.mm_model_ln_post_b);
  856. }
  857. embeddings = ggml_mul_mat(ctx0, model.mm_model_proj, embeddings);
  858. }
  859. else {
  860. GGML_ASSERT(false);
  861. }
  862. }
  863. // build the graph
  864. ggml_build_forward_expand(gf, embeddings);
  865. ggml_free(ctx0);
  866. return gf;
  867. }
  868. // read and create ggml_context containing the tensors and their data
  869. struct clip_ctx * clip_model_load(const char * fname, const int verbosity = 1) {
  870. struct ggml_context * meta = NULL;
  871. struct gguf_init_params params = {
  872. /*.no_alloc = */ true,
  873. /*.ctx = */ &meta,
  874. };
  875. struct gguf_context * ctx = gguf_init_from_file(fname, params);
  876. if (!ctx) {
  877. throw std::runtime_error(format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  878. }
  879. if (verbosity >= 1) {
  880. const int n_tensors = gguf_get_n_tensors(ctx);
  881. const int n_kv = gguf_get_n_kv(ctx);
  882. const int ftype = get_u32(ctx, KEY_FTYPE);
  883. const std::string ftype_str = get_ftype(ftype);
  884. const int idx_desc = get_key_idx(ctx, KEY_DESCRIPTION);
  885. const std::string description = gguf_get_val_str(ctx, idx_desc);
  886. const int idx_name = gguf_find_key(ctx, KEY_NAME);
  887. if (idx_name != -1) { // make name optional temporarily as some of the uploaded models missing it due to a bug
  888. const std::string name = gguf_get_val_str(ctx, idx_name);
  889. LOG_TEE("%s: model name: %s\n", __func__, name.c_str());
  890. }
  891. LOG_TEE("%s: description: %s\n", __func__, description.c_str());
  892. LOG_TEE("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx));
  893. LOG_TEE("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx));
  894. LOG_TEE("%s: n_tensors: %d\n", __func__, n_tensors);
  895. LOG_TEE("%s: n_kv: %d\n", __func__, n_kv);
  896. LOG_TEE("%s: ftype: %s\n", __func__, ftype_str.c_str());
  897. LOG_TEE("\n");
  898. }
  899. const int n_tensors = gguf_get_n_tensors(ctx);
  900. // kv
  901. const int n_kv = gguf_get_n_kv(ctx);
  902. LOG_TEE("%s: loaded meta data with %d key-value pairs and %d tensors from %s\n",
  903. __func__, n_kv, n_tensors, fname);
  904. {
  905. std::map<enum ggml_type, uint32_t> n_type;
  906. for (int i = 0; i < n_tensors; i++) {
  907. enum ggml_type type = gguf_get_tensor_type(ctx, i);
  908. n_type[type]++;
  909. }
  910. LOG_TEE("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  911. for (int i = 0; i < n_kv; i++) {
  912. const char * name = gguf_get_key(ctx, i);
  913. const enum gguf_type type = gguf_get_kv_type(ctx, i);
  914. const std::string type_name =
  915. type == GGUF_TYPE_ARRAY
  916. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx, i)), gguf_get_arr_n(ctx, i))
  917. : gguf_type_name(type);
  918. std::string value = gguf_kv_to_str(ctx, i);
  919. const size_t MAX_VALUE_LEN = 40;
  920. if (value.size() > MAX_VALUE_LEN) {
  921. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  922. }
  923. replace_all(value, "\n", "\\n");
  924. LOG_TEE("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  925. }
  926. // print type counts
  927. for (auto & kv : n_type) {
  928. if (kv.second == 0) {
  929. continue;
  930. }
  931. LOG_TEE("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  932. }
  933. }
  934. // data
  935. size_t model_size = 0;
  936. {
  937. for (int i = 0; i < n_tensors; ++i) {
  938. const char * name = gguf_get_tensor_name(ctx, i);
  939. const size_t offset = gguf_get_tensor_offset(ctx, i);
  940. enum ggml_type type = gguf_get_tensor_type(ctx, i);
  941. struct ggml_tensor * cur = ggml_get_tensor(meta, name);
  942. size_t tensor_size = ggml_nbytes(cur);
  943. model_size += tensor_size;
  944. if (verbosity >= 3) {
  945. LOG_TEE("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu, shape:[%" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "], type = %s\n",
  946. __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));
  947. }
  948. }
  949. }
  950. clip_ctx * new_clip = new clip_ctx{};
  951. // update projector type
  952. {
  953. int idx = gguf_find_key(ctx, KEY_PROJ_TYPE);
  954. if (idx != -1) {
  955. const std::string proj_type = gguf_get_val_str(ctx, idx);
  956. new_clip->proj_type = clip_projector_type_from_string(proj_type);
  957. } else {
  958. new_clip->proj_type = PROJECTOR_TYPE_MLP;
  959. }
  960. if (new_clip->proj_type == PROJECTOR_TYPE_MLP) {
  961. if (gguf_find_tensor(ctx, format(TN_LLAVA_PROJ, 3, "weight").c_str()) != -1) {
  962. new_clip->proj_type = PROJECTOR_TYPE_MLP_NORM;
  963. }
  964. }
  965. }
  966. #ifdef GGML_USE_CUDA
  967. new_clip->backend = ggml_backend_cuda_init(0);
  968. LOG_TEE("%s: CLIP using CUDA backend\n", __func__);
  969. #endif
  970. #ifdef GGML_USE_METAL
  971. new_clip->backend = ggml_backend_metal_init();
  972. LOG_TEE("%s: CLIP using Metal backend\n", __func__);
  973. #endif
  974. #ifdef GGML_USE_CANN
  975. new_clip->backend = ggml_backend_cann_init(0);
  976. LOG_TEE("%s: CLIP using CANN backend\n", __func__);
  977. #endif
  978. #ifdef GGML_USE_VULKAN
  979. new_clip->backend = ggml_backend_vk_init(0);
  980. LOG_TEE("%s: CLIP using Vulkan backend\n", __func__);
  981. #endif
  982. if (!new_clip->backend) {
  983. new_clip->backend = ggml_backend_cpu_init();
  984. LOG_TEE("%s: CLIP using CPU backend\n", __func__);
  985. }
  986. // model size and capabilities
  987. {
  988. int idx = get_key_idx(ctx, KEY_HAS_TEXT_ENC);
  989. new_clip->has_text_encoder = gguf_get_val_bool(ctx, idx);
  990. idx = get_key_idx(ctx, KEY_HAS_VIS_ENC);
  991. new_clip->has_vision_encoder = gguf_get_val_bool(ctx, idx);
  992. idx = gguf_find_key(ctx, KEY_HAS_LLAVA_PROJ);
  993. if (idx != -1) {
  994. new_clip->has_llava_projector = gguf_get_val_bool(ctx, idx);
  995. }
  996. idx = gguf_find_key(ctx, KEY_HAS_MINICPMV_PROJ);
  997. if (idx != -1) {
  998. new_clip->has_minicpmv_projector = gguf_get_val_bool(ctx, idx);
  999. }
  1000. idx = gguf_find_key(ctx, KEY_MINICPMV_VERSION);
  1001. if (idx != -1) {
  1002. new_clip->minicpmv_version = gguf_get_val_i32(ctx, idx);
  1003. }
  1004. // GGML_ASSERT(new_clip->has_llava_projector); // see monatis/clip.cpp for image and/or text encoding for semantic search
  1005. GGML_ASSERT(new_clip->has_vision_encoder);
  1006. GGML_ASSERT(!new_clip->has_text_encoder);
  1007. idx = get_key_idx(ctx, KEY_USE_GELU);
  1008. new_clip->use_gelu = gguf_get_val_bool(ctx, idx);
  1009. if (verbosity >= 1) {
  1010. LOG_TEE("%s: text_encoder: %d\n", __func__, new_clip->has_text_encoder);
  1011. LOG_TEE("%s: vision_encoder: %d\n", __func__, new_clip->has_vision_encoder);
  1012. LOG_TEE("%s: llava_projector: %d\n", __func__, new_clip->has_llava_projector);
  1013. LOG_TEE("%s: minicpmv_projector: %d\n", __func__, new_clip->has_minicpmv_projector);
  1014. LOG_TEE("%s: model size: %.2f MB\n", __func__, model_size / 1024.0 / 1024.0);
  1015. LOG_TEE("%s: metadata size: %.2f MB\n", __func__, ggml_get_mem_size(meta) / 1024.0 / 1024.0);
  1016. }
  1017. }
  1018. LOG_TEE("%s: params backend buffer size = % 6.2f MB (%i tensors)\n", __func__, model_size / (1024.0 * 1024.0), n_tensors);
  1019. // load tensors
  1020. {
  1021. std::vector<uint8_t> read_buf;
  1022. struct ggml_init_params params = {
  1023. /*.mem_size =*/ (n_tensors + 1) * ggml_tensor_overhead(),
  1024. /*.mem_buffer =*/ NULL,
  1025. /*.no_alloc =*/ true,
  1026. };
  1027. new_clip->ctx_data = ggml_init(params);
  1028. if (!new_clip->ctx_data) {
  1029. LOG_TEE("%s: ggml_init() failed\n", __func__);
  1030. clip_free(new_clip);
  1031. gguf_free(ctx);
  1032. return nullptr;
  1033. }
  1034. auto fin = std::ifstream(fname, std::ios::binary);
  1035. if (!fin) {
  1036. LOG_TEE("cannot open model file for loading tensors\n");
  1037. clip_free(new_clip);
  1038. gguf_free(ctx);
  1039. return nullptr;
  1040. }
  1041. // add tensors to context
  1042. for (int i = 0; i < n_tensors; ++i) {
  1043. const char * name = gguf_get_tensor_name(ctx, i);
  1044. struct ggml_tensor * t = ggml_get_tensor(meta, name);
  1045. struct ggml_tensor * cur = ggml_dup_tensor(new_clip->ctx_data, t);
  1046. ggml_set_name(cur, name);
  1047. }
  1048. // alloc memory and offload data
  1049. new_clip->params_buffer = ggml_backend_alloc_ctx_tensors(new_clip->ctx_data, new_clip->backend);
  1050. for (int i = 0; i < n_tensors; ++i) {
  1051. const char * name = gguf_get_tensor_name(ctx, i);
  1052. struct ggml_tensor * cur = ggml_get_tensor(new_clip->ctx_data, name);
  1053. const size_t offset = gguf_get_data_offset(ctx) + gguf_get_tensor_offset(ctx, i);
  1054. fin.seekg(offset, std::ios::beg);
  1055. if (!fin) {
  1056. LOG_TEE("%s: failed to seek for tensor %s\n", __func__, name);
  1057. clip_free(new_clip);
  1058. gguf_free(ctx);
  1059. return nullptr;
  1060. }
  1061. int num_bytes = ggml_nbytes(cur);
  1062. if (ggml_backend_buffer_is_host(new_clip->params_buffer)) {
  1063. // for the CPU and Metal backend, we can read directly into the tensor
  1064. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  1065. } else {
  1066. // read into a temporary buffer first, then copy to device memory
  1067. read_buf.resize(num_bytes);
  1068. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  1069. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  1070. }
  1071. }
  1072. fin.close();
  1073. }
  1074. // vision model
  1075. if (new_clip->has_vision_encoder) {
  1076. // load vision model
  1077. auto & vision_model = new_clip->vision_model;
  1078. auto & hparams = vision_model.hparams;
  1079. hparams.hidden_size = get_u32(ctx, format(KEY_N_EMBD, "vision"));
  1080. hparams.n_head = get_u32(ctx, format(KEY_N_HEAD, "vision"));
  1081. hparams.n_intermediate = get_u32(ctx, format(KEY_N_FF, "vision"));
  1082. hparams.n_layer = get_u32(ctx, format(KEY_N_BLOCK, "vision"));
  1083. hparams.image_size = get_u32(ctx, KEY_IMAGE_SIZE);
  1084. hparams.patch_size = get_u32(ctx, KEY_PATCH_SIZE);
  1085. hparams.projection_dim = get_u32(ctx, format(KEY_PROJ_DIM, "vision"));
  1086. hparams.eps = get_f32(ctx, format(KEY_LAYER_NORM_EPS, "vision"));
  1087. try {
  1088. int idx = get_key_idx(ctx, KEY_IMAGE_GRID_PINPOINTS);
  1089. int n = gguf_get_arr_n(ctx, idx);
  1090. const int32_t * pinpoints = (const int32_t *)gguf_get_arr_data(ctx, idx);
  1091. for (int i = 0; i < 32 && i < n && pinpoints[i] != 0; ++i) {
  1092. hparams.image_grid_pinpoints[i] = pinpoints[i];
  1093. }
  1094. if (n < 32)
  1095. hparams.image_grid_pinpoints[n] = 0;
  1096. } catch (std::runtime_error & /*e*/) {
  1097. hparams.image_grid_pinpoints[0]=0;
  1098. }
  1099. try {
  1100. int idx = get_key_idx(ctx, KEY_MM_PATCH_MERGE_TYPE);
  1101. strcpy(hparams.mm_patch_merge_type, gguf_get_val_str(ctx, idx));
  1102. } catch (std::runtime_error & /*e*/) {
  1103. strcpy(hparams.mm_patch_merge_type, "flat");
  1104. }
  1105. try {
  1106. hparams.image_crop_resolution = get_u32(ctx, KEY_IMAGE_CROP_RESOLUTION); // llava-1.6
  1107. } catch(const std::exception& /*e*/) {
  1108. hparams.image_crop_resolution = hparams.image_size;
  1109. }
  1110. int idx_mean = get_key_idx(ctx, KEY_IMAGE_MEAN);
  1111. int idx_std = get_key_idx(ctx, KEY_IMAGE_STD);
  1112. const float * mean_data = (const float *)gguf_get_arr_data(ctx, idx_mean);
  1113. const float * std_data = (const float *)gguf_get_arr_data(ctx, idx_std);
  1114. for (int i = 0; i < 3; ++i) {
  1115. new_clip->image_mean[i] = mean_data[i];
  1116. new_clip->image_std[i] = std_data[i];
  1117. }
  1118. if (verbosity >= 2) {
  1119. LOG_TEE("\n%s: vision model hparams\n", __func__);
  1120. LOG_TEE("image_size %d\n", hparams.image_size);
  1121. LOG_TEE("patch_size %d\n", hparams.patch_size);
  1122. LOG_TEE("v_hidden_size %d\n", hparams.hidden_size);
  1123. LOG_TEE("v_n_intermediate %d\n", hparams.n_intermediate);
  1124. LOG_TEE("v_projection_dim %d\n", hparams.projection_dim);
  1125. LOG_TEE("v_n_head %d\n", hparams.n_head);
  1126. LOG_TEE("v_n_layer %d\n", hparams.n_layer);
  1127. LOG_TEE("v_eps %f\n", hparams.eps);
  1128. LOG_TEE("v_image_mean %f %f %f\n", new_clip->image_mean[0], new_clip->image_mean[1], new_clip->image_mean[2]);
  1129. LOG_TEE("v_image_std %f %f %f\n", new_clip->image_std[0], new_clip->image_std[1], new_clip->image_std[2]);
  1130. LOG_TEE("v_image_grid_pinpoints: ");
  1131. for (int i = 0; i < 32 && (hparams.image_grid_pinpoints[i] != 0); ++i) {
  1132. LOG_TEE("%d ", hparams.image_grid_pinpoints[i]);
  1133. }
  1134. LOG_TEE("\n");
  1135. LOG_TEE("v_mm_patch_merge_type: %s\n", hparams.mm_patch_merge_type);
  1136. }
  1137. try {
  1138. vision_model.class_embedding = get_tensor(new_clip->ctx_data, TN_CLASS_EMBD);
  1139. new_clip->has_class_embedding = true;
  1140. } catch (const std::exception& /*e*/) {
  1141. new_clip->has_class_embedding = false;
  1142. }
  1143. try {
  1144. vision_model.pre_ln_w = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "weight"));
  1145. vision_model.pre_ln_b = get_tensor(new_clip->ctx_data, format(TN_LN_PRE, "v", "bias"));
  1146. new_clip->has_pre_norm = true;
  1147. } catch (std::exception & /*e*/) {
  1148. new_clip->has_pre_norm = false;
  1149. }
  1150. try {
  1151. vision_model.post_ln_w = get_tensor(new_clip->ctx_data, format(TN_LN_POST, "v", "weight"));
  1152. vision_model.post_ln_b = get_tensor(new_clip->ctx_data, format(TN_LN_POST, "v", "bias"));
  1153. new_clip->has_post_norm = true;
  1154. } catch (std::exception & /*e*/) {
  1155. new_clip->has_post_norm = false;
  1156. }
  1157. try {
  1158. vision_model.patch_bias = get_tensor(new_clip->ctx_data, TN_PATCH_BIAS);
  1159. new_clip->has_patch_bias = true;
  1160. } catch (std::exception & /*e*/) {
  1161. new_clip->has_patch_bias = false;
  1162. }
  1163. try {
  1164. vision_model.patch_embeddings = get_tensor(new_clip->ctx_data, TN_PATCH_EMBD);
  1165. vision_model.position_embeddings = get_tensor(new_clip->ctx_data, format(TN_POS_EMBD, "v"));
  1166. } catch(const std::exception& /*e*/) {
  1167. LOG_TEE("%s: failed to load vision model tensors\n", __func__);
  1168. }
  1169. // LLaVA projection
  1170. if (new_clip->proj_type == PROJECTOR_TYPE_MLP || new_clip->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  1171. vision_model.mm_0_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "weight"));
  1172. vision_model.mm_0_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 0, "bias"));
  1173. try {
  1174. // Yi-type llava
  1175. vision_model.mm_1_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 1, "weight"));
  1176. vision_model.mm_1_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 1, "bias"));
  1177. } catch (std::runtime_error & /*e*/) { }
  1178. try {
  1179. // missing in Yi-type llava
  1180. vision_model.mm_2_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "weight"));
  1181. vision_model.mm_2_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 2, "bias"));
  1182. } catch (std::runtime_error & /*e*/) { }
  1183. try {
  1184. // Yi-type llava
  1185. vision_model.mm_3_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 3, "weight"));
  1186. vision_model.mm_3_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 3, "bias"));
  1187. } catch (std::runtime_error & /*e*/) { }
  1188. try {
  1189. // Yi-type llava
  1190. vision_model.mm_4_w = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 4, "weight"));
  1191. vision_model.mm_4_b = get_tensor(new_clip->ctx_data, format(TN_LLAVA_PROJ, 4, "bias"));
  1192. } catch (std::runtime_error & /*e*/) { }
  1193. try {
  1194. vision_model.image_newline = get_tensor(new_clip->ctx_data, TN_IMAGE_NEWLINE);
  1195. // LOG_TEE("%s: image_newline tensor (llava-1.6) found\n", __func__);
  1196. } catch (std::runtime_error & /*e*/) { }
  1197. } else if (new_clip->proj_type == PROJECTOR_TYPE_LDP) {
  1198. // MobileVLM projection
  1199. vision_model.mm_model_mlp_1_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1200. vision_model.mm_model_mlp_1_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 1, "bias"));
  1201. vision_model.mm_model_mlp_3_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 3, "weight"));
  1202. vision_model.mm_model_mlp_3_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 3, "bias"));
  1203. 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"));
  1204. 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"));
  1205. 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"));
  1206. 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"));
  1207. 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"));
  1208. 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"));
  1209. 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"));
  1210. 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"));
  1211. 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"));
  1212. 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"));
  1213. 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"));
  1214. 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"));
  1215. 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"));
  1216. 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"));
  1217. 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"));
  1218. 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"));
  1219. 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"));
  1220. 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"));
  1221. 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"));
  1222. 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"));
  1223. }
  1224. else if (new_clip->proj_type == PROJECTOR_TYPE_LDPV2)
  1225. {
  1226. // MobilVLM_V2 projection
  1227. vision_model.mm_model_mlp_0_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 0, "weight"));
  1228. vision_model.mm_model_mlp_0_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 0, "bias"));
  1229. vision_model.mm_model_mlp_2_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 2, "weight"));
  1230. vision_model.mm_model_mlp_2_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_MLP, 2, "bias"));
  1231. vision_model.mm_model_peg_0_w = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_PEG, 0, "weight"));
  1232. vision_model.mm_model_peg_0_b = get_tensor(new_clip->ctx_data, format(TN_MVLM_PROJ_PEG, 0, "bias"));
  1233. }
  1234. else if (new_clip->proj_type == PROJECTOR_TYPE_RESAMPLER) {
  1235. // vision_model.mm_model_pos_embed = get_tensor(new_clip->ctx_data, TN_MINICPMV_POS_EMBD);
  1236. vision_model.mm_model_pos_embed_k = get_tensor(new_clip->ctx_data, TN_MINICPMV_POS_EMBD_K);
  1237. vision_model.mm_model_query = get_tensor(new_clip->ctx_data, TN_MINICPMV_QUERY);
  1238. vision_model.mm_model_proj = get_tensor(new_clip->ctx_data, TN_MINICPMV_PROJ);
  1239. vision_model.mm_model_kv_proj = get_tensor(new_clip->ctx_data, TN_MINICPMV_KV_PROJ);
  1240. vision_model.mm_model_attn_q_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "q", "weight"));
  1241. vision_model.mm_model_attn_k_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "k", "weight"));
  1242. vision_model.mm_model_attn_v_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "v", "weight"));
  1243. vision_model.mm_model_attn_q_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "q", "bias"));
  1244. vision_model.mm_model_attn_k_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "k", "bias"));
  1245. vision_model.mm_model_attn_v_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "v", "bias"));
  1246. vision_model.mm_model_attn_o_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "out", "weight"));
  1247. vision_model.mm_model_attn_o_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_ATTN, "out", "bias"));
  1248. vision_model.mm_model_ln_q_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_LN, "q", "weight"));
  1249. vision_model.mm_model_ln_q_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_LN, "q", "bias"));
  1250. vision_model.mm_model_ln_kv_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_LN, "kv", "weight"));
  1251. vision_model.mm_model_ln_kv_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_LN, "kv", "bias"));
  1252. vision_model.mm_model_ln_post_w = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_LN, "post", "weight"));
  1253. vision_model.mm_model_ln_post_b = get_tensor(new_clip->ctx_data, format(TN_MINICPMV_LN, "post", "bias"));
  1254. }
  1255. else {
  1256. std::string proj_type = PROJECTOR_TYPE_NAMES[new_clip->proj_type];
  1257. throw std::runtime_error(format("%s: don't support projector with: %s currently\n", __func__, proj_type.c_str()));
  1258. }
  1259. vision_model.layers.resize(hparams.n_layer);
  1260. for (int il = 0; il < hparams.n_layer; ++il) {
  1261. auto & layer = vision_model.layers[il];
  1262. layer.k_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "weight"));
  1263. layer.q_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "weight"));
  1264. layer.v_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "weight"));
  1265. layer.o_w = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "weight"));
  1266. layer.ln_1_w = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "weight"));
  1267. layer.ln_2_w = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "weight"));
  1268. layer.ff_i_w = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "weight"));
  1269. layer.ff_o_w = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "weight"));
  1270. layer.k_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_K, "v", il, "bias"));
  1271. layer.q_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_Q, "v", il, "bias"));
  1272. layer.v_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_V, "v", il, "bias"));
  1273. layer.o_b = get_tensor(new_clip->ctx_data, format(TN_ATTN_OUTPUT, "v", il, "bias"));
  1274. layer.ln_1_b = get_tensor(new_clip->ctx_data, format(TN_LN_1, "v", il, "bias"));
  1275. layer.ln_2_b = get_tensor(new_clip->ctx_data, format(TN_LN_2, "v", il, "bias"));
  1276. layer.ff_i_b = get_tensor(new_clip->ctx_data, format(TN_FFN_DOWN, "v", il, "bias"));
  1277. layer.ff_o_b = get_tensor(new_clip->ctx_data, format(TN_FFN_UP, "v", il, "bias"));
  1278. }
  1279. }
  1280. ggml_free(meta);
  1281. new_clip->ctx_gguf = ctx;
  1282. // measure mem requirement and allocate
  1283. {
  1284. new_clip->buf_compute_meta.resize(GGML_DEFAULT_GRAPH_SIZE * ggml_tensor_overhead() + ggml_graph_overhead());
  1285. new_clip->compute_alloc = ggml_gallocr_new(ggml_backend_get_default_buffer_type(new_clip->backend));
  1286. clip_image_f32_batch batch;
  1287. batch.size = 1;
  1288. ggml_cgraph * gf = clip_image_build_graph(new_clip, &batch, nullptr, false);
  1289. ggml_gallocr_reserve(new_clip->compute_alloc, gf);
  1290. size_t compute_memory_buffer_size = ggml_gallocr_get_buffer_size(new_clip->compute_alloc, 0);
  1291. LOG_TEE("%s: compute allocated memory: %.2f MB\n", __func__, compute_memory_buffer_size /1024.0/1024.0);
  1292. }
  1293. return new_clip;
  1294. }
  1295. void clip_add_load_image_size(struct clip_ctx * ctx_clip, struct clip_image_size * load_image_size) {
  1296. ctx_clip->load_image_size = load_image_size;
  1297. }
  1298. struct clip_image_size * clip_image_size_init() {
  1299. struct clip_image_size * load_image_size = new struct clip_image_size();
  1300. load_image_size->width = 448;
  1301. load_image_size->height = 448;
  1302. return load_image_size;
  1303. }
  1304. struct clip_image_u8 * clip_image_u8_init() {
  1305. return new clip_image_u8();
  1306. }
  1307. struct clip_image_f32 * clip_image_f32_init() {
  1308. return new clip_image_f32();
  1309. }
  1310. void clip_image_u8_free(struct clip_image_u8 * img) { delete img; }
  1311. void clip_image_f32_free(struct clip_image_f32 * img) { delete img; }
  1312. void clip_image_u8_batch_free(struct clip_image_u8_batch * batch) {
  1313. if (batch->size > 0) {
  1314. delete[] batch->data;
  1315. batch->size = 0;
  1316. }
  1317. }
  1318. void clip_image_f32_batch_free(struct clip_image_f32_batch * batch) {
  1319. if (batch->size > 0) {
  1320. delete[] batch->data;
  1321. batch->size = 0;
  1322. }
  1323. }
  1324. static void build_clip_img_from_data(const stbi_uc * data, int nx, int ny, clip_image_u8 * img) {
  1325. img->nx = nx;
  1326. img->ny = ny;
  1327. img->buf.resize(3 * nx * ny);
  1328. memcpy(img->buf.data(), data, img->buf.size());
  1329. }
  1330. bool clip_image_load_from_file(const char * fname, clip_image_u8 * img) {
  1331. int nx, ny, nc;
  1332. auto * data = stbi_load(fname, &nx, &ny, &nc, 3);
  1333. if (!data) {
  1334. LOG_TEE("%s: failed to load image '%s'\n", __func__, fname);
  1335. return false;
  1336. }
  1337. build_clip_img_from_data(data, nx, ny, img);
  1338. stbi_image_free(data);
  1339. return true;
  1340. }
  1341. bool clip_image_load_from_bytes(const unsigned char * bytes, size_t bytes_length, struct clip_image_u8 * img) {
  1342. int nx, ny, nc;
  1343. auto * data = stbi_load_from_memory(bytes, bytes_length, &nx, &ny, &nc, 3);
  1344. if (!data) {
  1345. LOG_TEE("%s: failed to decode image bytes\n", __func__);
  1346. return false;
  1347. }
  1348. build_clip_img_from_data(data, nx, ny, img);
  1349. stbi_image_free(data);
  1350. return true;
  1351. }
  1352. // Linear interpolation between two points
  1353. inline float clip_lerp(float s, float e, float t) {
  1354. return s + (e - s) * t;
  1355. }
  1356. // Bilinear resize function
  1357. static void bilinear_resize(const clip_image_u8& src, clip_image_u8& dst, int target_width, int target_height) {
  1358. dst.nx = target_width;
  1359. dst.ny = target_height;
  1360. dst.buf.resize(3 * target_width * target_height);
  1361. float x_ratio = static_cast<float>(src.nx - 1) / target_width;
  1362. float y_ratio = static_cast<float>(src.ny - 1) / target_height;
  1363. for (int y = 0; y < target_height; y++) {
  1364. for (int x = 0; x < target_width; x++) {
  1365. float px = x_ratio * x;
  1366. float py = y_ratio * y;
  1367. int x_floor = static_cast<int>(px);
  1368. int y_floor = static_cast<int>(py);
  1369. float x_lerp = px - x_floor;
  1370. float y_lerp = py - y_floor;
  1371. for (int c = 0; c < 3; c++) {
  1372. float top = clip_lerp(
  1373. static_cast<float>(src.buf[3 * (y_floor * src.nx + x_floor) + c]),
  1374. static_cast<float>(src.buf[3 * (y_floor * src.nx + (x_floor + 1)) + c]),
  1375. x_lerp
  1376. );
  1377. float bottom = clip_lerp(
  1378. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + x_floor) + c]),
  1379. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + (x_floor + 1)) + c]),
  1380. x_lerp
  1381. );
  1382. dst.buf[3 * (y * target_width + x) + c] = static_cast<uint8_t>(clip_lerp(top, bottom, y_lerp));
  1383. }
  1384. }
  1385. }
  1386. }
  1387. // Normalize image to float32 - careful with pytorch .to(model.device, dtype=torch.float16) - this sometimes reduces precision (32>16>32), sometimes not
  1388. static void normalize_image_u8_to_f32(const clip_image_u8* src, clip_image_f32* dst, const float mean[3], const float std[3]) {
  1389. dst->nx = src->nx;
  1390. dst->ny = src->ny;
  1391. dst->buf.resize(src->buf.size());
  1392. for (size_t i = 0; i < src->buf.size(); ++i) {
  1393. int c = i % 3; // rgb
  1394. dst->buf[i] = (static_cast<float>(src->buf[i]) / 255.0f - mean[c]) / std[c];
  1395. }
  1396. }
  1397. inline float clip(float x, float lower, float upper) {
  1398. return std::max(lower, std::min(x, upper));
  1399. }
  1400. static bool bicubic_resize(const clip_image_u8 &img, clip_image_u8 &dst, int target_width, int target_height) {
  1401. const int nx = img.nx;
  1402. const int ny = img.ny;
  1403. dst.nx = target_width;
  1404. dst.ny = target_height;
  1405. dst.buf.resize(3 * target_width * target_height);
  1406. float Cc;
  1407. float C[5];
  1408. float d0, d2, d3, a0, a1, a2, a3;
  1409. int i, j, k, jj;
  1410. int x, y;
  1411. float dx, dy;
  1412. float tx, ty;
  1413. tx = (float)nx / (float)target_width;
  1414. ty = (float)ny / (float)target_height;
  1415. // Bicubic interpolation; adapted from ViT.cpp, inspired from :
  1416. // -> https://github.com/yglukhov/bicubic-interpolation-image-processing/blob/master/libimage.c#L36
  1417. // -> https://en.wikipedia.org/wiki/Bicubic_interpolation
  1418. for (i = 0; i < target_height; i++) {
  1419. for (j = 0; j < target_width; j++) {
  1420. x = (int)(tx * j);
  1421. y = (int)(ty * i);
  1422. dx = tx * j - x;
  1423. dy = ty * i - y;
  1424. for (k = 0; k < 3; k++) {
  1425. for (jj = 0; jj <= 3; jj++) {
  1426. 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];
  1427. 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];
  1428. 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];
  1429. a0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  1430. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  1431. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  1432. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  1433. C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx;
  1434. d0 = C[0] - C[1];
  1435. d2 = C[2] - C[1];
  1436. d3 = C[3] - C[1];
  1437. a0 = C[1];
  1438. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  1439. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  1440. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  1441. Cc = a0 + a1 * dy + a2 * dy * dy + a3 * dy * dy * dy;
  1442. const uint8_t Cc2 = std::min(std::max(std::round(Cc), 0.0f), 255.0f);
  1443. dst.buf[(i * target_width + j) * 3 + k] = float(Cc2);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. return true;
  1449. }
  1450. // llava-1.6 type of resize_and_pad (black)
  1451. static void resize_and_pad_image(const clip_image_u8& image, clip_image_u8 &image_output, const std::pair<int, int>& target_resolution) {
  1452. int target_width = target_resolution.first;
  1453. int target_height = target_resolution.second;
  1454. float scale_w = static_cast<float>(target_width) / image.nx;
  1455. float scale_h = static_cast<float>(target_height) / image.ny;
  1456. int new_width, new_height;
  1457. if (scale_w < scale_h) {
  1458. new_width = target_width;
  1459. new_height = std::min(static_cast<int>(std::ceil(image.ny * scale_w)), target_height);
  1460. } else {
  1461. new_height = target_height;
  1462. new_width = std::min(static_cast<int>(std::ceil(image.nx * scale_h)), target_width);
  1463. }
  1464. clip_image_u8 resized_image;
  1465. // bilinear_resize(image, resized_image, new_width, new_height);
  1466. bicubic_resize(image, resized_image, new_width, new_height);
  1467. clip_image_u8 padded_image;
  1468. padded_image.nx = target_width;
  1469. padded_image.ny = target_height;
  1470. padded_image.buf.resize(3 * target_width * target_height, 0); // Initialize with black
  1471. // Calculate padding offsets
  1472. int pad_x = (target_width - new_width) / 2;
  1473. int pad_y = (target_height - new_height) / 2;
  1474. // Copy the resized image into the center of the padded buffer
  1475. for (int y = 0; y < new_height; ++y) {
  1476. for (int x = 0; x < new_width; ++x) {
  1477. for (int c = 0; c < 3; ++c) {
  1478. padded_image.buf[3 * ((y + pad_y) * target_width + (x + pad_x)) + c] = resized_image.buf[3 * (y * new_width + x) + c];
  1479. }
  1480. }
  1481. }
  1482. image_output = std::move(padded_image);
  1483. }
  1484. /**
  1485. * Selects the best resolution from a list of possible resolutions based on the original size.
  1486. *
  1487. * @param original_size The original size of the image in the format (width, height).
  1488. * @param possible_resolutions A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
  1489. * @return The best fit resolution in the format (width, height).
  1490. */
  1491. static std::pair<int, int> select_best_resolution(const std::pair<int, int> & original_size, const std::vector<std::pair<int, int>> & possible_resolutions) {
  1492. int original_width = original_size.first;
  1493. int original_height = original_size.second;
  1494. std::pair<int, int> best_fit;
  1495. int max_effective_resolution = 0;
  1496. int min_wasted_resolution = std::numeric_limits<int>::max();
  1497. for (const auto& resolution : possible_resolutions) {
  1498. int width = resolution.first;
  1499. int height = resolution.second;
  1500. float scale = std::min(static_cast<float>(width) / original_width, static_cast<float>(height) / original_height);
  1501. int downscaled_width = static_cast<int>(original_width * scale);
  1502. int downscaled_height = static_cast<int>(original_height * scale);
  1503. int effective_resolution = std::min(downscaled_width * downscaled_height, original_width * original_height);
  1504. int wasted_resolution = (width * height) - effective_resolution;
  1505. // LOG_TEE("resolution: %d %d, scale: %f, downscaled: %d %d, effective: %d, wasted: %d\n", width, height, scale, downscaled_width, downscaled_height, effective_resolution, wasted_resolution);
  1506. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_resolution < min_wasted_resolution)) {
  1507. max_effective_resolution = effective_resolution;
  1508. min_wasted_resolution = wasted_resolution;
  1509. best_fit = resolution;
  1510. }
  1511. }
  1512. return best_fit;
  1513. }
  1514. static std::vector<clip_image_u8*> divide_to_patches_u8(const clip_image_u8 & image, int patch_size) {
  1515. std::vector<clip_image_u8*> patches;
  1516. int width = image.nx;
  1517. int height = image.ny;
  1518. for (int i = 0; i < height; i += patch_size) {
  1519. for (int j = 0; j < width; j += patch_size) {
  1520. clip_image_u8 *patch = clip_image_u8_init();
  1521. patch->nx = std::min(patch_size, width - j);
  1522. patch->ny = std::min(patch_size, height - i);
  1523. patch->buf.resize(3 * patch->nx * patch->ny);
  1524. for (int y = 0; y < patch->ny; ++y) {
  1525. for (int x = 0; x < patch->nx; ++x) {
  1526. for (int c = 0; c < 3; ++c) {
  1527. patch->buf[3 * (y * patch->nx + x) + c] = image.buf[3 * ((i + y) * width + (j + x)) + c];
  1528. }
  1529. }
  1530. }
  1531. patches.push_back(patch);
  1532. }
  1533. }
  1534. return patches;
  1535. }
  1536. static int ensure_divide(int length, int patch_size) {
  1537. return std::max(static_cast<int>(std::round(static_cast<float>(length) / patch_size) * patch_size), patch_size);
  1538. }
  1539. static std::pair<int, int> uhd_find_best_resize(std::pair<int, int> original_size, int scale_resolution, int patch_size, bool allow_upscale = false) {
  1540. int width = original_size.first;
  1541. int height = original_size.second;
  1542. if ((width * height > scale_resolution * scale_resolution) || allow_upscale) {
  1543. float r = static_cast<float>(width) / height;
  1544. height = static_cast<int>(scale_resolution / std::sqrt(r));
  1545. width = static_cast<int>(height * r);
  1546. }
  1547. int best_width = ensure_divide(width, patch_size);
  1548. int best_height = ensure_divide(height, patch_size);
  1549. return std::make_pair(best_width, best_height);
  1550. }
  1551. static std::pair<int, int> uhd_get_refine_size(std::pair<int, int> original_size, std::pair<int, int> grid, int scale_resolution, int patch_size, bool allow_upscale = false) {
  1552. int width, height;
  1553. std::tie(width, height) = original_size;
  1554. int grid_x, grid_y;
  1555. std::tie(grid_x, grid_y) = grid;
  1556. int refine_width = ensure_divide(width, grid_x);
  1557. int refine_height = ensure_divide(height, grid_y);
  1558. int grid_width = refine_width / grid_x;
  1559. int grid_height = refine_height / grid_y;
  1560. // auto best_grid_size = find_best_resize(std::make_tuple(grid_width, grid_height), scale_resolution, patch_size, allow_upscale); (old line)
  1561. auto best_grid_size = uhd_find_best_resize(std::make_pair(grid_width, grid_height), scale_resolution, patch_size, allow_upscale); // (new line) => fixes conversion for make_tuple to make_pair
  1562. int best_grid_width, best_grid_height;
  1563. std::tie(best_grid_width, best_grid_height) = best_grid_size;
  1564. // std::pair<int, int> refine_size = std::make_tuple(best_grid_width * grid_x, best_grid_height * grid_y); (old line)
  1565. std::pair<int, int> refine_size = std::make_pair(best_grid_width * grid_x, best_grid_height * grid_y); // (new line)
  1566. return refine_size;
  1567. }
  1568. inline int clip(int x, int lower, int upper) {
  1569. return std::max(lower, std::min(x, upper));
  1570. }
  1571. static std::pair<int, int> uhd_best_grid(const int max_slice_nums, const int multiple, const float log_ratio) {
  1572. std::vector<int> candidate_split_grids_nums;
  1573. for (int i : {multiple - 1, multiple, multiple + 1}) {
  1574. if (i == 1 || i > max_slice_nums) {
  1575. continue;
  1576. }
  1577. candidate_split_grids_nums.push_back(i);
  1578. }
  1579. std::vector<std::pair<int, int>> candidate_grids;
  1580. for (int split_grids_nums : candidate_split_grids_nums) {
  1581. int m = 1;
  1582. while (m <= split_grids_nums) {
  1583. if (split_grids_nums % m == 0) {
  1584. candidate_grids.emplace_back(m, split_grids_nums / m);
  1585. }
  1586. ++m;
  1587. }
  1588. }
  1589. std::pair<int, int> best_grid{1, 1};
  1590. float min_error = std::numeric_limits<float>::infinity();
  1591. for (const auto& grid : candidate_grids) {
  1592. float error = std::abs(log_ratio - std::log(1.0 * grid.first / grid.second));
  1593. if (error < min_error) {
  1594. best_grid = grid;
  1595. min_error = error;
  1596. }
  1597. }
  1598. return best_grid;
  1599. }
  1600. // inspired from LLaVA-UHD:
  1601. // -> https://arxiv.org/pdf/2403.11703
  1602. // -> https://github.com/thunlp/LLaVA-UHD
  1603. // -> https://github.com/thunlp/LLaVA-UHD/blob/302301bc2175f7e717fb8548516188e89f649753/llava_uhd/train/llava-uhd/slice_logic.py#L118
  1604. static std::vector<std::vector<clip_image_u8 *>> uhd_slice_image(const clip_image_u8 * img, const int max_slice_nums=9, const int scale_resolution=448, const int patch_size=14) {
  1605. const std::pair<int, int> original_size={img->nx,img->ny};
  1606. const int original_width = img->nx;
  1607. const int original_height = img->ny;
  1608. const float log_ratio = log(1.0*original_width/original_height);
  1609. const float ratio = 1.0 * original_width * original_height/ (scale_resolution * scale_resolution);
  1610. const int multiple = fmin(ceil(ratio), max_slice_nums);
  1611. std::vector<std::vector<clip_image_u8 *>> images;
  1612. LOG_TEE("%s: multiple %d\n", __func__, multiple);
  1613. images.push_back(std::vector<clip_image_u8 *>());
  1614. if (multiple <= 1) {
  1615. auto best_size = uhd_find_best_resize(original_size, scale_resolution, patch_size, true);
  1616. clip_image_u8 * source_image = clip_image_u8_init();
  1617. bicubic_resize(*img, *source_image, best_size.first, best_size.second);
  1618. // source_image = image.resize(best_size, Image.Resampling.BICUBIC)
  1619. images[images.size()-1].push_back(source_image);
  1620. }
  1621. else if (multiple > 1) {
  1622. auto best_size = uhd_find_best_resize(original_size, scale_resolution, patch_size);
  1623. clip_image_u8 * source_image = clip_image_u8_init();
  1624. bicubic_resize(*img, *source_image, best_size.first, best_size.second);
  1625. // source_image = image.copy().resize(best_resize, Image.Resampling.BICUBIC)
  1626. LOG_TEE("%s: image_size: %d %d; source_image size: %d %d\n", __func__, img->nx, img->ny, best_size.first, best_size.second);
  1627. images[images.size()-1].push_back(source_image);
  1628. std::pair<int, int> best_grid = uhd_best_grid(max_slice_nums, multiple, log_ratio);
  1629. LOG_TEE("%s: image_size: %d %d; best_grid: %d %d\n", __func__, img->nx, img->ny, best_grid.first, best_grid.second);
  1630. auto refine_size = uhd_get_refine_size(original_size, best_grid, scale_resolution, patch_size, true);
  1631. clip_image_u8 * refine_image = clip_image_u8_init();
  1632. bicubic_resize(*img, *refine_image, refine_size.first, refine_size.second);
  1633. LOG_TEE("%s: refine_image_size: %d %d; refine_size: %d %d\n", __func__, refine_image->nx, refine_image->ny, refine_size.first, refine_size.second);
  1634. // split_to_patches
  1635. int width = refine_image->nx;
  1636. int height = refine_image->ny;
  1637. int grid_x = int(width / best_grid.first);
  1638. int grid_y = int(height / best_grid.second);
  1639. for (int patches_i = 0, ic = 0; patches_i < height && ic < best_grid.second; patches_i += grid_y, ic += 1){
  1640. images.push_back(std::vector<clip_image_u8 *>());
  1641. for(int patches_j = 0, jc = 0; patches_j < width && jc < best_grid.first; patches_j += grid_x, jc += 1){
  1642. clip_image_u8 * patch = clip_image_u8_init();
  1643. patch->nx = grid_x;
  1644. patch->ny = grid_y;
  1645. patch->buf.resize(3 * patch->nx * patch->ny);
  1646. for (int y = patches_i; y < patches_i + grid_y; ++y) {
  1647. for (int x = patches_j; x < patches_j + grid_x; ++x) {
  1648. const int i = 3 * (y * refine_image->nx + x);
  1649. const int j = 3 * ((y-patches_i) * patch->nx + (x-patches_j));
  1650. patch->buf[j] = refine_image->buf[i];
  1651. patch->buf[j+1] = refine_image->buf[i+1];
  1652. patch->buf[j+2] = refine_image->buf[i+2];
  1653. }
  1654. }
  1655. images[images.size()-1].push_back(patch);
  1656. }
  1657. }
  1658. }
  1659. return images;
  1660. }
  1661. int clip_uhd_num_image_embeds_col(struct clip_ctx * ctx_clip) {
  1662. const int max_slice_nums=9;
  1663. const int scale_resolution=448;
  1664. const int original_width = ctx_clip->load_image_size->width;
  1665. const int original_height = ctx_clip->load_image_size->height;
  1666. const float log_ratio = log(1.0*original_width/original_height);
  1667. const float ratio = 1.0 * original_width * original_height/ (scale_resolution * scale_resolution);
  1668. const int multiple = fmin(ceil(ratio), max_slice_nums);
  1669. std::pair<int, int> best_grid = uhd_best_grid(max_slice_nums, multiple, log_ratio);
  1670. return best_grid.first;
  1671. }
  1672. // 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
  1673. // res_imgs memory is being allocated here, previous allocations will be freed if found
  1674. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, clip_image_f32_batch * res_imgs) {
  1675. if(clip_is_minicpmv(ctx)){
  1676. int max_slice_nums = 9;
  1677. std::vector<std::vector<clip_image_u8 *>> imgs = uhd_slice_image(img, max_slice_nums);
  1678. res_imgs->size = 0;
  1679. for (size_t i = 0; i < imgs.size(); ++i){
  1680. res_imgs->size += imgs[i].size();
  1681. }
  1682. res_imgs->data = new clip_image_f32[res_imgs->size];
  1683. int idx = 0;
  1684. for (size_t i = 0; i < imgs.size(); ++i) {
  1685. for (size_t j = 0; j < imgs[i].size(); ++j) {
  1686. LOG_TEE("%s: %d %d\n", __func__,imgs[i][j]->nx,imgs[i][j]->ny);
  1687. clip_image_f32 * res = clip_image_f32_init();
  1688. normalize_image_u8_to_f32(imgs[i][j], res, ctx->image_mean, ctx->image_std);
  1689. res_imgs->data[idx++] = *res;
  1690. clip_image_f32_free(res);
  1691. }
  1692. }
  1693. return true;
  1694. }
  1695. bool pad_to_square = true;
  1696. if (!ctx->has_vision_encoder) {
  1697. LOG_TEE("This gguf file seems to have no vision encoder\n");
  1698. return false;
  1699. }
  1700. auto & params = ctx->vision_model.hparams;
  1701. // 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
  1702. if (strcmp(params.mm_patch_merge_type, "spatial_unpad") == 0) {
  1703. pad_to_square = false;
  1704. }
  1705. // free the previous res_imgs if any set
  1706. if (res_imgs->size > 0) {
  1707. clip_image_f32_batch_free(res_imgs);
  1708. }
  1709. res_imgs->data = nullptr;
  1710. res_imgs->size = 0;
  1711. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  1712. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  1713. clip_image_u8 * temp = clip_image_u8_init(); // we will keep the input image data here temporarily
  1714. if (pad_to_square && img->nx != img->ny) {
  1715. int longer_side = std::max(img->nx, img->ny);
  1716. temp->nx = longer_side;
  1717. temp->ny = longer_side;
  1718. temp->buf.resize(3 * longer_side * longer_side);
  1719. const uint8_t bc[3] = {122, 116, 104}; // background color in RGB from LLaVA (this is the mean rgb color * 255)
  1720. // fill with background color
  1721. for (size_t i = 0; i < temp->buf.size(); i++) {
  1722. temp->buf[i] = bc[i % 3];
  1723. }
  1724. // copy from the input image
  1725. for (int y = 0; y < img->ny; y++) {
  1726. for (int x = 0; x < img->nx; x++) {
  1727. const int i = 3 * (y * img->nx + x);
  1728. const int j = 3 * (y * temp->nx + x);
  1729. temp->buf[j] = img->buf[i];
  1730. temp->buf[j+1] = img->buf[i+1];
  1731. temp->buf[j+2] = img->buf[i+2];
  1732. }
  1733. }
  1734. } else {
  1735. if (params.image_grid_pinpoints[0] != 0) {
  1736. // "spatial_unpad" with "anyres" processing for llava-1.6
  1737. std::vector<std::pair<int, int>> possible_resolutions;
  1738. for (int i = 0; i < 32 && params.image_grid_pinpoints[i] != 0; i+=2) {
  1739. possible_resolutions.push_back({params.image_grid_pinpoints[i], params.image_grid_pinpoints[i+1]});
  1740. }
  1741. std::pair<int, int> best_resolution = select_best_resolution({img->nx, img->ny}, possible_resolutions);
  1742. // clip_image_save_to_bmp(*img, "input.bmp");
  1743. resize_and_pad_image(*img, *temp, best_resolution); // we do not pad with mean-bg color anymore in llava-1.6
  1744. // clip_image_save_to_bmp(*temp, "resized.bmp");
  1745. // visually verify normalized image:
  1746. // normalize_image_u8_to_f32(*temp, *res, ctx->image_mean, ctx->image_std);
  1747. // {
  1748. // clip_image_u8 * temp2 = clip_image_u8_init();
  1749. // clip_image_convert_f32_to_u8(*res, *temp2);
  1750. // clip_image_save_to_bmp(*temp2, "resized_normalized_f32.bmp");
  1751. // clip_image_u8_free(temp2);
  1752. // }
  1753. 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)
  1754. clip_image_u8 *image_original_resize = clip_image_u8_init();
  1755. // bilinear_resize(*img, *image_original_resize, params.image_size, params.image_size); // in python this is "shortest_edge", but all CLIP are square
  1756. bicubic_resize(*img, *image_original_resize, params.image_size, params.image_size); // in python this is "shortest_edge", but all CLIP are square
  1757. patches.insert(patches.begin(), image_original_resize);
  1758. // clip_image_f32_batch_init(patches.size());
  1759. res_imgs->size = patches.size();
  1760. res_imgs->data = new clip_image_f32[res_imgs->size];
  1761. int num=0;
  1762. for (auto& patch : patches) {
  1763. normalize_image_u8_to_f32(patch, &res_imgs->data[num], ctx->image_mean, ctx->image_std);
  1764. num++;
  1765. }
  1766. for (size_t i = 0; i < patches.size(); i++) {
  1767. // LOG_TEE("patch %d: %d %d\n", i, patches[i]->nx, patches[i]->ny);
  1768. clip_image_u8_free(patches[i]);
  1769. }
  1770. clip_image_u8_free(temp);
  1771. return true;
  1772. } else {
  1773. temp->nx = img->nx;
  1774. temp->ny = img->ny;
  1775. temp->buf.resize(img->buf.size());
  1776. memcpy(temp->buf.data(), img->buf.data(), temp->buf.size());
  1777. }
  1778. }
  1779. const int nx = temp->nx;
  1780. const int ny = temp->ny;
  1781. // clip_image_save_to_bmp(*temp, "resized_vanilla.bmp");
  1782. const int nx2 = ctx->vision_model.hparams.image_size;
  1783. const int ny2 = ctx->vision_model.hparams.image_size;
  1784. clip_image_f32 * res = clip_image_f32_init();
  1785. res->nx = nx2;
  1786. res->ny = ny2;
  1787. res->buf.resize(3 * nx2 * ny2);
  1788. const float scale = std::max(nx, ny) / (float)ctx->vision_model.hparams.image_size;
  1789. const int nx3 = int(nx / scale + 0.5f);
  1790. const int ny3 = int(ny / scale + 0.5f);
  1791. const auto & m3 = ctx->image_mean; // {0.48145466f, 0.4578275f, 0.40821073f};
  1792. const auto & s3 = ctx->image_std; // {0.26862954f, 0.26130258f, 0.27577711f};
  1793. for (int y = 0; y < ny3; y++) {
  1794. for (int x = 0; x < nx3; x++) {
  1795. for (int c = 0; c < 3; c++) {
  1796. // linear interpolation
  1797. const float sx = (x + 0.5f) * scale - 0.5f;
  1798. const float sy = (y + 0.5f) * scale - 0.5f;
  1799. const int x0 = std::max(0, (int)std::floor(sx));
  1800. const int y0 = std::max(0, (int)std::floor(sy));
  1801. const int x1 = std::min(x0 + 1, nx - 1);
  1802. const int y1 = std::min(y0 + 1, ny - 1);
  1803. const float dx = sx - x0;
  1804. const float dy = sy - y0;
  1805. const int j00 = 3 * (y0 * nx + x0) + c;
  1806. const int j01 = 3 * (y0 * nx + x1) + c;
  1807. const int j10 = 3 * (y1 * nx + x0) + c;
  1808. const int j11 = 3 * (y1 * nx + x1) + c;
  1809. const float v00 = temp->buf[j00];
  1810. const float v01 = temp->buf[j01];
  1811. const float v10 = temp->buf[j10];
  1812. const float v11 = temp->buf[j11];
  1813. const float v0 = v00 * (1.0f - dx) + v01 * dx;
  1814. const float v1 = v10 * (1.0f - dx) + v11 * dx;
  1815. const float v = v0 * (1.0f - dy) + v1 * dy;
  1816. const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
  1817. const int i = 3 * (y * nx3 + x) + c;
  1818. res->buf[i] = ((float(v2) / 255.0f) - m3[c]) / s3[c];
  1819. }
  1820. }
  1821. }
  1822. clip_image_u8_free(temp);
  1823. // {
  1824. // clip_image_u8 * temp2 = clip_image_u8_init();
  1825. // clip_image_convert_f32_to_u8(*res, *temp2);
  1826. // clip_image_save_to_bmp(*temp2, "resized_normalized_f32_vanilla.bmp");
  1827. // clip_image_u8_free(temp2);
  1828. // }
  1829. // res_imgs.push_back(res);
  1830. res_imgs->size = 1;
  1831. res_imgs->data = new clip_image_f32[res_imgs->size];
  1832. res_imgs->data[0] = *res;
  1833. clip_image_f32_free(res);
  1834. return true;
  1835. }
  1836. ggml_tensor * clip_get_newline_tensor(const struct clip_ctx * ctx) {
  1837. return ctx->vision_model.image_newline;
  1838. }
  1839. void clip_free(clip_ctx * ctx) {
  1840. ggml_free(ctx->ctx_data);
  1841. gguf_free(ctx->ctx_gguf);
  1842. ggml_backend_buffer_free(ctx->params_buffer);
  1843. ggml_backend_free(ctx->backend);
  1844. ggml_gallocr_free(ctx->compute_alloc);
  1845. delete ctx;
  1846. }
  1847. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  1848. return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);
  1849. }
  1850. int32_t clip_image_size(const struct clip_ctx * ctx) {
  1851. return ctx->vision_model.hparams.image_size;
  1852. }
  1853. int32_t clip_patch_size(const struct clip_ctx * ctx) {
  1854. return ctx->vision_model.hparams.patch_size;
  1855. }
  1856. int32_t clip_hidden_size(const struct clip_ctx * ctx) {
  1857. return ctx->vision_model.hparams.hidden_size;
  1858. }
  1859. const char * clip_patch_merge_type(const struct clip_ctx * ctx) {
  1860. return ctx->vision_model.hparams.mm_patch_merge_type;
  1861. }
  1862. const int32_t * clip_image_grid(const struct clip_ctx * ctx) {
  1863. return ctx->vision_model.hparams.image_grid_pinpoints;
  1864. }
  1865. int clip_n_patches(const struct clip_ctx * ctx) {
  1866. const auto & params = ctx->vision_model.hparams;
  1867. int n_patches = (params.image_size / params.patch_size) * (params.image_size / params.patch_size);
  1868. if (ctx->proj_type == PROJECTOR_TYPE_LDP || ctx->proj_type == PROJECTOR_TYPE_LDPV2) {
  1869. n_patches /= 4;
  1870. } else if (ctx->proj_type == PROJECTOR_TYPE_RESAMPLER) {
  1871. if (ctx->minicpmv_version == 2) {
  1872. n_patches = 96;
  1873. }
  1874. else if (ctx->minicpmv_version == 3) {
  1875. n_patches = 64;
  1876. }
  1877. }
  1878. return n_patches;
  1879. }
  1880. static std::vector<std::vector<std::vector<float>>> get_1d_sincos_pos_embed_from_grid_new(int embed_dim, const std::vector<std::vector<float>> & pos) {
  1881. assert(embed_dim % 2 == 0);
  1882. int H = pos.size();
  1883. int W = pos[0].size();
  1884. std::vector<float> omega(embed_dim / 2);
  1885. for (int i = 0; i < embed_dim / 2; ++i) {
  1886. omega[i] = 1.0 / pow(10000.0, static_cast<float>(i) / (embed_dim / 2));
  1887. }
  1888. std::vector<std::vector<std::vector<float>>> emb(H, std::vector<std::vector<float>>(W, std::vector<float>(embed_dim)));
  1889. for (int h = 0; h < H; ++h) {
  1890. for (int w = 0; w < W; ++w) {
  1891. for (int d = 0; d < embed_dim / 2; ++d) {
  1892. float out_value = pos[h][w] * omega[d];
  1893. emb[h][w][d] = sin(out_value);
  1894. emb[h][w][d + embed_dim / 2] = cos(out_value);
  1895. }
  1896. }
  1897. }
  1898. return emb;
  1899. }
  1900. static std::vector<std::vector<std::vector<float>>> get_2d_sincos_pos_embed_from_grid(int embed_dim, const std::vector<std::vector<std::vector<float>>> & grid) {
  1901. assert(embed_dim % 2 == 0);
  1902. std::vector<std::vector<std::vector<float>>> emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim / 2, grid[0]); // (H, W, D/2)
  1903. std::vector<std::vector<std::vector<float>>> emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim / 2, grid[1]); // (H, W, D/2)
  1904. int H = emb_h.size();
  1905. int W = emb_h[0].size();
  1906. std::vector<std::vector<std::vector<float>>> emb(H, std::vector<std::vector<float>>(W, std::vector<float>(embed_dim)));
  1907. for (int h = 0; h < H; ++h) {
  1908. for (int w = 0; w < W; ++w) {
  1909. for (int d = 0; d < embed_dim / 2; ++d) {
  1910. emb[h][w][d] = emb_h[h][w][d];
  1911. emb[h][w][d + embed_dim / 2] = emb_w[h][w][d];
  1912. }
  1913. }
  1914. }
  1915. return emb;
  1916. }
  1917. static std::vector<std::vector<float>> get_2d_sincos_pos_embed(int embed_dim, const std::pair<int, int> image_size) {
  1918. int grid_h_size = image_size.first;
  1919. int grid_w_size = image_size.second;
  1920. std::vector<float> grid_h(grid_h_size);
  1921. std::vector<float> grid_w(grid_w_size);
  1922. for (int i = 0; i < grid_h_size; ++i) {
  1923. grid_h[i] = static_cast<float>(i);
  1924. }
  1925. for (int i = 0; i < grid_w_size; ++i) {
  1926. grid_w[i] = static_cast<float>(i);
  1927. }
  1928. std::vector<std::vector<float>> grid(grid_h_size, std::vector<float>(grid_w_size));
  1929. for (int h = 0; h < grid_h_size; ++h) {
  1930. for (int w = 0; w < grid_w_size; ++w) {
  1931. grid[h][w] = grid_w[w];
  1932. }
  1933. }
  1934. std::vector<std::vector<std::vector<float>>> grid_2d = {grid, grid};
  1935. for (int h = 0; h < grid_h_size; ++h) {
  1936. for (int w = 0; w < grid_w_size; ++w) {
  1937. grid_2d[0][h][w] = grid_h[h];
  1938. grid_2d[1][h][w] = grid_w[w];
  1939. }
  1940. }
  1941. std::vector<std::vector<std::vector<float>>> pos_embed_3d = get_2d_sincos_pos_embed_from_grid(embed_dim, grid_2d);
  1942. int H = image_size.first;
  1943. int W = image_size.second;
  1944. std::vector<std::vector<float>> pos_embed_2d(H * W, std::vector<float>(embed_dim));
  1945. for (int h = 0; h < H; ++h) {
  1946. for (int w = 0; w < W; ++w) {
  1947. pos_embed_2d[w * H + h] = pos_embed_3d[h][w];
  1948. }
  1949. }
  1950. return pos_embed_2d;
  1951. }
  1952. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  1953. if (!ctx->has_vision_encoder) {
  1954. LOG_TEE("This gguf file seems to have no vision encoder\n");
  1955. return false;
  1956. }
  1957. clip_image_f32_batch imgs{};
  1958. imgs.size = 1;
  1959. imgs.data = img;
  1960. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  1961. }
  1962. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs, float * vec) {
  1963. if (!ctx->has_vision_encoder) {
  1964. LOG_TEE("This gguf file seems to have no vision encoder\n");
  1965. return false;
  1966. }
  1967. int batch_size = imgs->size;
  1968. if (ctx->has_llava_projector) {
  1969. GGML_ASSERT(batch_size == 1); // TODO: support multiple images
  1970. }
  1971. if (ctx->has_minicpmv_projector) {
  1972. GGML_ASSERT(batch_size == 1);
  1973. }
  1974. // build the inference graph
  1975. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs, ctx->load_image_size, true);
  1976. ggml_gallocr_alloc_graph(ctx->compute_alloc, gf);
  1977. // set inputs
  1978. const auto & model = ctx->vision_model;
  1979. const auto & hparams = model.hparams;
  1980. const int image_size = hparams.image_size;
  1981. int image_size_width = image_size;
  1982. int image_size_height = image_size;
  1983. if (ctx->has_minicpmv_projector) {
  1984. image_size_width = imgs->data[0].nx;
  1985. image_size_height = imgs->data[0].ny;
  1986. }
  1987. const int patch_size = hparams.patch_size;
  1988. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  1989. const int num_positions = num_patches + (ctx->has_class_embedding ? 1 : 0);
  1990. if(ctx->load_image_size==nullptr){
  1991. ctx->load_image_size= clip_image_size_init();
  1992. }
  1993. const int pos_w = ctx->load_image_size->width/patch_size;
  1994. const int pos_h = ctx->load_image_size->height/patch_size;
  1995. {
  1996. struct ggml_tensor * inp_raw = ggml_graph_get_tensor(gf, "inp_raw");
  1997. float * data = (float *)malloc(ggml_nbytes(inp_raw));
  1998. for (size_t i = 0; i < imgs->size; i++) {
  1999. const int nx = imgs->data[i].nx;
  2000. const int ny = imgs->data[i].ny;
  2001. if (!ctx->has_minicpmv_projector) {
  2002. GGML_ASSERT(nx == image_size && ny == image_size);
  2003. }
  2004. const int n = nx * ny;
  2005. for (int b = 0; b < batch_size; b++) {
  2006. for (int k = 0; k < 3; k++) {
  2007. for (int y = 0; y < ny; y++) {
  2008. for (int x = 0; x < nx; x++) {
  2009. data[(b * 3 * n) + k * n + y * nx + x] = imgs->data[b].buf[3 * (y * nx + x) + k];
  2010. }
  2011. }
  2012. }
  2013. }
  2014. }
  2015. ggml_backend_tensor_set(inp_raw, data, 0, ggml_nbytes(inp_raw));
  2016. free(data);
  2017. }
  2018. if (ctx->has_minicpmv_projector) {
  2019. {
  2020. // inspired from siglip:
  2021. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit
  2022. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit/blob/d66538faeba44480d0bfaa42145eef26f9423199/modeling_siglip.py#L316
  2023. struct ggml_tensor * positions = ggml_graph_get_tensor(gf, "positions");
  2024. int* positions_data = (int*)malloc(ggml_nbytes(positions));
  2025. int bucket_coords_h[70];
  2026. int bucket_coords_w[70];
  2027. for (int i = 0; i < pos_h; i++){
  2028. bucket_coords_h[i] = std::floor(70.0*i/pos_h);
  2029. }
  2030. for (int i = 0; i < pos_w; i++){
  2031. bucket_coords_w[i] = std::floor(70.0*i/pos_w);
  2032. }
  2033. for (int i = 0, id = 0; i < pos_h; i++){
  2034. for (int j = 0; j < pos_w; j++){
  2035. positions_data[id++] = bucket_coords_h[i]*70 + bucket_coords_w[j];
  2036. }
  2037. }
  2038. ggml_backend_tensor_set(positions, positions_data, 0, ggml_nbytes(positions));
  2039. free(positions_data);
  2040. }
  2041. {
  2042. // inspired from resampler of Qwen-VL:
  2043. // -> https://huggingface.co/Qwen/Qwen-VL/tree/main
  2044. // -> https://huggingface.co/Qwen/Qwen-VL/blob/0547ed36a86561e2e42fecec8fd0c4f6953e33c4/visual.py#L23
  2045. struct ggml_tensor * pos_embed = ggml_graph_get_tensor(gf, "pos_embed");
  2046. int embed_dim = 4096;
  2047. if (ctx->minicpmv_version == 2) {
  2048. embed_dim = 4096;
  2049. }
  2050. else if (ctx->minicpmv_version == 3) {
  2051. embed_dim = 3584;
  2052. }
  2053. auto pos_embed_t = get_2d_sincos_pos_embed(embed_dim, std::make_pair(pos_w, pos_h));
  2054. float * pos_embed_data = (float *)malloc(ggml_nbytes(pos_embed));
  2055. for(int i=0;i<pos_w * pos_h;++i){
  2056. for(int j=0;j<embed_dim;++j){
  2057. pos_embed_data[i*embed_dim+j]=pos_embed_t[i][j];
  2058. }
  2059. }
  2060. ggml_backend_tensor_set(pos_embed, pos_embed_data, 0, ggml_nbytes(pos_embed));
  2061. free(pos_embed_data);
  2062. }
  2063. }
  2064. else{
  2065. {
  2066. if (ctx->has_class_embedding) {
  2067. struct ggml_tensor * embeddings = ggml_graph_get_tensor(gf, "embeddings");
  2068. void* zero_mem = malloc(ggml_nbytes(embeddings));
  2069. memset(zero_mem, 0, ggml_nbytes(embeddings));
  2070. ggml_backend_tensor_set(embeddings, zero_mem, 0, ggml_nbytes(embeddings));
  2071. free(zero_mem);
  2072. }
  2073. }
  2074. {
  2075. struct ggml_tensor * positions = ggml_graph_get_tensor(gf, "positions");
  2076. int* positions_data = (int*)malloc(ggml_nbytes(positions));
  2077. for (int i = 0; i < num_positions; i++) {
  2078. positions_data[i] = i;
  2079. }
  2080. ggml_backend_tensor_set(positions, positions_data, 0, ggml_nbytes(positions));
  2081. free(positions_data);
  2082. }
  2083. {
  2084. struct ggml_tensor * patches = ggml_graph_get_tensor(gf, "patches");
  2085. int* patches_data = (int*)malloc(ggml_nbytes(patches));
  2086. for (int i = 0; i < num_patches; i++) {
  2087. patches_data[i] = i + 1;
  2088. }
  2089. ggml_backend_tensor_set(patches, patches_data, 0, ggml_nbytes(patches));
  2090. free(patches_data);
  2091. }
  2092. }
  2093. if (ggml_backend_is_cpu(ctx->backend)) {
  2094. ggml_backend_cpu_set_n_threads(ctx->backend, n_threads);
  2095. }
  2096. #ifdef GGML_USE_METAL
  2097. if (ggml_backend_is_metal(ctx->backend)) {
  2098. ggml_backend_metal_set_n_cb(ctx->backend, n_threads);
  2099. }
  2100. #endif
  2101. ggml_backend_graph_compute(ctx->backend, gf);
  2102. // the last node is the embedding tensor
  2103. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 1];
  2104. // copy the embeddings to the location passed by the user
  2105. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  2106. return true;
  2107. }
  2108. bool clip_model_quantize(const char * fname_inp, const char * fname_out, const int itype) {
  2109. ggml_type type = GGML_TYPE_Q4_1;
  2110. assert(itype < GGML_TYPE_COUNT);
  2111. type = static_cast<ggml_type>(itype);
  2112. auto * ctx_clip = clip_model_load(fname_inp, 2);
  2113. const auto & ctx_src = ctx_clip->ctx_gguf;
  2114. const auto & ctx_data = ctx_clip->ctx_data;
  2115. auto * ctx_out = gguf_init_empty();
  2116. gguf_set_kv(ctx_out, ctx_src);
  2117. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  2118. gguf_set_val_u32(ctx_out, "general.file_type", itype);
  2119. auto fout = std::ofstream(fname_out, std::ios::binary);
  2120. const int n_tensors = gguf_get_n_tensors(ctx_src);
  2121. for (int i = 0; i < n_tensors; ++i) {
  2122. const char * name = gguf_get_tensor_name(ctx_src, i);
  2123. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name);
  2124. gguf_add_tensor(ctx_out, cur);
  2125. }
  2126. const size_t meta_size = gguf_get_meta_size(ctx_out);
  2127. for (size_t i = 0; i < meta_size; ++i) {
  2128. fout.put(0);
  2129. }
  2130. // regexes of tensor names to be quantized
  2131. const std::vector<std::string> k_names = {
  2132. ".*weight",
  2133. };
  2134. std::vector<uint8_t> work(512);
  2135. std::vector<float> conv_buf(512);
  2136. size_t total_size_org = 0;
  2137. size_t total_size_new = 0;
  2138. for (int i = 0; i < n_tensors; ++i) {
  2139. const std::string name = gguf_get_tensor_name(ctx_src, i);
  2140. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name.c_str());
  2141. enum ggml_type new_type;
  2142. void * new_data;
  2143. size_t new_size;
  2144. bool quantize = false;
  2145. for (const auto & s : k_names) {
  2146. if (std::regex_match(name, std::regex(s))) {
  2147. quantize = true;
  2148. break;
  2149. }
  2150. }
  2151. // quantize only 2D tensors
  2152. quantize &= (ggml_n_dims(cur) == 2);
  2153. if (quantize) {
  2154. new_type = type;
  2155. if (new_type >= GGML_TYPE_Q2_K && name.find("embd") != std::string::npos) {
  2156. new_type = GGML_TYPE_Q8_0; // ggml_get_rows needs non K type
  2157. // LOG_TEE("%s: quantizing %s to %s\n", __func__, name.c_str(), ggml_type_name(new_type));
  2158. }
  2159. const size_t n_elms = ggml_nelements(cur);
  2160. float * f32_data;
  2161. switch (cur->type) {
  2162. case GGML_TYPE_F32:
  2163. f32_data = (float *)cur->data;
  2164. break;
  2165. case GGML_TYPE_F16:
  2166. if (conv_buf.size() < n_elms) {
  2167. conv_buf.resize(n_elms);
  2168. }
  2169. for (size_t j = 0; j < n_elms; ++j) {
  2170. conv_buf[j] = ggml_fp16_to_fp32(((ggml_fp16_t *)cur->data)[j]);
  2171. }
  2172. f32_data = (float *)conv_buf.data();
  2173. break;
  2174. default:
  2175. LOG_TEE("Please use an input file in f32 or f16\n");
  2176. gguf_free(ctx_out);
  2177. return false;
  2178. }
  2179. if (work.size() < n_elms * 4) {
  2180. work.resize(n_elms * 4);
  2181. }
  2182. new_data = work.data();
  2183. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, n_elms/cur->ne[0], cur->ne[0], nullptr);
  2184. } else {
  2185. new_type = cur->type;
  2186. new_data = cur->data;
  2187. new_size = ggml_nbytes(cur);
  2188. }
  2189. const size_t orig_size = ggml_nbytes(cur);
  2190. total_size_org += orig_size;
  2191. total_size_new += new_size;
  2192. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  2193. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  2194. fout.write((const char *)new_data, new_size);
  2195. size_t pad = GGML_PAD(new_size, gguf_get_alignment(ctx_out)) - new_size;
  2196. for (size_t j = 0; j < pad; ++j) {
  2197. fout.put(0);
  2198. }
  2199. LOG_TEE("%s: n_dims = %d | quantize=%d | size = %f MB -> %f MB\n", name.c_str(), ggml_n_dims(cur), quantize,
  2200. orig_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  2201. }
  2202. // go back to beginning of file and write the updated metadata
  2203. fout.seekp(0, std::ios::beg);
  2204. std::vector<uint8_t> meta(meta_size);
  2205. gguf_get_meta_data(ctx_out, meta.data());
  2206. fout.write((const char *)meta.data(), meta_size);
  2207. fout.close();
  2208. clip_free(ctx_clip);
  2209. gguf_free(ctx_out);
  2210. {
  2211. LOG_TEE("%s: original size = %8.2f MB\n", __func__, total_size_org / 1024.0 / 1024.0);
  2212. LOG_TEE("%s: quantized size = %8.2f MB\n", __func__, total_size_new / 1024.0 / 1024.0);
  2213. }
  2214. return true;
  2215. }
  2216. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  2217. if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  2218. return ctx->vision_model.mm_model_block_1_block_2_1_b->ne[0];
  2219. }
  2220. if (ctx->proj_type == PROJECTOR_TYPE_LDPV2) {
  2221. return ctx->vision_model.mm_model_peg_0_b->ne[0];
  2222. }
  2223. if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  2224. return ctx->vision_model.mm_2_b->ne[0];
  2225. }
  2226. if (ctx->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  2227. return ctx->vision_model.mm_3_b->ne[0];
  2228. }
  2229. if (ctx->proj_type == PROJECTOR_TYPE_RESAMPLER) {
  2230. if (ctx->minicpmv_version == 2) {
  2231. return 4096;
  2232. }
  2233. else if (ctx->minicpmv_version == 3) {
  2234. return 3584;
  2235. }
  2236. }
  2237. std::string proj_type = PROJECTOR_TYPE_NAMES[ctx->proj_type];
  2238. throw std::runtime_error(format("%s: don't support projector with: %s currently\n", __func__, proj_type.c_str()));
  2239. }
  2240. int clip_is_minicpmv(const struct clip_ctx * ctx) {
  2241. if (ctx->has_minicpmv_projector) {
  2242. return ctx->minicpmv_version;
  2243. }
  2244. return 0;
  2245. }