1
0

clip.cpp 155 KB

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