clip.cpp 127 KB

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