clip.cpp 124 KB

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