clip.cpp 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621
  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. #include <array>
  29. #include <numeric>
  30. struct clip_logger_state g_logger_state = {GGML_LOG_LEVEL_CONT, clip_log_callback_default, NULL};
  31. //#define CLIP_DEBUG_FUNCTIONS
  32. #ifdef CLIP_DEBUG_FUNCTIONS
  33. static void clip_image_write_image_to_ppm(const clip_image_u8& img, const std::string& filename) {
  34. std::ofstream file(filename, std::ios::binary);
  35. if (!file.is_open()) {
  36. LOG_ERR("Failed to open file for writing: %s\n", filename.c_str());
  37. return;
  38. }
  39. // PPM header: P6 format, width, height, and max color value
  40. file << "P6\n" << img.nx << " " << img.ny << "\n255\n";
  41. // Write pixel data
  42. for (size_t i = 0; i < img.buf.size(); i += 3) {
  43. // PPM expects binary data in RGB format, which matches our image buffer
  44. file.write(reinterpret_cast<const char*>(&img.buf[i]), 3);
  45. }
  46. file.close();
  47. }
  48. static void clip_image_save_to_bmp(const clip_image_u8& img, const std::string& filename) {
  49. std::ofstream file(filename, std::ios::binary);
  50. if (!file.is_open()) {
  51. LOG_ERR("Failed to open file for writing: %s\n", filename.c_str());
  52. return;
  53. }
  54. int fileSize = 54 + 3 * img.nx * img.ny; // File header + info header + pixel data
  55. int bytesPerPixel = 3;
  56. int widthInBytes = img.nx * bytesPerPixel;
  57. int paddingAmount = (4 - (widthInBytes % 4)) % 4;
  58. int stride = widthInBytes + paddingAmount;
  59. // Bitmap file header
  60. unsigned char fileHeader[14] = {
  61. 'B','M', // Signature
  62. 0,0,0,0, // Image file size in bytes
  63. 0,0,0,0, // Reserved
  64. 54,0,0,0 // Start of pixel array
  65. };
  66. // Total file size
  67. fileSize = 54 + (stride * img.ny);
  68. fileHeader[2] = (unsigned char)(fileSize);
  69. fileHeader[3] = (unsigned char)(fileSize >> 8);
  70. fileHeader[4] = (unsigned char)(fileSize >> 16);
  71. fileHeader[5] = (unsigned char)(fileSize >> 24);
  72. // Bitmap information header (BITMAPINFOHEADER)
  73. unsigned char infoHeader[40] = {
  74. 40,0,0,0, // Size of this header (40 bytes)
  75. 0,0,0,0, // Image width
  76. 0,0,0,0, // Image height
  77. 1,0, // Number of color planes
  78. 24,0, // Bits per pixel
  79. 0,0,0,0, // No compression
  80. 0,0,0,0, // Image size (can be 0 for no compression)
  81. 0,0,0,0, // X pixels per meter (not specified)
  82. 0,0,0,0, // Y pixels per meter (not specified)
  83. 0,0,0,0, // Total colors (color table not used)
  84. 0,0,0,0 // Important colors (all are important)
  85. };
  86. // Width and height in the information header
  87. infoHeader[4] = (unsigned char)(img.nx);
  88. infoHeader[5] = (unsigned char)(img.nx >> 8);
  89. infoHeader[6] = (unsigned char)(img.nx >> 16);
  90. infoHeader[7] = (unsigned char)(img.nx >> 24);
  91. infoHeader[8] = (unsigned char)(img.ny);
  92. infoHeader[9] = (unsigned char)(img.ny >> 8);
  93. infoHeader[10] = (unsigned char)(img.ny >> 16);
  94. infoHeader[11] = (unsigned char)(img.ny >> 24);
  95. // Write file headers
  96. file.write(reinterpret_cast<char*>(fileHeader), sizeof(fileHeader));
  97. file.write(reinterpret_cast<char*>(infoHeader), sizeof(infoHeader));
  98. // Pixel data
  99. std::vector<unsigned char> padding(3, 0); // Max padding size to be added to each row
  100. for (int y = img.ny - 1; y >= 0; --y) { // BMP files are stored bottom-to-top
  101. for (int x = 0; x < img.nx; ++x) {
  102. // Each pixel
  103. size_t pixelIndex = (y * img.nx + x) * 3;
  104. unsigned char pixel[3] = {
  105. img.buf[pixelIndex + 2], // BMP stores pixels in BGR format
  106. img.buf[pixelIndex + 1],
  107. img.buf[pixelIndex]
  108. };
  109. file.write(reinterpret_cast<char*>(pixel), 3);
  110. }
  111. // Write padding for the row
  112. file.write(reinterpret_cast<char*>(padding.data()), paddingAmount);
  113. }
  114. file.close();
  115. }
  116. // debug function to convert f32 to u8
  117. static void clip_image_convert_f32_to_u8(const clip_image_f32& src, clip_image_u8& dst) {
  118. dst.nx = src.nx;
  119. dst.ny = src.ny;
  120. dst.buf.resize(3 * src.nx * src.ny);
  121. for (size_t i = 0; i < src.buf.size(); ++i) {
  122. dst.buf[i] = static_cast<uint8_t>(std::min(std::max(int(src.buf[i] * 255.0f), 0), 255));
  123. }
  124. }
  125. #endif
  126. //
  127. // clip layers
  128. //
  129. enum patch_merge_type {
  130. PATCH_MERGE_FLAT,
  131. PATCH_MERGE_SPATIAL_UNPAD,
  132. };
  133. struct clip_hparams {
  134. int32_t image_size;
  135. int32_t patch_size;
  136. int32_t hidden_size;
  137. int32_t n_intermediate;
  138. int32_t projection_dim;
  139. int32_t n_head;
  140. int32_t n_layer;
  141. int32_t proj_scale_factor = 0; // idefics3
  142. patch_merge_type mm_patch_merge_type = PATCH_MERGE_FLAT;
  143. float eps = 1e-6;
  144. float rope_theta = 0.0;
  145. std::vector<int32_t> image_grid_pinpoints;
  146. int32_t image_crop_resolution;
  147. std::unordered_set<int32_t> vision_feature_layer;
  148. int32_t attn_window_size = 0;
  149. int32_t n_wa_pattern = 0;
  150. int32_t spatial_merge_size = 0;
  151. };
  152. struct clip_layer {
  153. // attention
  154. struct ggml_tensor * k_w = nullptr;
  155. struct ggml_tensor * k_b = nullptr;
  156. struct ggml_tensor * q_w = nullptr;
  157. struct ggml_tensor * q_b = nullptr;
  158. struct ggml_tensor * v_w = nullptr;
  159. struct ggml_tensor * v_b = nullptr;
  160. struct ggml_tensor * o_w = nullptr;
  161. struct ggml_tensor * o_b = nullptr;
  162. // layernorm 1
  163. struct ggml_tensor * ln_1_w = nullptr;
  164. struct ggml_tensor * ln_1_b = nullptr;
  165. // ff
  166. struct ggml_tensor * ff_i_w = nullptr; // legacy naming
  167. struct ggml_tensor * ff_i_b = nullptr; // legacy naming
  168. struct ggml_tensor * ff_o_w = nullptr; // legacy naming
  169. struct ggml_tensor * ff_o_b = nullptr; // legacy naming
  170. struct ggml_tensor * ff_up_w = nullptr;
  171. struct ggml_tensor * ff_up_b = nullptr;
  172. struct ggml_tensor * ff_gate_w = nullptr;
  173. struct ggml_tensor * ff_gate_b = nullptr;
  174. struct ggml_tensor * ff_down_w = nullptr;
  175. struct ggml_tensor * ff_down_b = nullptr;
  176. struct ggml_tensor * ff_g_w = NULL;
  177. struct ggml_tensor * ff_g_b = NULL;
  178. // layernorm 2
  179. struct ggml_tensor * ln_2_w = nullptr;
  180. struct ggml_tensor * ln_2_b = nullptr;
  181. };
  182. struct clip_vision_model {
  183. struct clip_hparams hparams;
  184. // embeddings
  185. struct ggml_tensor * class_embedding = nullptr;
  186. struct ggml_tensor * patch_embeddings_0 = nullptr;
  187. struct ggml_tensor * patch_embeddings_1 = nullptr; // second Conv2D kernel when we decouple Conv3D along temproal dimension (Qwen2VL)
  188. struct ggml_tensor * patch_bias = nullptr;
  189. struct ggml_tensor * position_embeddings = nullptr;
  190. struct ggml_tensor * pre_ln_w = nullptr;
  191. struct ggml_tensor * pre_ln_b = nullptr;
  192. std::vector<clip_layer> layers;
  193. struct ggml_tensor * post_ln_w;
  194. struct ggml_tensor * post_ln_b;
  195. struct ggml_tensor * projection;
  196. // LLaVA projection
  197. struct ggml_tensor * mm_input_norm_w = nullptr;
  198. struct ggml_tensor * mm_0_w = nullptr;
  199. struct ggml_tensor * mm_0_b = nullptr;
  200. struct ggml_tensor * mm_2_w = nullptr;
  201. struct ggml_tensor * mm_2_b = nullptr;
  202. struct ggml_tensor * image_newline = nullptr;
  203. // Yi type models with mlp+normalization projection
  204. struct ggml_tensor * mm_1_w = nullptr; // Yi type models have 0, 1, 3, 4
  205. struct ggml_tensor * mm_1_b = nullptr;
  206. struct ggml_tensor * mm_3_w = nullptr;
  207. struct ggml_tensor * mm_3_b = nullptr;
  208. struct ggml_tensor * mm_4_w = nullptr;
  209. struct ggml_tensor * mm_4_b = nullptr;
  210. // GLMV-Edge projection
  211. struct ggml_tensor * mm_model_adapter_conv_w = nullptr;
  212. struct ggml_tensor * mm_model_adapter_conv_b = nullptr;
  213. struct ggml_tensor * mm_glm_tok_boi = nullptr;
  214. struct ggml_tensor * mm_glm_tok_eoi = nullptr;
  215. // MobileVLM projection
  216. struct ggml_tensor * mm_model_mlp_1_w = nullptr;
  217. struct ggml_tensor * mm_model_mlp_1_b = nullptr;
  218. struct ggml_tensor * mm_model_mlp_3_w = nullptr;
  219. struct ggml_tensor * mm_model_mlp_3_b = nullptr;
  220. struct ggml_tensor * mm_model_block_1_block_0_0_w = nullptr;
  221. struct ggml_tensor * mm_model_block_1_block_0_1_w = nullptr;
  222. struct ggml_tensor * mm_model_block_1_block_0_1_b = nullptr;
  223. struct ggml_tensor * mm_model_block_1_block_1_fc1_w = nullptr;
  224. struct ggml_tensor * mm_model_block_1_block_1_fc1_b = nullptr;
  225. struct ggml_tensor * mm_model_block_1_block_1_fc2_w = nullptr;
  226. struct ggml_tensor * mm_model_block_1_block_1_fc2_b = nullptr;
  227. struct ggml_tensor * mm_model_block_1_block_2_0_w = nullptr;
  228. struct ggml_tensor * mm_model_block_1_block_2_1_w = nullptr;
  229. struct ggml_tensor * mm_model_block_1_block_2_1_b = nullptr;
  230. struct ggml_tensor * mm_model_block_2_block_0_0_w = nullptr;
  231. struct ggml_tensor * mm_model_block_2_block_0_1_w = nullptr;
  232. struct ggml_tensor * mm_model_block_2_block_0_1_b = nullptr;
  233. struct ggml_tensor * mm_model_block_2_block_1_fc1_w = nullptr;
  234. struct ggml_tensor * mm_model_block_2_block_1_fc1_b = nullptr;
  235. struct ggml_tensor * mm_model_block_2_block_1_fc2_w = nullptr;
  236. struct ggml_tensor * mm_model_block_2_block_1_fc2_b = nullptr;
  237. struct ggml_tensor * mm_model_block_2_block_2_0_w = nullptr;
  238. struct ggml_tensor * mm_model_block_2_block_2_1_w = nullptr;
  239. struct ggml_tensor * mm_model_block_2_block_2_1_b = nullptr;
  240. // MobileVLM_V2 projection
  241. struct ggml_tensor * mm_model_mlp_0_w = nullptr;
  242. struct ggml_tensor * mm_model_mlp_0_b = nullptr;
  243. struct ggml_tensor * mm_model_mlp_2_w = nullptr;
  244. struct ggml_tensor * mm_model_mlp_2_b = nullptr;
  245. struct ggml_tensor * mm_model_peg_0_w = nullptr;
  246. struct ggml_tensor * mm_model_peg_0_b = nullptr;
  247. // MINICPMV projection
  248. struct ggml_tensor * mm_model_pos_embed_k = nullptr;
  249. struct ggml_tensor * mm_model_query = nullptr;
  250. struct ggml_tensor * mm_model_proj = nullptr;
  251. struct ggml_tensor * mm_model_kv_proj = nullptr;
  252. struct ggml_tensor * mm_model_attn_q_w = nullptr;
  253. struct ggml_tensor * mm_model_attn_q_b = nullptr;
  254. struct ggml_tensor * mm_model_attn_k_w = nullptr;
  255. struct ggml_tensor * mm_model_attn_k_b = nullptr;
  256. struct ggml_tensor * mm_model_attn_v_w = nullptr;
  257. struct ggml_tensor * mm_model_attn_v_b = nullptr;
  258. struct ggml_tensor * mm_model_attn_o_w = nullptr;
  259. struct ggml_tensor * mm_model_attn_o_b = nullptr;
  260. struct ggml_tensor * mm_model_ln_q_w = nullptr;
  261. struct ggml_tensor * mm_model_ln_q_b = nullptr;
  262. struct ggml_tensor * mm_model_ln_kv_w = nullptr;
  263. struct ggml_tensor * mm_model_ln_kv_b = nullptr;
  264. struct ggml_tensor * mm_model_ln_post_w = nullptr;
  265. struct ggml_tensor * mm_model_ln_post_b = nullptr;
  266. // gemma3
  267. struct ggml_tensor * mm_input_proj_w = nullptr;
  268. struct ggml_tensor * mm_soft_emb_norm_w = nullptr;
  269. // pixtral
  270. struct ggml_tensor * token_embd_img_break = nullptr;
  271. struct ggml_tensor * mm_patch_merger_w = nullptr;
  272. };
  273. struct clip_ctx {
  274. bool has_llava_projector = false;
  275. int minicpmv_version = 0;
  276. struct clip_vision_model vision_model;
  277. projector_type proj_type = PROJECTOR_TYPE_MLP;
  278. int32_t max_feature_layer; // unused in newer models like gemma3
  279. float image_mean[3];
  280. float image_std[3];
  281. bool use_gelu = false;
  282. bool use_silu = false;
  283. gguf_context_ptr ctx_gguf;
  284. ggml_context_ptr ctx_data;
  285. std::vector<uint8_t> buf_compute_meta;
  286. std::vector<ggml_backend_t> backend_ptrs;
  287. std::vector<ggml_backend_buffer_type_t> backend_buft;
  288. ggml_backend_t backend;
  289. ggml_backend_t backend_cpu;
  290. ggml_backend_buffer_ptr buf;
  291. int max_nodes = 8192;
  292. ggml_backend_sched_ptr sched;
  293. clip_image_size load_image_size;
  294. clip_ctx(clip_context_params & ctx_params) {
  295. backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  296. backend = ctx_params.use_gpu
  297. ? ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)
  298. : nullptr;
  299. if (backend) {
  300. LOG_INF("%s: CLIP using %s backend\n", __func__, ggml_backend_name(backend));
  301. backend_ptrs.push_back(backend);
  302. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  303. } else {
  304. backend = backend_cpu;
  305. LOG_INF("%s: CLIP using CPU backend\n", __func__);
  306. }
  307. backend_ptrs.push_back(backend_cpu);
  308. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend_cpu));
  309. sched.reset(
  310. ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), 8192, false)
  311. );
  312. }
  313. ~clip_ctx() {
  314. ggml_backend_free(backend);
  315. if (backend != backend_cpu) {
  316. ggml_backend_free(backend_cpu);
  317. }
  318. }
  319. };
  320. static ggml_cgraph * clip_image_build_graph_siglip(clip_ctx * ctx, const clip_image_f32 & img) {
  321. const auto & model = ctx->vision_model;
  322. const auto & hparams = model.hparams;
  323. int image_size_width = img.nx;
  324. int image_size_height = img.ny;
  325. const int patch_size = hparams.patch_size;
  326. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  327. const int hidden_size = hparams.hidden_size;
  328. const int n_head = hparams.n_head;
  329. const int d_head = hidden_size / n_head;
  330. const int n_layer = hparams.n_layer;
  331. const float eps = hparams.eps;
  332. struct ggml_init_params params = {
  333. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  334. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  335. /*.no_alloc =*/ true,
  336. };
  337. ggml_context_ptr ctx0_ptr(ggml_init(params));
  338. auto ctx0 = ctx0_ptr.get();
  339. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  340. // input raw
  341. struct ggml_tensor * inp_raw = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, image_size_width, image_size_height, 3);
  342. ggml_set_name(inp_raw, "inp_raw");
  343. ggml_set_input(inp_raw);
  344. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  345. inp = ggml_reshape_2d(ctx0, inp, num_patches, hidden_size);
  346. inp = ggml_cont(ctx0, ggml_transpose(ctx0, inp));
  347. inp = ggml_add(ctx0, inp, model.patch_bias);
  348. // position embeddings
  349. struct ggml_tensor * embeddings = ggml_add(ctx0, inp, model.position_embeddings);
  350. // loop over layers
  351. for (int il = 0; il < n_layer; il++) {
  352. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  353. // layernorm1
  354. {
  355. cur = ggml_norm(ctx0, cur, eps);
  356. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_1_w), model.layers[il].ln_1_b);
  357. }
  358. // self-attention
  359. {
  360. struct ggml_tensor * Q =
  361. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  362. Q = ggml_reshape_3d(ctx0, Q, d_head, n_head, num_patches);
  363. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  364. struct ggml_tensor * K =
  365. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  366. K = ggml_reshape_3d(ctx0, K, d_head, n_head, num_patches);
  367. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  368. struct ggml_tensor * V =
  369. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  370. V = ggml_reshape_3d(ctx0, V, d_head, n_head, num_patches);
  371. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  372. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  373. KQ = ggml_soft_max_ext(ctx0, KQ, nullptr, 1.0f / sqrtf((float)d_head), 0.0f);
  374. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  375. KQV = ggml_reshape_3d(ctx0, KQV, d_head, num_patches, n_head);
  376. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  377. cur = ggml_cont_2d(ctx0, KQV, hidden_size, num_patches);
  378. }
  379. // attention output
  380. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  381. // re-add the layer input, e.g., residual
  382. cur = ggml_add(ctx0, cur, embeddings);
  383. embeddings = cur; // embeddings = residual, cur = hidden_states
  384. // layernorm2
  385. {
  386. cur = ggml_norm(ctx0, cur, eps);
  387. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_2_w), model.layers[il].ln_2_b);
  388. }
  389. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  390. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  391. // siglip uses gelu
  392. cur = ggml_gelu(ctx0, cur);
  393. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  394. cur = ggml_add(ctx0, cur, model.layers[il].ff_o_b);
  395. // residual 2
  396. cur = ggml_add(ctx0, embeddings, cur);
  397. embeddings = cur;
  398. }
  399. // post-layernorm
  400. if (model.post_ln_w) {
  401. embeddings = ggml_norm(ctx0, embeddings, eps);
  402. ggml_set_name(embeddings, "post_ln");
  403. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.post_ln_w), model.post_ln_b);
  404. }
  405. if (ctx->proj_type == PROJECTOR_TYPE_GEMMA3) {
  406. const int batch_size = 1;
  407. const int mm_tokens_per_image = 256; // default value for gemma3
  408. const int tokens_per_side = sqrt(mm_tokens_per_image);
  409. const int patches_per_image = sqrt(num_patches);
  410. const int kernel_size = patches_per_image / tokens_per_side;
  411. embeddings = ggml_cont(ctx0, ggml_transpose(ctx0, embeddings));
  412. embeddings = ggml_reshape_4d(ctx0, embeddings, patches_per_image, patches_per_image, hidden_size, batch_size);
  413. // doing a pool2d to reduce the number of output tokens to 256
  414. embeddings = ggml_pool_2d(ctx0, embeddings, GGML_OP_POOL_AVG, kernel_size, kernel_size, kernel_size, kernel_size, 0, 0);
  415. embeddings = ggml_reshape_3d(ctx0, embeddings, embeddings->ne[0] * embeddings->ne[0], hidden_size, batch_size);
  416. embeddings = ggml_cont(ctx0, ggml_transpose(ctx0, embeddings));
  417. // apply norm before projection
  418. embeddings = ggml_rms_norm(ctx0, embeddings, eps);
  419. embeddings = ggml_mul(ctx0, embeddings, model.mm_soft_emb_norm_w);
  420. // apply projection
  421. embeddings = ggml_mul_mat(ctx0,
  422. ggml_cont(ctx0, ggml_transpose(ctx0, model.mm_input_proj_w)),
  423. embeddings);
  424. } else if (ctx->proj_type == PROJECTOR_TYPE_IDEFICS3) {
  425. // https://github.com/huggingface/transformers/blob/0a950e0bbe1ed58d5401a6b547af19f15f0c195e/src/transformers/models/idefics3/modeling_idefics3.py#L578
  426. ggml_tensor * cur = embeddings;
  427. const int scale_factor = model.hparams.proj_scale_factor;
  428. const int n_embd = cur->ne[0];
  429. const int seq = cur->ne[1];
  430. const int bsz = 1; // batch size, always 1 for now since we don't support batching
  431. const int height = std::sqrt(seq);
  432. const int width = std::sqrt(seq);
  433. GGML_ASSERT(scale_factor != 0);
  434. cur = ggml_reshape_4d(ctx0, cur, n_embd * scale_factor, width / scale_factor, height, bsz);
  435. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  436. cur = ggml_reshape_4d(ctx0, ggml_cont(ctx0, cur),
  437. n_embd * scale_factor * scale_factor,
  438. height / scale_factor,
  439. width / scale_factor,
  440. bsz);
  441. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  442. cur = ggml_reshape_3d(ctx0, ggml_cont(ctx0, cur),
  443. n_embd * scale_factor * scale_factor,
  444. seq / (scale_factor * scale_factor),
  445. bsz);
  446. cur = ggml_mul_mat(ctx0, model.projection, cur);
  447. embeddings = cur;
  448. } else {
  449. GGML_ABORT("SigLIP: Unsupported projector type");
  450. }
  451. // build the graph
  452. ggml_build_forward_expand(gf, embeddings);
  453. return gf;
  454. }
  455. // implementation of the 2D RoPE without adding a new op in ggml
  456. // this is not efficient (use double the memory), but works on all backends
  457. // TODO: there was a more efficient which relies on ggml_view and ggml_rope_ext_inplace, but the rope inplace does not work well with non-contiguous tensors ; we should fix that and revert back to the original implementation in https://github.com/ggml-org/llama.cpp/pull/13065
  458. static ggml_tensor * build_rope_2d(
  459. ggml_context * ctx0,
  460. ggml_tensor * cur,
  461. ggml_tensor * pos_h,
  462. ggml_tensor * pos_w,
  463. const float freq_base
  464. ) {
  465. const int64_t n_dim = cur->ne[0];
  466. const int64_t n_head = cur->ne[1];
  467. const int64_t n_pos = cur->ne[2];
  468. // for example, if we have cur tensor of shape (n_dim=8, n_head, n_pos)
  469. // we will have a list of 4 inv_freq: 1e-0, 1e-1, 1e-2, 1e-3
  470. // first half of cur will use 1e-0, 1e-2 (even)
  471. // second half of cur will use 1e-1, 1e-3 (odd)
  472. // the trick here is to rotate just half of n_dim, so inv_freq will automatically be even
  473. // ^ don't ask me why, it's math! -2(2i) / n_dim == -2i / (n_dim/2)
  474. // then for the second half, we use freq_scale to shift the inv_freq
  475. // ^ why? replace (2i) with (2i+1) in the above equation
  476. const float freq_scale_odd = std::pow(freq_base, (float)-2/n_dim);
  477. // first half
  478. ggml_tensor * first;
  479. {
  480. first = ggml_view_3d(ctx0, cur,
  481. n_dim/2, n_head, n_pos,
  482. ggml_row_size(cur->type, n_dim),
  483. ggml_row_size(cur->type, n_dim*n_head),
  484. 0);
  485. first = ggml_rope_ext(
  486. ctx0,
  487. first,
  488. pos_h, // positions
  489. nullptr, // freq factors
  490. n_dim/2, // n_dims
  491. 0, 0, freq_base,
  492. 1.0f, 0.0f, 1.0f, 0.0f, 0.0f
  493. );
  494. }
  495. // second half
  496. ggml_tensor * second;
  497. {
  498. second = ggml_view_3d(ctx0, cur,
  499. n_dim/2, n_head, n_pos,
  500. ggml_row_size(cur->type, n_dim),
  501. ggml_row_size(cur->type, n_dim*n_head),
  502. n_dim/2 * ggml_element_size(cur));
  503. second = ggml_cont(ctx0, second); // copy, because ggml_rope don't play well with non-contiguous tensors
  504. second = ggml_rope_ext(
  505. ctx0,
  506. second,
  507. pos_w, // positions
  508. nullptr, // freq factors
  509. n_dim/2, // n_dims
  510. 0, 0, freq_base,
  511. freq_scale_odd,
  512. 0.0f, 1.0f, 0.0f, 0.0f
  513. );
  514. }
  515. cur = ggml_concat(ctx0, first, second, 0);
  516. return cur;
  517. }
  518. static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_image_f32 & img) {
  519. const auto & model = ctx->vision_model;
  520. const auto & hparams = model.hparams;
  521. GGML_ASSERT(ctx->proj_type == PROJECTOR_TYPE_PIXTRAL);
  522. int image_size_width = img.nx;
  523. int image_size_height = img.ny;
  524. const int patch_size = hparams.patch_size;
  525. const int n_patches_x = image_size_width / patch_size;
  526. const int n_patches_y = image_size_height / patch_size;
  527. const int num_patches = n_patches_x * n_patches_y;
  528. const int hidden_size = hparams.hidden_size;
  529. const int n_head = hparams.n_head;
  530. const int d_head = hidden_size / n_head;
  531. const int n_layer = hparams.n_layer;
  532. const float eps = hparams.eps;
  533. const int n_merge = hparams.spatial_merge_size;
  534. struct ggml_init_params params = {
  535. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  536. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  537. /*.no_alloc =*/ true,
  538. };
  539. ggml_context_ptr ctx0_ptr(ggml_init(params));
  540. auto ctx0 = ctx0_ptr.get();
  541. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  542. // input raw
  543. struct ggml_tensor * inp_raw = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, image_size_width, image_size_height, 3);
  544. ggml_set_name(inp_raw, "inp_raw");
  545. ggml_set_input(inp_raw);
  546. // 2D input positions
  547. struct ggml_tensor * pos_h = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  548. ggml_set_name(pos_h, "pos_h");
  549. ggml_set_input(pos_h);
  550. struct ggml_tensor * pos_w = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  551. ggml_set_name(pos_w, "pos_w");
  552. ggml_set_input(pos_w);
  553. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  554. inp = ggml_reshape_2d(ctx0, inp, num_patches, hidden_size);
  555. inp = ggml_cont(ctx0, ggml_transpose(ctx0, inp));
  556. struct ggml_tensor * embeddings = inp;
  557. // pre-layer norm
  558. embeddings = ggml_mul(ctx0, ggml_rms_norm(ctx0, embeddings, eps), model.pre_ln_w);
  559. // loop over layers
  560. for (int il = 0; il < n_layer; il++) {
  561. struct ggml_tensor * cur = embeddings;
  562. // pre-attention norm
  563. cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, cur, eps), model.layers[il].ln_1_w);
  564. // self-attention
  565. {
  566. struct ggml_tensor * Q = ggml_mul_mat(ctx0, model.layers[il].q_w, cur);
  567. Q = ggml_reshape_3d(ctx0, Q, d_head, n_head, num_patches);
  568. Q = build_rope_2d(ctx0, Q, pos_h, pos_w, hparams.rope_theta);
  569. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  570. struct ggml_tensor * K = ggml_mul_mat(ctx0, model.layers[il].k_w, cur);
  571. K = ggml_reshape_3d(ctx0, K, d_head, n_head, num_patches);
  572. K = build_rope_2d(ctx0, K, pos_h, pos_w, hparams.rope_theta);
  573. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  574. struct ggml_tensor * V = ggml_mul_mat(ctx0, model.layers[il].v_w, cur);
  575. V = ggml_reshape_3d(ctx0, V, d_head, n_head, num_patches);
  576. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  577. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  578. KQ = ggml_soft_max_ext(ctx0, KQ, nullptr, 1.0f / sqrtf((float)d_head), 0.0f);
  579. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  580. KQV = ggml_reshape_3d(ctx0, KQV, d_head, num_patches, n_head);
  581. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  582. cur = ggml_cont_2d(ctx0, KQV, hidden_size, num_patches);
  583. cur = ggml_mul_mat(ctx0, model.layers[il].o_w, cur);
  584. }
  585. // re-add the layer input, e.g., residual
  586. cur = ggml_add(ctx0, cur, embeddings);
  587. embeddings = cur; // embeddings = residual, cur = hidden_states
  588. // pre-ffn norm
  589. cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, cur, eps), model.layers[il].ln_2_w);
  590. // feed-forward
  591. {
  592. ggml_tensor * gate_proj = ggml_mul_mat(ctx0, model.layers[il].ff_gate_w, cur);
  593. ggml_tensor * up_proj = ggml_mul_mat(ctx0, model.layers[il].ff_up_w, cur);
  594. if (ctx->use_silu) {
  595. gate_proj = ggml_silu(ctx0, gate_proj);
  596. } else if (ctx->use_gelu) {
  597. gate_proj = ggml_gelu(ctx0, gate_proj);
  598. } else {
  599. GGML_ABORT("Pixtral: Unsupported activation");
  600. }
  601. cur = ggml_mul(ctx0, up_proj, gate_proj);
  602. cur = ggml_mul_mat(ctx0, model.layers[il].ff_down_w, cur);
  603. }
  604. // residual 2
  605. cur = ggml_add(ctx0, embeddings, cur);
  606. embeddings = cur;
  607. }
  608. // mistral small 3.1 patch merger
  609. // ref: https://github.com/huggingface/transformers/blob/7a3e208892c06a5e278144eaf38c8599a42f53e7/src/transformers/models/mistral3/modeling_mistral3.py#L67
  610. if (model.mm_patch_merger_w) {
  611. GGML_ASSERT(hparams.spatial_merge_size > 0);
  612. ggml_tensor * cur = embeddings;
  613. cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, cur, eps), model.mm_input_norm_w);
  614. // reshape image tokens to 2D grid
  615. cur = ggml_reshape_3d(ctx0, cur, hidden_size, n_patches_x, n_patches_y);
  616. cur = ggml_permute(ctx0, cur, 2, 0, 1, 3); // [x, y, hidden_size]
  617. cur = ggml_cont(ctx0, cur);
  618. // torch.nn.functional.unfold is just an im2col under the hood
  619. // we just need a dummy kernel to make it work
  620. ggml_tensor * kernel = ggml_view_3d(ctx0, cur, n_merge, n_merge, cur->ne[2], 0, 0, 0);
  621. cur = ggml_im2col(ctx0, kernel, cur, n_merge, n_merge, 0, 0, 1, 1, true, inp->type);
  622. // project to hidden_size
  623. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0], cur->ne[1] * cur->ne[2]);
  624. cur = ggml_mul_mat(ctx0, model.mm_patch_merger_w, cur);
  625. embeddings = cur;
  626. }
  627. // LlavaMultiModalProjector (always using GELU activation)
  628. {
  629. embeddings = ggml_mul_mat(ctx0, model.mm_1_w, embeddings);
  630. if (model.mm_1_b) {
  631. embeddings = ggml_add(ctx0, embeddings, model.mm_1_b);
  632. }
  633. embeddings = ggml_gelu(ctx0, embeddings);
  634. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  635. if (model.mm_2_b) {
  636. embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
  637. }
  638. }
  639. // arrangement of the [IMG_BREAK] token
  640. {
  641. // not efficient, but works
  642. // the trick is to view the embeddings as a 3D tensor with shape [hidden_size, n_patches_per_row, n_rows]
  643. // and then concatenate the [IMG_BREAK] token to the end of each row, aka n_patches_per_row dimension
  644. // after the concatenation, we have a tensor with shape [hidden_size, n_patches_per_row + 1, n_rows]
  645. const int p_y = n_merge > 0 ? n_patches_y / n_merge : n_patches_y;
  646. const int p_x = n_merge > 0 ? n_patches_x / n_merge : n_patches_x;
  647. const int p_total = p_x * p_y;
  648. const int n_embd_text = embeddings->ne[0];
  649. const int n_tokens_output = p_total + p_y - 1; // one [IMG_BREAK] per row, except the last row
  650. ggml_tensor * cur = ggml_reshape_3d(ctx0, embeddings, n_embd_text, p_x, p_y);
  651. ggml_tensor * tok = ggml_new_tensor_3d(ctx0, embeddings->type, n_embd_text, 1, p_y);
  652. tok = ggml_scale(ctx0, tok, 0.0); // clear the tensor
  653. tok = ggml_add(ctx0, tok, model.token_embd_img_break);
  654. cur = ggml_concat(ctx0, cur, tok, 1);
  655. embeddings = ggml_view_2d(ctx0, cur,
  656. n_embd_text, n_tokens_output,
  657. ggml_row_size(cur->type, n_embd_text), 0);
  658. }
  659. // build the graph
  660. ggml_build_forward_expand(gf, embeddings);
  661. return gf;
  662. }
  663. static ggml_cgraph * clip_image_build_graph_qwen25vl(clip_ctx * ctx, const clip_image_f32_batch & imgs) {
  664. const auto & model = ctx->vision_model;
  665. const auto & hparams = model.hparams;
  666. const int image_size_width = imgs.entries[0]->nx;
  667. const int image_size_height = imgs.entries[0]->ny;
  668. const bool use_window_attn = hparams.n_wa_pattern > 0;
  669. const int n_wa_pattern = hparams.n_wa_pattern;
  670. const int patch_size = hparams.patch_size;
  671. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  672. const int patches_w = image_size_width / patch_size;
  673. const int patches_h = image_size_height / patch_size;
  674. const int num_positions = num_patches + (model.class_embedding ? 1 : 0);
  675. const int num_position_ids = num_positions * 4; // m-rope requires 4 dim per position
  676. const int hidden_size = hparams.hidden_size;
  677. const int n_head = hparams.n_head;
  678. const int d_head = hidden_size / n_head;
  679. const int n_layer = hparams.n_layer;
  680. const float eps = hparams.eps;
  681. int mrope_sections[4] = {d_head/4, d_head/4, d_head/4, d_head/4};
  682. const int batch_size = imgs.entries.size();
  683. GGML_ASSERT(batch_size == 1);
  684. struct ggml_init_params params = {
  685. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  686. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  687. /*.no_alloc =*/ true,
  688. };
  689. ggml_context_ptr ctx0_ptr(ggml_init(params));
  690. auto ctx0 = ctx0_ptr.get();
  691. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  692. struct ggml_tensor * inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size_width, image_size_height, 3, batch_size);
  693. ggml_set_name(inp_raw, "inp_raw");
  694. ggml_set_input(inp_raw);
  695. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  696. GGML_ASSERT(image_size_width % (patch_size * 2) == 0);
  697. GGML_ASSERT(image_size_height % (patch_size * 2) == 0);
  698. auto inp_1 = ggml_conv_2d(ctx0, model.patch_embeddings_1, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  699. inp = ggml_add(ctx0, inp, inp_1);
  700. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 2, 0, 3)); // [w, h, c, b] -> [c, w, h, b]
  701. inp = ggml_reshape_4d(
  702. ctx0, inp,
  703. hidden_size * 2, patches_w / 2, patches_h, batch_size);
  704. inp = ggml_reshape_4d(
  705. ctx0, inp,
  706. hidden_size * 2, patches_w / 2, 2, batch_size * (patches_h / 2));
  707. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 0, 2, 1, 3));
  708. inp = ggml_reshape_3d(
  709. ctx0, inp,
  710. hidden_size, patches_w * patches_h, batch_size);
  711. if (model.patch_bias) {
  712. // inp = ggml_add(ctx0, inp, ggml_repeat(ctx0, model.patch_bias, inp));
  713. inp = ggml_add(ctx0, inp, model.patch_bias);
  714. }
  715. struct ggml_tensor * embeddings = inp;
  716. struct ggml_tensor * window_mask = nullptr;
  717. struct ggml_tensor * window_idx = nullptr;
  718. struct ggml_tensor * inv_window_idx = nullptr;
  719. struct ggml_tensor * positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_position_ids);
  720. ggml_set_name(positions, "positions");
  721. ggml_set_input(positions);
  722. // pre-layernorm
  723. if (model.pre_ln_w) {
  724. embeddings = ggml_rms_norm(ctx0, embeddings, eps);
  725. ggml_set_name(embeddings, "pre_ln");
  726. embeddings = ggml_mul(ctx0, embeddings, model.pre_ln_w);
  727. }
  728. if (use_window_attn) {
  729. // handle window attention inputs
  730. inv_window_idx = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions / 4);
  731. ggml_set_name(inv_window_idx, "inv_window_idx");
  732. ggml_set_input(inv_window_idx);
  733. // mask for window attention
  734. window_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, num_positions, num_positions);
  735. ggml_set_name(window_mask, "window_mask");
  736. ggml_set_input(window_mask);
  737. // embeddings shape: [hidden_size, patches_w * patches_h, batch_size]
  738. GGML_ASSERT(batch_size == 1);
  739. embeddings = ggml_reshape_2d(ctx0, embeddings, hidden_size * 4, patches_w * patches_h * batch_size / 4);
  740. embeddings = ggml_get_rows(ctx0, embeddings, inv_window_idx);
  741. embeddings = ggml_reshape_3d(ctx0, embeddings, hidden_size, patches_w * patches_h, batch_size);
  742. }
  743. // loop over layers
  744. for (int il = 0; il < n_layer; il++) {
  745. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  746. // rmsnorm1
  747. cur = ggml_rms_norm(ctx0, cur, eps);
  748. cur = ggml_mul(ctx0, cur, model.layers[il].ln_1_w);
  749. // self-attention
  750. {
  751. struct ggml_tensor * Q =
  752. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  753. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  754. Q = ggml_rope_multi(
  755. ctx0, Q, positions, nullptr,
  756. d_head/2, mrope_sections, GGML_ROPE_TYPE_VISION, 32768, 10000, 1, 0, 1, 32, 1);
  757. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  758. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  759. struct ggml_tensor * K =
  760. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  761. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  762. K = ggml_rope_multi(
  763. ctx0, K, positions, nullptr,
  764. d_head/2, mrope_sections, GGML_ROPE_TYPE_VISION, 32768, 10000, 1, 0, 1, 32, 1);
  765. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  766. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  767. struct ggml_tensor * V =
  768. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  769. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  770. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  771. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  772. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  773. const bool full_attn = use_window_attn ? (il + 1) % n_wa_pattern == 0 : true;
  774. if (full_attn) {
  775. KQ = ggml_soft_max_ext(ctx0, KQ, nullptr, 1.0f / sqrtf((float)d_head), 0.0f);
  776. } else {
  777. KQ = ggml_soft_max_ext(ctx0, KQ, window_mask, 1.0f / sqrtf((float)d_head), 0.0f);
  778. }
  779. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  780. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  781. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  782. cur = ggml_cont_3d(ctx0, KQV, hidden_size, num_positions, batch_size);
  783. }
  784. // attention output
  785. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  786. // re-add the layer input, e.g., residual
  787. cur = ggml_add(ctx0, cur, embeddings);
  788. embeddings = cur; // embeddings = residual, cur = hidden_states
  789. // rms norm2
  790. cur = ggml_rms_norm(ctx0, cur, eps);
  791. cur = ggml_mul(ctx0, cur, model.layers[il].ln_2_w);
  792. // mlp
  793. // ffn_up
  794. auto cur_up = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  795. cur_up = ggml_add(ctx0, cur_up, model.layers[il].ff_o_b);
  796. auto cur_gate = ggml_mul_mat(ctx0, model.layers[il].ff_g_w, cur);
  797. cur_gate = ggml_add(ctx0, cur_gate, model.layers[il].ff_g_b);
  798. // TODO : only 2 of these 3 are actually used, should we remove one of them?
  799. if (ctx->use_gelu) {
  800. cur_gate = ggml_gelu_inplace(ctx0, cur_gate);
  801. } else if (ctx->use_silu) {
  802. cur_gate = ggml_silu_inplace(ctx0, cur_gate);
  803. } else {
  804. cur_gate = ggml_gelu_quick_inplace(ctx0, cur_gate);
  805. }
  806. cur = ggml_mul(ctx0, cur_gate, cur_up);
  807. // ffn_down
  808. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  809. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  810. // residual 2
  811. cur = ggml_add(ctx0, embeddings, cur);
  812. embeddings = cur;
  813. }
  814. // post-layernorm
  815. if (model.post_ln_w) {
  816. embeddings = ggml_rms_norm(ctx0, embeddings, eps);
  817. ggml_set_name(embeddings, "post_ln");
  818. embeddings = ggml_mul(ctx0, embeddings, model.post_ln_w);
  819. }
  820. embeddings = ggml_reshape_3d(ctx0, embeddings, hidden_size * 4, num_positions / 4, batch_size);
  821. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  822. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  823. // GELU activation
  824. embeddings = ggml_gelu(ctx0, embeddings);
  825. // Second linear layer
  826. embeddings = ggml_mul_mat(ctx0, model.mm_1_w, embeddings);
  827. embeddings = ggml_add(ctx0, embeddings, model.mm_1_b);
  828. if (use_window_attn) {
  829. window_idx = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions / 4);
  830. ggml_set_name(window_idx, "window_idx");
  831. ggml_set_input(window_idx);
  832. // embeddings shape: [hidden_size, patches_w * patches_h, batch_size]
  833. GGML_ASSERT(batch_size == 1);
  834. embeddings = ggml_reshape_2d(ctx0, embeddings, hparams.projection_dim, patches_w * patches_h / 4);
  835. embeddings = ggml_get_rows(ctx0, embeddings, window_idx);
  836. embeddings = ggml_reshape_3d(ctx0, embeddings, hparams.projection_dim, patches_w * patches_h / 4, batch_size);
  837. }
  838. // build the graph
  839. ggml_build_forward_expand(gf, embeddings);
  840. return gf;
  841. }
  842. 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) {
  843. const auto & model = ctx->vision_model;
  844. const auto & hparams = model.hparams;
  845. const int image_size = hparams.image_size;
  846. int image_size_width = image_size;
  847. int image_size_height = image_size;
  848. if (ctx->proj_type == PROJECTOR_TYPE_MINICPMV) {
  849. LOG_DBG("%s: %d %d\n", __func__, load_image_size.width, load_image_size.height);
  850. image_size_width = load_image_size.width;
  851. image_size_height = load_image_size.height;
  852. if (is_inf) {
  853. image_size_width = imgs.entries[0]->nx;
  854. image_size_height = imgs.entries[0]->ny;
  855. }
  856. }
  857. else if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL) {
  858. // use the image's native resolution when image is avaible
  859. if (is_inf) {
  860. // if (imgs->data->nx && imgs->data->ny) {
  861. image_size_width = imgs.entries[0]->nx;
  862. image_size_height = imgs.entries[0]->ny;
  863. }
  864. }
  865. const int patch_size = hparams.patch_size;
  866. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  867. const int patches_w = image_size_width / patch_size;
  868. const int patches_h = image_size_height / patch_size;
  869. const int num_positions = num_patches + (model.class_embedding ? 1 : 0);
  870. const int num_position_ids = ctx->proj_type == PROJECTOR_TYPE_QWEN2VL ? num_positions * 4 : num_positions;
  871. const int hidden_size = hparams.hidden_size;
  872. const int n_head = hparams.n_head;
  873. const int d_head = hidden_size / n_head;
  874. const float eps = hparams.eps;
  875. int mrope_sections[4] = {d_head/4, d_head/4, d_head/4, d_head/4};
  876. const int batch_size = imgs.entries.size();
  877. if (ctx->has_llava_projector
  878. || ctx->proj_type == PROJECTOR_TYPE_MINICPMV
  879. || ctx->proj_type == PROJECTOR_TYPE_GLM_EDGE) {
  880. GGML_ASSERT(batch_size == 1);
  881. }
  882. struct ggml_init_params params = {
  883. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  884. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  885. /*.no_alloc =*/ true,
  886. };
  887. ggml_context_ptr ctx0_ptr(ggml_init(params));
  888. auto ctx0 = ctx0_ptr.get();
  889. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  890. struct ggml_tensor * inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size_width, image_size_height, 3, batch_size);
  891. ggml_set_name(inp_raw, "inp_raw");
  892. ggml_set_input(inp_raw);
  893. struct ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  894. if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL) {
  895. GGML_ASSERT(image_size_width % (patch_size * 2) == 0);
  896. GGML_ASSERT(image_size_height % (patch_size * 2) == 0);
  897. auto inp_1 = ggml_conv_2d(ctx0, model.patch_embeddings_1, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  898. inp = ggml_add(ctx0, inp, inp_1);
  899. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 2, 0, 3)); // [w, h, c, b] -> [c, w, h, b]
  900. inp = ggml_reshape_4d(
  901. ctx0, inp,
  902. hidden_size * 2, patches_w / 2, patches_h, batch_size);
  903. inp = ggml_reshape_4d(
  904. ctx0, inp,
  905. hidden_size * 2, patches_w / 2, 2, batch_size * (patches_h / 2));
  906. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 0, 2, 1, 3));
  907. inp = ggml_reshape_3d(
  908. ctx0, inp,
  909. hidden_size, patches_w * patches_h, batch_size);
  910. }
  911. else {
  912. inp = ggml_reshape_3d(ctx0, inp, num_patches, hidden_size, batch_size);
  913. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 0, 2, 3));
  914. }
  915. if (model.patch_bias) {
  916. // inp = ggml_add(ctx0, inp, ggml_repeat(ctx0, model.patch_bias, inp));
  917. inp = ggml_add(ctx0, inp, model.patch_bias);
  918. }
  919. struct ggml_tensor * embeddings = inp;
  920. struct ggml_tensor * pos_embed = nullptr;
  921. // concat class_embeddings and patch_embeddings
  922. if (model.class_embedding) {
  923. embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, batch_size);
  924. embeddings = ggml_scale(ctx0, embeddings, 0.0f); // set to all zeros
  925. embeddings = ggml_acc(ctx0, embeddings, model.class_embedding,
  926. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], 0);
  927. embeddings = ggml_acc(ctx0, embeddings, inp,
  928. embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], model.class_embedding->nb[1]);
  929. }
  930. struct ggml_tensor * positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_position_ids);
  931. ggml_set_name(positions, "positions");
  932. ggml_set_input(positions);
  933. if (ctx->proj_type != PROJECTOR_TYPE_QWEN2VL) { // qwen2vl does NOT use learned position embeddings
  934. embeddings =
  935. ggml_add(ctx0, embeddings, ggml_get_rows(ctx0, model.position_embeddings, positions));
  936. }
  937. if (ctx->proj_type == PROJECTOR_TYPE_MINICPMV) {
  938. int pos_w = image_size_width/patch_size;
  939. int pos_h = image_size_height/patch_size;
  940. int n_output_dim = clip_n_mmproj_embd(ctx);
  941. pos_embed = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_output_dim, pos_w * pos_h, 1);
  942. ggml_set_name(pos_embed, "pos_embed");
  943. ggml_set_input(pos_embed);
  944. }
  945. // pre-layernorm
  946. if (model.pre_ln_w) {
  947. embeddings = ggml_norm(ctx0, embeddings, eps);
  948. ggml_set_name(embeddings, "pre_ln");
  949. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.pre_ln_w), model.pre_ln_b);
  950. }
  951. std::vector<struct ggml_tensor *> embedding_stack;
  952. const auto & vision_feature_layer = hparams.vision_feature_layer;
  953. // loop over layers
  954. for (int il = 0; il < ctx->max_feature_layer; il++) {
  955. struct ggml_tensor * cur = embeddings; // embeddings = residual, cur = hidden_states
  956. // If this is an embedding feature layer, save the output.
  957. // NOTE: 0 index here refers to the input to the encoder.
  958. if (vision_feature_layer.find(il) != vision_feature_layer.end()) {
  959. embedding_stack.push_back(embeddings);
  960. }
  961. //const size_t nb_q_w = model.layers[il].q_w->nb[0];
  962. // layernorm1
  963. {
  964. cur = ggml_norm(ctx0, cur, eps);
  965. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_1_w),
  966. model.layers[il].ln_1_b);
  967. }
  968. // self-attention
  969. {
  970. struct ggml_tensor * Q =
  971. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].q_w, cur), model.layers[il].q_b);
  972. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_positions, batch_size);
  973. if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL) {
  974. Q = ggml_rope_multi(
  975. ctx0, Q, positions, nullptr,
  976. d_head/2, mrope_sections, GGML_ROPE_TYPE_VISION, 32768, 10000, 1, 0, 1, 32, 1);
  977. }
  978. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  979. Q = ggml_reshape_3d(ctx0, Q, d_head, num_positions, n_head * batch_size);
  980. struct ggml_tensor * K =
  981. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].k_w, cur), model.layers[il].k_b);
  982. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  983. if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL) {
  984. K = ggml_rope_multi(
  985. ctx0, K, positions, nullptr,
  986. d_head/2, mrope_sections, GGML_ROPE_TYPE_VISION, 32768, 10000, 1, 0, 1, 32, 1);
  987. }
  988. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  989. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  990. struct ggml_tensor * V =
  991. ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].v_w, cur), model.layers[il].v_b);
  992. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  993. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  994. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  995. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  996. KQ = ggml_soft_max_ext(ctx0, KQ, nullptr, 1.0f / sqrtf((float)d_head), 0.0f);
  997. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  998. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_positions, n_head, batch_size);
  999. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1000. cur = ggml_cont_3d(ctx0, KQV, hidden_size, num_positions, batch_size);
  1001. }
  1002. // attention output
  1003. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].o_w, cur), model.layers[il].o_b);
  1004. // re-add the layer input, e.g., residual
  1005. cur = ggml_add(ctx0, cur, embeddings);
  1006. embeddings = cur; // embeddings = residual, cur = hidden_states
  1007. // layernorm2
  1008. {
  1009. cur = ggml_norm(ctx0, cur, eps);
  1010. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ln_2_w), model.layers[il].ln_2_b);
  1011. }
  1012. cur = ggml_mul_mat(ctx0, model.layers[il].ff_i_w, cur);
  1013. cur = ggml_add(ctx0, cur, model.layers[il].ff_i_b);
  1014. if (ctx->use_gelu) {
  1015. cur = ggml_gelu_inplace(ctx0, cur);
  1016. } else if (ctx->use_silu) {
  1017. cur = ggml_silu_inplace(ctx0, cur);
  1018. } else {
  1019. cur = ggml_gelu_quick_inplace(ctx0, cur);
  1020. }
  1021. cur = ggml_mul_mat(ctx0, model.layers[il].ff_o_w, cur);
  1022. cur = ggml_add(ctx0, cur, model.layers[il].ff_o_b);
  1023. // residual 2
  1024. cur = ggml_add(ctx0, embeddings, cur);
  1025. embeddings = cur;
  1026. }
  1027. // post-layernorm
  1028. if (model.post_ln_w) {
  1029. embeddings = ggml_norm(ctx0, embeddings, eps);
  1030. ggml_set_name(embeddings, "post_ln");
  1031. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.post_ln_w), model.post_ln_b);
  1032. }
  1033. // final layer is a vision feature layer
  1034. if (vision_feature_layer.find(ctx->max_feature_layer) != vision_feature_layer.end()) {
  1035. embedding_stack.push_back(embeddings);
  1036. }
  1037. // If feature layers are explicitly set, stack them (if we have multiple)
  1038. if (!embedding_stack.empty()) {
  1039. embeddings = embedding_stack[0];
  1040. for (size_t i = 1; i < embedding_stack.size(); i++) {
  1041. embeddings = ggml_concat(ctx0, embeddings, embedding_stack[i], 0);
  1042. }
  1043. }
  1044. // llava projector
  1045. if (ctx->has_llava_projector) {
  1046. embeddings = ggml_reshape_2d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1]);
  1047. struct ggml_tensor * patches = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_patches);
  1048. ggml_set_name(patches, "patches");
  1049. ggml_set_input(patches);
  1050. // shape [1, 576, 1024]
  1051. // ne is whcn, ne = [1024, 576, 1, 1]
  1052. embeddings = ggml_get_rows(ctx0, embeddings, patches);
  1053. // print_tensor_info(embeddings, "embeddings");
  1054. // llava projector
  1055. if (ctx->proj_type == PROJECTOR_TYPE_MLP) {
  1056. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  1057. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  1058. embeddings = ggml_gelu(ctx0, embeddings);
  1059. if (model.mm_2_w) {
  1060. embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
  1061. embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
  1062. }
  1063. }
  1064. else if (ctx->proj_type == PROJECTOR_TYPE_MLP_NORM) {
  1065. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  1066. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  1067. // ggml_tensor_printf(embeddings, "mm_0_w",0,true,false);
  1068. // First LayerNorm
  1069. embeddings = ggml_norm(ctx0, embeddings, eps);
  1070. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_1_w),
  1071. model.mm_1_b);
  1072. // GELU activation
  1073. embeddings = ggml_gelu(ctx0, embeddings);
  1074. // Second linear layer
  1075. embeddings = ggml_mul_mat(ctx0, model.mm_3_w, embeddings);
  1076. embeddings = ggml_add(ctx0, embeddings, model.mm_3_b);
  1077. // Second LayerNorm
  1078. embeddings = ggml_norm(ctx0, embeddings, eps);
  1079. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_4_w),
  1080. model.mm_4_b);
  1081. }
  1082. else if (ctx->proj_type == PROJECTOR_TYPE_LDP) {
  1083. // MobileVLM projector
  1084. int n_patch = 24;
  1085. struct ggml_tensor * mlp_1 = ggml_mul_mat(ctx0, model.mm_model_mlp_1_w, embeddings);
  1086. mlp_1 = ggml_add(ctx0, mlp_1, model.mm_model_mlp_1_b);
  1087. mlp_1 = ggml_gelu(ctx0, mlp_1);
  1088. struct ggml_tensor * mlp_3 = ggml_mul_mat(ctx0, model.mm_model_mlp_3_w, mlp_1);
  1089. mlp_3 = ggml_add(ctx0, mlp_3, model.mm_model_mlp_3_b);
  1090. // mlp_3 shape = [1, 576, 2048], ne = [2048, 576, 1, 1]
  1091. // block 1
  1092. struct ggml_tensor * block_1 = nullptr;
  1093. {
  1094. // transpose from [1, 576, 2048] --> [1, 2048, 576] --> [1, 2048, 24, 24]
  1095. mlp_3 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_3, 1, 0, 2, 3));
  1096. mlp_3 = ggml_reshape_4d(ctx0, mlp_3, n_patch, n_patch, mlp_3->ne[1], mlp_3->ne[2]);
  1097. // stride = 1, padding = 1, bias is nullptr
  1098. block_1 = ggml_conv_2d_dw(ctx0, model.mm_model_block_1_block_0_0_w, mlp_3, 1, 1, 1, 1, 1, 1);
  1099. // layer norm
  1100. // // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  1101. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  1102. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  1103. block_1 = ggml_norm(ctx0, block_1, eps);
  1104. 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);
  1105. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  1106. // block_1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  1107. // hardswish
  1108. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  1109. 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);
  1110. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  1111. // pointwise conv
  1112. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  1113. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc1_w, block_1);
  1114. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc1_b);
  1115. block_1 = ggml_relu(ctx0, block_1);
  1116. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_1_fc2_w, block_1);
  1117. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_1_block_1_fc2_b);
  1118. block_1 = ggml_hardsigmoid(ctx0, block_1);
  1119. // block_1_hw shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1], block_1 shape = [1, 2048], ne = [2048, 1, 1, 1]
  1120. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  1121. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  1122. int w = block_1->ne[0], h = block_1->ne[1];
  1123. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  1124. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  1125. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  1126. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_1_block_2_0_w, block_1);
  1127. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  1128. // block_1 shape = [1, 24, 24, 2048], ne = [2048, 24, 24, 1]
  1129. block_1 = ggml_norm(ctx0, block_1, eps);
  1130. 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);
  1131. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  1132. // block1 shape = [1, 2048, 24, 24], ne = [24, 24, 2048, 1]
  1133. // residual
  1134. block_1 = ggml_add(ctx0, mlp_3, block_1);
  1135. }
  1136. // block_2
  1137. {
  1138. // stride = 2
  1139. block_1 = ggml_conv_2d_dw(ctx0, model.mm_model_block_2_block_0_0_w, block_1, 2, 2, 1, 1, 1, 1);
  1140. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  1141. // layer norm
  1142. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 2, 0, 3));
  1143. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  1144. block_1 = ggml_norm(ctx0, block_1, eps);
  1145. 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);
  1146. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 2, 0, 1, 3));
  1147. // block_1 shape = [1, 2048, 12, 12], ne = [12, 12, 2048, 1]
  1148. // hardswish
  1149. struct ggml_tensor * block_1_hw = ggml_hardswish(ctx0, block_1);
  1150. // not sure the parameters is right for globalAvgPooling
  1151. 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);
  1152. // block_1 shape = [1, 2048, 1, 1], ne = [1, 1, 2048, 1]
  1153. // pointwise conv
  1154. block_1 = ggml_reshape_2d(ctx0, block_1, block_1->ne[0]*block_1->ne[1]*block_1->ne[2], block_1->ne[3]);
  1155. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc1_w, block_1);
  1156. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc1_b);
  1157. block_1 = ggml_relu(ctx0, block_1);
  1158. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_1_fc2_w, block_1);
  1159. block_1 = ggml_add(ctx0, block_1, model.mm_model_block_2_block_1_fc2_b);
  1160. block_1 = ggml_hardsigmoid(ctx0, block_1);
  1161. // 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]
  1162. block_1 = ggml_reshape_4d(ctx0, block_1, 1, 1, block_1->ne[0], block_1->ne[1]);
  1163. block_1 = ggml_mul(ctx0, block_1_hw, block_1);
  1164. int w = block_1->ne[0], h = block_1->ne[1];
  1165. block_1 = ggml_reshape_3d(ctx0, block_1, w*h, block_1->ne[2], block_1->ne[3]);
  1166. block_1 = ggml_cont(ctx0, ggml_permute(ctx0, block_1, 1, 0, 2, 3));
  1167. // block_1 shape = [1, 24*24, 2048], ne = [24*24, 2048, 1]
  1168. block_1 = ggml_mul_mat(ctx0, model.mm_model_block_2_block_2_0_w, block_1);
  1169. block_1 = ggml_reshape_4d(ctx0, block_1, block_1->ne[0], w, h, block_1->ne[3]);
  1170. // block_1 shape = [1, 12, 12, 2048], ne = [2048, 12, 12, 1]
  1171. block_1 = ggml_norm(ctx0, block_1, eps);
  1172. 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);
  1173. block_1 = ggml_reshape_3d(ctx0, block_1, block_1->ne[0], block_1->ne[1] * block_1->ne[2], block_1->ne[3]);
  1174. // block_1 shape = [1, 144, 2048], ne = [2048, 144, 1]
  1175. }
  1176. embeddings = block_1;
  1177. }
  1178. else if (ctx->proj_type == PROJECTOR_TYPE_LDPV2)
  1179. {
  1180. int n_patch = 24;
  1181. struct ggml_tensor * mlp_0 = ggml_mul_mat(ctx0, model.mm_model_mlp_0_w, embeddings);
  1182. mlp_0 = ggml_add(ctx0, mlp_0, model.mm_model_mlp_0_b);
  1183. mlp_0 = ggml_gelu(ctx0, mlp_0);
  1184. struct ggml_tensor * mlp_2 = ggml_mul_mat(ctx0, model.mm_model_mlp_2_w, mlp_0);
  1185. mlp_2 = ggml_add(ctx0, mlp_2, model.mm_model_mlp_2_b);
  1186. // mlp_2 ne = [2048, 576, 1, 1]
  1187. // // AVG Pool Layer 2*2, strides = 2
  1188. mlp_2 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_2, 1, 0, 2, 3));
  1189. // mlp_2 ne = [576, 2048, 1, 1]
  1190. mlp_2 = ggml_reshape_4d(ctx0, mlp_2, n_patch, n_patch, mlp_2->ne[1], mlp_2->ne[2]);
  1191. // mlp_2 ne [24, 24, 2048, 1]
  1192. mlp_2 = ggml_pool_2d(ctx0, mlp_2, GGML_OP_POOL_AVG, 2, 2, 2, 2, 0, 0);
  1193. // weight ne = [3, 3, 2048, 1]
  1194. struct ggml_tensor * peg_0 = ggml_conv_2d_dw(ctx0, model.mm_model_peg_0_w, mlp_2, 1, 1, 1, 1, 1, 1);
  1195. peg_0 = ggml_cont(ctx0, ggml_permute(ctx0, peg_0, 1, 2, 0, 3));
  1196. peg_0 = ggml_add(ctx0, peg_0, model.mm_model_peg_0_b);
  1197. mlp_2 = ggml_cont(ctx0, ggml_permute(ctx0, mlp_2, 1, 2, 0, 3));
  1198. peg_0 = ggml_add(ctx0, peg_0, mlp_2);
  1199. peg_0 = ggml_reshape_3d(ctx0, peg_0, peg_0->ne[0], peg_0->ne[1] * peg_0->ne[2], peg_0->ne[3]);
  1200. embeddings = peg_0;
  1201. }
  1202. else {
  1203. GGML_ABORT("fatal error");
  1204. }
  1205. }
  1206. // minicpmv projector
  1207. else if (ctx->proj_type == PROJECTOR_TYPE_MINICPMV) {
  1208. struct ggml_tensor * q = model.mm_model_query;
  1209. { // layernorm
  1210. q = ggml_norm(ctx0, q, eps);
  1211. q = ggml_add(ctx0, ggml_mul(ctx0, q, model.mm_model_ln_q_w), model.mm_model_ln_q_b);
  1212. }
  1213. struct ggml_tensor * v = ggml_mul_mat(ctx0, model.mm_model_kv_proj, embeddings);
  1214. { // layernorm
  1215. v = ggml_norm(ctx0, v, eps);
  1216. v = ggml_add(ctx0, ggml_mul(ctx0, v, model.mm_model_ln_kv_w), model.mm_model_ln_kv_b);
  1217. }
  1218. struct ggml_tensor * k;
  1219. { // position
  1220. // q = ggml_add(ctx0, q, model.mm_model_pos_embed);
  1221. k = ggml_add(ctx0, v, pos_embed);
  1222. }
  1223. { // attention
  1224. int hidden_size = clip_n_mmproj_embd(ctx);
  1225. const int d_head = 128;
  1226. int n_head = hidden_size/d_head;
  1227. int num_query = 96;
  1228. if (ctx->minicpmv_version == 2) {
  1229. num_query = 96;
  1230. }
  1231. else if (ctx->minicpmv_version == 3) {
  1232. num_query = 64;
  1233. }
  1234. else if (ctx->minicpmv_version == 4) {
  1235. num_query = 64;
  1236. }
  1237. struct ggml_tensor * Q = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_q_w, q), model.mm_model_attn_q_b);
  1238. struct ggml_tensor * K = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_k_w, k), model.mm_model_attn_k_b);
  1239. struct ggml_tensor * V = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_v_w, v), model.mm_model_attn_v_b);
  1240. // permute
  1241. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, num_query, batch_size);
  1242. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  1243. Q = ggml_reshape_3d(ctx0, Q, d_head, num_query, n_head * batch_size);
  1244. K = ggml_reshape_4d(ctx0, K, d_head, n_head, num_positions, batch_size);
  1245. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  1246. K = ggml_reshape_3d(ctx0, K, d_head, num_positions, n_head * batch_size);
  1247. V = ggml_reshape_4d(ctx0, V, d_head, n_head, num_positions, batch_size);
  1248. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  1249. V = ggml_reshape_3d(ctx0, V, num_positions, d_head, n_head * batch_size);
  1250. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1251. KQ = ggml_soft_max_ext(ctx0, KQ, nullptr, 1.0f / sqrtf((float)d_head), 0.0f);
  1252. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ);
  1253. KQV = ggml_reshape_4d(ctx0, KQV, d_head, num_query, n_head, batch_size);
  1254. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1255. KQV = ggml_cont_3d(ctx0, KQV, hidden_size, num_query, batch_size);
  1256. embeddings = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_model_attn_o_w, KQV), model.mm_model_attn_o_b);
  1257. }
  1258. { // layernorm
  1259. embeddings = ggml_norm(ctx0, embeddings, eps);
  1260. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_model_ln_post_w), model.mm_model_ln_post_b);
  1261. }
  1262. embeddings = ggml_mul_mat(ctx0, model.mm_model_proj, embeddings);
  1263. }
  1264. // glm projector
  1265. else if (ctx->proj_type == PROJECTOR_TYPE_GLM_EDGE) {
  1266. size_t gridsz = (size_t)sqrt(embeddings->ne[1]);
  1267. embeddings = ggml_cont(ctx0, ggml_permute(ctx0,embeddings,1,0,2,3));
  1268. embeddings = ggml_reshape_3d(ctx0, embeddings, gridsz, gridsz, embeddings->ne[1]);
  1269. embeddings = ggml_conv_2d(ctx0, model.mm_model_adapter_conv_w, embeddings, 2, 2, 0, 0, 1, 1);
  1270. embeddings = ggml_reshape_3d(ctx0, embeddings,embeddings->ne[0]*embeddings->ne[1] , embeddings->ne[2], batch_size);
  1271. embeddings = ggml_cont(ctx0, ggml_permute(ctx0,embeddings, 1, 0, 2, 3));
  1272. embeddings = ggml_add(ctx0, embeddings, model.mm_model_adapter_conv_b);
  1273. // GLU
  1274. {
  1275. embeddings = ggml_mul_mat(ctx0, model.mm_model_mlp_0_w, embeddings);
  1276. embeddings = ggml_norm(ctx0, embeddings, eps);
  1277. embeddings = ggml_add(ctx0, ggml_mul(ctx0, embeddings, model.mm_model_ln_q_w), model.mm_model_ln_q_b);
  1278. embeddings = ggml_gelu_inplace(ctx0, embeddings);
  1279. struct ggml_tensor * x = embeddings;
  1280. embeddings = ggml_mul_mat(ctx0, model.mm_model_mlp_2_w, embeddings);
  1281. x = ggml_mul_mat(ctx0, model.mm_model_mlp_1_w,x);
  1282. embeddings = ggml_silu_inplace(ctx0, embeddings);
  1283. embeddings = ggml_mul(ctx0, embeddings,x);
  1284. embeddings = ggml_mul_mat(ctx0, model.mm_model_mlp_3_w, embeddings);
  1285. }
  1286. // arrangement of BOI/EOI token embeddings
  1287. // note: these embeddings are not present in text model, hence we cannot process them as text tokens
  1288. // see: https://huggingface.co/THUDM/glm-edge-v-2b/blob/main/siglip.py#L53
  1289. {
  1290. embeddings = ggml_concat(ctx0, model.mm_glm_tok_boi, embeddings, 1); // BOI
  1291. embeddings = ggml_concat(ctx0, embeddings, model.mm_glm_tok_eoi, 1); // EOI
  1292. }
  1293. }
  1294. else if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL) {
  1295. embeddings = ggml_reshape_3d(ctx0, embeddings, hidden_size * 4, num_positions / 4, batch_size);
  1296. embeddings = ggml_mul_mat(ctx0, model.mm_0_w, embeddings);
  1297. embeddings = ggml_add(ctx0, embeddings, model.mm_0_b);
  1298. // GELU activation
  1299. embeddings = ggml_gelu(ctx0, embeddings);
  1300. // Second linear layer
  1301. embeddings = ggml_mul_mat(ctx0, model.mm_1_w, embeddings);
  1302. embeddings = ggml_add(ctx0, embeddings, model.mm_1_b);
  1303. }
  1304. // build the graph
  1305. ggml_build_forward_expand(gf, embeddings);
  1306. return gf;
  1307. }
  1308. 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) {
  1309. ggml_cgraph * res;
  1310. switch (ctx->proj_type) {
  1311. case PROJECTOR_TYPE_GEMMA3:
  1312. case PROJECTOR_TYPE_IDEFICS3:
  1313. {
  1314. GGML_ASSERT(imgs.entries.size() == 1);
  1315. res = clip_image_build_graph_siglip(ctx, *imgs.entries[0]);
  1316. } break;
  1317. case PROJECTOR_TYPE_PIXTRAL:
  1318. {
  1319. GGML_ASSERT(imgs.entries.size() == 1);
  1320. res = clip_image_build_graph_pixtral(ctx, *imgs.entries[0]);
  1321. } break;
  1322. case PROJECTOR_TYPE_QWEN25VL:
  1323. {
  1324. res = clip_image_build_graph_qwen25vl(ctx, imgs);
  1325. } break;
  1326. default:
  1327. {
  1328. // TODO: we should have one build_* function per model
  1329. res = clip_image_build_graph_legacy(ctx, imgs, load_image_size, is_inf);
  1330. } break;
  1331. }
  1332. return res;
  1333. }
  1334. struct clip_model_loader {
  1335. ggml_context_ptr ctx_meta;
  1336. gguf_context_ptr ctx_gguf;
  1337. clip_ctx & ctx_clip;
  1338. std::string fname;
  1339. size_t model_size = 0; // in bytes
  1340. // TODO @ngxson : we should not pass clip_ctx here, it should be clip_vision_model
  1341. clip_model_loader(const char * fname, clip_ctx & ctx_clip) : ctx_clip(ctx_clip), fname(fname) {
  1342. struct ggml_context * meta = nullptr;
  1343. struct gguf_init_params params = {
  1344. /*.no_alloc = */ true,
  1345. /*.ctx = */ &meta,
  1346. };
  1347. ctx_gguf = gguf_context_ptr(gguf_init_from_file(fname, params));
  1348. if (!ctx_gguf.get()) {
  1349. throw std::runtime_error(string_format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  1350. }
  1351. ctx_meta.reset(meta);
  1352. const int n_tensors = gguf_get_n_tensors(ctx_gguf.get());
  1353. // print gguf info
  1354. {
  1355. std::string name;
  1356. get_string(KEY_NAME, name, false);
  1357. std::string description;
  1358. get_string(KEY_DESCRIPTION, description, false);
  1359. LOG_INF("%s: model name: %s\n", __func__, name.c_str());
  1360. LOG_INF("%s: description: %s\n", __func__, description.c_str());
  1361. LOG_INF("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx_gguf.get()));
  1362. LOG_INF("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx_gguf.get()));
  1363. LOG_INF("%s: n_tensors: %d\n", __func__, n_tensors);
  1364. LOG_INF("%s: n_kv: %d\n", __func__, (int)gguf_get_n_kv(ctx_gguf.get()));
  1365. LOG_INF("\n");
  1366. }
  1367. // tensors
  1368. {
  1369. for (int i = 0; i < n_tensors; ++i) {
  1370. const char * name = gguf_get_tensor_name(ctx_gguf.get(), i);
  1371. const size_t offset = gguf_get_tensor_offset(ctx_gguf.get(), i);
  1372. enum ggml_type type = gguf_get_tensor_type(ctx_gguf.get(), i);
  1373. struct ggml_tensor * cur = ggml_get_tensor(meta, name);
  1374. size_t tensor_size = ggml_nbytes(cur);
  1375. model_size += tensor_size;
  1376. LOG_DBG("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu, shape:[%" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "], type = %s\n",
  1377. __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));
  1378. }
  1379. }
  1380. }
  1381. void load_hparams() {
  1382. auto & hparams = ctx_clip.vision_model.hparams;
  1383. // projector type
  1384. std::string proj_type;
  1385. {
  1386. get_string(KEY_PROJ_TYPE, proj_type, false);
  1387. if (!proj_type.empty()) {
  1388. ctx_clip.proj_type = clip_projector_type_from_string(proj_type);
  1389. }
  1390. if (ctx_clip.proj_type == PROJECTOR_TYPE_UNKNOWN) {
  1391. throw std::runtime_error(string_format("%s: unknown projector type: %s\n", __func__, proj_type.c_str()));
  1392. }
  1393. }
  1394. // other hparams
  1395. {
  1396. get_i32(KEY_MINICPMV_VERSION, ctx_clip.minicpmv_version, false);
  1397. get_bool(KEY_USE_GELU, ctx_clip.use_gelu, false);
  1398. get_bool(KEY_USE_SILU, ctx_clip.use_silu, false);
  1399. get_u32(KEY_N_EMBD, hparams.hidden_size);
  1400. get_u32(KEY_N_HEAD, hparams.n_head);
  1401. get_u32(KEY_N_FF, hparams.n_intermediate);
  1402. get_u32(KEY_N_BLOCK, hparams.n_layer);
  1403. get_u32(KEY_PROJ_DIM, hparams.projection_dim);
  1404. get_f32(KEY_LAYER_NORM_EPS, hparams.eps);
  1405. get_u32(KEY_IMAGE_SIZE, hparams.image_size);
  1406. get_u32(KEY_PATCH_SIZE, hparams.patch_size);
  1407. get_u32(KEY_IMAGE_CROP_RESOLUTION, hparams.image_crop_resolution, false);
  1408. get_arr_int(KEY_IMAGE_GRID_PINPOINTS, hparams.image_grid_pinpoints, false);
  1409. ctx_clip.has_llava_projector = ctx_clip.proj_type == PROJECTOR_TYPE_MLP
  1410. || ctx_clip.proj_type == PROJECTOR_TYPE_MLP_NORM
  1411. || ctx_clip.proj_type == PROJECTOR_TYPE_LDP
  1412. || ctx_clip.proj_type == PROJECTOR_TYPE_LDPV2;
  1413. {
  1414. std::string mm_patch_merge_type;
  1415. get_string(KEY_MM_PATCH_MERGE_TYPE, mm_patch_merge_type, false);
  1416. if (mm_patch_merge_type == "spatial_unpad") {
  1417. hparams.mm_patch_merge_type = PATCH_MERGE_SPATIAL_UNPAD;
  1418. }
  1419. }
  1420. {
  1421. int idx_mean = gguf_find_key(ctx_gguf.get(), KEY_IMAGE_MEAN);
  1422. int idx_std = gguf_find_key(ctx_gguf.get(), KEY_IMAGE_STD);
  1423. GGML_ASSERT(idx_mean >= 0 && "image_mean not found");
  1424. GGML_ASSERT(idx_std >= 0 && "image_std not found");
  1425. const float * mean_data = (const float *) gguf_get_arr_data(ctx_gguf.get(), idx_mean);
  1426. const float * std_data = (const float *) gguf_get_arr_data(ctx_gguf.get(), idx_std);
  1427. for (int i = 0; i < 3; ++i) {
  1428. ctx_clip.image_mean[i] = mean_data[i];
  1429. ctx_clip.image_std[i] = std_data[i];
  1430. }
  1431. }
  1432. // Load the vision feature layer indices if they are explicitly provided;
  1433. // if multiple vision feature layers are present, the values will be concatenated
  1434. // to form the final visual features.
  1435. // NOTE: gguf conversions should standardize the values of the vision feature layer to
  1436. // be non-negative, since we use -1 to mark values as unset here.
  1437. std::vector<int> vision_feature_layer;
  1438. get_arr_int(KEY_FEATURE_LAYER, vision_feature_layer, false);
  1439. // convert std::vector to std::unordered_set
  1440. for (auto & layer : vision_feature_layer) {
  1441. hparams.vision_feature_layer.insert(layer);
  1442. }
  1443. // Calculate the deepest feature layer based on hparams and projector type
  1444. // NOTE: This is only used by build_graph_legacy()
  1445. {
  1446. // Get the index of the second to last layer; this is the default for models that have a llava projector
  1447. int n_layer = hparams.n_layer - 1;
  1448. int deepest_feature_layer = -1;
  1449. if (ctx_clip.proj_type == PROJECTOR_TYPE_MINICPMV
  1450. || ctx_clip.proj_type == PROJECTOR_TYPE_GLM_EDGE
  1451. || ctx_clip.proj_type == PROJECTOR_TYPE_QWEN2VL
  1452. || ctx_clip.proj_type == PROJECTOR_TYPE_QWEN25VL) {
  1453. n_layer += 1;
  1454. }
  1455. // If we set explicit vision feature layers, only go up to the deepest one
  1456. // NOTE: only used by granite-vision models for now
  1457. for (const auto & feature_layer : hparams.vision_feature_layer) {
  1458. if (feature_layer > deepest_feature_layer) {
  1459. deepest_feature_layer = feature_layer;
  1460. }
  1461. }
  1462. ctx_clip.max_feature_layer = deepest_feature_layer < 0 ? n_layer : deepest_feature_layer;
  1463. }
  1464. // model-specific params
  1465. switch (ctx_clip.proj_type) {
  1466. case PROJECTOR_TYPE_MINICPMV:
  1467. {
  1468. if (ctx_clip.minicpmv_version == 0) {
  1469. ctx_clip.minicpmv_version = 2; // default to 2 if not set
  1470. }
  1471. } break;
  1472. case PROJECTOR_TYPE_IDEFICS3:
  1473. {
  1474. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.proj_scale_factor, false);
  1475. } break;
  1476. case PROJECTOR_TYPE_PIXTRAL:
  1477. {
  1478. hparams.rope_theta = 10000.0f;
  1479. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.spatial_merge_size, false);
  1480. } break;
  1481. case PROJECTOR_TYPE_QWEN25VL:
  1482. {
  1483. get_u32(KEY_WIN_ATTN_PATTERN, hparams.n_wa_pattern);
  1484. } break;
  1485. default:
  1486. break;
  1487. }
  1488. LOG_INF("%s: projector: %s\n", __func__, proj_type.c_str());
  1489. LOG_INF("%s: has_llava_proj: %d\n", __func__, ctx_clip.has_llava_projector);
  1490. LOG_INF("%s: minicpmv_version: %d\n", __func__, ctx_clip.minicpmv_version);
  1491. LOG_INF("%s: proj_scale_factor: %d\n", __func__, hparams.proj_scale_factor);
  1492. LOG_INF("%s: n_wa_pattern: %d\n", __func__, hparams.n_wa_pattern);
  1493. LOG_INF("%s: use_silu: %d\n", __func__, ctx_clip.use_silu);
  1494. LOG_INF("%s: use_gelu: %d\n", __func__, ctx_clip.use_gelu);
  1495. LOG_INF("%s: model size: %.2f MiB\n", __func__, model_size / 1024.0 / 1024.0);
  1496. LOG_INF("%s: metadata size: %.2f MiB\n", __func__, ggml_get_mem_size(ctx_meta.get()) / 1024.0 / 1024.0);
  1497. }
  1498. }
  1499. void load_tensors() {
  1500. std::map<std::string, size_t> tensor_offset;
  1501. std::vector<ggml_tensor *> tensors_to_load;
  1502. // get offsets
  1503. for (int64_t i = 0; i < gguf_get_n_tensors(ctx_gguf.get()); ++i) {
  1504. const char * name = gguf_get_tensor_name(ctx_gguf.get(), i);
  1505. tensor_offset[name] = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), i);
  1506. }
  1507. // create data context
  1508. struct ggml_init_params params = {
  1509. /*.mem_size =*/ (gguf_get_n_tensors(ctx_gguf.get()) + 1) * ggml_tensor_overhead(),
  1510. /*.mem_buffer =*/ NULL,
  1511. /*.no_alloc =*/ true,
  1512. };
  1513. ctx_clip.ctx_data.reset(ggml_init(params));
  1514. if (!ctx_clip.ctx_data) {
  1515. throw std::runtime_error(string_format("%s: failed to init ggml context\n", __func__));
  1516. }
  1517. // helper function
  1518. auto get_tensor = [&](const std::string & name, bool required = true) {
  1519. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta.get(), name.c_str());
  1520. if (!cur && required) {
  1521. throw std::runtime_error(string_format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  1522. }
  1523. if (cur) {
  1524. tensors_to_load.push_back(cur);
  1525. // add tensors to context
  1526. struct ggml_tensor * data_tensor = ggml_dup_tensor(ctx_clip.ctx_data.get(), cur);
  1527. ggml_set_name(data_tensor, cur->name);
  1528. cur = data_tensor;
  1529. }
  1530. return cur;
  1531. };
  1532. auto & vision_model = ctx_clip.vision_model;
  1533. vision_model.class_embedding = get_tensor(TN_CLASS_EMBD, false);
  1534. vision_model.pre_ln_w = get_tensor(string_format(TN_LN_PRE, "v", "weight"), false);
  1535. vision_model.pre_ln_b = get_tensor(string_format(TN_LN_PRE, "v", "bias"), false);
  1536. vision_model.post_ln_w = get_tensor(string_format(TN_LN_POST, "v", "weight"), false);
  1537. vision_model.post_ln_b = get_tensor(string_format(TN_LN_POST, "v", "bias"), false);
  1538. vision_model.patch_bias = get_tensor(TN_PATCH_BIAS, false);
  1539. vision_model.patch_embeddings_0 = get_tensor(TN_PATCH_EMBD, false);
  1540. vision_model.patch_embeddings_1 = get_tensor(TN_PATCH_EMBD_1, false);
  1541. vision_model.position_embeddings = get_tensor(string_format(TN_POS_EMBD, "v"), false);
  1542. // layers
  1543. vision_model.layers.resize(vision_model.hparams.n_layer);
  1544. for (int il = 0; il < vision_model.hparams.n_layer; ++il) {
  1545. auto & layer = vision_model.layers[il];
  1546. layer.k_w = get_tensor(string_format(TN_ATTN_K, "v", il, "weight"));
  1547. layer.q_w = get_tensor(string_format(TN_ATTN_Q, "v", il, "weight"));
  1548. layer.v_w = get_tensor(string_format(TN_ATTN_V, "v", il, "weight"));
  1549. layer.o_w = get_tensor(string_format(TN_ATTN_OUTPUT, "v", il, "weight"));
  1550. layer.ln_1_w = get_tensor(string_format(TN_LN_1, "v", il, "weight"), false);
  1551. layer.ln_2_w = get_tensor(string_format(TN_LN_2, "v", il, "weight"), false);
  1552. layer.k_b = get_tensor(string_format(TN_ATTN_K, "v", il, "bias"), false);
  1553. layer.q_b = get_tensor(string_format(TN_ATTN_Q, "v", il, "bias"), false);
  1554. layer.v_b = get_tensor(string_format(TN_ATTN_V, "v", il, "bias"), false);
  1555. layer.o_b = get_tensor(string_format(TN_ATTN_OUTPUT, "v", il, "bias"), false);
  1556. layer.ln_1_b = get_tensor(string_format(TN_LN_1, "v", il, "bias"), false);
  1557. layer.ln_2_b = get_tensor(string_format(TN_LN_2, "v", il, "bias"), false);
  1558. // new naming
  1559. layer.ff_up_w = get_tensor(string_format(TN_FFN_UP, "v", il, "weight"));
  1560. layer.ff_up_b = get_tensor(string_format(TN_FFN_UP, "v", il, "bias"), false);
  1561. layer.ff_gate_w = get_tensor(string_format(TN_FFN_GATE, "v", il, "weight"), false);
  1562. layer.ff_gate_b = get_tensor(string_format(TN_FFN_GATE, "v", il, "bias"), false);
  1563. layer.ff_down_w = get_tensor(string_format(TN_FFN_DOWN, "v", il, "weight"));
  1564. layer.ff_down_b = get_tensor(string_format(TN_FFN_DOWN, "v", il, "bias"), false);
  1565. // legacy naming (the in and out is reversed! don't ask me why)
  1566. layer.ff_i_w = layer.ff_down_w;
  1567. layer.ff_o_w = layer.ff_up_w;
  1568. layer.ff_g_w = layer.ff_gate_w;
  1569. layer.ff_i_b = layer.ff_down_b;
  1570. layer.ff_o_b = layer.ff_up_b;
  1571. layer.ff_g_b = layer.ff_gate_b;
  1572. }
  1573. switch (ctx_clip.proj_type) {
  1574. case PROJECTOR_TYPE_MLP:
  1575. case PROJECTOR_TYPE_MLP_NORM:
  1576. {
  1577. // LLaVA projection
  1578. vision_model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"), false);
  1579. vision_model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"), false);
  1580. // Yi-type llava
  1581. vision_model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"), false);
  1582. vision_model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1583. // missing in Yi-type llava
  1584. vision_model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"), false);
  1585. vision_model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1586. // Yi-type llava
  1587. vision_model.mm_3_w = get_tensor(string_format(TN_LLAVA_PROJ, 3, "weight"), false);
  1588. vision_model.mm_3_b = get_tensor(string_format(TN_LLAVA_PROJ, 3, "bias"), false);
  1589. vision_model.mm_4_w = get_tensor(string_format(TN_LLAVA_PROJ, 4, "weight"), false);
  1590. vision_model.mm_4_b = get_tensor(string_format(TN_LLAVA_PROJ, 4, "bias"), false);
  1591. if (vision_model.mm_3_w) {
  1592. // TODO: this is a hack to support Yi-type llava
  1593. ctx_clip.proj_type = PROJECTOR_TYPE_MLP_NORM;
  1594. }
  1595. vision_model.image_newline = get_tensor(TN_IMAGE_NEWLINE, false);
  1596. } break;
  1597. case PROJECTOR_TYPE_LDP:
  1598. {
  1599. // MobileVLM projection
  1600. vision_model.mm_model_mlp_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1601. vision_model.mm_model_mlp_1_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "bias"));
  1602. vision_model.mm_model_mlp_3_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "weight"));
  1603. vision_model.mm_model_mlp_3_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "bias"));
  1604. vision_model.mm_model_block_1_block_0_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "0.weight"));
  1605. vision_model.mm_model_block_1_block_0_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.weight"));
  1606. vision_model.mm_model_block_1_block_0_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.bias"));
  1607. vision_model.mm_model_block_1_block_1_fc1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.weight"));
  1608. vision_model.mm_model_block_1_block_1_fc1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.bias"));
  1609. vision_model.mm_model_block_1_block_1_fc2_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.weight"));
  1610. vision_model.mm_model_block_1_block_1_fc2_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.bias"));
  1611. vision_model.mm_model_block_1_block_2_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "0.weight"));
  1612. vision_model.mm_model_block_1_block_2_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.weight"));
  1613. vision_model.mm_model_block_1_block_2_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.bias"));
  1614. vision_model.mm_model_block_2_block_0_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "0.weight"));
  1615. vision_model.mm_model_block_2_block_0_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.weight"));
  1616. vision_model.mm_model_block_2_block_0_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.bias"));
  1617. vision_model.mm_model_block_2_block_1_fc1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.weight"));
  1618. vision_model.mm_model_block_2_block_1_fc1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.bias"));
  1619. vision_model.mm_model_block_2_block_1_fc2_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.weight"));
  1620. vision_model.mm_model_block_2_block_1_fc2_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.bias"));
  1621. vision_model.mm_model_block_2_block_2_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "0.weight"));
  1622. vision_model.mm_model_block_2_block_2_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.weight"));
  1623. vision_model.mm_model_block_2_block_2_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.bias"));
  1624. } break;
  1625. case PROJECTOR_TYPE_LDPV2:
  1626. {
  1627. // MobilVLM_V2 projection
  1628. vision_model.mm_model_mlp_0_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "weight"));
  1629. vision_model.mm_model_mlp_0_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "bias"));
  1630. vision_model.mm_model_mlp_2_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "weight"));
  1631. vision_model.mm_model_mlp_2_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "bias"));
  1632. vision_model.mm_model_peg_0_w = get_tensor(string_format(TN_MVLM_PROJ_PEG, 0, "weight"));
  1633. vision_model.mm_model_peg_0_b = get_tensor(string_format(TN_MVLM_PROJ_PEG, 0, "bias"));
  1634. } break;
  1635. case PROJECTOR_TYPE_MINICPMV:
  1636. {
  1637. // vision_model.mm_model_pos_embed = get_tensor(new_clip->ctx_data, TN_MINICPMV_POS_EMBD);
  1638. vision_model.mm_model_pos_embed_k = get_tensor(TN_MINICPMV_POS_EMBD_K);
  1639. vision_model.mm_model_query = get_tensor(TN_MINICPMV_QUERY);
  1640. vision_model.mm_model_proj = get_tensor(TN_MINICPMV_PROJ);
  1641. vision_model.mm_model_kv_proj = get_tensor(TN_MINICPMV_KV_PROJ);
  1642. vision_model.mm_model_attn_q_w = get_tensor(string_format(TN_MINICPMV_ATTN, "q", "weight"));
  1643. vision_model.mm_model_attn_k_w = get_tensor(string_format(TN_MINICPMV_ATTN, "k", "weight"));
  1644. vision_model.mm_model_attn_v_w = get_tensor(string_format(TN_MINICPMV_ATTN, "v", "weight"));
  1645. vision_model.mm_model_attn_q_b = get_tensor(string_format(TN_MINICPMV_ATTN, "q", "bias"));
  1646. vision_model.mm_model_attn_k_b = get_tensor(string_format(TN_MINICPMV_ATTN, "k", "bias"));
  1647. vision_model.mm_model_attn_v_b = get_tensor(string_format(TN_MINICPMV_ATTN, "v", "bias"));
  1648. vision_model.mm_model_attn_o_w = get_tensor(string_format(TN_MINICPMV_ATTN, "out", "weight"));
  1649. vision_model.mm_model_attn_o_b = get_tensor(string_format(TN_MINICPMV_ATTN, "out", "bias"));
  1650. vision_model.mm_model_ln_q_w = get_tensor(string_format(TN_MINICPMV_LN, "q", "weight"));
  1651. vision_model.mm_model_ln_q_b = get_tensor(string_format(TN_MINICPMV_LN, "q", "bias"));
  1652. vision_model.mm_model_ln_kv_w = get_tensor(string_format(TN_MINICPMV_LN, "kv", "weight"));
  1653. vision_model.mm_model_ln_kv_b = get_tensor(string_format(TN_MINICPMV_LN, "kv", "bias"));
  1654. vision_model.mm_model_ln_post_w = get_tensor(string_format(TN_MINICPMV_LN, "post", "weight"));
  1655. vision_model.mm_model_ln_post_b = get_tensor(string_format(TN_MINICPMV_LN, "post", "bias"));
  1656. } break;
  1657. case PROJECTOR_TYPE_GLM_EDGE:
  1658. {
  1659. vision_model.mm_model_adapter_conv_w = get_tensor(string_format(TN_GLM_ADAPER_CONV, "weight"));
  1660. vision_model.mm_model_adapter_conv_b = get_tensor(string_format(TN_GLM_ADAPER_CONV, "bias"));
  1661. vision_model.mm_model_mlp_0_w = get_tensor(string_format(TN_GLM_ADAPTER_LINEAR, "weight"));
  1662. vision_model.mm_model_ln_q_w = get_tensor(string_format(TN_GLM_ADAPTER_NORM_1, "weight"));
  1663. vision_model.mm_model_ln_q_b = get_tensor(string_format(TN_GLM_ADAPTER_NORM_1, "bias"));
  1664. vision_model.mm_model_mlp_1_w = get_tensor(string_format(TN_GLM_ADAPTER_D_H_2_4H, "weight"));
  1665. vision_model.mm_model_mlp_2_w = get_tensor(string_format(TN_GLM_ADAPTER_GATE, "weight"));
  1666. vision_model.mm_model_mlp_3_w = get_tensor(string_format(TN_GLM_ADAPTER_D_4H_2_H, "weight"));
  1667. vision_model.mm_glm_tok_boi = get_tensor(string_format(TN_TOK_GLM_BOI, "weight"));
  1668. vision_model.mm_glm_tok_eoi = get_tensor(string_format(TN_TOK_GLM_EOI, "weight"));
  1669. } break;
  1670. case PROJECTOR_TYPE_QWEN2VL:
  1671. case PROJECTOR_TYPE_QWEN25VL:
  1672. {
  1673. vision_model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1674. vision_model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1675. vision_model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1676. vision_model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1677. } break;
  1678. case PROJECTOR_TYPE_GEMMA3:
  1679. {
  1680. vision_model.mm_input_proj_w = get_tensor(TN_MM_INP_PROJ);
  1681. vision_model.mm_soft_emb_norm_w = get_tensor(TN_MM_SOFT_EMB_N);
  1682. } break;
  1683. case PROJECTOR_TYPE_IDEFICS3:
  1684. {
  1685. vision_model.projection = get_tensor(TN_MM_PROJECTOR);
  1686. } break;
  1687. case PROJECTOR_TYPE_PIXTRAL:
  1688. {
  1689. vision_model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1690. vision_model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1691. vision_model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1692. vision_model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1693. // [IMG_BREAK] token embedding
  1694. vision_model.token_embd_img_break = get_tensor(TN_TOK_IMG_BREAK);
  1695. // for mistral small 3.1
  1696. vision_model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
  1697. vision_model.mm_patch_merger_w = get_tensor(TN_MM_PATCH_MERGER, false);
  1698. } break;
  1699. default:
  1700. GGML_ASSERT(false && "unknown projector type");
  1701. }
  1702. // load data
  1703. {
  1704. std::vector<uint8_t> read_buf;
  1705. auto fin = std::ifstream(fname, std::ios::binary);
  1706. if (!fin) {
  1707. throw std::runtime_error(string_format("%s: failed to open %s\n", __func__, fname.c_str()));
  1708. }
  1709. // alloc memory and offload data
  1710. ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(ctx_clip.backend);
  1711. ctx_clip.buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_clip.ctx_data.get(), buft));
  1712. ggml_backend_buffer_set_usage(ctx_clip.buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  1713. for (auto & t : tensors_to_load) {
  1714. struct ggml_tensor * cur = ggml_get_tensor(ctx_clip.ctx_data.get(), t->name);
  1715. const size_t offset = tensor_offset[t->name];
  1716. fin.seekg(offset, std::ios::beg);
  1717. if (!fin) {
  1718. throw std::runtime_error(string_format("%s: failed to seek for tensor %s\n", __func__, t->name));
  1719. }
  1720. size_t num_bytes = ggml_nbytes(cur);
  1721. if (ggml_backend_buft_is_host(buft)) {
  1722. // for the CPU and Metal backend, we can read directly into the tensor
  1723. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  1724. } else {
  1725. // read into a temporary buffer first, then copy to device memory
  1726. read_buf.resize(num_bytes);
  1727. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  1728. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  1729. }
  1730. }
  1731. fin.close();
  1732. LOG_DBG("%s: loaded %zu tensors from %s\n", __func__, tensors_to_load.size(), fname.c_str());
  1733. }
  1734. }
  1735. void alloc_compute_meta() {
  1736. ctx_clip.buf_compute_meta.resize(ctx_clip.max_nodes * ggml_tensor_overhead() + ggml_graph_overhead());
  1737. // create a fake batch
  1738. clip_image_f32_batch batch;
  1739. clip_image_f32_ptr img(clip_image_f32_init());
  1740. clip_image_size image_size;
  1741. image_size.width = ctx_clip.vision_model.hparams.image_size;
  1742. image_size.height = ctx_clip.vision_model.hparams.image_size;
  1743. img->nx = image_size.width;
  1744. img->ny = image_size.height;
  1745. img->buf.resize(image_size.width * image_size.height * 3);
  1746. batch.entries.push_back(std::move(img));
  1747. ggml_cgraph * gf = clip_image_build_graph(&ctx_clip, batch, image_size, false);
  1748. ggml_backend_sched_reserve(ctx_clip.sched.get(), gf);
  1749. for (size_t i = 0; i < ctx_clip.backend_ptrs.size(); ++i) {
  1750. ggml_backend_t backend = ctx_clip.backend_ptrs[i];
  1751. ggml_backend_buffer_type_t buft = ctx_clip.backend_buft[i];
  1752. size_t size = ggml_backend_sched_get_buffer_size(ctx_clip.sched.get(), backend);
  1753. if (size > 1) {
  1754. LOG_INF("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  1755. ggml_backend_buft_name(buft),
  1756. size / 1024.0 / 1024.0);
  1757. }
  1758. }
  1759. }
  1760. void get_bool(const std::string & key, bool & output, bool required = true) {
  1761. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1762. if (i < 0) {
  1763. if (required) throw std::runtime_error("Key not found: " + key);
  1764. return;
  1765. }
  1766. output = gguf_get_val_bool(ctx_gguf.get(), i);
  1767. }
  1768. void get_i32(const std::string & key, int & output, bool required = true) {
  1769. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1770. if (i < 0) {
  1771. if (required) throw std::runtime_error("Key not found: " + key);
  1772. return;
  1773. }
  1774. output = gguf_get_val_i32(ctx_gguf.get(), i);
  1775. }
  1776. void get_u32(const std::string & key, int & output, bool required = true) {
  1777. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1778. if (i < 0) {
  1779. if (required) throw std::runtime_error("Key not found: " + key);
  1780. return;
  1781. }
  1782. output = gguf_get_val_u32(ctx_gguf.get(), i);
  1783. }
  1784. void get_f32(const std::string & key, float & output, bool required = true) {
  1785. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1786. if (i < 0) {
  1787. if (required) throw std::runtime_error("Key not found: " + key);
  1788. return;
  1789. }
  1790. output = gguf_get_val_f32(ctx_gguf.get(), i);
  1791. }
  1792. void get_string(const std::string & key, std::string & output, bool required = true) {
  1793. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1794. if (i < 0) {
  1795. if (required) throw std::runtime_error("Key not found: " + key);
  1796. return;
  1797. }
  1798. output = std::string(gguf_get_val_str(ctx_gguf.get(), i));
  1799. }
  1800. void get_arr_int(const std::string & key, std::vector<int> & output, bool required = true) {
  1801. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1802. if (i < 0) {
  1803. if (required) throw std::runtime_error("Key not found: " + key);
  1804. return;
  1805. }
  1806. int n = gguf_get_arr_n(ctx_gguf.get(), i);
  1807. output.resize(n);
  1808. const int32_t * values = (const int32_t *)gguf_get_arr_data(ctx_gguf.get(), i);
  1809. for (int i = 0; i < n; ++i) {
  1810. output[i] = values[i];
  1811. }
  1812. }
  1813. };
  1814. // read and create ggml_context containing the tensors and their data
  1815. struct clip_ctx * clip_model_load(const char * fname, const int verbosity) {
  1816. return clip_init(fname, clip_context_params{
  1817. /* use_gpu */ true,
  1818. /* verbosity */ static_cast<ggml_log_level>(verbosity),
  1819. });
  1820. }
  1821. struct clip_ctx * clip_init(const char * fname, struct clip_context_params ctx_params) {
  1822. g_logger_state.verbosity_thold = ctx_params.verbosity;
  1823. clip_ctx * ctx_clip = new clip_ctx(ctx_params);
  1824. try {
  1825. clip_model_loader loader(fname, *ctx_clip);
  1826. loader.load_hparams();
  1827. loader.load_tensors();
  1828. loader.alloc_compute_meta();
  1829. } catch (const std::exception & e) {
  1830. LOG_ERR("%s: failed to load model '%s': %s\n", __func__, fname, e.what());
  1831. delete ctx_clip;
  1832. return nullptr;
  1833. }
  1834. return ctx_clip;
  1835. }
  1836. void clip_add_load_image_size(struct clip_ctx * ctx_clip, struct clip_image_size * load_image_size) {
  1837. ctx_clip->load_image_size = *load_image_size; // copy
  1838. }
  1839. struct clip_image_size * clip_get_load_image_size(struct clip_ctx * ctx_clip) {
  1840. return &ctx_clip->load_image_size;
  1841. }
  1842. struct clip_image_size * clip_image_size_init() {
  1843. struct clip_image_size * load_image_size = new struct clip_image_size();
  1844. load_image_size->width = 448;
  1845. load_image_size->height = 448;
  1846. return load_image_size;
  1847. }
  1848. struct clip_image_u8 * clip_image_u8_init() {
  1849. return new clip_image_u8();
  1850. }
  1851. struct clip_image_f32 * clip_image_f32_init() {
  1852. return new clip_image_f32();
  1853. }
  1854. struct clip_image_f32_batch * clip_image_f32_batch_init() {
  1855. return new clip_image_f32_batch();
  1856. }
  1857. unsigned char * clip_image_u8_get_data(struct clip_image_u8 * img, uint32_t * nx, uint32_t * ny) {
  1858. if (nx) *nx = img->nx;
  1859. if (ny) *ny = img->ny;
  1860. return img->buf.data();
  1861. }
  1862. void clip_image_size_free(struct clip_image_size * load_image_size) {
  1863. if (load_image_size == nullptr) {
  1864. return;
  1865. }
  1866. delete load_image_size;
  1867. }
  1868. void clip_image_u8_free(struct clip_image_u8 * img) { if (img) delete img; }
  1869. void clip_image_f32_free(struct clip_image_f32 * img) { if (img) delete img; }
  1870. void clip_image_u8_batch_free(struct clip_image_u8_batch * batch) { if (batch) delete batch; }
  1871. void clip_image_f32_batch_free(struct clip_image_f32_batch * batch) { if (batch) delete batch; }
  1872. size_t clip_image_f32_batch_n_images(const struct clip_image_f32_batch * batch) {
  1873. return batch->entries.size();
  1874. }
  1875. size_t clip_image_f32_batch_nx(const struct clip_image_f32_batch * batch, int idx) {
  1876. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1877. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1878. return 0;
  1879. }
  1880. return batch->entries[idx]->nx;
  1881. }
  1882. size_t clip_image_f32_batch_ny(const struct clip_image_f32_batch * batch, int idx) {
  1883. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1884. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1885. return 0;
  1886. }
  1887. return batch->entries[idx]->ny;
  1888. }
  1889. clip_image_f32 * clip_image_f32_get_img(const struct clip_image_f32_batch * batch, int idx) {
  1890. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1891. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1892. return nullptr;
  1893. }
  1894. return batch->entries[idx].get();
  1895. }
  1896. void clip_build_img_from_pixels(const unsigned char * rgb_pixels, int nx, int ny, clip_image_u8 * img) {
  1897. img->nx = nx;
  1898. img->ny = ny;
  1899. img->buf.resize(3 * nx * ny);
  1900. memcpy(img->buf.data(), rgb_pixels, img->buf.size());
  1901. }
  1902. bool clip_image_load_from_file(const char * fname, clip_image_u8 * img) {
  1903. int nx, ny, nc;
  1904. auto * data = stbi_load(fname, &nx, &ny, &nc, 3);
  1905. if (!data) {
  1906. LOG_ERR("%s: failed to load image '%s'\n", __func__, fname);
  1907. return false;
  1908. }
  1909. clip_build_img_from_pixels(data, nx, ny, img);
  1910. stbi_image_free(data);
  1911. return true;
  1912. }
  1913. bool clip_image_load_from_bytes(const unsigned char * bytes, size_t bytes_length, struct clip_image_u8 * img) {
  1914. int nx, ny, nc;
  1915. auto * data = stbi_load_from_memory(bytes, bytes_length, &nx, &ny, &nc, 3);
  1916. if (!data) {
  1917. LOG_ERR("%s: failed to decode image bytes\n", __func__);
  1918. return false;
  1919. }
  1920. clip_build_img_from_pixels(data, nx, ny, img);
  1921. stbi_image_free(data);
  1922. return true;
  1923. }
  1924. // Normalize image to float32 - careful with pytorch .to(model.device, dtype=torch.float16) - this sometimes reduces precision (32>16>32), sometimes not
  1925. static void normalize_image_u8_to_f32(const clip_image_u8 & src, clip_image_f32 & dst, const float mean[3], const float std[3]) {
  1926. dst.nx = src.nx;
  1927. dst.ny = src.ny;
  1928. dst.buf.resize(src.buf.size());
  1929. // TODO @ngxson : seems like this could be done more efficiently on cgraph
  1930. for (size_t i = 0; i < src.buf.size(); ++i) {
  1931. int c = i % 3; // rgb
  1932. dst.buf[i] = (static_cast<float>(src.buf[i]) / 255.0f - mean[c]) / std[c];
  1933. }
  1934. }
  1935. // set of tools to manupulate images
  1936. // in the future, we can have HW acceleration by allowing this struct to access 3rd party lib like imagick or opencv
  1937. struct image_manipulation {
  1938. // Bilinear resize function
  1939. static void bilinear_resize(const clip_image_u8& src, clip_image_u8& dst, int target_width, int target_height) {
  1940. dst.nx = target_width;
  1941. dst.ny = target_height;
  1942. dst.buf.resize(3 * target_width * target_height);
  1943. float x_ratio = static_cast<float>(src.nx - 1) / target_width;
  1944. float y_ratio = static_cast<float>(src.ny - 1) / target_height;
  1945. for (int y = 0; y < target_height; y++) {
  1946. for (int x = 0; x < target_width; x++) {
  1947. float px = x_ratio * x;
  1948. float py = y_ratio * y;
  1949. int x_floor = static_cast<int>(px);
  1950. int y_floor = static_cast<int>(py);
  1951. float x_lerp = px - x_floor;
  1952. float y_lerp = py - y_floor;
  1953. for (int c = 0; c < 3; c++) {
  1954. float top = lerp(
  1955. static_cast<float>(src.buf[3 * (y_floor * src.nx + x_floor) + c]),
  1956. static_cast<float>(src.buf[3 * (y_floor * src.nx + (x_floor + 1)) + c]),
  1957. x_lerp
  1958. );
  1959. float bottom = lerp(
  1960. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + x_floor) + c]),
  1961. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + (x_floor + 1)) + c]),
  1962. x_lerp
  1963. );
  1964. dst.buf[3 * (y * target_width + x) + c] = static_cast<uint8_t>(lerp(top, bottom, y_lerp));
  1965. }
  1966. }
  1967. }
  1968. }
  1969. // Bicubic resize function
  1970. // part of image will be cropped if the aspect ratio is different
  1971. static bool bicubic_resize(const clip_image_u8 & img, clip_image_u8 & dst, int target_width, int target_height) {
  1972. const int nx = img.nx;
  1973. const int ny = img.ny;
  1974. dst.nx = target_width;
  1975. dst.ny = target_height;
  1976. dst.buf.resize(3 * target_width * target_height);
  1977. float Cc;
  1978. float C[5];
  1979. float d0, d2, d3, a0, a1, a2, a3;
  1980. int i, j, k, jj;
  1981. int x, y;
  1982. float dx, dy;
  1983. float tx, ty;
  1984. tx = (float)nx / (float)target_width;
  1985. ty = (float)ny / (float)target_height;
  1986. // Bicubic interpolation; adapted from ViT.cpp, inspired from :
  1987. // -> https://github.com/yglukhov/bicubic-interpolation-image-processing/blob/master/libimage.c#L36
  1988. // -> https://en.wikipedia.org/wiki/Bicubic_interpolation
  1989. for (i = 0; i < target_height; i++) {
  1990. for (j = 0; j < target_width; j++) {
  1991. x = (int)(tx * j);
  1992. y = (int)(ty * i);
  1993. dx = tx * j - x;
  1994. dy = ty * i - y;
  1995. for (k = 0; k < 3; k++) {
  1996. for (jj = 0; jj <= 3; jj++) {
  1997. 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];
  1998. 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];
  1999. 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];
  2000. a0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  2001. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  2002. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  2003. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  2004. C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx;
  2005. d0 = C[0] - C[1];
  2006. d2 = C[2] - C[1];
  2007. d3 = C[3] - C[1];
  2008. a0 = C[1];
  2009. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  2010. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  2011. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  2012. Cc = a0 + a1 * dy + a2 * dy * dy + a3 * dy * dy * dy;
  2013. const uint8_t Cc2 = std::min(std::max(std::round(Cc), 0.0f), 255.0f);
  2014. dst.buf[(i * target_width + j) * 3 + k] = float(Cc2);
  2015. }
  2016. }
  2017. }
  2018. }
  2019. return true;
  2020. }
  2021. // llava-1.6 type of resize_and_pad
  2022. // if the ratio is not 1:1, padding with pad_color will be applied
  2023. // pad_color is single channel, default is 0 (black)
  2024. static void resize_and_pad_image(const clip_image_u8 & image, clip_image_u8 & dst, const clip_image_size & target_resolution, std::array<uint8_t, 3> pad_color = {0, 0, 0}) {
  2025. int target_width = target_resolution.width;
  2026. int target_height = target_resolution.height;
  2027. float scale_w = static_cast<float>(target_width) / image.nx;
  2028. float scale_h = static_cast<float>(target_height) / image.ny;
  2029. int new_width, new_height;
  2030. if (scale_w < scale_h) {
  2031. new_width = target_width;
  2032. new_height = std::min(static_cast<int>(std::ceil(image.ny * scale_w)), target_height);
  2033. } else {
  2034. new_height = target_height;
  2035. new_width = std::min(static_cast<int>(std::ceil(image.nx * scale_h)), target_width);
  2036. }
  2037. clip_image_u8 resized_image;
  2038. bicubic_resize(image, resized_image, new_width, new_height);
  2039. clip_image_u8 padded_image;
  2040. padded_image.nx = target_width;
  2041. padded_image.ny = target_height;
  2042. padded_image.buf.resize(3 * target_width * target_height);
  2043. // Fill the padded image with the fill color
  2044. for (size_t i = 0; i < padded_image.buf.size(); i += 3) {
  2045. padded_image.buf[i] = pad_color[0];
  2046. padded_image.buf[i + 1] = pad_color[1];
  2047. padded_image.buf[i + 2] = pad_color[2];
  2048. }
  2049. // Calculate padding offsets
  2050. int pad_x = (target_width - new_width) / 2;
  2051. int pad_y = (target_height - new_height) / 2;
  2052. // Copy the resized image into the center of the padded buffer
  2053. for (int y = 0; y < new_height; ++y) {
  2054. for (int x = 0; x < new_width; ++x) {
  2055. for (int c = 0; c < 3; ++c) {
  2056. padded_image.buf[3 * ((y + pad_y) * target_width + (x + pad_x)) + c] = resized_image.buf[3 * (y * new_width + x) + c];
  2057. }
  2058. }
  2059. }
  2060. dst = std::move(padded_image);
  2061. }
  2062. static void crop_image(const clip_image_u8 & image, clip_image_u8 & dst, int x, int y, int w, int h) {
  2063. dst.nx = w;
  2064. dst.ny = h;
  2065. dst.buf.resize(3 * w * h);
  2066. for (int i = 0; i < h; ++i) {
  2067. for (int j = 0; j < w; ++j) {
  2068. int src_idx = 3 * ((y + i)*image.nx + (x + j));
  2069. int dst_idx = 3 * (i*w + j);
  2070. dst.buf[dst_idx] = image.buf[src_idx];
  2071. dst.buf[dst_idx + 1] = image.buf[src_idx + 1];
  2072. dst.buf[dst_idx + 2] = image.buf[src_idx + 2];
  2073. }
  2074. }
  2075. }
  2076. // calculate the size of the **resized** image, while preserving the aspect ratio
  2077. // the calculated size will be aligned to the nearest multiple of align_size
  2078. // if H or W size is larger than max_dimension, it will be resized to max_dimension
  2079. static clip_image_size calc_size_preserved_ratio(const clip_image_size & inp_size, const int align_size, const int max_dimension) {
  2080. if (inp_size.width <= 0 || inp_size.height <= 0 || align_size <= 0 || max_dimension <= 0) {
  2081. return {0, 0};
  2082. }
  2083. float scale = std::min(1.0f, std::min(static_cast<float>(max_dimension) / inp_size.width,
  2084. static_cast<float>(max_dimension) / inp_size.height));
  2085. float target_width_f = static_cast<float>(inp_size.width) * scale;
  2086. float target_height_f = static_cast<float>(inp_size.height) * scale;
  2087. int aligned_width = GGML_PAD((int)target_width_f, align_size);
  2088. int aligned_height = GGML_PAD((int)target_height_f, align_size);
  2089. return {aligned_width, aligned_height};
  2090. }
  2091. private:
  2092. static inline int clip(int x, int lower, int upper) {
  2093. return std::max(lower, std::min(x, upper));
  2094. }
  2095. // Linear interpolation between two points
  2096. static inline float lerp(float s, float e, float t) {
  2097. return s + (e - s) * t;
  2098. }
  2099. };
  2100. /**
  2101. * implementation of LLaVA-UHD:
  2102. * - https://arxiv.org/pdf/2403.11703
  2103. * - https://github.com/thunlp/LLaVA-UHD
  2104. * - https://github.com/thunlp/LLaVA-UHD/blob/302301bc2175f7e717fb8548516188e89f649753/llava_uhd/train/llava-uhd/slice_logic.py#L118
  2105. *
  2106. * overview:
  2107. * - an image always have a single overview (downscaled image)
  2108. * - an image can have 0 or multiple slices, depending on the image size
  2109. * - each slice can then be considered as a separate image
  2110. *
  2111. * for example:
  2112. *
  2113. * [overview] --> [slice 1] --> [slice 2]
  2114. * | |
  2115. * +--> [slice 3] --> [slice 4]
  2116. */
  2117. struct llava_uhd {
  2118. struct slice_coordinates {
  2119. int x;
  2120. int y;
  2121. clip_image_size size;
  2122. };
  2123. struct slice_instructions {
  2124. clip_image_size overview_size; // size of downscaled image
  2125. clip_image_size refined_size; // size of image right before slicing (must be multiple of slice size)
  2126. clip_image_size grid_size; // grid_size.width * grid_size.height = number of slices
  2127. std::vector<slice_coordinates> slices;
  2128. bool padding_refined = false; // if true, refine image will be padded to the grid size (e.g. llava-1.6)
  2129. };
  2130. static int get_max_slices(struct clip_ctx * ctx) {
  2131. if (clip_is_minicpmv(ctx)) {
  2132. return 9;
  2133. }
  2134. return 0;
  2135. }
  2136. static slice_instructions get_slice_instructions(struct clip_ctx * ctx, const clip_image_size & original_size) {
  2137. slice_instructions res;
  2138. const int patch_size = clip_get_patch_size(ctx);
  2139. const int slice_size = clip_get_image_size(ctx);
  2140. const int max_slice_nums = get_max_slices(ctx);
  2141. const int original_width = original_size.width;
  2142. const int original_height = original_size.height;
  2143. const float log_ratio = log((float)original_width / original_height);
  2144. const float ratio = (float)original_width * original_height / (slice_size * slice_size);
  2145. const int multiple = fmin(ceil(ratio), max_slice_nums);
  2146. const bool has_slices = (multiple > 1);
  2147. const bool has_pinpoints = !ctx->vision_model.hparams.image_grid_pinpoints.empty();
  2148. if (has_pinpoints) {
  2149. // has pinpoints, use them to calculate the grid size (e.g. llava-1.6)
  2150. auto refine_size = llava_uhd::select_best_resolution(
  2151. ctx->vision_model.hparams.image_grid_pinpoints,
  2152. original_size);
  2153. res.overview_size = clip_image_size{slice_size, slice_size};
  2154. res.refined_size = refine_size;
  2155. res.grid_size = clip_image_size{0, 0};
  2156. res.padding_refined = true;
  2157. for (int y = 0; y < refine_size.height; y += slice_size) {
  2158. for (int x = 0; x < refine_size.width; x += slice_size) {
  2159. slice_coordinates slice;
  2160. slice.x = x;
  2161. slice.y = y;
  2162. slice.size.width = std::min(slice_size, refine_size.width - x);
  2163. slice.size.height = std::min(slice_size, refine_size.height - y);
  2164. res.slices.push_back(slice);
  2165. if (x == 0) {
  2166. res.grid_size.width++;
  2167. }
  2168. }
  2169. res.grid_size.height++;
  2170. }
  2171. return res;
  2172. }
  2173. // no pinpoints, dynamically calculate the grid size (e.g. minicpmv)
  2174. auto best_size = get_best_resize(original_size, slice_size, patch_size, !has_slices);
  2175. res.overview_size = best_size;
  2176. if (!has_slices) {
  2177. // skip slicing logic
  2178. res.refined_size = clip_image_size{0, 0};
  2179. res.grid_size = clip_image_size{0, 0};
  2180. } else {
  2181. auto best_grid = get_best_grid(max_slice_nums, multiple, log_ratio);
  2182. auto refine_size = get_refine_size(original_size, best_grid, slice_size, patch_size, true);
  2183. res.grid_size = best_grid;
  2184. res.refined_size = refine_size;
  2185. int width = refine_size.width;
  2186. int height = refine_size.height;
  2187. int grid_x = int(width / best_grid.width);
  2188. int grid_y = int(height / best_grid.height);
  2189. for (int patches_y = 0, ic = 0;
  2190. patches_y < refine_size.height && ic < best_grid.height;
  2191. patches_y += grid_y, ic += 1) {
  2192. for (int patches_x = 0, jc = 0;
  2193. patches_x < refine_size.width && jc < best_grid.width;
  2194. patches_x += grid_x, jc += 1) {
  2195. slice_coordinates slice;
  2196. slice.x = patches_x;
  2197. slice.y = patches_y;
  2198. slice.size.width = grid_x;
  2199. slice.size.height = grid_y;
  2200. res.slices.push_back(slice);
  2201. // LOG_INF("slice %d: %d %d %d %d\n", ic, patches_i, patches_j, grid_x, grid_y);
  2202. }
  2203. }
  2204. }
  2205. return res;
  2206. }
  2207. static std::vector<clip_image_u8_ptr> slice_image(const clip_image_u8 * img, const slice_instructions & inst) {
  2208. std::vector<clip_image_u8_ptr> output;
  2209. // resize to overview size
  2210. clip_image_u8_ptr resized_img(clip_image_u8_init());
  2211. image_manipulation::bicubic_resize(*img, *resized_img, inst.overview_size.width, inst.overview_size.height);
  2212. output.push_back(std::move(resized_img));
  2213. if (inst.slices.empty()) {
  2214. // no slices, just return the resized image
  2215. return output;
  2216. }
  2217. // resize to refined size
  2218. clip_image_u8_ptr refined_img(clip_image_u8_init());
  2219. if (inst.padding_refined) {
  2220. image_manipulation::resize_and_pad_image(*img, *refined_img, inst.refined_size);
  2221. } else {
  2222. image_manipulation::bilinear_resize(*img, *refined_img, inst.refined_size.width, inst.refined_size.height);
  2223. }
  2224. // create slices
  2225. for (const auto & slice : inst.slices) {
  2226. int x = slice.x;
  2227. int y = slice.y;
  2228. int w = slice.size.width;
  2229. int h = slice.size.height;
  2230. clip_image_u8_ptr img_slice(clip_image_u8_init());
  2231. image_manipulation::crop_image(*refined_img, *img_slice, x, y, w, h);
  2232. output.push_back(std::move(img_slice));
  2233. }
  2234. return output;
  2235. }
  2236. private:
  2237. static clip_image_size get_best_resize(const clip_image_size & original_size, int scale_resolution, int patch_size, bool allow_upscale = false) {
  2238. int width = original_size.width;
  2239. int height = original_size.height;
  2240. if ((width * height > scale_resolution * scale_resolution) || allow_upscale) {
  2241. float r = static_cast<float>(width) / height;
  2242. height = static_cast<int>(scale_resolution / std::sqrt(r));
  2243. width = static_cast<int>(height * r);
  2244. }
  2245. clip_image_size res;
  2246. res.width = ensure_divide(width, patch_size);
  2247. res.height = ensure_divide(height, patch_size);
  2248. return res;
  2249. }
  2250. /**
  2251. * Selects the best resolution from a list of possible resolutions based on the original size.
  2252. *
  2253. * @param original_size The original size of the image
  2254. * @param possible_resolutions A list of possible resolutions
  2255. * @return The best fit resolution
  2256. */
  2257. static clip_image_size select_best_resolution(const clip_image_size & original_size, const std::vector<clip_image_size> & possible_resolutions) {
  2258. int original_width = original_size.width;
  2259. int original_height = original_size.height;
  2260. clip_image_size best_fit;
  2261. int max_effective_resolution = 0;
  2262. int min_wasted_resolution = std::numeric_limits<int>::max();
  2263. for (const auto & resolution : possible_resolutions) {
  2264. int width = resolution.width;
  2265. int height = resolution.height;
  2266. float scale = std::min(static_cast<float>(width) / original_width, static_cast<float>(height) / original_height);
  2267. int downscaled_width = static_cast<int>(original_width * scale);
  2268. int downscaled_height = static_cast<int>(original_height * scale);
  2269. int effective_resolution = std::min(downscaled_width * downscaled_height, original_width * original_height);
  2270. int wasted_resolution = (width * height) - effective_resolution;
  2271. // 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);
  2272. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_resolution < min_wasted_resolution)) {
  2273. max_effective_resolution = effective_resolution;
  2274. min_wasted_resolution = wasted_resolution;
  2275. best_fit = resolution;
  2276. }
  2277. }
  2278. return best_fit;
  2279. }
  2280. // used by llava 1.6 with custom list of pinpoints
  2281. static clip_image_size select_best_resolution(const std::vector<int32_t> & pinpoints, const clip_image_size & original_size) {
  2282. std::vector<clip_image_size> possible_resolutions;
  2283. for (size_t i = 0; i < pinpoints.size(); i += 2) {
  2284. possible_resolutions.push_back(clip_image_size{pinpoints[i], pinpoints[i+1]});
  2285. }
  2286. return select_best_resolution(original_size, possible_resolutions);
  2287. }
  2288. static int ensure_divide(int length, int patch_size) {
  2289. return std::max(static_cast<int>(std::round(static_cast<float>(length) / patch_size) * patch_size), patch_size);
  2290. }
  2291. static clip_image_size get_refine_size(const clip_image_size & original_size, const clip_image_size & grid, int scale_resolution, int patch_size, bool allow_upscale = false) {
  2292. int width = original_size.width;
  2293. int height = original_size.height;
  2294. int grid_x = grid.width;
  2295. int grid_y = grid.height;
  2296. int refine_width = ensure_divide(width, grid_x);
  2297. int refine_height = ensure_divide(height, grid_y);
  2298. clip_image_size grid_size;
  2299. grid_size.width = refine_width / grid_x;
  2300. grid_size.height = refine_height / grid_y;
  2301. auto best_grid_size = get_best_resize(grid_size, scale_resolution, patch_size, allow_upscale);
  2302. int best_grid_width = best_grid_size.width;
  2303. int best_grid_height = best_grid_size.height;
  2304. clip_image_size refine_size;
  2305. refine_size.width = best_grid_width * grid_x;
  2306. refine_size.height = best_grid_height * grid_y;
  2307. return refine_size;
  2308. }
  2309. static clip_image_size get_best_grid(const int max_slice_nums, const int multiple, const float log_ratio) {
  2310. std::vector<int> candidate_split_grids_nums;
  2311. for (int i : {multiple - 1, multiple, multiple + 1}) {
  2312. if (i == 1 || i > max_slice_nums) {
  2313. continue;
  2314. }
  2315. candidate_split_grids_nums.push_back(i);
  2316. }
  2317. std::vector<clip_image_size> candidate_grids;
  2318. for (int split_grids_nums : candidate_split_grids_nums) {
  2319. int m = 1;
  2320. while (m <= split_grids_nums) {
  2321. if (split_grids_nums % m == 0) {
  2322. candidate_grids.push_back(clip_image_size{m, split_grids_nums / m});
  2323. }
  2324. ++m;
  2325. }
  2326. }
  2327. clip_image_size best_grid{1, 1};
  2328. float min_error = std::numeric_limits<float>::infinity();
  2329. for (const auto& grid : candidate_grids) {
  2330. float error = std::abs(log_ratio - std::log(1.0 * grid.width / grid.height));
  2331. if (error < min_error) {
  2332. best_grid = grid;
  2333. min_error = error;
  2334. }
  2335. }
  2336. return best_grid;
  2337. }
  2338. };
  2339. // TODO @ngxson : decprecate the load_image_size singleton pattern
  2340. int clip_uhd_num_image_embeds_col(struct clip_ctx * ctx_clip) {
  2341. const auto inst = llava_uhd::get_slice_instructions(ctx_clip, ctx_clip->load_image_size);
  2342. return inst.grid_size.width;
  2343. }
  2344. // 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
  2345. // res_imgs memory is being allocated here, previous allocations will be freed if found
  2346. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, struct clip_image_f32_batch * res_imgs) {
  2347. clip_image_size original_size{img->nx, img->ny};
  2348. bool pad_to_square = true;
  2349. auto & params = ctx->vision_model.hparams;
  2350. // 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
  2351. if (params.mm_patch_merge_type == PATCH_MERGE_SPATIAL_UNPAD) {
  2352. pad_to_square = false;
  2353. }
  2354. if (clip_is_minicpmv(ctx)) {
  2355. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2356. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2357. for (size_t i = 0; i < imgs.size(); ++i) {
  2358. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2359. clip_image_f32_ptr res(clip_image_f32_init());
  2360. normalize_image_u8_to_f32(*imgs[i], *res, ctx->image_mean, ctx->image_std);
  2361. res_imgs->entries.push_back(std::move(res));
  2362. }
  2363. return true;
  2364. }
  2365. else if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL || ctx->proj_type == PROJECTOR_TYPE_QWEN25VL) {
  2366. clip_image_u8 resized;
  2367. auto patch_size = clip_get_patch_size(ctx) * 2;
  2368. int nx = ceil((float)img->nx / patch_size) * patch_size;
  2369. int ny = ceil((float)img->ny / patch_size) * patch_size;
  2370. image_manipulation::bicubic_resize(*img, resized, nx, ny);
  2371. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2372. // clip_image_f32_ptr res(clip_image_f32_init());
  2373. normalize_image_u8_to_f32(resized, *img_f32, ctx->image_mean, ctx->image_std);
  2374. // res_imgs->data[0] = *res;
  2375. res_imgs->entries.push_back(std::move(img_f32));
  2376. return true;
  2377. }
  2378. else if (ctx->proj_type == PROJECTOR_TYPE_GLM_EDGE
  2379. || ctx->proj_type == PROJECTOR_TYPE_GEMMA3
  2380. || ctx->proj_type == PROJECTOR_TYPE_IDEFICS3) {
  2381. clip_image_u8 resized_image;
  2382. int sz = params.image_size;
  2383. image_manipulation::resize_and_pad_image(*img, resized_image, {sz, sz});
  2384. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2385. //clip_image_save_to_bmp(resized_image, "resized.bmp");
  2386. normalize_image_u8_to_f32(resized_image, *img_f32, ctx->image_mean, ctx->image_std);
  2387. res_imgs->entries.push_back(std::move(img_f32));
  2388. return true;
  2389. }
  2390. else if (ctx->proj_type == PROJECTOR_TYPE_PIXTRAL) {
  2391. clip_image_u8 resized_image;
  2392. auto new_size = image_manipulation::calc_size_preserved_ratio(original_size, params.patch_size, params.image_size);
  2393. image_manipulation::bilinear_resize(*img, resized_image, new_size.width, new_size.height);
  2394. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2395. normalize_image_u8_to_f32(resized_image, *img_f32, ctx->image_mean, ctx->image_std);
  2396. res_imgs->entries.push_back(std::move(img_f32));
  2397. return true;
  2398. }
  2399. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  2400. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  2401. clip_image_u8_ptr temp(clip_image_u8_init()); // we will keep the input image data here temporarily
  2402. if (pad_to_square) {
  2403. // for llava-1.5, we resize image to a square, and pad the shorter side with a background color
  2404. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  2405. const int longer_side = std::max(img->nx, img->ny);
  2406. temp->nx = longer_side;
  2407. temp->ny = longer_side;
  2408. temp->buf.resize(3 * longer_side * longer_side);
  2409. // background color in RGB from LLaVA (this is the mean rgb color * 255)
  2410. const std::array<uint8_t, 3> pad_color = {122, 116, 104};
  2411. // resize the image to the target_size
  2412. image_manipulation::resize_and_pad_image(*img, *temp, clip_image_size{params.image_size, params.image_size}, pad_color);
  2413. clip_image_f32_ptr res(clip_image_f32_init());
  2414. normalize_image_u8_to_f32(*temp, *res, ctx->image_mean, ctx->image_std);
  2415. res_imgs->entries.push_back(std::move(res));
  2416. return true;
  2417. } else if (!params.image_grid_pinpoints.empty()) {
  2418. // "spatial_unpad" with "anyres" processing for llava-1.6
  2419. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2420. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2421. for (size_t i = 0; i < imgs.size(); ++i) {
  2422. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2423. clip_image_f32_ptr res(clip_image_f32_init());
  2424. normalize_image_u8_to_f32(*imgs[i], *res, ctx->image_mean, ctx->image_std);
  2425. res_imgs->entries.push_back(std::move(res));
  2426. }
  2427. return true;
  2428. }
  2429. GGML_ASSERT(false && "Unknown image preprocessing type");
  2430. }
  2431. ggml_tensor * clip_get_newline_tensor(const struct clip_ctx * ctx) {
  2432. return ctx->vision_model.image_newline;
  2433. }
  2434. void clip_free(clip_ctx * ctx) {
  2435. if (ctx == nullptr) {
  2436. return;
  2437. }
  2438. delete ctx;
  2439. }
  2440. // deprecated
  2441. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  2442. const int32_t nx = ctx->vision_model.hparams.image_size;
  2443. const int32_t ny = ctx->vision_model.hparams.image_size;
  2444. return clip_embd_nbytes_by_img(ctx, nx, ny);
  2445. }
  2446. size_t clip_embd_nbytes_by_img(const struct clip_ctx * ctx, int img_w, int img_h) {
  2447. clip_image_f32 img;
  2448. img.nx = img_w;
  2449. img.ny = img_h;
  2450. return clip_n_output_tokens(ctx, &img) * clip_n_mmproj_embd(ctx) * sizeof(float);
  2451. }
  2452. int32_t clip_get_image_size(const struct clip_ctx * ctx) {
  2453. return ctx->vision_model.hparams.image_size;
  2454. }
  2455. int32_t clip_get_patch_size(const struct clip_ctx * ctx) {
  2456. return ctx->vision_model.hparams.patch_size;
  2457. }
  2458. int32_t clip_get_hidden_size(const struct clip_ctx * ctx) {
  2459. return ctx->vision_model.hparams.hidden_size;
  2460. }
  2461. const char * clip_patch_merge_type(const struct clip_ctx * ctx) {
  2462. return ctx->vision_model.hparams.mm_patch_merge_type == PATCH_MERGE_SPATIAL_UNPAD ? "spatial_unpad" : "flat";
  2463. }
  2464. const int32_t * clip_image_grid(const struct clip_ctx * ctx) {
  2465. if (ctx->vision_model.hparams.image_grid_pinpoints.size()) {
  2466. return &ctx->vision_model.hparams.image_grid_pinpoints.front();
  2467. }
  2468. return nullptr;
  2469. }
  2470. size_t get_clip_image_grid_size(const struct clip_ctx * ctx) {
  2471. return ctx->vision_model.hparams.image_grid_pinpoints.size();
  2472. }
  2473. // deprecated
  2474. int clip_n_patches(const struct clip_ctx * ctx) {
  2475. clip_image_f32 img;
  2476. img.nx = ctx->vision_model.hparams.image_size;
  2477. img.ny = ctx->vision_model.hparams.image_size;
  2478. return clip_n_output_tokens(ctx, &img);
  2479. }
  2480. // deprecated
  2481. int clip_n_patches_by_img(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2482. return clip_n_output_tokens(ctx, img);
  2483. }
  2484. int clip_n_output_tokens_x(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2485. const auto & params = ctx->vision_model.hparams;
  2486. const int n_total = clip_n_output_tokens(ctx, img);
  2487. if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL || ctx->proj_type == PROJECTOR_TYPE_QWEN25VL) {
  2488. return img->nx / (params.patch_size * 2) + (int)(img->nx % params.patch_size > 0);
  2489. }
  2490. return n_total;
  2491. }
  2492. int clip_n_output_tokens_y(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2493. const auto & params = ctx->vision_model.hparams;
  2494. if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL || ctx->proj_type == PROJECTOR_TYPE_QWEN25VL) {
  2495. return img->ny / (params.patch_size * 2) + (int)(img->ny % params.patch_size > 0);
  2496. }
  2497. return 1;
  2498. }
  2499. int clip_n_output_tokens(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2500. const auto & params = ctx->vision_model.hparams;
  2501. int n_patches = (params.image_size / params.patch_size) * (params.image_size / params.patch_size);
  2502. if (ctx->proj_type == PROJECTOR_TYPE_LDP || ctx->proj_type == PROJECTOR_TYPE_LDPV2 || ctx->proj_type == PROJECTOR_TYPE_GLM_EDGE) {
  2503. n_patches /= 4;
  2504. n_patches += 2; // for BOI and EOI token embeddings
  2505. } else if (ctx->proj_type == PROJECTOR_TYPE_MINICPMV) {
  2506. if (ctx->minicpmv_version == 2) {
  2507. n_patches = 96;
  2508. }
  2509. else if (ctx->minicpmv_version == 3) {
  2510. n_patches = 64;
  2511. }
  2512. else if (ctx->minicpmv_version == 4) {
  2513. n_patches = 64;
  2514. }
  2515. else {
  2516. GGML_ABORT("Unknown minicpmv version");
  2517. }
  2518. } else if (ctx->proj_type == PROJECTOR_TYPE_QWEN2VL || ctx->proj_type == PROJECTOR_TYPE_QWEN25VL) {
  2519. int patch_size = params.patch_size * 2;
  2520. int x_patch = img->nx / patch_size + (int)(img->nx % patch_size > 0);
  2521. int y_patch = img->ny / patch_size + (int)(img->ny % patch_size > 0);
  2522. n_patches = x_patch * y_patch;
  2523. } else if (ctx->proj_type == PROJECTOR_TYPE_GEMMA3) {
  2524. n_patches = 256;
  2525. } else if (ctx->proj_type == PROJECTOR_TYPE_IDEFICS3) {
  2526. n_patches /= ctx->vision_model.hparams.proj_scale_factor;
  2527. } else if (ctx->proj_type == PROJECTOR_TYPE_PIXTRAL) {
  2528. int n_merge = ctx->vision_model.hparams.spatial_merge_size;
  2529. int n_patches_x = img->nx / params.patch_size / (n_merge > 0 ? n_merge : 1);
  2530. int n_patches_y = img->ny / params.patch_size / (n_merge > 0 ? n_merge : 1);
  2531. n_patches = n_patches_y*n_patches_x + n_patches_y - 1; // + one [IMG_BREAK] per row, except the last row
  2532. }
  2533. return n_patches;
  2534. }
  2535. 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) {
  2536. assert(embed_dim % 2 == 0);
  2537. int H = pos.size();
  2538. int W = pos[0].size();
  2539. std::vector<float> omega(embed_dim / 2);
  2540. for (int i = 0; i < embed_dim / 2; ++i) {
  2541. omega[i] = 1.0 / pow(10000.0, static_cast<float>(i) / (embed_dim / 2));
  2542. }
  2543. std::vector<std::vector<std::vector<float>>> emb(H, std::vector<std::vector<float>>(W, std::vector<float>(embed_dim)));
  2544. for (int h = 0; h < H; ++h) {
  2545. for (int w = 0; w < W; ++w) {
  2546. for (int d = 0; d < embed_dim / 2; ++d) {
  2547. float out_value = pos[h][w] * omega[d];
  2548. emb[h][w][d] = sin(out_value);
  2549. emb[h][w][d + embed_dim / 2] = cos(out_value);
  2550. }
  2551. }
  2552. }
  2553. return emb;
  2554. }
  2555. 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) {
  2556. assert(embed_dim % 2 == 0);
  2557. 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)
  2558. 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)
  2559. int H = emb_h.size();
  2560. int W = emb_h[0].size();
  2561. std::vector<std::vector<std::vector<float>>> emb(H, std::vector<std::vector<float>>(W, std::vector<float>(embed_dim)));
  2562. for (int h = 0; h < H; ++h) {
  2563. for (int w = 0; w < W; ++w) {
  2564. for (int d = 0; d < embed_dim / 2; ++d) {
  2565. emb[h][w][d] = emb_h[h][w][d];
  2566. emb[h][w][d + embed_dim / 2] = emb_w[h][w][d];
  2567. }
  2568. }
  2569. }
  2570. return emb;
  2571. }
  2572. static std::vector<std::vector<float>> get_2d_sincos_pos_embed(int embed_dim, const std::pair<int, int> image_size) {
  2573. int grid_h_size = image_size.first;
  2574. int grid_w_size = image_size.second;
  2575. std::vector<float> grid_h(grid_h_size);
  2576. std::vector<float> grid_w(grid_w_size);
  2577. for (int i = 0; i < grid_h_size; ++i) {
  2578. grid_h[i] = static_cast<float>(i);
  2579. }
  2580. for (int i = 0; i < grid_w_size; ++i) {
  2581. grid_w[i] = static_cast<float>(i);
  2582. }
  2583. std::vector<std::vector<float>> grid(grid_h_size, std::vector<float>(grid_w_size));
  2584. for (int h = 0; h < grid_h_size; ++h) {
  2585. for (int w = 0; w < grid_w_size; ++w) {
  2586. grid[h][w] = grid_w[w];
  2587. }
  2588. }
  2589. std::vector<std::vector<std::vector<float>>> grid_2d = {grid, grid};
  2590. for (int h = 0; h < grid_h_size; ++h) {
  2591. for (int w = 0; w < grid_w_size; ++w) {
  2592. grid_2d[0][h][w] = grid_h[h];
  2593. grid_2d[1][h][w] = grid_w[w];
  2594. }
  2595. }
  2596. std::vector<std::vector<std::vector<float>>> pos_embed_3d = get_2d_sincos_pos_embed_from_grid(embed_dim, grid_2d);
  2597. int H = image_size.first;
  2598. int W = image_size.second;
  2599. std::vector<std::vector<float>> pos_embed_2d(H * W, std::vector<float>(embed_dim));
  2600. for (int h = 0; h < H; ++h) {
  2601. for (int w = 0; w < W; ++w) {
  2602. pos_embed_2d[w * H + h] = pos_embed_3d[h][w];
  2603. }
  2604. }
  2605. return pos_embed_2d;
  2606. }
  2607. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  2608. clip_image_f32_batch imgs;
  2609. clip_image_f32_ptr img_copy(clip_image_f32_init());
  2610. *img_copy = *img;
  2611. imgs.entries.push_back(std::move(img_copy));
  2612. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  2613. }
  2614. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs_c_ptr, float * vec) {
  2615. const clip_image_f32_batch & imgs = *imgs_c_ptr;
  2616. int batch_size = imgs.entries.size();
  2617. if (ctx->has_llava_projector
  2618. || ctx->proj_type == PROJECTOR_TYPE_MINICPMV
  2619. || ctx->proj_type == PROJECTOR_TYPE_GLM_EDGE) {
  2620. GGML_ASSERT(batch_size == 1);
  2621. }
  2622. // build the inference graph
  2623. ggml_backend_sched_reset(ctx->sched.get());
  2624. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs, ctx->load_image_size, true);
  2625. ggml_backend_sched_alloc_graph(ctx->sched.get(), gf);
  2626. // set inputs
  2627. const auto & model = ctx->vision_model;
  2628. const auto & hparams = model.hparams;
  2629. const int image_size_width = imgs.entries[0]->nx;
  2630. const int image_size_height = imgs.entries[0]->ny;
  2631. const int patch_size = hparams.patch_size;
  2632. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  2633. const int num_positions = num_patches + (model.class_embedding ? 1 : 0);
  2634. const int pos_w = ctx->load_image_size.width / patch_size;
  2635. const int pos_h = ctx->load_image_size.height / patch_size;
  2636. const bool use_window_attn = hparams.n_wa_pattern > 0; // for qwen2.5vl
  2637. auto get_inp_tensor = [&gf](const char * name) {
  2638. struct ggml_tensor * inp = ggml_graph_get_tensor(gf, name);
  2639. if (inp == nullptr) {
  2640. GGML_ABORT("Failed to get tensor %s", name);
  2641. }
  2642. if (!(inp->flags & GGML_TENSOR_FLAG_INPUT)) {
  2643. GGML_ABORT("Tensor %s is not an input tensor", name);
  2644. }
  2645. return inp;
  2646. };
  2647. auto set_input_f32 = [&get_inp_tensor](const char * name, std::vector<float> & values) {
  2648. ggml_tensor * cur = get_inp_tensor(name);
  2649. GGML_ASSERT(cur->type == GGML_TYPE_F32);
  2650. GGML_ASSERT(ggml_nelements(cur) == (int64_t)values.size());
  2651. ggml_backend_tensor_set(cur, values.data(), 0, ggml_nbytes(cur));
  2652. };
  2653. auto set_input_i32 = [&get_inp_tensor](const char * name, std::vector<int32_t> & values) {
  2654. ggml_tensor * cur = get_inp_tensor(name);
  2655. GGML_ASSERT(cur->type == GGML_TYPE_I32);
  2656. GGML_ASSERT(ggml_nelements(cur) == (int64_t)values.size());
  2657. ggml_backend_tensor_set(cur, values.data(), 0, ggml_nbytes(cur));
  2658. };
  2659. // set input pixel values
  2660. {
  2661. size_t nelem = 0;
  2662. for (const auto & img : imgs.entries) {
  2663. nelem += img->nx * img->ny * 3;
  2664. }
  2665. std::vector<float> inp_raw(nelem);
  2666. // layout of data (note: the channel dim is unrolled to better visualize the layout):
  2667. //
  2668. // ┌──W──┐
  2669. // │ H │ channel = R
  2670. // ├─────┤ │
  2671. // │ H │ channel = G
  2672. // ├─────┤ │
  2673. // │ H │ channel = B
  2674. // └─────┘ │
  2675. // ──────┘ x B
  2676. for (size_t i = 0; i < imgs.entries.size(); i++) {
  2677. const int nx = imgs.entries[i]->nx;
  2678. const int ny = imgs.entries[i]->ny;
  2679. const int n = nx * ny;
  2680. for (int b = 0; b < batch_size; b++) {
  2681. float * batch_entry = inp_raw.data() + b * (3*n);
  2682. for (int y = 0; y < ny; y++) {
  2683. for (int x = 0; x < nx; x++) {
  2684. size_t base_src = 3*(y * nx + x); // idx of the first channel
  2685. size_t base_dst = y * nx + x; // idx of the first channel
  2686. batch_entry[ base_dst] = imgs.entries[b]->buf[base_src ];
  2687. batch_entry[1*n + base_dst] = imgs.entries[b]->buf[base_src + 1];
  2688. batch_entry[2*n + base_dst] = imgs.entries[b]->buf[base_src + 2];
  2689. }
  2690. }
  2691. }
  2692. }
  2693. set_input_f32("inp_raw", inp_raw);
  2694. }
  2695. // set input per projector
  2696. switch (ctx->proj_type) {
  2697. case PROJECTOR_TYPE_MINICPMV:
  2698. {
  2699. // inspired from siglip:
  2700. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit
  2701. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit/blob/d66538faeba44480d0bfaa42145eef26f9423199/modeling_siglip.py#L316
  2702. std::vector<int32_t> positions(pos_h * pos_w);
  2703. int bucket_coords_h[1024];
  2704. int bucket_coords_w[1024];
  2705. for (int i = 0; i < pos_h; i++){
  2706. bucket_coords_h[i] = std::floor(70.0*i/pos_h);
  2707. }
  2708. for (int i = 0; i < pos_w; i++){
  2709. bucket_coords_w[i] = std::floor(70.0*i/pos_w);
  2710. }
  2711. for (int i = 0, id = 0; i < pos_h; i++){
  2712. for (int j = 0; j < pos_w; j++){
  2713. positions[id++] = bucket_coords_h[i]*70 + bucket_coords_w[j];
  2714. }
  2715. }
  2716. set_input_i32("positions", positions);
  2717. // inspired from resampler of Qwen-VL:
  2718. // -> https://huggingface.co/Qwen/Qwen-VL/tree/main
  2719. // -> https://huggingface.co/Qwen/Qwen-VL/blob/0547ed36a86561e2e42fecec8fd0c4f6953e33c4/visual.py#L23
  2720. int embed_dim = clip_n_mmproj_embd(ctx);
  2721. // TODO @ngxson : this is very inefficient, can we do this using ggml_sin and ggml_cos?
  2722. auto pos_embed_t = get_2d_sincos_pos_embed(embed_dim, std::make_pair(pos_w, pos_h));
  2723. std::vector<float> pos_embed(embed_dim * pos_w * pos_h);
  2724. for(int i = 0; i < pos_w * pos_h; ++i){
  2725. for(int j = 0; j < embed_dim; ++j){
  2726. pos_embed[i * embed_dim + j] = pos_embed_t[i][j];
  2727. }
  2728. }
  2729. set_input_f32("pos_embed", pos_embed);
  2730. } break;
  2731. case PROJECTOR_TYPE_QWEN2VL:
  2732. {
  2733. const int merge_ratio = 2;
  2734. const int pw = image_size_width / patch_size;
  2735. const int ph = image_size_height / patch_size;
  2736. std::vector<int> positions(num_positions * 4);
  2737. int ptr = 0;
  2738. for (int y = 0; y < ph; y += merge_ratio) {
  2739. for (int x = 0; x < pw; x += merge_ratio) {
  2740. for (int dy = 0; dy < 2; dy++) {
  2741. for (int dx = 0; dx < 2; dx++) {
  2742. positions[ ptr] = y + dy;
  2743. positions[ num_patches + ptr] = x + dx;
  2744. positions[2 * num_patches + ptr] = y + dy;
  2745. positions[3 * num_patches + ptr] = x + dx;
  2746. ptr++;
  2747. }
  2748. }
  2749. }
  2750. }
  2751. set_input_i32("positions", positions);
  2752. } break;
  2753. case PROJECTOR_TYPE_QWEN25VL:
  2754. {
  2755. // pw * ph = number of tokens output by ViT after apply patch merger
  2756. // ipw * ipw = number of vision token been processed inside ViT
  2757. const int merge_ratio = 2;
  2758. const int pw = image_size_width / patch_size / merge_ratio;
  2759. const int ph = image_size_height / patch_size / merge_ratio;
  2760. const int ipw = image_size_width / patch_size;
  2761. const int iph = image_size_height / patch_size;
  2762. std::vector<int> idx (ph * pw);
  2763. std::vector<int> inv_idx(ph * pw);
  2764. if (use_window_attn) {
  2765. const int attn_window_size = 112;
  2766. const int grid_window = attn_window_size / patch_size / merge_ratio;
  2767. int dst = 0;
  2768. // [num_vision_tokens, num_vision_tokens] attention mask tensor
  2769. std::vector<float> mask(pow(ipw * iph, 2), std::numeric_limits<float>::lowest());
  2770. int mask_row = 0;
  2771. for (int y = 0; y < ph; y += grid_window) {
  2772. for (int x = 0; x < pw; x += grid_window) {
  2773. const int win_h = std::min(grid_window, ph - y);
  2774. const int win_w = std::min(grid_window, pw - x);
  2775. const int dst_0 = dst;
  2776. // group all tokens belong to the same window togather (to a continue range)
  2777. for (int dy = 0; dy < win_h; dy++) {
  2778. for (int dx = 0; dx < win_w; dx++) {
  2779. const int src = (y + dy) * pw + (x + dx);
  2780. GGML_ASSERT(src < (int)idx.size());
  2781. GGML_ASSERT(dst < (int)inv_idx.size());
  2782. idx [src] = dst;
  2783. inv_idx[dst] = src;
  2784. dst++;
  2785. }
  2786. }
  2787. for (int r=0; r < win_h * win_w * merge_ratio * merge_ratio; r++) {
  2788. int row_offset = mask_row * (ipw * iph);
  2789. std::fill(
  2790. mask.begin() + row_offset + (dst_0 * merge_ratio * merge_ratio),
  2791. mask.begin() + row_offset + (dst * merge_ratio * merge_ratio),
  2792. 0.0);
  2793. mask_row++;
  2794. }
  2795. }
  2796. }
  2797. set_input_i32("window_idx", idx);
  2798. set_input_i32("inv_window_idx", inv_idx);
  2799. set_input_f32("window_mask", mask);
  2800. } else {
  2801. for (int i = 0; i < ph * pw; i++) {
  2802. idx[i] = i;
  2803. }
  2804. }
  2805. const int mpow = merge_ratio * merge_ratio;
  2806. std::vector<int> positions(num_positions * 4);
  2807. int ptr = 0;
  2808. for (int y = 0; y < iph; y += merge_ratio) {
  2809. for (int x = 0; x < ipw; x += merge_ratio) {
  2810. for (int dy = 0; dy < 2; dy++) {
  2811. for (int dx = 0; dx < 2; dx++) {
  2812. auto remap = idx[ptr / mpow];
  2813. remap = (remap * mpow) + (ptr % mpow);
  2814. positions[ remap] = y + dy;
  2815. positions[ num_patches + remap] = x + dx;
  2816. positions[2 * num_patches + remap] = y + dy;
  2817. positions[3 * num_patches + remap] = x + dx;
  2818. ptr++;
  2819. }
  2820. }
  2821. }
  2822. }
  2823. set_input_i32("positions", positions);
  2824. } break;
  2825. case PROJECTOR_TYPE_PIXTRAL:
  2826. {
  2827. // set the 2D positions
  2828. int n_patches_per_col = image_size_width / patch_size;
  2829. std::vector<int> pos_data(num_positions);
  2830. // dimension H
  2831. for (int i = 0; i < num_positions; i++) {
  2832. pos_data[i] = i / n_patches_per_col;
  2833. }
  2834. set_input_i32("pos_h", pos_data);
  2835. // dimension W
  2836. for (int i = 0; i < num_positions; i++) {
  2837. pos_data[i] = i % n_patches_per_col;
  2838. }
  2839. set_input_i32("pos_w", pos_data);
  2840. } break;
  2841. case PROJECTOR_TYPE_GLM_EDGE:
  2842. {
  2843. // llava and other models
  2844. std::vector<int32_t> positions(num_positions);
  2845. for (int i = 0; i < num_positions; i++) {
  2846. positions[i] = i;
  2847. }
  2848. set_input_i32("positions", positions);
  2849. } break;
  2850. case PROJECTOR_TYPE_MLP:
  2851. case PROJECTOR_TYPE_MLP_NORM:
  2852. case PROJECTOR_TYPE_LDP:
  2853. case PROJECTOR_TYPE_LDPV2:
  2854. {
  2855. // llava and other models
  2856. std::vector<int32_t> positions(num_positions);
  2857. for (int i = 0; i < num_positions; i++) {
  2858. positions[i] = i;
  2859. }
  2860. set_input_i32("positions", positions);
  2861. // The patches vector is used to get rows to index into the embeds with;
  2862. // we should skip dim 0 only if we have CLS to avoid going out of bounds
  2863. // when retrieving the rows.
  2864. int patch_offset = model.class_embedding ? 1 : 0;
  2865. std::vector<int32_t> patches(num_patches);
  2866. for (int i = 0; i < num_patches; i++) {
  2867. patches[i] = i + patch_offset;
  2868. }
  2869. set_input_i32("patches", patches);
  2870. } break;
  2871. case PROJECTOR_TYPE_GEMMA3:
  2872. case PROJECTOR_TYPE_IDEFICS3:
  2873. {
  2874. // do nothing
  2875. } break;
  2876. default:
  2877. GGML_ABORT("Unknown projector type");
  2878. }
  2879. // ggml_backend_cpu_set_n_threads(ctx->backend_cpu, n_threads);
  2880. ggml_backend_dev_t dev = ggml_backend_get_device(ctx->backend_cpu);
  2881. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  2882. if (reg) {
  2883. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  2884. if (ggml_backend_set_n_threads_fn) {
  2885. ggml_backend_set_n_threads_fn(ctx->backend_cpu, n_threads);
  2886. }
  2887. }
  2888. auto status = ggml_backend_sched_graph_compute(ctx->sched.get(), gf);
  2889. if (status != GGML_STATUS_SUCCESS) {
  2890. LOG_ERR("%s: ggml_backend_sched_graph_compute failed with error %d\n", __func__, status);
  2891. return false;
  2892. }
  2893. // the last node is the embedding tensor
  2894. struct ggml_tensor * embeddings = ggml_graph_node(gf, -1);
  2895. // copy the embeddings to the location passed by the user
  2896. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  2897. return true;
  2898. }
  2899. bool clip_model_quantize(const char * fname_inp, const char * fname_out, const int itype) {
  2900. assert(itype < GGML_TYPE_COUNT);
  2901. ggml_type type = static_cast<ggml_type>(itype);
  2902. auto * ctx_clip = clip_init(fname_inp, clip_context_params{
  2903. /* use_gpu */ false,
  2904. /* verbosity */ GGML_LOG_LEVEL_ERROR,
  2905. });
  2906. const auto & ctx_src = ctx_clip->ctx_gguf.get();
  2907. const auto & ctx_data = ctx_clip->ctx_data.get();
  2908. auto * ctx_out = gguf_init_empty();
  2909. gguf_set_kv(ctx_out, ctx_src);
  2910. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  2911. gguf_set_val_u32(ctx_out, "general.file_type", itype);
  2912. auto fout = std::ofstream(fname_out, std::ios::binary);
  2913. const int n_tensors = gguf_get_n_tensors(ctx_src);
  2914. for (int i = 0; i < n_tensors; ++i) {
  2915. const char * name = gguf_get_tensor_name(ctx_src, i);
  2916. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name);
  2917. gguf_add_tensor(ctx_out, cur);
  2918. }
  2919. const size_t meta_size = gguf_get_meta_size(ctx_out);
  2920. for (size_t i = 0; i < meta_size; ++i) {
  2921. fout.put(0);
  2922. }
  2923. // regexes of tensor names to be quantized
  2924. const std::vector<std::string> k_names = {
  2925. ".*weight",
  2926. };
  2927. std::vector<uint8_t> work(512);
  2928. std::vector<float> conv_buf(512);
  2929. size_t total_size_org = 0;
  2930. size_t total_size_new = 0;
  2931. for (int i = 0; i < n_tensors; ++i) {
  2932. const std::string name = gguf_get_tensor_name(ctx_src, i);
  2933. struct ggml_tensor * cur = ggml_get_tensor(ctx_data, name.c_str());
  2934. enum ggml_type new_type;
  2935. void * new_data;
  2936. size_t new_size;
  2937. bool quantize = false;
  2938. for (const auto & s : k_names) {
  2939. if (std::regex_match(name, std::regex(s))) {
  2940. quantize = true;
  2941. break;
  2942. }
  2943. }
  2944. // quantize only 2D tensors and bigger than block size
  2945. quantize &= (ggml_n_dims(cur) == 2) && cur->ne[0] > ggml_blck_size(type);
  2946. if (quantize) {
  2947. new_type = type;
  2948. if (new_type >= GGML_TYPE_Q2_K && name.find("embd") != std::string::npos) {
  2949. new_type = GGML_TYPE_Q8_0; // ggml_get_rows needs non K type
  2950. // LOG_ERR("%s: quantizing %s to %s\n", __func__, name.c_str(), ggml_type_name(new_type));
  2951. }
  2952. const size_t n_elms = ggml_nelements(cur);
  2953. float * f32_data;
  2954. switch (cur->type) {
  2955. case GGML_TYPE_F32:
  2956. f32_data = (float *)cur->data;
  2957. break;
  2958. case GGML_TYPE_F16:
  2959. if (conv_buf.size() < n_elms) {
  2960. conv_buf.resize(n_elms);
  2961. }
  2962. for (size_t j = 0; j < n_elms; ++j) {
  2963. conv_buf[j] = ggml_fp16_to_fp32(((ggml_fp16_t *)cur->data)[j]);
  2964. }
  2965. f32_data = (float *)conv_buf.data();
  2966. break;
  2967. default:
  2968. LOG_ERR("%s: Please use an input file in f32 or f16\n", __func__);
  2969. gguf_free(ctx_out);
  2970. return false;
  2971. }
  2972. if (work.size() < n_elms * 4) {
  2973. work.resize(n_elms * 4);
  2974. }
  2975. new_data = work.data();
  2976. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, n_elms/cur->ne[0], cur->ne[0], nullptr);
  2977. } else {
  2978. new_type = cur->type;
  2979. new_data = cur->data;
  2980. new_size = ggml_nbytes(cur);
  2981. }
  2982. const size_t orig_size = ggml_nbytes(cur);
  2983. total_size_org += orig_size;
  2984. total_size_new += new_size;
  2985. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  2986. GGML_ASSERT(gguf_get_tensor_size(ctx_out, gguf_find_tensor(ctx_out, name.c_str())) == new_size);
  2987. gguf_set_tensor_data(ctx_out, name.c_str(), new_data);
  2988. fout.write((const char *)new_data, new_size);
  2989. size_t pad = GGML_PAD(new_size, gguf_get_alignment(ctx_out)) - new_size;
  2990. for (size_t j = 0; j < pad; ++j) {
  2991. fout.put(0);
  2992. }
  2993. LOG_INF("%s: n_dims = %d | quantize=%d | size = %f MB -> %f MB\n", name.c_str(), ggml_n_dims(cur), quantize,
  2994. orig_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  2995. }
  2996. // go back to beginning of file and write the updated metadata
  2997. fout.seekp(0, std::ios::beg);
  2998. std::vector<uint8_t> meta(meta_size);
  2999. gguf_get_meta_data(ctx_out, meta.data());
  3000. fout.write((const char *)meta.data(), meta_size);
  3001. fout.close();
  3002. clip_free(ctx_clip);
  3003. gguf_free(ctx_out);
  3004. {
  3005. LOG_INF("%s: original size = %8.2f MB\n", __func__, total_size_org / 1024.0 / 1024.0);
  3006. LOG_INF("%s: quantized size = %8.2f MB\n", __func__, total_size_new / 1024.0 / 1024.0);
  3007. }
  3008. return true;
  3009. }
  3010. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  3011. switch (ctx->proj_type) {
  3012. case PROJECTOR_TYPE_LDP:
  3013. return ctx->vision_model.mm_model_block_1_block_2_1_b->ne[0];
  3014. case PROJECTOR_TYPE_LDPV2:
  3015. return ctx->vision_model.mm_model_peg_0_b->ne[0];
  3016. case PROJECTOR_TYPE_MLP:
  3017. case PROJECTOR_TYPE_PIXTRAL:
  3018. return ctx->vision_model.mm_2_w->ne[1];
  3019. case PROJECTOR_TYPE_MLP_NORM:
  3020. return ctx->vision_model.mm_3_b->ne[0];
  3021. case PROJECTOR_TYPE_MINICPMV:
  3022. if (ctx->minicpmv_version == 2) {
  3023. return 4096;
  3024. } else if (ctx->minicpmv_version == 3) {
  3025. return 3584;
  3026. } else if (ctx->minicpmv_version == 4) {
  3027. return 3584;
  3028. }
  3029. GGML_ABORT("Unknown minicpmv version");
  3030. case PROJECTOR_TYPE_GLM_EDGE:
  3031. return ctx->vision_model.mm_model_mlp_3_w->ne[1];
  3032. case PROJECTOR_TYPE_QWEN2VL:
  3033. case PROJECTOR_TYPE_QWEN25VL:
  3034. return ctx->vision_model.mm_1_b->ne[0];
  3035. case PROJECTOR_TYPE_GEMMA3:
  3036. return ctx->vision_model.mm_input_proj_w->ne[0];
  3037. case PROJECTOR_TYPE_IDEFICS3:
  3038. return ctx->vision_model.projection->ne[1];
  3039. default:
  3040. GGML_ABORT("Unknown projector type");
  3041. }
  3042. }
  3043. int clip_is_minicpmv(const struct clip_ctx * ctx) {
  3044. if (ctx->proj_type == PROJECTOR_TYPE_MINICPMV) {
  3045. return ctx->minicpmv_version;
  3046. }
  3047. return 0;
  3048. }
  3049. bool clip_is_glm(const struct clip_ctx * ctx) {
  3050. return ctx->proj_type == PROJECTOR_TYPE_GLM_EDGE;
  3051. }
  3052. bool clip_is_qwen2vl(const struct clip_ctx * ctx) {
  3053. return ctx->proj_type == PROJECTOR_TYPE_QWEN2VL || ctx->proj_type == PROJECTOR_TYPE_QWEN25VL;
  3054. }
  3055. bool clip_is_llava(const struct clip_ctx * ctx) {
  3056. return ctx->has_llava_projector;
  3057. }
  3058. bool clip_is_gemma3(const struct clip_ctx * ctx) {
  3059. return ctx->proj_type == PROJECTOR_TYPE_GEMMA3;
  3060. }
  3061. bool clip_encode_float_image (struct clip_ctx * ctx, int n_threads, float * img, int h, int w, float * vec) {
  3062. clip_image_f32 clip_img;
  3063. clip_img.buf.resize(h * w * 3);
  3064. for (int i = 0; i < h*w*3; i++)
  3065. {
  3066. clip_img.buf[i] = img[i];
  3067. }
  3068. clip_img.nx = w;
  3069. clip_img.ny = h;
  3070. clip_image_encode(ctx, n_threads, &clip_img, vec);
  3071. return true;
  3072. }
  3073. //
  3074. // API used internally with mtmd
  3075. //
  3076. projector_type clip_get_projector_type(const struct clip_ctx * ctx) {
  3077. return ctx->proj_type;
  3078. }