clip.cpp 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "clip-model.h"
  4. #include "clip-graph.h"
  5. #include "models/models.h"
  6. #include "ggml.h"
  7. #include "ggml-cpp.h"
  8. #include "ggml-alloc.h"
  9. #include "ggml-backend.h"
  10. #include "gguf.h"
  11. #include <cassert>
  12. #include <cmath>
  13. #include <cstdlib>
  14. #include <cstring>
  15. #include <fstream>
  16. #include <map>
  17. #include <stdexcept>
  18. #include <unordered_set>
  19. #include <vector>
  20. #include <cinttypes>
  21. #include <limits>
  22. #include <array>
  23. #include <functional>
  24. struct clip_logger_state g_logger_state = {clip_log_callback_default, NULL};
  25. //#define CLIP_DEBUG_FUNCTIONS
  26. #ifdef CLIP_DEBUG_FUNCTIONS
  27. static void clip_image_write_image_to_ppm(const clip_image_u8& img, const std::string& filename) {
  28. std::ofstream file(filename, std::ios::binary);
  29. if (!file.is_open()) {
  30. LOG_ERR("Failed to open file for writing: %s\n", filename.c_str());
  31. return;
  32. }
  33. // PPM header: P6 format, width, height, and max color value
  34. file << "P6\n" << img.nx << " " << img.ny << "\n255\n";
  35. // Write pixel data
  36. for (size_t i = 0; i < img.buf.size(); i += 3) {
  37. // PPM expects binary data in RGB format, which matches our image buffer
  38. file.write(reinterpret_cast<const char*>(&img.buf[i]), 3);
  39. }
  40. file.close();
  41. }
  42. static void clip_image_save_to_bmp(const clip_image_u8& img, const std::string& filename) {
  43. std::ofstream file(filename, std::ios::binary);
  44. if (!file.is_open()) {
  45. LOG_ERR("Failed to open file for writing: %s\n", filename.c_str());
  46. return;
  47. }
  48. int fileSize = 54 + 3 * img.nx * img.ny; // File header + info header + pixel data
  49. int bytesPerPixel = 3;
  50. int widthInBytes = img.nx * bytesPerPixel;
  51. int paddingAmount = (4 - (widthInBytes % 4)) % 4;
  52. int stride = widthInBytes + paddingAmount;
  53. // Bitmap file header
  54. unsigned char fileHeader[14] = {
  55. 'B','M', // Signature
  56. 0,0,0,0, // Image file size in bytes
  57. 0,0,0,0, // Reserved
  58. 54,0,0,0 // Start of pixel array
  59. };
  60. // Total file size
  61. fileSize = 54 + (stride * img.ny);
  62. fileHeader[2] = (unsigned char)(fileSize);
  63. fileHeader[3] = (unsigned char)(fileSize >> 8);
  64. fileHeader[4] = (unsigned char)(fileSize >> 16);
  65. fileHeader[5] = (unsigned char)(fileSize >> 24);
  66. // Bitmap information header (BITMAPINFOHEADER)
  67. unsigned char infoHeader[40] = {
  68. 40,0,0,0, // Size of this header (40 bytes)
  69. 0,0,0,0, // Image width
  70. 0,0,0,0, // Image height
  71. 1,0, // Number of color planes
  72. 24,0, // Bits per pixel
  73. 0,0,0,0, // No compression
  74. 0,0,0,0, // Image size (can be 0 for no compression)
  75. 0,0,0,0, // X pixels per meter (not specified)
  76. 0,0,0,0, // Y pixels per meter (not specified)
  77. 0,0,0,0, // Total colors (color table not used)
  78. 0,0,0,0 // Important colors (all are important)
  79. };
  80. // Width and height in the information header
  81. infoHeader[4] = (unsigned char)(img.nx);
  82. infoHeader[5] = (unsigned char)(img.nx >> 8);
  83. infoHeader[6] = (unsigned char)(img.nx >> 16);
  84. infoHeader[7] = (unsigned char)(img.nx >> 24);
  85. infoHeader[8] = (unsigned char)(img.ny);
  86. infoHeader[9] = (unsigned char)(img.ny >> 8);
  87. infoHeader[10] = (unsigned char)(img.ny >> 16);
  88. infoHeader[11] = (unsigned char)(img.ny >> 24);
  89. // Write file headers
  90. file.write(reinterpret_cast<char*>(fileHeader), sizeof(fileHeader));
  91. file.write(reinterpret_cast<char*>(infoHeader), sizeof(infoHeader));
  92. // Pixel data
  93. std::vector<unsigned char> padding(3, 0); // Max padding size to be added to each row
  94. for (int y = img.ny - 1; y >= 0; --y) { // BMP files are stored bottom-to-top
  95. for (int x = 0; x < img.nx; ++x) {
  96. // Each pixel
  97. size_t pixelIndex = (y * img.nx + x) * 3;
  98. unsigned char pixel[3] = {
  99. img.buf[pixelIndex + 2], // BMP stores pixels in BGR format
  100. img.buf[pixelIndex + 1],
  101. img.buf[pixelIndex]
  102. };
  103. file.write(reinterpret_cast<char*>(pixel), 3);
  104. }
  105. // Write padding for the row
  106. file.write(reinterpret_cast<char*>(padding.data()), paddingAmount);
  107. }
  108. file.close();
  109. }
  110. // debug function to convert f32 to u8
  111. static void clip_image_convert_f32_to_u8(const clip_image_f32& src, clip_image_u8& dst) {
  112. dst.nx = src.nx;
  113. dst.ny = src.ny;
  114. dst.buf.resize(3 * src.nx * src.ny);
  115. for (size_t i = 0; i < src.buf.size(); ++i) {
  116. dst.buf[i] = static_cast<uint8_t>(std::min(std::max(int(src.buf[i] * 255.0f), 0), 255));
  117. }
  118. }
  119. #endif
  120. struct clip_ctx {
  121. clip_model model;
  122. gguf_context_ptr ctx_gguf;
  123. ggml_context_ptr ctx_data;
  124. std::vector<uint8_t> buf_compute_meta;
  125. std::vector<ggml_backend_t> backend_ptrs;
  126. std::vector<ggml_backend_buffer_type_t> backend_buft;
  127. ggml_backend_t backend = nullptr;
  128. ggml_backend_t backend_cpu = nullptr;
  129. ggml_backend_buffer_ptr buf;
  130. int max_nodes = 8192;
  131. ggml_backend_sched_ptr sched;
  132. clip_flash_attn_type flash_attn_type = CLIP_FLASH_ATTN_TYPE_AUTO;
  133. bool is_allocated = false;
  134. clip_ctx(clip_context_params & ctx_params) {
  135. flash_attn_type = ctx_params.flash_attn_type;
  136. backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  137. if (!backend_cpu) {
  138. throw std::runtime_error("failed to initialize CPU backend");
  139. }
  140. if (ctx_params.use_gpu) {
  141. auto backend_name = std::getenv("MTMD_BACKEND_DEVICE");
  142. if (backend_name != nullptr) {
  143. backend = ggml_backend_init_by_name(backend_name, nullptr);
  144. if (!backend) {
  145. LOG_WRN("%s: Warning: Failed to initialize \"%s\" backend, falling back to default GPU backend\n", __func__, backend_name);
  146. }
  147. }
  148. if (!backend) {
  149. backend = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr);
  150. backend = backend ? backend : ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU, nullptr);
  151. }
  152. }
  153. if (backend) {
  154. LOG_INF("%s: CLIP using %s backend\n", __func__, ggml_backend_name(backend));
  155. backend_ptrs.push_back(backend);
  156. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  157. } else {
  158. backend = backend_cpu;
  159. LOG_INF("%s: CLIP using CPU backend\n", __func__);
  160. }
  161. if (ctx_params.image_min_tokens > 0) {
  162. model.hparams.custom_image_min_tokens = ctx_params.image_min_tokens;
  163. }
  164. if (ctx_params.image_max_tokens > 0) {
  165. model.hparams.custom_image_max_tokens = ctx_params.image_max_tokens;
  166. }
  167. backend_ptrs.push_back(backend_cpu);
  168. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend_cpu));
  169. sched.reset(
  170. ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), 8192, false, true)
  171. );
  172. if (ctx_params.cb_eval != nullptr) {
  173. ggml_backend_sched_set_eval_callback(sched.get(), ctx_params.cb_eval, ctx_params.cb_eval_user_data);
  174. }
  175. }
  176. ~clip_ctx() {
  177. ggml_backend_free(backend);
  178. if (backend != backend_cpu) {
  179. ggml_backend_free(backend_cpu);
  180. }
  181. }
  182. // this function is added so that we don't change too much of the existing code
  183. projector_type proj_type() const {
  184. return model.proj_type;
  185. }
  186. };
  187. //
  188. // clip_graph
  189. //
  190. clip_graph::clip_graph(clip_ctx * ctx, const clip_image_f32 & img) :
  191. model(ctx->model),
  192. hparams(model.hparams),
  193. proj_type(ctx->proj_type()),
  194. img(img),
  195. patch_size(hparams.patch_size),
  196. n_patches_x(img.nx / patch_size),
  197. n_patches_y(img.ny / patch_size),
  198. n_patches(n_patches_x * n_patches_y),
  199. n_embd(hparams.n_embd),
  200. n_head(hparams.n_head),
  201. d_head(n_embd / n_head),
  202. n_layer(hparams.n_layer),
  203. n_mmproj_embd(clip_n_mmproj_embd(ctx)),
  204. eps(hparams.eps),
  205. kq_scale(1.0f / sqrtf((float)d_head)),
  206. flash_attn_type(ctx->flash_attn_type) {
  207. struct ggml_init_params params = {
  208. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  209. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  210. /*.no_alloc =*/ true,
  211. };
  212. ctx0_ptr.reset(ggml_init(params));
  213. ctx0 = ctx0_ptr.get();
  214. gf = ggml_new_graph_custom(ctx0, ctx->max_nodes, false);
  215. }
  216. void clip_graph::cb(ggml_tensor * cur, const char * name, int il) const {
  217. if (il >= 0) {
  218. ggml_format_name(cur, "%s-%d", name, il);
  219. } else {
  220. ggml_set_name(cur, name);
  221. }
  222. }
  223. // siglip2 naflex
  224. ggml_tensor * clip_graph::resize_position_embeddings(uint32_t interpolation_mode) {
  225. ggml_tensor * pos_embd = model.position_embeddings;
  226. const int height = img.ny / patch_size;
  227. const int width = img.nx / patch_size;
  228. const uint32_t mode = interpolation_mode;
  229. const int n_per_side = (int)std::sqrt(pos_embd->ne[1]);
  230. GGML_ASSERT(pos_embd);
  231. if (height == n_per_side && width == n_per_side) {
  232. return pos_embd;
  233. }
  234. pos_embd = ggml_reshape_3d(ctx0, pos_embd, n_embd, n_per_side, n_per_side); // -> (n_embd, n_per_side, n_per_side)
  235. pos_embd = ggml_permute(ctx0, pos_embd, 2, 0, 1, 3); // -> (n_per_side, n_per_side, n_embd)
  236. pos_embd = ggml_interpolate(ctx0, pos_embd, width, height, n_embd, 1, mode); // -> (width, height, n_embd)
  237. pos_embd = ggml_permute(ctx0, pos_embd, 1, 2, 0, 3); // -> (n_embd, width, height)
  238. pos_embd = ggml_cont_2d(ctx0, pos_embd, n_embd, width * height); // -> (n_embd, width * height)
  239. return pos_embd;
  240. }
  241. // build vision transformer (ViT) cgraph
  242. // this function should cover most of the models
  243. // if your model has specific features, you should probably duplicate this function
  244. ggml_tensor * clip_graph::build_vit(
  245. ggml_tensor * inp,
  246. int64_t n_pos,
  247. norm_type norm_t,
  248. ffn_op_type ffn_t,
  249. ggml_tensor * learned_pos_embd,
  250. std::function<ggml_tensor *(ggml_tensor *, const clip_layer &)> add_pos
  251. ) {
  252. if (learned_pos_embd) {
  253. inp = ggml_add(ctx0, inp, learned_pos_embd);
  254. cb(inp, "pos_embed", -1);
  255. }
  256. ggml_tensor * inpL = inp;
  257. // pre-layernorm
  258. if (model.pre_ln_w) {
  259. inpL = build_norm(inpL, model.pre_ln_w, model.pre_ln_b, norm_t, eps, -1);
  260. cb(inpL, "pre_ln", -1);
  261. }
  262. // loop over layers
  263. for (int il = 0; il < n_layer; il++) {
  264. auto & layer = model.layers[il];
  265. ggml_tensor * cur = inpL; // inpL = residual, cur = hidden_states
  266. // layernorm1
  267. cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, norm_t, eps, il);
  268. cb(cur, "layer_inp_normed", il);
  269. // self-attention
  270. {
  271. ggml_tensor * Qcur = nullptr;
  272. ggml_tensor * Kcur = nullptr;
  273. ggml_tensor * Vcur = nullptr;
  274. if (layer.qkv_w != nullptr) {
  275. // fused qkv
  276. cur = ggml_mul_mat(ctx0, layer.qkv_w, cur);
  277. if (layer.qkv_b != nullptr) {
  278. cur = ggml_add(ctx0, cur, layer.qkv_b);
  279. }
  280. Qcur = ggml_view_3d(ctx0, cur, d_head, n_head, n_pos,
  281. /* nb1 */ ggml_row_size(cur->type, d_head),
  282. /* nb2 */ cur->nb[1],
  283. /* offset */ 0);
  284. Kcur = ggml_view_3d(ctx0, cur, d_head, n_head, n_pos,
  285. /* nb1 */ ggml_row_size(cur->type, d_head),
  286. /* nb2 */ cur->nb[1],
  287. /* offset */ ggml_row_size(cur->type, n_embd));
  288. Vcur = ggml_view_3d(ctx0, cur, d_head, n_head, n_pos,
  289. /* nb1 */ ggml_row_size(cur->type, d_head),
  290. /* nb2 */ cur->nb[1],
  291. /* offset */ ggml_row_size(cur->type, 2 * n_embd));
  292. // TODO: q/k norm requires row size == n_embd, while here it's d_head
  293. // we can add support in the future if needed
  294. GGML_ASSERT(layer.q_norm == nullptr && layer.k_norm == nullptr);
  295. } else {
  296. // separate q, k, v
  297. Qcur = ggml_mul_mat(ctx0, layer.q_w, cur);
  298. if (layer.q_b) {
  299. Qcur = ggml_add(ctx0, Qcur, layer.q_b);
  300. }
  301. Kcur = ggml_mul_mat(ctx0, layer.k_w, cur);
  302. if (layer.k_b) {
  303. Kcur = ggml_add(ctx0, Kcur, layer.k_b);
  304. }
  305. Vcur = ggml_mul_mat(ctx0, layer.v_w, cur);
  306. if (layer.v_b) {
  307. Vcur = ggml_add(ctx0, Vcur, layer.v_b);
  308. }
  309. if (layer.q_norm) {
  310. Qcur = build_norm(Qcur, layer.q_norm, NULL, norm_t, eps, il);
  311. cb(Qcur, "Qcur_norm", il);
  312. }
  313. if (layer.k_norm) {
  314. Kcur = build_norm(Kcur, layer.k_norm, NULL, norm_t, eps, il);
  315. cb(Kcur, "Kcur_norm", il);
  316. }
  317. Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos);
  318. Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos);
  319. Vcur = ggml_reshape_3d(ctx0, Vcur, d_head, n_head, n_pos);
  320. }
  321. cb(Qcur, "Qcur", il);
  322. cb(Kcur, "Kcur", il);
  323. cb(Vcur, "Vcur", il);
  324. if (add_pos) {
  325. Qcur = add_pos(Qcur, layer);
  326. Kcur = add_pos(Kcur, layer);
  327. cb(Qcur, "Qcur_pos", il);
  328. cb(Kcur, "Kcur_pos", il);
  329. }
  330. cur = build_attn(layer.o_w, layer.o_b,
  331. Qcur, Kcur, Vcur, nullptr, kq_scale, il);
  332. cb(cur, "attn_out", il);
  333. }
  334. if (layer.ls_1_w) {
  335. cur = ggml_mul(ctx0, cur, layer.ls_1_w);
  336. cb(cur, "attn_out_scaled", il);
  337. }
  338. // re-add the layer input, e.g., residual
  339. cur = ggml_add(ctx0, cur, inpL);
  340. inpL = cur; // inpL = residual, cur = hidden_states
  341. cb(cur, "ffn_inp", il);
  342. // layernorm2
  343. cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, norm_t, eps, il);
  344. cb(cur, "ffn_inp_normed", il);
  345. // ffn
  346. cur = build_ffn(cur,
  347. layer.ff_up_w, layer.ff_up_b,
  348. layer.ff_gate_w, layer.ff_gate_b,
  349. layer.ff_down_w, layer.ff_down_b,
  350. ffn_t, il);
  351. cb(cur, "ffn_out", il);
  352. if (layer.ls_2_w) {
  353. cur = ggml_mul(ctx0, cur, layer.ls_2_w);
  354. cb(cur, "ffn_out_scaled", il);
  355. }
  356. // residual 2
  357. cur = ggml_add(ctx0, inpL, cur);
  358. cb(cur, "layer_out", il);
  359. inpL = cur;
  360. }
  361. if (model.audio_has_avgpool()) {
  362. ggml_tensor * cur = inpL;
  363. cur = ggml_transpose(ctx0, cur);
  364. cur = ggml_cont(ctx0, cur);
  365. cur = ggml_pool_1d(ctx0, cur, GGML_OP_POOL_AVG, 2, 2, 0);
  366. cur = ggml_transpose(ctx0, cur);
  367. cur = ggml_cont(ctx0, cur);
  368. inpL = cur;
  369. }
  370. // post-layernorm
  371. if (model.post_ln_w) {
  372. inpL = build_norm(inpL, model.post_ln_w, model.post_ln_b, norm_t, eps, -1);
  373. }
  374. return inpL;
  375. }
  376. // build the input after conv2d (inp_raw --> patches)
  377. // returns tensor with shape [n_embd, n_patches]
  378. ggml_tensor * clip_graph::build_inp() {
  379. ggml_tensor * inp_raw = build_inp_raw();
  380. ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  381. inp = ggml_reshape_2d(ctx0, inp, n_patches, n_embd);
  382. inp = ggml_cont(ctx0, ggml_transpose(ctx0, inp));
  383. if (model.patch_bias) {
  384. inp = ggml_add(ctx0, inp, model.patch_bias);
  385. cb(inp, "patch_bias", -1);
  386. }
  387. return inp;
  388. }
  389. ggml_tensor * clip_graph::build_inp_raw(int channels) {
  390. ggml_tensor * inp_raw = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, img.nx, img.ny, channels);
  391. ggml_set_name(inp_raw, "inp_raw");
  392. ggml_set_input(inp_raw);
  393. return inp_raw;
  394. }
  395. ggml_tensor * clip_graph::build_norm(
  396. ggml_tensor * cur,
  397. ggml_tensor * mw,
  398. ggml_tensor * mb,
  399. norm_type type,
  400. float norm_eps,
  401. int il) const {
  402. cur = type == NORM_TYPE_RMS
  403. ? ggml_rms_norm(ctx0, cur, norm_eps)
  404. : ggml_norm(ctx0, cur, norm_eps);
  405. if (mw) {
  406. cur = ggml_mul(ctx0, cur, mw);
  407. cb(cur, "norm_w", il);
  408. }
  409. if (mb) {
  410. cur = ggml_add(ctx0, cur, mb);
  411. cb(cur, "norm_b", il);
  412. }
  413. return cur;
  414. }
  415. ggml_tensor * clip_graph::build_ffn(
  416. ggml_tensor * cur,
  417. ggml_tensor * up,
  418. ggml_tensor * up_b,
  419. ggml_tensor * gate,
  420. ggml_tensor * gate_b,
  421. ggml_tensor * down,
  422. ggml_tensor * down_b,
  423. ffn_op_type type_op,
  424. int il) const {
  425. ggml_tensor * tmp = up ? ggml_mul_mat(ctx0, up, cur) : cur;
  426. cb(tmp, "ffn_up", il);
  427. if (up_b) {
  428. tmp = ggml_add(ctx0, tmp, up_b);
  429. cb(tmp, "ffn_up_b", il);
  430. }
  431. if (gate) {
  432. cur = ggml_mul_mat(ctx0, gate, cur);
  433. cb(cur, "ffn_gate", il);
  434. if (gate_b) {
  435. cur = ggml_add(ctx0, cur, gate_b);
  436. cb(cur, "ffn_gate_b", il);
  437. }
  438. } else {
  439. cur = tmp;
  440. }
  441. // we only support parallel ffn for now
  442. switch (type_op) {
  443. case FFN_SILU:
  444. if (gate) {
  445. cur = ggml_swiglu_split(ctx0, cur, tmp);
  446. cb(cur, "ffn_swiglu", il);
  447. } else {
  448. cur = ggml_silu(ctx0, cur);
  449. cb(cur, "ffn_silu", il);
  450. } break;
  451. case FFN_GELU:
  452. if (gate) {
  453. cur = ggml_geglu_split(ctx0, cur, tmp);
  454. cb(cur, "ffn_geglu", il);
  455. } else {
  456. cur = ggml_gelu(ctx0, cur);
  457. cb(cur, "ffn_gelu", il);
  458. } break;
  459. case FFN_GELU_ERF:
  460. if (gate) {
  461. cur = ggml_geglu_erf_split(ctx0, cur, tmp);
  462. cb(cur, "ffn_geglu_erf", il);
  463. } else {
  464. cur = ggml_gelu_erf(ctx0, cur);
  465. cb(cur, "ffn_gelu_erf", il);
  466. } break;
  467. case FFN_GELU_QUICK:
  468. if (gate) {
  469. cur = ggml_geglu_quick_split(ctx0, cur, tmp);
  470. cb(cur, "ffn_geglu_quick", il);
  471. } else {
  472. cur = ggml_gelu_quick(ctx0, cur);
  473. cb(cur, "ffn_gelu_quick", il);
  474. } break;
  475. }
  476. if (down) {
  477. cur = ggml_mul_mat(ctx0, down, cur);
  478. }
  479. if (down_b) {
  480. cb(cur, "ffn_down", il);
  481. }
  482. if (down_b) {
  483. cur = ggml_add(ctx0, cur, down_b);
  484. }
  485. return cur;
  486. }
  487. ggml_tensor * clip_graph::build_attn(
  488. ggml_tensor * wo,
  489. ggml_tensor * wo_b,
  490. ggml_tensor * q_cur,
  491. ggml_tensor * k_cur,
  492. ggml_tensor * v_cur,
  493. ggml_tensor * kq_mask,
  494. float kq_scale,
  495. int il) const {
  496. // these nodes are added to the graph together so that they are not reordered
  497. // by doing so, the number of splits in the graph is reduced
  498. ggml_build_forward_expand(gf, q_cur);
  499. ggml_build_forward_expand(gf, k_cur);
  500. ggml_build_forward_expand(gf, v_cur);
  501. ggml_tensor * q = ggml_permute(ctx0, q_cur, 0, 2, 1, 3);
  502. //cb(q, "q", il);
  503. ggml_tensor * k = ggml_permute(ctx0, k_cur, 0, 2, 1, 3);
  504. //cb(k, "k", il);
  505. ggml_tensor * cur;
  506. if (flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) {
  507. ggml_tensor * v = ggml_permute(ctx0, v_cur, 0, 2, 1, 3);
  508. k = ggml_cast(ctx0, k, GGML_TYPE_F16);
  509. v = ggml_cast(ctx0, v, GGML_TYPE_F16);
  510. cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, 0.0f, 0.0f);
  511. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  512. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]);
  513. } else {
  514. ggml_tensor * v = ggml_permute(ctx0, v_cur, 1, 2, 0, 3);
  515. v = ggml_cont(ctx0, v);
  516. const auto n_tokens = q->ne[1];
  517. const auto n_head = q->ne[2];
  518. ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  519. // F32 may not needed for vision encoders?
  520. // ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  521. kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, 0.0f);
  522. ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  523. cur = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  524. cur = ggml_cont_2d(ctx0, cur, cur->ne[0]*n_head, n_tokens);
  525. }
  526. cb(cur, "kqv_out", il);
  527. if (wo) {
  528. cur = ggml_mul_mat(ctx0, wo, cur);
  529. }
  530. if (wo_b) {
  531. cur = ggml_add(ctx0, cur, wo_b);
  532. }
  533. return cur;
  534. }
  535. // implementation of the 2D RoPE without adding a new op in ggml
  536. // this is not efficient (use double the memory), but works on all backends
  537. // 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
  538. ggml_tensor * clip_graph::build_rope_2d(
  539. ggml_context * ctx0,
  540. ggml_tensor * cur,
  541. ggml_tensor * pos_a, // first half
  542. ggml_tensor * pos_b, // second half
  543. const float freq_base,
  544. const bool interleave_freq
  545. ) {
  546. const int64_t n_dim = cur->ne[0];
  547. const int64_t n_head = cur->ne[1];
  548. const int64_t n_pos = cur->ne[2];
  549. // for example, if we have cur tensor of shape (n_dim=8, n_head, n_pos)
  550. // we will have a list of 4 inv_freq: 1e-0, 1e-1, 1e-2, 1e-3
  551. // first half of cur will use 1e-0, 1e-2 (even)
  552. // second half of cur will use 1e-1, 1e-3 (odd)
  553. // the trick here is to rotate just half of n_dim, so inv_freq will automatically be even
  554. // ^ don't ask me why, it's math! -2(2i) / n_dim == -2i / (n_dim/2)
  555. // then for the second half, we use freq_scale to shift the inv_freq
  556. // ^ why? replace (2i) with (2i+1) in the above equation
  557. const float freq_scale_odd = interleave_freq
  558. ? std::pow(freq_base, (float)-2/n_dim)
  559. : 1.0;
  560. // first half
  561. ggml_tensor * first;
  562. {
  563. first = ggml_view_3d(ctx0, cur,
  564. n_dim/2, n_head, n_pos,
  565. ggml_row_size(cur->type, n_dim),
  566. ggml_row_size(cur->type, n_dim*n_head),
  567. 0);
  568. first = ggml_rope_ext(
  569. ctx0,
  570. first,
  571. pos_a, // positions
  572. nullptr, // freq factors
  573. n_dim/2, // n_dims
  574. 0, 0, freq_base,
  575. 1.0f, 0.0f, 1.0f, 0.0f, 0.0f
  576. );
  577. }
  578. // second half
  579. ggml_tensor * second;
  580. {
  581. second = ggml_view_3d(ctx0, cur,
  582. n_dim/2, n_head, n_pos,
  583. ggml_row_size(cur->type, n_dim),
  584. ggml_row_size(cur->type, n_dim*n_head),
  585. n_dim/2 * ggml_element_size(cur));
  586. second = ggml_rope_ext(
  587. ctx0,
  588. second,
  589. pos_b, // positions
  590. nullptr, // freq factors
  591. n_dim/2, // n_dims
  592. 0, 0, freq_base,
  593. freq_scale_odd,
  594. 0.0f, 1.0f, 0.0f, 0.0f
  595. );
  596. }
  597. cur = ggml_concat(ctx0, first, second, 0);
  598. return cur;
  599. }
  600. // Generic function to stack frames for audio processing
  601. // Abstracts out the StackAudioFrames logic used by ultravox
  602. ggml_tensor * clip_graph::build_stack(ggml_tensor * cur, int32_t stack_factor, int32_t n_embed) {
  603. if (stack_factor <= 1) {
  604. return cur;
  605. }
  606. int64_t total_elements = ggml_nelements(cur);
  607. int64_t stride = n_embed * stack_factor;
  608. // Calculate padded length
  609. int64_t padded_len = GGML_PAD(total_elements, stride);
  610. int64_t pad = padded_len - total_elements;
  611. if (pad > 0) {
  612. // Pad the tensor to make it divisible by stride
  613. cur = ggml_view_1d(ctx0, cur, total_elements, 0);
  614. cur = ggml_pad(ctx0, cur, pad, 0, 0, 0);
  615. }
  616. // Reshape to [stride, padded_len / stride]
  617. cur = ggml_view_2d(ctx0, cur, stride, padded_len / stride,
  618. ggml_row_size(cur->type, stride), 0);
  619. return cur;
  620. }
  621. // aka pixel_shuffle / pixel_unshuffle / patch_merger (Kimi-VL)
  622. // support dynamic resolution
  623. ggml_tensor * clip_graph::build_patch_merge_permute(ggml_tensor * cur, int scale_factor) {
  624. GGML_ASSERT(scale_factor > 1);
  625. const int n_embd = cur->ne[0];
  626. int width = img.nx / patch_size;
  627. int height = img.ny / patch_size;
  628. // pad width and height to factor
  629. const int64_t pad_width = CLIP_ALIGN(width, scale_factor) - width;
  630. const int64_t pad_height = CLIP_ALIGN(height, scale_factor) - height;
  631. cur = ggml_reshape_3d(ctx0, cur, n_embd, width, height);
  632. if (pad_width || pad_height) {
  633. cur = ggml_pad(ctx0, cur, 0, pad_width, pad_height, 0);
  634. width += pad_width;
  635. height += pad_height;
  636. }
  637. // unshuffle h
  638. cur = ggml_reshape_3d(ctx0, cur, n_embd * scale_factor, width / scale_factor, height);
  639. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  640. // unshuffle w
  641. cur = ggml_cont_3d(ctx0, cur, n_embd * scale_factor * scale_factor, height / scale_factor, width / scale_factor);
  642. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  643. cur = ggml_cont_2d(ctx0, cur, cur->ne[0], cur->ne[1] * cur->ne[2]);
  644. cb(cur, "pixel_shuffle", -1);
  645. return cur;
  646. }
  647. static ggml_cgraph * clip_image_build_graph(clip_ctx * ctx, const clip_image_f32_batch & imgs) {
  648. GGML_ASSERT(imgs.entries.size() == 1 && "n_batch > 1 is not supported");
  649. const clip_image_f32 & img = *imgs.entries[0];
  650. std::unique_ptr<clip_graph> builder;
  651. switch (ctx->proj_type()) {
  652. case PROJECTOR_TYPE_GEMMA3:
  653. case PROJECTOR_TYPE_IDEFICS3:
  654. case PROJECTOR_TYPE_LFM2:
  655. case PROJECTOR_TYPE_JANUS_PRO:
  656. {
  657. builder = std::make_unique<clip_graph_siglip>(ctx, img);
  658. } break;
  659. case PROJECTOR_TYPE_GEMMA3NV:
  660. {
  661. builder = std::make_unique<clip_graph_mobilenetv5>(ctx, img);
  662. } break;
  663. case PROJECTOR_TYPE_PIXTRAL:
  664. case PROJECTOR_TYPE_LIGHTONOCR:
  665. {
  666. builder = std::make_unique<clip_graph_pixtral>(ctx, img);
  667. } break;
  668. case PROJECTOR_TYPE_QWEN2VL:
  669. case PROJECTOR_TYPE_QWEN25VL:
  670. {
  671. builder = std::make_unique<clip_graph_qwen2vl>(ctx, img);
  672. } break;
  673. case PROJECTOR_TYPE_QWEN3VL:
  674. {
  675. builder = std::make_unique<clip_graph_qwen3vl>(ctx, img);
  676. } break;
  677. case PROJECTOR_TYPE_MINICPMV:
  678. {
  679. builder = std::make_unique<clip_graph_minicpmv>(ctx, img);
  680. } break;
  681. case PROJECTOR_TYPE_INTERNVL:
  682. {
  683. builder = std::make_unique<clip_graph_internvl>(ctx, img);
  684. } break;
  685. case PROJECTOR_TYPE_LLAMA4:
  686. {
  687. builder = std::make_unique<clip_graph_llama4>(ctx, img);
  688. } break;
  689. case PROJECTOR_TYPE_ULTRAVOX:
  690. case PROJECTOR_TYPE_VOXTRAL:
  691. case PROJECTOR_TYPE_QWEN2A:
  692. case PROJECTOR_TYPE_GLMA:
  693. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  694. {
  695. builder = std::make_unique<clip_graph_whisper_enc>(ctx, img);
  696. } break;
  697. case PROJECTOR_TYPE_KIMIVL:
  698. {
  699. builder = std::make_unique<clip_graph_kimivl>(ctx, img);
  700. } break;
  701. case PROJECTOR_TYPE_COGVLM:
  702. {
  703. builder = std::make_unique<clip_graph_cogvlm>(ctx, img);
  704. } break;
  705. case PROJECTOR_TYPE_MLP:
  706. case PROJECTOR_TYPE_MLP_NORM:
  707. case PROJECTOR_TYPE_LDP:
  708. case PROJECTOR_TYPE_LDPV2:
  709. case PROJECTOR_TYPE_GLM_EDGE:
  710. {
  711. builder = std::make_unique<clip_graph_llava>(ctx, img);
  712. } break;
  713. case PROJECTOR_TYPE_LFM2A:
  714. {
  715. builder = std::make_unique<clip_graph_conformer>(ctx, img);
  716. } break;
  717. case PROJECTOR_TYPE_GLM4V:
  718. {
  719. builder = std::make_unique<clip_graph_glm4v>(ctx, img);
  720. } break;
  721. case PROJECTOR_TYPE_YOUTUVL:
  722. {
  723. builder = std::make_unique<clip_graph_youtuvl>(ctx, img);
  724. } break;
  725. default:
  726. GGML_ABORT("missing cgraph builder");
  727. }
  728. return builder->build();
  729. }
  730. //
  731. // clip_model_loader
  732. //
  733. struct clip_model_loader {
  734. ggml_context_ptr ctx_meta;
  735. gguf_context_ptr ctx_gguf;
  736. std::string fname;
  737. size_t model_size = 0; // in bytes
  738. bool has_vision = false;
  739. bool has_audio = false;
  740. // TODO @ngxson : we should not pass clip_ctx here, it should be clip_model
  741. clip_model_loader(const char * fname) : fname(fname) {
  742. struct ggml_context * meta = nullptr;
  743. struct gguf_init_params params = {
  744. /*.no_alloc = */ true,
  745. /*.ctx = */ &meta,
  746. };
  747. ctx_gguf = gguf_context_ptr(gguf_init_from_file(fname, params));
  748. if (!ctx_gguf.get()) {
  749. throw std::runtime_error(string_format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  750. }
  751. ctx_meta.reset(meta);
  752. const int n_tensors = gguf_get_n_tensors(ctx_gguf.get());
  753. // print gguf info
  754. {
  755. std::string name;
  756. get_string(KEY_NAME, name, false);
  757. std::string description;
  758. get_string(KEY_DESCRIPTION, description, false);
  759. LOG_INF("%s: model name: %s\n", __func__, name.c_str());
  760. LOG_INF("%s: description: %s\n", __func__, description.c_str());
  761. LOG_INF("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx_gguf.get()));
  762. LOG_INF("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx_gguf.get()));
  763. LOG_INF("%s: n_tensors: %d\n", __func__, n_tensors);
  764. LOG_INF("%s: n_kv: %d\n", __func__, (int)gguf_get_n_kv(ctx_gguf.get()));
  765. LOG_INF("\n");
  766. }
  767. // modalities
  768. {
  769. get_bool(KEY_HAS_VISION_ENC, has_vision, false);
  770. get_bool(KEY_HAS_AUDIO_ENC, has_audio, false);
  771. if (has_vision) {
  772. LOG_INF("%s: has vision encoder\n", __func__);
  773. }
  774. if (has_audio) {
  775. LOG_INF("%s: has audio encoder\n", __func__);
  776. }
  777. }
  778. // tensors
  779. {
  780. for (int i = 0; i < n_tensors; ++i) {
  781. const char * name = gguf_get_tensor_name(ctx_gguf.get(), i);
  782. const size_t offset = gguf_get_tensor_offset(ctx_gguf.get(), i);
  783. enum ggml_type type = gguf_get_tensor_type(ctx_gguf.get(), i);
  784. ggml_tensor * cur = ggml_get_tensor(meta, name);
  785. size_t tensor_size = ggml_nbytes(cur);
  786. model_size += tensor_size;
  787. LOG_DBG("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu, shape:[%" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "], type = %s\n",
  788. __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));
  789. }
  790. }
  791. }
  792. void load_hparams(clip_model & model, clip_modality modality) {
  793. auto & hparams = model.hparams;
  794. std::string log_ffn_op; // for logging
  795. // sanity check
  796. if (modality == CLIP_MODALITY_VISION) {
  797. GGML_ASSERT(has_vision);
  798. } else if (modality == CLIP_MODALITY_AUDIO) {
  799. GGML_ASSERT(has_audio);
  800. }
  801. model.modality = modality;
  802. // projector type
  803. std::string proj_type;
  804. {
  805. // default key
  806. get_string(KEY_PROJ_TYPE, proj_type, false);
  807. // for models with mixed modalities
  808. if (proj_type.empty()) {
  809. if (modality == CLIP_MODALITY_VISION) {
  810. get_string(KEY_VISION_PROJ_TYPE, proj_type, false);
  811. } else if (modality == CLIP_MODALITY_AUDIO) {
  812. get_string(KEY_AUDIO_PROJ_TYPE, proj_type, false);
  813. } else {
  814. GGML_ABORT("unknown modality");
  815. }
  816. }
  817. model.proj_type = clip_projector_type_from_string(proj_type);
  818. if (model.proj_type == PROJECTOR_TYPE_UNKNOWN) {
  819. throw std::runtime_error(string_format("%s: unknown projector type: %s\n", __func__, proj_type.c_str()));
  820. }
  821. // correct arch for multimodal models (legacy method)
  822. if (model.proj_type == PROJECTOR_TYPE_QWEN25O) {
  823. model.proj_type = modality == CLIP_MODALITY_VISION
  824. ? PROJECTOR_TYPE_QWEN25VL
  825. : PROJECTOR_TYPE_QWEN2A;
  826. }
  827. }
  828. const bool is_vision = model.modality == CLIP_MODALITY_VISION;
  829. const bool is_audio = model.modality == CLIP_MODALITY_AUDIO;
  830. // other hparams
  831. {
  832. const char * prefix = is_vision ? "vision" : "audio";
  833. get_u32(string_format(KEY_N_EMBD, prefix), hparams.n_embd);
  834. get_u32(string_format(KEY_N_HEAD, prefix), hparams.n_head);
  835. get_u32(string_format(KEY_N_FF, prefix), hparams.n_ff);
  836. get_u32(string_format(KEY_N_BLOCK, prefix), hparams.n_layer);
  837. get_u32(string_format(KEY_PROJ_DIM, prefix), hparams.projection_dim);
  838. get_f32(string_format(KEY_LAYER_NORM_EPS, prefix), hparams.eps);
  839. if (is_vision) {
  840. get_u32(KEY_IMAGE_SIZE, hparams.image_size);
  841. get_u32(KEY_PATCH_SIZE, hparams.patch_size);
  842. get_u32(KEY_IMAGE_CROP_RESOLUTION, hparams.image_crop_resolution, false);
  843. get_i32(KEY_MINICPMV_VERSION, hparams.minicpmv_version, false); // legacy
  844. get_u32(KEY_MINICPMV_QUERY_NUM, hparams.minicpmv_query_num, false);
  845. if (hparams.minicpmv_query_num == 0) {
  846. // Fallback to hardcoded values for legacy models
  847. if (hparams.minicpmv_version == 3) {
  848. hparams.minicpmv_query_num = 64;
  849. } else if (hparams.minicpmv_version == 4) {
  850. hparams.minicpmv_query_num = 64;
  851. } else if (hparams.minicpmv_version == 5) {
  852. hparams.minicpmv_query_num = 64;
  853. } else if (hparams.minicpmv_version == 6) {
  854. hparams.minicpmv_query_num = 64;
  855. } else {
  856. hparams.minicpmv_query_num = 96;
  857. }
  858. }
  859. } else if (is_audio) {
  860. get_u32(KEY_A_NUM_MEL_BINS, hparams.n_mel_bins);
  861. // some hparams are unused, but still need to set to avoid issues
  862. hparams.image_size = 0;
  863. hparams.patch_size = 1;
  864. } else {
  865. GGML_ASSERT(false && "unknown modality");
  866. }
  867. // for pinpoints, we need to convert it into a list of resolution candidates
  868. {
  869. std::vector<int> pinpoints;
  870. get_arr_int(KEY_IMAGE_GRID_PINPOINTS, pinpoints, false);
  871. if (!pinpoints.empty()) {
  872. for (size_t i = 0; i < pinpoints.size(); i += 2) {
  873. hparams.image_res_candidates.push_back({
  874. pinpoints[i],
  875. pinpoints[i+1],
  876. });
  877. }
  878. }
  879. }
  880. // default warmup value
  881. hparams.warmup_image_size = hparams.image_size;
  882. hparams.has_llava_projector = model.proj_type == PROJECTOR_TYPE_MLP
  883. || model.proj_type == PROJECTOR_TYPE_MLP_NORM
  884. || model.proj_type == PROJECTOR_TYPE_LDP
  885. || model.proj_type == PROJECTOR_TYPE_LDPV2;
  886. {
  887. bool use_gelu = false;
  888. bool use_silu = false;
  889. get_bool(KEY_USE_GELU, use_gelu, false);
  890. get_bool(KEY_USE_SILU, use_silu, false);
  891. if (use_gelu && use_silu) {
  892. throw std::runtime_error(string_format("%s: both use_gelu and use_silu are set to true\n", __func__));
  893. }
  894. if (use_gelu) {
  895. hparams.ffn_op = FFN_GELU;
  896. log_ffn_op = "gelu";
  897. } else if (use_silu) {
  898. hparams.ffn_op = FFN_SILU;
  899. log_ffn_op = "silu";
  900. } else {
  901. hparams.ffn_op = FFN_GELU_QUICK;
  902. log_ffn_op = "gelu_quick";
  903. }
  904. }
  905. {
  906. std::string mm_patch_merge_type;
  907. get_string(KEY_MM_PATCH_MERGE_TYPE, mm_patch_merge_type, false);
  908. if (mm_patch_merge_type == "spatial_unpad") {
  909. hparams.mm_patch_merge_type = PATCH_MERGE_SPATIAL_UNPAD;
  910. }
  911. }
  912. if (is_vision) {
  913. int idx_mean = gguf_find_key(ctx_gguf.get(), KEY_IMAGE_MEAN);
  914. int idx_std = gguf_find_key(ctx_gguf.get(), KEY_IMAGE_STD);
  915. GGML_ASSERT(idx_mean >= 0 && "image_mean not found");
  916. GGML_ASSERT(idx_std >= 0 && "image_std not found");
  917. const float * mean_data = (const float *) gguf_get_arr_data(ctx_gguf.get(), idx_mean);
  918. const float * std_data = (const float *) gguf_get_arr_data(ctx_gguf.get(), idx_std);
  919. for (int i = 0; i < 3; ++i) {
  920. hparams.image_mean[i] = mean_data[i];
  921. hparams.image_std[i] = std_data[i];
  922. }
  923. }
  924. // Load the vision feature layer indices if they are explicitly provided;
  925. // if multiple vision feature layers are present, the values will be concatenated
  926. // to form the final visual features.
  927. // NOTE: gguf conversions should standardize the values of the vision feature layer to
  928. // be non-negative, since we use -1 to mark values as unset here.
  929. std::vector<int> vision_feature_layer;
  930. get_arr_int(KEY_FEATURE_LAYER, vision_feature_layer, false);
  931. // convert std::vector to std::unordered_set
  932. for (auto & layer : vision_feature_layer) {
  933. hparams.vision_feature_layer.insert(layer);
  934. }
  935. // model-specific params
  936. switch (model.proj_type) {
  937. case PROJECTOR_TYPE_MINICPMV:
  938. {
  939. if (hparams.minicpmv_version == 0) {
  940. hparams.minicpmv_version = 2; // default to 2 if not set
  941. }
  942. } break;
  943. case PROJECTOR_TYPE_INTERNVL:
  944. {
  945. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  946. } break;
  947. case PROJECTOR_TYPE_IDEFICS3:
  948. {
  949. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  950. get_u32(KEY_PREPROC_IMAGE_SIZE, hparams.image_longest_edge, false);
  951. } break;
  952. case PROJECTOR_TYPE_LFM2:
  953. {
  954. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  955. // ref: https://huggingface.co/LiquidAI/LFM2-VL-3B/blob/main/preprocessor_config.json
  956. // config above specifies number of tokens after downsampling, while here it is before, relax lowerbound to 64
  957. hparams.set_limit_image_tokens(64, 1024);
  958. } break;
  959. case PROJECTOR_TYPE_PIXTRAL:
  960. case PROJECTOR_TYPE_LIGHTONOCR:
  961. {
  962. // ref: https://huggingface.co/mistral-community/pixtral-12b/blob/main/preprocessor_config.json
  963. // TODO: verify the image_min_tokens
  964. hparams.n_merge = 1; // the original pixtral does not use patch merging
  965. hparams.rope_theta = 10000.0f;
  966. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  967. hparams.set_limit_image_tokens(8, 1024);
  968. hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
  969. } break;
  970. case PROJECTOR_TYPE_KIMIVL:
  971. {
  972. hparams.rope_theta = 10000.0f;
  973. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  974. // TODO: check kimivl preprocessor for exact values
  975. hparams.set_limit_image_tokens(8, 1024);
  976. hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
  977. } break;
  978. case PROJECTOR_TYPE_GEMMA3:
  979. {
  980. // default value (used by all model sizes in gemma 3 family)
  981. // number of patches for each **side** is reduced by a factor of 4
  982. hparams.n_merge = 4;
  983. // test model (tinygemma3) has a different value, we optionally read it
  984. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  985. } break;
  986. case PROJECTOR_TYPE_GEMMA3NV:
  987. {
  988. // Gemma3n uses MobileNetV5 which produces 256 tokens (16x16)
  989. // Similar configuration to Gemma3
  990. hparams.n_merge = 1; // MobileNetV5 handles resizing internally
  991. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  992. } break;
  993. case PROJECTOR_TYPE_QWEN2VL:
  994. case PROJECTOR_TYPE_QWEN25VL:
  995. case PROJECTOR_TYPE_QWEN3VL:
  996. {
  997. hparams.n_merge = 2; // default value for Qwen 2 and 2.5
  998. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  999. get_u32(KEY_WIN_ATTN_PATTERN, hparams.n_wa_pattern, model.proj_type == PROJECTOR_TYPE_QWEN25VL); // only 2.5 requires it
  1000. // ref: https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct/blob/main/preprocessor_config.json
  1001. hparams.set_limit_image_tokens(8, 4096);
  1002. hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
  1003. const int warn_min_pixels = 1024 * hparams.n_merge * hparams.n_merge * hparams.patch_size * hparams.patch_size;
  1004. if (hparams.image_min_pixels < warn_min_pixels) {
  1005. LOG_WRN("%s: Qwen-VL models require at minimum 1024 image tokens to function correctly on grounding tasks\n", __func__);
  1006. LOG_WRN("%s: if you encounter problems with accuracy, try adding --image-min-tokens 1024\n", __func__);
  1007. LOG_WRN("%s: more info: https://github.com/ggml-org/llama.cpp/issues/16842\n\n", __func__);
  1008. }
  1009. } break;
  1010. case PROJECTOR_TYPE_YOUTUVL:
  1011. {
  1012. hparams.n_merge = 2;
  1013. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  1014. get_u32(KEY_ATTN_WINDOW_SIZE, hparams.attn_window_size, true);
  1015. std::vector<int> wa_layer_indexes_vec;
  1016. get_arr_int(KEY_WIN_ATTN_LAYER_INDEXES, wa_layer_indexes_vec, true);
  1017. for (auto & layer : wa_layer_indexes_vec) {
  1018. hparams.wa_layer_indexes.insert(layer);
  1019. }
  1020. // support max_height * max_width = 8000 * 8000. 8000/16/2 = 250 image tokens
  1021. hparams.set_limit_image_tokens(1, 62500);
  1022. hparams.set_warmup_n_tokens(16*16); // avoid OOM on warmup
  1023. } break;
  1024. case PROJECTOR_TYPE_GLM4V:
  1025. {
  1026. hparams.rope_theta = 10000.0f;
  1027. hparams.n_merge = 2; // default value for GLM4-V
  1028. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  1029. hparams.set_limit_image_tokens(8, 4096);
  1030. hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
  1031. } break;
  1032. case PROJECTOR_TYPE_LLAMA4:
  1033. {
  1034. hparams.rope_theta = 10000.0f;
  1035. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  1036. set_llava_uhd_res_candidates(model, 3);
  1037. } break;
  1038. case PROJECTOR_TYPE_ULTRAVOX:
  1039. case PROJECTOR_TYPE_QWEN2A:
  1040. case PROJECTOR_TYPE_GLMA:
  1041. case PROJECTOR_TYPE_VOXTRAL:
  1042. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  1043. {
  1044. bool require_stack = model.proj_type == PROJECTOR_TYPE_ULTRAVOX ||
  1045. model.proj_type == PROJECTOR_TYPE_VOXTRAL ||
  1046. model.proj_type == PROJECTOR_TYPE_GLMA;
  1047. get_u32(KEY_A_PROJ_STACK_FACTOR, hparams.proj_stack_factor, require_stack);
  1048. hparams.ffn_op = FFN_GELU_ERF;
  1049. log_ffn_op = "gelu_erf"; // temporary solution for logging
  1050. // audio preprocessing params
  1051. hparams.audio_chunk_len = 30; // in seconds
  1052. hparams.audio_sample_rate = 16000;
  1053. hparams.audio_n_fft = 400;
  1054. hparams.audio_window_len = 400;
  1055. hparams.audio_hop_len = 160;
  1056. } break;
  1057. case PROJECTOR_TYPE_LFM2A:
  1058. {
  1059. // audio preprocessing params
  1060. hparams.audio_chunk_len = 1; // in seconds
  1061. hparams.audio_sample_rate = 16000;
  1062. hparams.audio_n_fft = 512;
  1063. hparams.audio_window_len = 400;
  1064. hparams.audio_hop_len = 160;
  1065. } break;
  1066. default:
  1067. break;
  1068. }
  1069. // sanity check
  1070. {
  1071. if (hparams.image_max_pixels < hparams.image_min_pixels) {
  1072. throw std::runtime_error(string_format("%s: image_max_pixels (%d) is less than image_min_pixels (%d)\n", __func__, hparams.image_max_pixels, hparams.image_min_pixels));
  1073. }
  1074. }
  1075. LOG_INF("%s: projector: %s\n", __func__, proj_type.c_str());
  1076. LOG_INF("%s: n_embd: %d\n", __func__, hparams.n_embd);
  1077. LOG_INF("%s: n_head: %d\n", __func__, hparams.n_head);
  1078. LOG_INF("%s: n_ff: %d\n", __func__, hparams.n_ff);
  1079. LOG_INF("%s: n_layer: %d\n", __func__, hparams.n_layer);
  1080. LOG_INF("%s: ffn_op: %s\n", __func__, log_ffn_op.c_str());
  1081. LOG_INF("%s: projection_dim: %d\n", __func__, hparams.projection_dim);
  1082. if (is_vision) {
  1083. LOG_INF("\n--- vision hparams ---\n");
  1084. LOG_INF("%s: image_size: %d\n", __func__, hparams.image_size);
  1085. LOG_INF("%s: patch_size: %d\n", __func__, hparams.patch_size);
  1086. LOG_INF("%s: has_llava_proj: %d\n", __func__, hparams.has_llava_projector);
  1087. LOG_INF("%s: minicpmv_version: %d\n", __func__, hparams.minicpmv_version);
  1088. LOG_INF("%s: n_merge: %d\n", __func__, hparams.n_merge);
  1089. LOG_INF("%s: n_wa_pattern: %d\n", __func__, hparams.n_wa_pattern);
  1090. if (!hparams.wa_layer_indexes.empty()) {
  1091. LOG_INF("%s: wa_layer_indexes: ", __func__);
  1092. for (auto & layer : hparams.wa_layer_indexes) {
  1093. LOG_INF("%d ", layer);
  1094. }
  1095. LOG_INF("\n");
  1096. }
  1097. if (hparams.image_min_pixels > 0) {
  1098. LOG_INF("%s: image_min_pixels: %d%s\n", __func__, hparams.image_min_pixels, hparams.custom_image_min_tokens > 0 ? " (custom value)" : "");
  1099. }
  1100. if (hparams.image_max_pixels > 0) {
  1101. LOG_INF("%s: image_max_pixels: %d%s\n", __func__, hparams.image_max_pixels, hparams.custom_image_max_tokens > 0 ? " (custom value)" : "");
  1102. }
  1103. } else if (is_audio) {
  1104. LOG_INF("\n--- audio hparams ---\n");
  1105. LOG_INF("%s: n_mel_bins: %d\n", __func__, hparams.n_mel_bins);
  1106. LOG_INF("%s: proj_stack_factor: %d\n", __func__, hparams.proj_stack_factor);
  1107. LOG_INF("%s: audio_chunk_len: %d\n", __func__, hparams.audio_chunk_len);
  1108. LOG_INF("%s: audio_sample_rate: %d\n", __func__, hparams.audio_sample_rate);
  1109. LOG_INF("%s: audio_n_fft: %d\n", __func__, hparams.audio_n_fft);
  1110. LOG_INF("%s: audio_window_len: %d\n", __func__, hparams.audio_window_len);
  1111. LOG_INF("%s: audio_hop_len: %d\n", __func__, hparams.audio_hop_len);
  1112. }
  1113. LOG_INF("\n");
  1114. LOG_INF("%s: model size: %.2f MiB\n", __func__, model_size / 1024.0 / 1024.0);
  1115. LOG_INF("%s: metadata size: %.2f MiB\n", __func__, ggml_get_mem_size(ctx_meta.get()) / 1024.0 / 1024.0);
  1116. }
  1117. }
  1118. void load_tensors(clip_ctx & ctx_clip) {
  1119. auto & model = ctx_clip.model;
  1120. auto & hparams = model.hparams;
  1121. std::map<std::string, size_t> tensor_offset;
  1122. std::vector<ggml_tensor *> tensors_to_load;
  1123. // TODO @ngxson : support both audio and video in the future
  1124. const char * prefix = model.modality == CLIP_MODALITY_AUDIO ? "a" : "v";
  1125. // get offsets
  1126. for (int64_t i = 0; i < gguf_get_n_tensors(ctx_gguf.get()); ++i) {
  1127. const char * name = gguf_get_tensor_name(ctx_gguf.get(), i);
  1128. tensor_offset[name] = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), i);
  1129. }
  1130. // create data context
  1131. struct ggml_init_params params = {
  1132. /*.mem_size =*/ static_cast<size_t>(gguf_get_n_tensors(ctx_gguf.get()) + 1) * ggml_tensor_overhead(),
  1133. /*.mem_buffer =*/ NULL,
  1134. /*.no_alloc =*/ true,
  1135. };
  1136. ctx_clip.ctx_data.reset(ggml_init(params));
  1137. if (!ctx_clip.ctx_data) {
  1138. throw std::runtime_error(string_format("%s: failed to init ggml context\n", __func__));
  1139. }
  1140. // helper function
  1141. auto get_tensor = [&](const std::string & name, bool required = true) {
  1142. ggml_tensor * cur = ggml_get_tensor(ctx_meta.get(), name.c_str());
  1143. if (!cur && required) {
  1144. throw std::runtime_error(string_format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  1145. }
  1146. if (cur) {
  1147. tensors_to_load.push_back(cur);
  1148. // add tensors to context
  1149. ggml_tensor * data_tensor = ggml_dup_tensor(ctx_clip.ctx_data.get(), cur);
  1150. ggml_set_name(data_tensor, cur->name);
  1151. cur = data_tensor;
  1152. }
  1153. return cur;
  1154. };
  1155. model.class_embedding = get_tensor(TN_CLASS_EMBD, false);
  1156. model.pre_ln_w = get_tensor(string_format(TN_LN_PRE, prefix, "weight"), false);
  1157. model.pre_ln_b = get_tensor(string_format(TN_LN_PRE, prefix, "bias"), false);
  1158. model.post_ln_w = get_tensor(string_format(TN_LN_POST, prefix, "weight"), false);
  1159. model.post_ln_b = get_tensor(string_format(TN_LN_POST, prefix, "bias"), false);
  1160. model.patch_bias = get_tensor(TN_PATCH_BIAS, false);
  1161. model.patch_embeddings_0 = get_tensor(TN_PATCH_EMBD, false);
  1162. model.patch_embeddings_1 = get_tensor(TN_PATCH_EMBD_1, false);
  1163. model.norm_embd_w = get_tensor(string_format(TN_NORM_EMBD, "weight"), false);
  1164. model.norm_embd_b = get_tensor(string_format(TN_NORM_EMBD, "bias"), false);
  1165. model.position_embeddings = get_tensor(string_format(TN_POS_EMBD, prefix), false);
  1166. if (model.proj_type == PROJECTOR_TYPE_GEMMA3NV) {
  1167. hparams.n_layer = 0; // gemma3n does not use normal layer structure
  1168. }
  1169. // layers
  1170. model.layers.resize(hparams.n_layer);
  1171. for (int il = 0; il < hparams.n_layer; ++il) {
  1172. auto & layer = model.layers[il];
  1173. layer.k_w = get_tensor(string_format(TN_ATTN_K, prefix, il, "weight"), false);
  1174. layer.q_w = get_tensor(string_format(TN_ATTN_Q, prefix, il, "weight"), false);
  1175. layer.v_w = get_tensor(string_format(TN_ATTN_V, prefix, il, "weight"), false);
  1176. layer.o_w = get_tensor(string_format(TN_ATTN_OUTPUT, prefix, il, "weight"));
  1177. layer.qkv_w = get_tensor(string_format(TN_ATTN_QKV, prefix, il, "weight"), false);
  1178. layer.k_norm = get_tensor(string_format(TN_ATTN_K_NORM, prefix, il, "weight"), false);
  1179. layer.q_norm = get_tensor(string_format(TN_ATTN_Q_NORM, prefix, il, "weight"), false);
  1180. layer.ln_1_w = get_tensor(string_format(TN_LN_1, prefix, il, "weight"), false);
  1181. layer.ln_2_w = get_tensor(string_format(TN_LN_2, prefix, il, "weight"), false);
  1182. layer.ls_1_w = get_tensor(string_format(TN_LS_1, prefix, il, "weight"), false); // no bias
  1183. layer.ls_2_w = get_tensor(string_format(TN_LS_2, prefix, il, "weight"), false); // no bias
  1184. layer.k_b = get_tensor(string_format(TN_ATTN_K, prefix, il, "bias"), false);
  1185. layer.q_b = get_tensor(string_format(TN_ATTN_Q, prefix, il, "bias"), false);
  1186. layer.v_b = get_tensor(string_format(TN_ATTN_V, prefix, il, "bias"), false);
  1187. layer.o_b = get_tensor(string_format(TN_ATTN_OUTPUT, prefix, il, "bias"), false);
  1188. layer.qkv_b = get_tensor(string_format(TN_ATTN_QKV, prefix, il, "bias"), false);
  1189. layer.ln_1_b = get_tensor(string_format(TN_LN_1, prefix, il, "bias"), false);
  1190. layer.ln_2_b = get_tensor(string_format(TN_LN_2, prefix, il, "bias"), false);
  1191. // ffn
  1192. layer.ff_up_w = get_tensor(string_format(TN_FFN_UP, prefix, il, "weight"));
  1193. layer.ff_up_b = get_tensor(string_format(TN_FFN_UP, prefix, il, "bias"), false);
  1194. layer.ff_gate_w = get_tensor(string_format(TN_FFN_GATE, prefix, il, "weight"), false);
  1195. layer.ff_gate_b = get_tensor(string_format(TN_FFN_GATE, prefix, il, "bias"), false);
  1196. layer.ff_down_w = get_tensor(string_format(TN_FFN_DOWN, prefix, il, "weight"));
  1197. layer.ff_down_b = get_tensor(string_format(TN_FFN_DOWN, prefix, il, "bias"), false);
  1198. // qwen3vl deepstack layer
  1199. layer.deepstack_norm_w = get_tensor(string_format(TN_DEEPSTACK_NORM, il, "weight"), false);
  1200. layer.deepstack_norm_b = get_tensor(string_format(TN_DEEPSTACK_NORM, il, "bias"), false);
  1201. layer.deepstack_fc1_w = get_tensor(string_format(TN_DEEPSTACK_FC1, il, "weight"), false);
  1202. layer.deepstack_fc1_b = get_tensor(string_format(TN_DEEPSTACK_FC1, il, "bias"), false);
  1203. layer.deepstack_fc2_w = get_tensor(string_format(TN_DEEPSTACK_FC2, il, "weight"), false);
  1204. layer.deepstack_fc2_b = get_tensor(string_format(TN_DEEPSTACK_FC2, il, "bias"), false);
  1205. if (layer.has_deepstack()) {
  1206. model.n_deepstack_layers++;
  1207. }
  1208. // some models already exported with legacy (incorrect) naming which is quite messy, let's fix it here
  1209. // note: Qwen model converted from the old surgery script has n_ff = 0, so we cannot use n_ff to check!
  1210. bool is_ffn_swapped = (
  1211. // only old models need this fix
  1212. model.proj_type == PROJECTOR_TYPE_MLP
  1213. || model.proj_type == PROJECTOR_TYPE_MLP_NORM
  1214. || model.proj_type == PROJECTOR_TYPE_LDP
  1215. || model.proj_type == PROJECTOR_TYPE_LDPV2
  1216. || model.proj_type == PROJECTOR_TYPE_QWEN2VL
  1217. || model.proj_type == PROJECTOR_TYPE_QWEN25VL
  1218. || model.proj_type == PROJECTOR_TYPE_GLM_EDGE
  1219. || model.proj_type == PROJECTOR_TYPE_GEMMA3
  1220. || model.proj_type == PROJECTOR_TYPE_IDEFICS3
  1221. || model.proj_type == PROJECTOR_TYPE_MINICPMV
  1222. ) && layer.ff_up_w && layer.ff_down_w && layer.ff_down_w->ne[0] == hparams.n_embd;
  1223. if (is_ffn_swapped) {
  1224. // swap up and down weights
  1225. ggml_tensor * tmp = layer.ff_up_w;
  1226. layer.ff_up_w = layer.ff_down_w;
  1227. layer.ff_down_w = tmp;
  1228. // swap up and down biases
  1229. tmp = layer.ff_up_b;
  1230. layer.ff_up_b = layer.ff_down_b;
  1231. layer.ff_down_b = tmp;
  1232. if (il == 0) {
  1233. LOG_WRN("%s: ffn up/down are swapped\n", __func__);
  1234. }
  1235. }
  1236. }
  1237. switch (model.proj_type) {
  1238. case PROJECTOR_TYPE_MLP:
  1239. case PROJECTOR_TYPE_MLP_NORM:
  1240. {
  1241. // LLaVA projection
  1242. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"), false);
  1243. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"), false);
  1244. // Yi-type llava
  1245. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"), false);
  1246. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1247. // missing in Yi-type llava
  1248. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"), false);
  1249. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1250. // Yi-type llava
  1251. model.mm_3_w = get_tensor(string_format(TN_LLAVA_PROJ, 3, "weight"), false);
  1252. model.mm_3_b = get_tensor(string_format(TN_LLAVA_PROJ, 3, "bias"), false);
  1253. model.mm_4_w = get_tensor(string_format(TN_LLAVA_PROJ, 4, "weight"), false);
  1254. model.mm_4_b = get_tensor(string_format(TN_LLAVA_PROJ, 4, "bias"), false);
  1255. if (model.mm_3_w) {
  1256. // TODO: this is a hack to support Yi-type llava
  1257. model.proj_type = PROJECTOR_TYPE_MLP_NORM;
  1258. }
  1259. model.image_newline = get_tensor(TN_IMAGE_NEWLINE, false);
  1260. } break;
  1261. case PROJECTOR_TYPE_LDP:
  1262. {
  1263. // MobileVLM projection
  1264. model.mm_model_mlp_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1265. model.mm_model_mlp_1_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "bias"));
  1266. model.mm_model_mlp_3_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "weight"));
  1267. model.mm_model_mlp_3_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "bias"));
  1268. model.mm_model_block_1_block_0_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "0.weight"));
  1269. model.mm_model_block_1_block_0_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.weight"));
  1270. model.mm_model_block_1_block_0_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.bias"));
  1271. model.mm_model_block_1_block_1_fc1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.weight"));
  1272. model.mm_model_block_1_block_1_fc1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.bias"));
  1273. model.mm_model_block_1_block_1_fc2_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.weight"));
  1274. model.mm_model_block_1_block_1_fc2_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.bias"));
  1275. model.mm_model_block_1_block_2_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "0.weight"));
  1276. model.mm_model_block_1_block_2_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.weight"));
  1277. model.mm_model_block_1_block_2_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.bias"));
  1278. model.mm_model_block_2_block_0_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "0.weight"));
  1279. model.mm_model_block_2_block_0_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.weight"));
  1280. model.mm_model_block_2_block_0_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.bias"));
  1281. model.mm_model_block_2_block_1_fc1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.weight"));
  1282. model.mm_model_block_2_block_1_fc1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.bias"));
  1283. model.mm_model_block_2_block_1_fc2_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.weight"));
  1284. model.mm_model_block_2_block_1_fc2_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.bias"));
  1285. model.mm_model_block_2_block_2_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "0.weight"));
  1286. model.mm_model_block_2_block_2_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.weight"));
  1287. model.mm_model_block_2_block_2_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.bias"));
  1288. } break;
  1289. case PROJECTOR_TYPE_LDPV2:
  1290. {
  1291. // MobilVLM_V2 projection
  1292. model.mm_model_mlp_0_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "weight"));
  1293. model.mm_model_mlp_0_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "bias"));
  1294. model.mm_model_mlp_2_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "weight"));
  1295. model.mm_model_mlp_2_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "bias"));
  1296. model.mm_model_peg_0_w = get_tensor(string_format(TN_MVLM_PROJ_PEG, 0, "weight"));
  1297. model.mm_model_peg_0_b = get_tensor(string_format(TN_MVLM_PROJ_PEG, 0, "bias"));
  1298. } break;
  1299. case PROJECTOR_TYPE_MINICPMV:
  1300. {
  1301. // model.mm_model_pos_embed = get_tensor(new_clip->ctx_data, TN_MINICPMV_POS_EMBD);
  1302. model.mm_model_pos_embed_k = get_tensor(TN_MINICPMV_POS_EMBD_K);
  1303. model.mm_model_query = get_tensor(TN_MINICPMV_QUERY);
  1304. model.mm_model_proj = get_tensor(TN_MINICPMV_PROJ);
  1305. model.mm_model_kv_proj = get_tensor(TN_MINICPMV_KV_PROJ);
  1306. model.mm_model_attn_q_w = get_tensor(string_format(TN_MINICPMV_ATTN, "q", "weight"));
  1307. model.mm_model_attn_k_w = get_tensor(string_format(TN_MINICPMV_ATTN, "k", "weight"));
  1308. model.mm_model_attn_v_w = get_tensor(string_format(TN_MINICPMV_ATTN, "v", "weight"));
  1309. model.mm_model_attn_q_b = get_tensor(string_format(TN_MINICPMV_ATTN, "q", "bias"));
  1310. model.mm_model_attn_k_b = get_tensor(string_format(TN_MINICPMV_ATTN, "k", "bias"));
  1311. model.mm_model_attn_v_b = get_tensor(string_format(TN_MINICPMV_ATTN, "v", "bias"));
  1312. model.mm_model_attn_o_w = get_tensor(string_format(TN_MINICPMV_ATTN, "out", "weight"));
  1313. model.mm_model_attn_o_b = get_tensor(string_format(TN_MINICPMV_ATTN, "out", "bias"));
  1314. model.mm_model_ln_q_w = get_tensor(string_format(TN_MINICPMV_LN, "q", "weight"));
  1315. model.mm_model_ln_q_b = get_tensor(string_format(TN_MINICPMV_LN, "q", "bias"));
  1316. model.mm_model_ln_kv_w = get_tensor(string_format(TN_MINICPMV_LN, "kv", "weight"));
  1317. model.mm_model_ln_kv_b = get_tensor(string_format(TN_MINICPMV_LN, "kv", "bias"));
  1318. model.mm_model_ln_post_w = get_tensor(string_format(TN_MINICPMV_LN, "post", "weight"));
  1319. model.mm_model_ln_post_b = get_tensor(string_format(TN_MINICPMV_LN, "post", "bias"));
  1320. } break;
  1321. case PROJECTOR_TYPE_GLM_EDGE:
  1322. {
  1323. model.mm_model_adapter_conv_w = get_tensor(string_format(TN_GLM_ADAPER_CONV, "weight"));
  1324. model.mm_model_adapter_conv_b = get_tensor(string_format(TN_GLM_ADAPER_CONV, "bias"));
  1325. model.mm_model_mlp_0_w = get_tensor(string_format(TN_GLM_ADAPTER_LINEAR, "weight"));
  1326. model.mm_model_ln_q_w = get_tensor(string_format(TN_GLM_ADAPTER_NORM_1, "weight"));
  1327. model.mm_model_ln_q_b = get_tensor(string_format(TN_GLM_ADAPTER_NORM_1, "bias"));
  1328. model.mm_model_mlp_1_w = get_tensor(string_format(TN_GLM_ADAPTER_D_H_2_4H, "weight"));
  1329. model.mm_model_mlp_2_w = get_tensor(string_format(TN_GLM_ADAPTER_GATE, "weight"));
  1330. model.mm_model_mlp_3_w = get_tensor(string_format(TN_GLM_ADAPTER_D_4H_2_H, "weight"));
  1331. model.mm_boi = get_tensor(string_format(TN_TOK_GLM_BOI));
  1332. model.mm_eoi = get_tensor(string_format(TN_TOK_GLM_EOI));
  1333. } break;
  1334. case PROJECTOR_TYPE_QWEN2VL:
  1335. case PROJECTOR_TYPE_QWEN25VL:
  1336. {
  1337. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1338. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1339. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1340. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1341. } break;
  1342. case PROJECTOR_TYPE_QWEN3VL:
  1343. {
  1344. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1345. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1346. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1347. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1348. } break;
  1349. case PROJECTOR_TYPE_YOUTUVL:
  1350. {
  1351. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM); // merger.ln_q (RMS norm)
  1352. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight")); // merger.mlp.0
  1353. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1354. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight")); // merger.mlp.2
  1355. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1356. } break;
  1357. case PROJECTOR_TYPE_GLM4V:
  1358. {
  1359. model.projection = get_tensor(TN_MM_PROJECTOR);
  1360. model.mm_ffn_up_w = get_tensor(string_format(TN_MM_UP, "weight"));
  1361. model.mm_ffn_up_b = get_tensor(string_format(TN_MM_UP, "bias"), false);
  1362. model.mm_ffn_gate_w = get_tensor(string_format(TN_MM_GATE, "weight"));
  1363. model.mm_ffn_gate_b = get_tensor(string_format(TN_MM_GATE, "bias"), false);
  1364. model.mm_ffn_down_w = get_tensor(string_format(TN_MM_DOWN, "weight"));
  1365. model.mm_ffn_down_b = get_tensor(string_format(TN_MM_DOWN, "bias"), false);
  1366. model.mm_post_norm_w = get_tensor(string_format(TN_MM_POST_NORM, "weight"));
  1367. model.mm_post_norm_b = get_tensor(string_format(TN_MM_POST_NORM, "bias"), false);
  1368. model.mm_patch_merger_w = get_tensor(string_format(TN_MM_PATCH_MERGER, "weight"));
  1369. model.mm_patch_merger_b = get_tensor(string_format(TN_MM_PATCH_MERGER, "bias"));
  1370. } break;
  1371. case PROJECTOR_TYPE_GEMMA3:
  1372. {
  1373. model.mm_input_proj_w = get_tensor(TN_MM_INP_PROJ);
  1374. model.mm_soft_emb_norm_w = get_tensor(TN_MM_SOFT_EMB_N);
  1375. } break;
  1376. case PROJECTOR_TYPE_GEMMA3NV:
  1377. {
  1378. model.mobilenet_stem_conv_w = get_tensor(TN_MNV5_STEM_CONV, false);
  1379. model.mobilenet_stem_conv_b = get_tensor(TN_MNV5_STEM_BIAS, false);
  1380. model.mobilenet_stem_norm_w = get_tensor(TN_MNV5_STEM_BN, false);
  1381. model.msfa_ffn_expand_w = get_tensor(TN_MNV5_MSFA_FFN_EXP_W, false);
  1382. model.msfa_ffn_expand_bn = get_tensor(TN_MNV5_MSFA_FFN_EXP_BN, false); // Consume BN if present but likely folded
  1383. model.msfa_ffn_project_w = get_tensor(TN_MNV5_MSFA_FFN_PROJ_W, false);
  1384. model.msfa_ffn_project_bn = get_tensor(TN_MNV5_MSFA_FFN_PROJ_BN, false);
  1385. model.msfa_concat_norm_w = get_tensor(TN_MNV5_MSFA_NORM, false);
  1386. // Dynamically load blocks stage by stage
  1387. for (int stage = 0; stage < 4; ++stage) {
  1388. int blocks_found_in_stage = 0;
  1389. for (int blk_idx = 0; ; ++blk_idx) {
  1390. bool found_block = false;
  1391. mobilenetv5_block block;
  1392. // 1. Check for Edge Residual (S0)
  1393. block.s0_conv_exp_w = get_tensor(string_format(TN_MNV5_BLK_S0_EXP_W, stage, blk_idx), false);
  1394. if (block.s0_conv_exp_w) {
  1395. found_block = true;
  1396. block.s0_bn1_w = get_tensor(string_format(TN_MNV5_BLK_S0_BN1_W, stage, blk_idx), false);
  1397. block.s0_conv_pwl_w = get_tensor(string_format(TN_MNV5_BLK_S0_PWL_W, stage, blk_idx), false);
  1398. block.s0_bn2_w = get_tensor(string_format(TN_MNV5_BLK_S0_BN2_W, stage, blk_idx), false);
  1399. }
  1400. // 2. Check for UIR (Universal Inverted Residual)
  1401. else {
  1402. // Check for dw_start OR pw_exp (some UIR blocks skip dw_start)
  1403. block.dw_start_w = get_tensor(string_format(TN_MNV5_BLK_DW_START_W, stage, blk_idx), false);
  1404. block.pw_exp_w = get_tensor(string_format(TN_MNV5_BLK_PW_EXP_W, stage, blk_idx), false);
  1405. if (block.dw_start_w || block.pw_exp_w) {
  1406. found_block = true;
  1407. if (block.dw_start_w) {
  1408. block.dw_start_bn_w = get_tensor(string_format(TN_MNV5_BLK_DW_START_BN, stage, blk_idx), false);
  1409. }
  1410. if (block.pw_exp_w) {
  1411. block.pw_exp_bn_w = get_tensor(string_format(TN_MNV5_BLK_PW_EXP_BN, stage, blk_idx), false);
  1412. }
  1413. block.dw_mid_w = get_tensor(string_format(TN_MNV5_BLK_DW_MID_W, stage, blk_idx), false);
  1414. if (block.dw_mid_w) {
  1415. block.dw_mid_bn_w = get_tensor(string_format(TN_MNV5_BLK_DW_MID_BN, stage, blk_idx), false);
  1416. }
  1417. block.pw_proj_w = get_tensor(string_format(TN_MNV5_BLK_PW_PROJ_W, stage, blk_idx), false);
  1418. if (block.pw_proj_w) {
  1419. block.pw_proj_bn_w = get_tensor(string_format(TN_MNV5_BLK_PW_PROJ_BN, stage, blk_idx), false);
  1420. }
  1421. block.layer_scale_w = get_tensor(string_format(TN_MNV5_BLK_LAYER_SCALE, stage, blk_idx), false);
  1422. }
  1423. }
  1424. // 3. Check for Attention (MQA)
  1425. // Even if UIR/Edge check failed, this might be a pure attention block
  1426. ggml_tensor* attn_q_check = get_tensor(string_format(TN_MNV5_ATTN_Q_W, stage, blk_idx), false);
  1427. if (attn_q_check) {
  1428. found_block = true;
  1429. block.attn_q_w = attn_q_check;
  1430. block.attn_k_w = get_tensor(string_format(TN_MNV5_ATTN_K_W, stage, blk_idx), false);
  1431. block.attn_v_w = get_tensor(string_format(TN_MNV5_ATTN_V_W, stage, blk_idx), false);
  1432. block.attn_o_w = get_tensor(string_format(TN_MNV5_ATTN_O_W, stage, blk_idx), false);
  1433. block.attn_k_dw_w = get_tensor(string_format(TN_MNV5_ATTN_K_DW, stage, blk_idx), false);
  1434. block.attn_k_norm_w = get_tensor(string_format(TN_MNV5_ATTN_K_NORM, stage, blk_idx), false);
  1435. block.attn_v_dw_w = get_tensor(string_format(TN_MNV5_ATTN_V_DW, stage, blk_idx), false);
  1436. block.attn_v_norm_w = get_tensor(string_format(TN_MNV5_ATTN_V_NORM, stage, blk_idx), false);
  1437. block.attn_norm_w = get_tensor(string_format(TN_MNV5_ATTN_NORM, stage, blk_idx), false);
  1438. // Note: Attention blocks also have layer_scale, load it if not already loaded by UIR check
  1439. if (!block.layer_scale_w) {
  1440. block.layer_scale_w = get_tensor(string_format(TN_MNV5_BLK_LAYER_SCALE, stage, blk_idx), false);
  1441. }
  1442. }
  1443. if (found_block) {
  1444. model.mobilenet_blocks.push_back(block);
  1445. blocks_found_in_stage++;
  1446. } else {
  1447. // End of blocks for this stage
  1448. break;
  1449. }
  1450. }
  1451. // Track where this stage ends in the flat vector
  1452. if (blocks_found_in_stage > 0) {
  1453. model.mobilenet_stage_ends.push_back(model.mobilenet_blocks.size() - 1);
  1454. LOG_INF("%s: Stage %d ended at global block index %zu\n", __func__, stage, model.mobilenet_blocks.size() - 1);
  1455. }
  1456. }
  1457. model.mm_input_proj_w = get_tensor(TN_MM_INP_PROJ);
  1458. model.mm_soft_emb_norm_w = get_tensor(TN_MM_SOFT_EMB_N);
  1459. } break;
  1460. case PROJECTOR_TYPE_IDEFICS3:
  1461. {
  1462. model.projection = get_tensor(TN_MM_PROJECTOR);
  1463. } break;
  1464. case PROJECTOR_TYPE_LFM2:
  1465. {
  1466. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
  1467. model.mm_input_norm_b = get_tensor(TN_MM_INP_NORM_B, false);
  1468. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1469. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"));
  1470. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1471. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1472. } break;
  1473. case PROJECTOR_TYPE_KIMIVL:
  1474. {
  1475. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM);
  1476. model.mm_input_norm_b = get_tensor(TN_MM_INP_NORM_B);
  1477. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1478. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"));
  1479. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1480. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1481. } break;
  1482. case PROJECTOR_TYPE_PIXTRAL:
  1483. {
  1484. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1485. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1486. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1487. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1488. // [IMG_BREAK] token embedding
  1489. model.token_embd_img_break = get_tensor(TN_TOK_IMG_BREAK);
  1490. // for mistral small 3.1
  1491. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
  1492. model.mm_patch_merger_w = get_tensor(string_format(TN_MM_PATCH_MERGER, "weight"), false);
  1493. } break;
  1494. case PROJECTOR_TYPE_LIGHTONOCR:
  1495. {
  1496. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1497. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1498. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1499. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1500. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
  1501. model.mm_patch_merger_w = get_tensor(string_format(TN_MM_PATCH_MERGER, "weight"), false);
  1502. } break;
  1503. case PROJECTOR_TYPE_ULTRAVOX:
  1504. {
  1505. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1506. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1507. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1508. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1509. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1510. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1511. model.mm_norm_pre_w = get_tensor(string_format(TN_MM_NORM_PRE, "weight"));
  1512. model.mm_norm_mid_w = get_tensor(string_format(TN_MM_NORM_MID, "weight"));
  1513. } break;
  1514. case PROJECTOR_TYPE_QWEN2A:
  1515. {
  1516. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1517. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1518. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1519. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1520. model.mm_fc_w = get_tensor(string_format(TN_MM_AUDIO_FC, "weight"));
  1521. model.mm_fc_b = get_tensor(string_format(TN_MM_AUDIO_FC, "bias"));
  1522. } break;
  1523. case PROJECTOR_TYPE_VOXTRAL:
  1524. {
  1525. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1526. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1527. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1528. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1529. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1530. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1531. } break;
  1532. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  1533. {
  1534. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1535. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1536. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1537. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1538. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1539. model.mm_1_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "bias"));
  1540. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1541. model.mm_2_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "bias"));
  1542. } break;
  1543. case PROJECTOR_TYPE_INTERNVL:
  1544. {
  1545. model.mm_0_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "weight"));
  1546. model.mm_0_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "bias"));
  1547. model.mm_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1548. model.mm_1_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "bias"));
  1549. model.mm_3_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "weight"));
  1550. model.mm_3_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "bias"));
  1551. } break;
  1552. case PROJECTOR_TYPE_GLMA:
  1553. {
  1554. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1555. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1556. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1557. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1558. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1559. model.mm_1_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "bias"));
  1560. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1561. model.mm_2_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "bias"));
  1562. model.mm_norm_pre_w = get_tensor(string_format(TN_MM_NORM_PRE, "weight"));
  1563. model.mm_norm_pre_b = get_tensor(string_format(TN_MM_NORM_PRE, "bias"));
  1564. model.mm_boi = get_tensor(string_format(TN_TOK_BOI));
  1565. model.mm_eoi = get_tensor(string_format(TN_TOK_EOI));
  1566. } break;
  1567. case PROJECTOR_TYPE_LLAMA4:
  1568. {
  1569. model.mm_model_proj = get_tensor(TN_MM_PROJECTOR);
  1570. model.mm_model_mlp_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1571. model.mm_model_mlp_2_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "weight"));
  1572. } break;
  1573. case PROJECTOR_TYPE_COGVLM:
  1574. {
  1575. model.mm_model_proj = get_tensor(TN_MM_PROJECTOR);
  1576. model.mm_post_fc_norm_w = get_tensor(string_format(TN_MM_POST_FC_NORM, "weight"));
  1577. model.mm_post_fc_norm_b = get_tensor(string_format(TN_MM_POST_FC_NORM, "bias"));
  1578. model.mm_h_to_4h_w = get_tensor(string_format(TN_MM_H_TO_4H, "weight"));
  1579. model.mm_gate_w = get_tensor(string_format(TN_MM_GATE, "weight"));
  1580. model.mm_4h_to_h_w = get_tensor(string_format(TN_MM_4H_TO_H, "weight"));
  1581. model.mm_boi = get_tensor(TN_TOK_BOI);
  1582. model.mm_eoi = get_tensor(TN_TOK_EOI);
  1583. } break;
  1584. case PROJECTOR_TYPE_JANUS_PRO:
  1585. {
  1586. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1587. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1588. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1589. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"));
  1590. } break;
  1591. case PROJECTOR_TYPE_LFM2A:
  1592. {
  1593. for (int i : {0, 2, 3, 5, 6}) {
  1594. model.pre_encode_conv_X_w[i] = get_tensor(string_format(TN_CONV1D, i, "weight"));
  1595. model.pre_encode_conv_X_b[i] = get_tensor(string_format(TN_CONV1D, i, "bias"));
  1596. }
  1597. model.pre_encode_out_w = get_tensor(string_format(TN_PRE_ENCODE_OUT, "weight"));
  1598. model.pre_encode_out_b = get_tensor(string_format(TN_PRE_ENCODE_OUT, "bias"));
  1599. model.mm_0_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 0, "weight"));
  1600. model.mm_0_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 0, "bias"));
  1601. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1602. model.mm_1_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "bias"));
  1603. model.mm_3_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 3, "weight"));
  1604. model.mm_3_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 3, "bias"));
  1605. for (int il = 0; il < hparams.n_layer; ++il) {
  1606. auto & layer = model.layers[il];
  1607. layer.ff_norm_w = get_tensor(string_format(TN_FFN_NORM, prefix, il, "weight"));
  1608. layer.ff_norm_b = get_tensor(string_format(TN_FFN_NORM, prefix, il, "bias"));
  1609. layer.ff_norm_1_w = get_tensor(string_format(TN_FFN_NORM_1, prefix, il, "weight"));
  1610. layer.ff_norm_1_b = get_tensor(string_format(TN_FFN_NORM_1, prefix, il, "bias"));
  1611. layer.ff_up_1_w = get_tensor(string_format(TN_FFN_UP_1, prefix, il, "weight"));
  1612. layer.ff_up_1_b = get_tensor(string_format(TN_FFN_UP_1, prefix, il, "bias"));
  1613. layer.ff_down_1_w = get_tensor(string_format(TN_FFN_DOWN_1, prefix, il, "weight"));
  1614. layer.ff_down_1_b = get_tensor(string_format(TN_FFN_DOWN_1, prefix, il, "bias"));
  1615. layer.pos_bias_u = get_tensor(string_format(TN_POS_BIAS_U, prefix, il));
  1616. layer.pos_bias_v = get_tensor(string_format(TN_POS_BIAS_V, prefix, il));
  1617. layer.norm_conv_w = get_tensor(string_format(TN_NORM_CONV, prefix, il, "weight"));
  1618. layer.norm_conv_b = get_tensor(string_format(TN_NORM_CONV, prefix, il, "bias"));
  1619. layer.linear_pos_w = get_tensor(string_format(TN_LINEAR_POS, prefix, il, "weight"));
  1620. layer.conv_norm_w = get_tensor(string_format(TN_CONV_NORM, prefix, il, "weight"));
  1621. layer.conv_norm_b = get_tensor(string_format(TN_CONV_NORM, prefix, il, "bias"));
  1622. layer.conv_dw_w = get_tensor(string_format(TN_CONV_DW, prefix, il, "weight"));
  1623. layer.conv_dw_b = get_tensor(string_format(TN_CONV_DW, prefix, il, "bias"));
  1624. layer.conv_pw1_w = get_tensor(string_format(TN_CONV_PW1, prefix, il, "weight"));
  1625. layer.conv_pw1_b = get_tensor(string_format(TN_CONV_PW1, prefix, il, "bias"));
  1626. layer.conv_pw2_w = get_tensor(string_format(TN_CONV_PW2, prefix, il, "weight"));
  1627. layer.conv_pw2_b = get_tensor(string_format(TN_CONV_PW2, prefix, il, "bias"));
  1628. }
  1629. } break;
  1630. default:
  1631. GGML_ASSERT(false && "unknown projector type");
  1632. }
  1633. // load data
  1634. {
  1635. std::vector<uint8_t> read_buf;
  1636. auto fin = std::ifstream(fname, std::ios::binary);
  1637. if (!fin) {
  1638. throw std::runtime_error(string_format("%s: failed to open %s\n", __func__, fname.c_str()));
  1639. }
  1640. // alloc memory and offload data
  1641. ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(ctx_clip.backend);
  1642. ctx_clip.buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_clip.ctx_data.get(), buft));
  1643. ggml_backend_buffer_set_usage(ctx_clip.buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  1644. for (auto & t : tensors_to_load) {
  1645. ggml_tensor * cur = ggml_get_tensor(ctx_clip.ctx_data.get(), t->name);
  1646. const size_t offset = tensor_offset[t->name];
  1647. fin.seekg(offset, std::ios::beg);
  1648. if (!fin) {
  1649. throw std::runtime_error(string_format("%s: failed to seek for tensor %s\n", __func__, t->name));
  1650. }
  1651. size_t num_bytes = ggml_nbytes(cur);
  1652. if (ggml_backend_buft_is_host(buft)) {
  1653. // for the CPU and Metal backend, we can read directly into the tensor
  1654. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  1655. } else {
  1656. // read into a temporary buffer first, then copy to device memory
  1657. read_buf.resize(num_bytes);
  1658. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  1659. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  1660. }
  1661. }
  1662. fin.close();
  1663. LOG_DBG("%s: loaded %zu tensors from %s\n", __func__, tensors_to_load.size(), fname.c_str());
  1664. }
  1665. }
  1666. struct support_info_op {
  1667. ggml_tensor * op;
  1668. // true if the op runs on the accelerated ctx_clip.backend
  1669. bool is_accel = true;
  1670. };
  1671. struct support_info_graph {
  1672. // whether the clip_ctx.backend supports flash attention
  1673. bool fattn = true;
  1674. ggml_tensor * fattn_op = nullptr; // for debugging
  1675. std::vector<support_info_op> ops;
  1676. };
  1677. static void warmup(clip_ctx & ctx_clip) {
  1678. // create a fake batch
  1679. const auto & hparams = ctx_clip.model.hparams;
  1680. clip_image_f32_batch batch;
  1681. clip_image_f32_ptr img(clip_image_f32_init());
  1682. if (ctx_clip.model.modality == CLIP_MODALITY_VISION) {
  1683. img->nx = hparams.warmup_image_size;
  1684. img->ny = hparams.warmup_image_size;
  1685. LOG_INF("%s: warmup with image size = %d x %d\n", __func__, img->nx, img->ny);
  1686. } else {
  1687. img->nx = hparams.warmup_audio_size;
  1688. img->ny = hparams.n_mel_bins;
  1689. LOG_INF("%s: warmup with audio size = %d\n", __func__, img->nx);
  1690. }
  1691. batch.entries.push_back(std::move(img));
  1692. warmup(ctx_clip, batch);
  1693. }
  1694. static void warmup(clip_ctx & ctx_clip, const clip_image_f32_batch & batch) {
  1695. support_info_graph info;
  1696. if (ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_AUTO) {
  1697. // try to enable flash attention to see if it's supported
  1698. ctx_clip.flash_attn_type = CLIP_FLASH_ATTN_TYPE_ENABLED;
  1699. info = alloc_compute_meta(ctx_clip, batch);
  1700. if (!info.fattn && info.fattn_op) {
  1701. auto op = info.fattn_op;
  1702. LOG_WRN("%s: *****************************************************************\n", __func__);
  1703. LOG_WRN("%s: WARNING: flash attention not supported by %s, memory usage will increase\n", __func__, ggml_backend_name(ctx_clip.backend));
  1704. LOG_WRN("%s: op params: \n", __func__);
  1705. static auto print_shape = [](const char * fn, const char * name, ggml_tensor * t) {
  1706. LOG_WRN("%s: %s: type = %s, ne = [%d %d %d %d], nb = [%d %d %d %d]\n", fn,
  1707. name, ggml_type_name(t->type),
  1708. t->ne[0], t->ne[1], t->ne[2], t->ne[3],
  1709. t->nb[0], t->nb[1], t->nb[2], t->nb[3]);
  1710. };
  1711. print_shape(__func__, " dst", op);
  1712. print_shape(__func__, "src0", op->src[0]);
  1713. print_shape(__func__, "src1", op->src[1]);
  1714. print_shape(__func__, "src2", op->src[2]);
  1715. LOG_WRN("%s: please report this on github as an issue\n", __func__);
  1716. LOG_WRN("%s: *****************************************************************\n", __func__);
  1717. ctx_clip.flash_attn_type = CLIP_FLASH_ATTN_TYPE_DISABLED;
  1718. alloc_compute_meta(ctx_clip, batch);
  1719. }
  1720. } else {
  1721. info = alloc_compute_meta(ctx_clip, batch);
  1722. if (!info.fattn && ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) {
  1723. LOG_WRN("%s: flash attention is not supported by the current backend; falling back to CPU (performance will be degraded)\n", __func__);
  1724. }
  1725. }
  1726. ctx_clip.is_allocated = true; // mark buffers as allocated
  1727. LOG_INF("%s: flash attention is %s\n", __func__,
  1728. (ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) ? "enabled" : "disabled");
  1729. // print ops that are not supported by the GPU backend (if there is one)
  1730. if (ctx_clip.backend && ctx_clip.backend != ctx_clip.backend_cpu) {
  1731. std::vector<support_info_op> unsupported_ops;
  1732. for (const auto & op : info.ops) {
  1733. if (!op.is_accel) {
  1734. unsupported_ops.push_back(op);
  1735. }
  1736. }
  1737. if (!unsupported_ops.empty()) {
  1738. LOG_WRN("%s: *****************************************************************\n", __func__);
  1739. LOG_WRN("%s: WARNING: the CLIP graph uses unsupported operators by the backend\n", __func__);
  1740. LOG_WRN("%s: the performance will be suboptimal \n", __func__);
  1741. LOG_WRN("%s: list of unsupported ops (backend=%s):\n", __func__, ggml_backend_name(ctx_clip.backend));
  1742. for (const auto & op : unsupported_ops) {
  1743. LOG_WRN("%s: %16s: type = %s, ne = [%d %d %d %d]\n", __func__,
  1744. ggml_op_name(op.op->op),
  1745. ggml_type_name(op.op->type),
  1746. op.op->ne[0], op.op->ne[1], op.op->ne[2], op.op->ne[3]);
  1747. }
  1748. LOG_WRN("%s: flash attention is %s\n", __func__,
  1749. (ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) ? "enabled" : "disabled");
  1750. LOG_WRN("%s: please report this on github as an issue\n", __func__);
  1751. LOG_WRN("%s: ref: https://github.com/ggml-org/llama.cpp/pull/16837#issuecomment-3461676118\n", __func__);
  1752. LOG_WRN("%s: *****************************************************************\n", __func__);
  1753. }
  1754. }
  1755. }
  1756. static support_info_graph alloc_compute_meta(clip_ctx & ctx_clip, const clip_image_f32_batch & batch) {
  1757. ctx_clip.buf_compute_meta.resize(ctx_clip.max_nodes * ggml_tensor_overhead() + ggml_graph_overhead());
  1758. ggml_cgraph * gf = clip_image_build_graph(&ctx_clip, batch);
  1759. ggml_backend_sched_reserve(ctx_clip.sched.get(), gf);
  1760. for (size_t i = 0; i < ctx_clip.backend_ptrs.size(); ++i) {
  1761. ggml_backend_t backend = ctx_clip.backend_ptrs[i];
  1762. ggml_backend_buffer_type_t buft = ctx_clip.backend_buft[i];
  1763. size_t size = ggml_backend_sched_get_buffer_size(ctx_clip.sched.get(), backend);
  1764. if (size > 1) {
  1765. LOG_INF("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  1766. ggml_backend_buft_name(buft),
  1767. size / 1024.0 / 1024.0);
  1768. }
  1769. }
  1770. const int n_splits = ggml_backend_sched_get_n_splits(ctx_clip.sched.get());
  1771. const int n_nodes = ggml_graph_n_nodes(gf);
  1772. LOG_INF("%s: graph splits = %d, nodes = %d\n", __func__, n_splits, n_nodes);
  1773. support_info_graph res {
  1774. /*.fattn = */ true,
  1775. /*.fattn_op = */ nullptr,
  1776. /*.ops = */ {},
  1777. };
  1778. // check op support
  1779. for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
  1780. ggml_tensor * node = ggml_graph_node(gf, i);
  1781. res.ops.push_back({node, true});
  1782. if (!ggml_backend_supports_op(ctx_clip.backend, node)) {
  1783. res.ops.back().is_accel = false;
  1784. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1785. res.fattn = false;
  1786. res.fattn_op = node;
  1787. }
  1788. }
  1789. }
  1790. return res;
  1791. }
  1792. void get_bool(const std::string & key, bool & output, bool required = true) const {
  1793. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1794. if (i < 0) {
  1795. if (required) {
  1796. throw std::runtime_error("Key not found: " + key);
  1797. }
  1798. return;
  1799. }
  1800. output = gguf_get_val_bool(ctx_gguf.get(), i);
  1801. }
  1802. void get_i32(const std::string & key, int & output, bool required = true) const {
  1803. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1804. if (i < 0) {
  1805. if (required) {
  1806. throw std::runtime_error("Key not found: " + key);
  1807. }
  1808. return;
  1809. }
  1810. output = gguf_get_val_i32(ctx_gguf.get(), i);
  1811. }
  1812. void get_u32(const std::string & key, int & output, bool required = true) const {
  1813. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1814. if (i < 0) {
  1815. if (required) {
  1816. throw std::runtime_error("Key not found: " + key);
  1817. }
  1818. return;
  1819. }
  1820. output = gguf_get_val_u32(ctx_gguf.get(), i);
  1821. }
  1822. void get_f32(const std::string & key, float & output, bool required = true) const {
  1823. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1824. if (i < 0) {
  1825. if (required) {
  1826. throw std::runtime_error("Key not found: " + key);
  1827. }
  1828. return;
  1829. }
  1830. output = gguf_get_val_f32(ctx_gguf.get(), i);
  1831. }
  1832. void get_string(const std::string & key, std::string & output, bool required = true) const {
  1833. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1834. if (i < 0) {
  1835. if (required) {
  1836. throw std::runtime_error("Key not found: " + key);
  1837. }
  1838. return;
  1839. }
  1840. output = std::string(gguf_get_val_str(ctx_gguf.get(), i));
  1841. }
  1842. void get_arr_int(const std::string & key, std::vector<int> & output, bool required = true) const {
  1843. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1844. if (i < 0) {
  1845. if (required) {
  1846. throw std::runtime_error("Key not found: " + key);
  1847. }
  1848. return;
  1849. }
  1850. int n = gguf_get_arr_n(ctx_gguf.get(), i);
  1851. output.resize(n);
  1852. const int32_t * values = (const int32_t *)gguf_get_arr_data(ctx_gguf.get(), i);
  1853. for (int i = 0; i < n; ++i) {
  1854. output[i] = values[i];
  1855. }
  1856. }
  1857. static void set_llava_uhd_res_candidates(clip_model & model, const int max_patches_per_side) {
  1858. auto & hparams = model.hparams;
  1859. for (int x = 1; x <= max_patches_per_side; x++) {
  1860. for (int y = 1; y <= max_patches_per_side; y++) {
  1861. if (x == 1 && y == 1) {
  1862. continue; // skip the first point
  1863. }
  1864. hparams.image_res_candidates.push_back(clip_image_size{
  1865. x*hparams.image_size,
  1866. y*hparams.image_size,
  1867. });
  1868. }
  1869. }
  1870. }
  1871. };
  1872. struct clip_init_result clip_init(const char * fname, struct clip_context_params ctx_params) {
  1873. clip_ctx * ctx_vision = nullptr;
  1874. clip_ctx * ctx_audio = nullptr;
  1875. try {
  1876. clip_model_loader loader(fname);
  1877. bool skip_audio = false;
  1878. if (loader.has_vision) {
  1879. ctx_vision = new clip_ctx(ctx_params);
  1880. loader.load_hparams(ctx_vision->model, CLIP_MODALITY_VISION);
  1881. loader.load_tensors(*ctx_vision);
  1882. if (ctx_params.warmup) {
  1883. loader.warmup(*ctx_vision);
  1884. }
  1885. // TODO: we don't support audio for Gemma 3N, but GGUF contains audio tensors
  1886. // we can remove this check when we implement audio support for Gemma 3N
  1887. skip_audio = ctx_vision->model.proj_type == PROJECTOR_TYPE_GEMMA3NV;
  1888. // clip_debug_encode(ctx_vision, 24*14, 24*14, 0.5f);
  1889. }
  1890. if (loader.has_audio && !skip_audio) {
  1891. ctx_audio = new clip_ctx(ctx_params);
  1892. loader.load_hparams(ctx_audio->model, CLIP_MODALITY_AUDIO);
  1893. loader.load_tensors(*ctx_audio);
  1894. if (ctx_params.warmup) {
  1895. loader.warmup(*ctx_audio);
  1896. }
  1897. }
  1898. } catch (const std::exception & e) {
  1899. LOG_ERR("%s: failed to load model '%s': %s\n", __func__, fname, e.what());
  1900. delete ctx_vision;
  1901. delete ctx_audio;
  1902. return {nullptr, nullptr};
  1903. }
  1904. return {ctx_vision, ctx_audio};
  1905. }
  1906. struct clip_image_size * clip_image_size_init() {
  1907. struct clip_image_size * load_image_size = new struct clip_image_size();
  1908. load_image_size->width = 448;
  1909. load_image_size->height = 448;
  1910. return load_image_size;
  1911. }
  1912. struct clip_image_u8 * clip_image_u8_init() {
  1913. return new clip_image_u8();
  1914. }
  1915. struct clip_image_f32 * clip_image_f32_init() {
  1916. return new clip_image_f32();
  1917. }
  1918. struct clip_image_f32_batch * clip_image_f32_batch_init() {
  1919. return new clip_image_f32_batch();
  1920. }
  1921. unsigned char * clip_image_u8_get_data(struct clip_image_u8 * img, uint32_t * nx, uint32_t * ny) {
  1922. if (nx) *nx = img->nx;
  1923. if (ny) *ny = img->ny;
  1924. return img->buf.data();
  1925. }
  1926. void clip_image_size_free(struct clip_image_size * load_image_size) {
  1927. if (load_image_size == nullptr) {
  1928. return;
  1929. }
  1930. delete load_image_size;
  1931. }
  1932. void clip_image_u8_free(struct clip_image_u8 * img) { delete img; }
  1933. void clip_image_f32_free(struct clip_image_f32 * img) { delete img; }
  1934. void clip_image_u8_batch_free(struct clip_image_u8_batch * batch) { delete batch; }
  1935. void clip_image_f32_batch_free(struct clip_image_f32_batch * batch) { delete batch; }
  1936. size_t clip_image_f32_batch_n_images(const struct clip_image_f32_batch * batch) {
  1937. return batch->entries.size();
  1938. }
  1939. size_t clip_image_f32_batch_nx(const struct clip_image_f32_batch * batch, int idx) {
  1940. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1941. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1942. return 0;
  1943. }
  1944. return batch->entries[idx]->nx;
  1945. }
  1946. size_t clip_image_f32_batch_ny(const struct clip_image_f32_batch * batch, int idx) {
  1947. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1948. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1949. return 0;
  1950. }
  1951. return batch->entries[idx]->ny;
  1952. }
  1953. clip_image_f32 * clip_image_f32_get_img(const struct clip_image_f32_batch * batch, int idx) {
  1954. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1955. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1956. return nullptr;
  1957. }
  1958. return batch->entries[idx].get();
  1959. }
  1960. void clip_build_img_from_pixels(const unsigned char * rgb_pixels, int nx, int ny, clip_image_u8 * img) {
  1961. img->nx = nx;
  1962. img->ny = ny;
  1963. img->buf.resize(3 * nx * ny);
  1964. memcpy(img->buf.data(), rgb_pixels, img->buf.size());
  1965. }
  1966. // Normalize image to float32 - careful with pytorch .to(model.device, dtype=torch.float16) - this sometimes reduces precision (32>16>32), sometimes not
  1967. static void normalize_image_u8_to_f32(const clip_image_u8 & src, clip_image_f32 & dst, const float mean[3], const float std[3]) {
  1968. dst.nx = src.nx;
  1969. dst.ny = src.ny;
  1970. dst.buf.resize(src.buf.size());
  1971. // TODO @ngxson : seems like this could be done more efficiently on cgraph
  1972. for (size_t i = 0; i < src.buf.size(); ++i) {
  1973. int c = i % 3; // rgb
  1974. dst.buf[i] = (static_cast<float>(src.buf[i]) / 255.0f - mean[c]) / std[c];
  1975. }
  1976. }
  1977. // set of tools to manupulate images
  1978. // in the future, we can have HW acceleration by allowing this struct to access 3rd party lib like imagick or opencv
  1979. struct img_tool {
  1980. enum resize_algo {
  1981. RESIZE_ALGO_BILINEAR,
  1982. RESIZE_ALGO_BICUBIC,
  1983. // RESIZE_ALGO_LANCZOS, // TODO
  1984. };
  1985. static void resize(
  1986. const clip_image_u8 & src,
  1987. clip_image_u8 & dst,
  1988. const clip_image_size & target_resolution,
  1989. resize_algo algo,
  1990. bool add_padding = true, // TODO: define the behavior for add_padding = false
  1991. std::array<uint8_t, 3> pad_color = {0, 0, 0}) {
  1992. dst.nx = target_resolution.width;
  1993. dst.ny = target_resolution.height;
  1994. dst.buf.resize(3 * dst.nx * dst.ny);
  1995. if (dst.nx == src.nx && dst.ny == src.ny) {
  1996. // no resize needed, simple copy
  1997. dst.buf = src.buf;
  1998. return;
  1999. }
  2000. if (!add_padding) {
  2001. // direct resize
  2002. switch (algo) {
  2003. case RESIZE_ALGO_BILINEAR:
  2004. resize_bilinear(src, dst, target_resolution.width, target_resolution.height);
  2005. break;
  2006. case RESIZE_ALGO_BICUBIC:
  2007. resize_bicubic(src, dst, target_resolution.width, target_resolution.height);
  2008. break;
  2009. default:
  2010. throw std::runtime_error("Unsupported resize algorithm");
  2011. }
  2012. } else {
  2013. // resize with padding
  2014. clip_image_u8 resized_image;
  2015. float scale_w = static_cast<float>(target_resolution.width) / src.nx;
  2016. float scale_h = static_cast<float>(target_resolution.height) / src.ny;
  2017. float scale = std::min(scale_w, scale_h);
  2018. int new_width = std::min(static_cast<int>(std::ceil(src.nx * scale)), target_resolution.width);
  2019. int new_height = std::min(static_cast<int>(std::ceil(src.ny * scale)), target_resolution.height);
  2020. switch (algo) {
  2021. case RESIZE_ALGO_BILINEAR:
  2022. resize_bilinear(src, resized_image, new_width, new_height);
  2023. break;
  2024. case RESIZE_ALGO_BICUBIC:
  2025. resize_bicubic(src, resized_image, new_width, new_height);
  2026. break;
  2027. default:
  2028. throw std::runtime_error("Unsupported resize algorithm");
  2029. }
  2030. // fill dst with pad_color
  2031. fill(dst, pad_color);
  2032. int offset_x = (target_resolution.width - new_width) / 2;
  2033. int offset_y = (target_resolution.height - new_height) / 2;
  2034. composite(dst, resized_image, offset_x, offset_y);
  2035. }
  2036. }
  2037. static void crop(const clip_image_u8 & image, clip_image_u8 & dst, int x, int y, int w, int h) {
  2038. dst.nx = w;
  2039. dst.ny = h;
  2040. dst.buf.resize(3 * w * h);
  2041. for (int i = 0; i < h; ++i) {
  2042. for (int j = 0; j < w; ++j) {
  2043. int src_idx = 3 * ((y + i)*image.nx + (x + j));
  2044. int dst_idx = 3 * (i*w + j);
  2045. dst.buf[dst_idx] = image.buf[src_idx];
  2046. dst.buf[dst_idx + 1] = image.buf[src_idx + 1];
  2047. dst.buf[dst_idx + 2] = image.buf[src_idx + 2];
  2048. }
  2049. }
  2050. }
  2051. // calculate the size of the **resized** image, while preserving the aspect ratio
  2052. // the calculated size will be aligned to the nearest multiple of align_size
  2053. // if H or W size is larger than longest_edge, it will be resized to longest_edge
  2054. static clip_image_size calc_size_preserved_ratio(const clip_image_size & inp_size, const int align_size, const int longest_edge) {
  2055. GGML_ASSERT(align_size > 0);
  2056. if (inp_size.width <= 0 || inp_size.height <= 0 || longest_edge <= 0) {
  2057. return {0, 0};
  2058. }
  2059. float scale = std::min(static_cast<float>(longest_edge) / inp_size.width,
  2060. static_cast<float>(longest_edge) / inp_size.height);
  2061. float target_width_f = static_cast<float>(inp_size.width) * scale;
  2062. float target_height_f = static_cast<float>(inp_size.height) * scale;
  2063. auto ceil_by_factor = [f = align_size](float x) { return static_cast<int>(std::ceil(x / static_cast<float>(f))) * f; };
  2064. int aligned_width = ceil_by_factor(target_width_f);
  2065. int aligned_height = ceil_by_factor(target_height_f);
  2066. return {aligned_width, aligned_height};
  2067. }
  2068. // calculate the size of the **resized** image, while preserving the aspect ratio
  2069. // the calculated size will have min_pixels <= W*H <= max_pixels
  2070. // this is referred as "smart_resize" in transformers code
  2071. static clip_image_size calc_size_preserved_ratio(const clip_image_size & inp_size, const int align_size, const int min_pixels, const int max_pixels) {
  2072. GGML_ASSERT(align_size > 0);
  2073. const int width = inp_size.width;
  2074. const int height = inp_size.height;
  2075. auto round_by_factor = [f = align_size](float x) { return static_cast<int>(std::round(x / static_cast<float>(f))) * f; };
  2076. auto ceil_by_factor = [f = align_size](float x) { return static_cast<int>(std::ceil(x / static_cast<float>(f))) * f; };
  2077. auto floor_by_factor = [f = align_size](float x) { return static_cast<int>(std::floor(x / static_cast<float>(f))) * f; };
  2078. // always align up first
  2079. int h_bar = std::max(align_size, round_by_factor(height));
  2080. int w_bar = std::max(align_size, round_by_factor(width));
  2081. if (h_bar * w_bar > max_pixels) {
  2082. const auto beta = std::sqrt(static_cast<float>(height * width) / max_pixels);
  2083. h_bar = std::max(align_size, floor_by_factor(height / beta));
  2084. w_bar = std::max(align_size, floor_by_factor(width / beta));
  2085. } else if (h_bar * w_bar < min_pixels) {
  2086. const auto beta = std::sqrt(static_cast<float>(min_pixels) / (height * width));
  2087. h_bar = ceil_by_factor(height * beta);
  2088. w_bar = ceil_by_factor(width * beta);
  2089. }
  2090. return {w_bar, h_bar};
  2091. }
  2092. // draw src image into dst image at offset (offset_x, offset_y)
  2093. static void composite(clip_image_u8 & dst, const clip_image_u8 & src, int offset_x, int offset_y) {
  2094. for (int y = 0; y < src.ny; ++y) {
  2095. for (int x = 0; x < src.nx; ++x) {
  2096. int dx = x + offset_x;
  2097. int dy = y + offset_y;
  2098. // skip pixels that would be out of bounds in the destination
  2099. if (dx < 0 || dy < 0 || dx >= dst.nx || dy >= dst.ny) {
  2100. continue;
  2101. }
  2102. size_t dst_idx = 3 * (static_cast<size_t>(dy) * dst.nx + static_cast<size_t>(dx));
  2103. size_t src_idx = 3 * (static_cast<size_t>(y) * src.nx + static_cast<size_t>(x));
  2104. dst.buf[dst_idx + 0] = src.buf[src_idx + 0];
  2105. dst.buf[dst_idx + 1] = src.buf[src_idx + 1];
  2106. dst.buf[dst_idx + 2] = src.buf[src_idx + 2];
  2107. }
  2108. }
  2109. }
  2110. // fill the image with a solid color
  2111. static void fill(clip_image_u8 & img, const std::array<uint8_t, 3> & color) {
  2112. for (size_t i = 0; i < img.buf.size(); i += 3) {
  2113. img.buf[i] = color[0];
  2114. img.buf[i + 1] = color[1];
  2115. img.buf[i + 2] = color[2];
  2116. }
  2117. }
  2118. private:
  2119. // Bilinear resize function
  2120. static void resize_bilinear(const clip_image_u8 & src, clip_image_u8 & dst, int target_width, int target_height) {
  2121. dst.nx = target_width;
  2122. dst.ny = target_height;
  2123. dst.buf.resize(3 * target_width * target_height);
  2124. float x_ratio = static_cast<float>(src.nx - 1) / target_width;
  2125. float y_ratio = static_cast<float>(src.ny - 1) / target_height;
  2126. for (int y = 0; y < target_height; y++) {
  2127. for (int x = 0; x < target_width; x++) {
  2128. float px = x_ratio * x;
  2129. float py = y_ratio * y;
  2130. int x_floor = static_cast<int>(px);
  2131. int y_floor = static_cast<int>(py);
  2132. float x_lerp = px - x_floor;
  2133. float y_lerp = py - y_floor;
  2134. for (int c = 0; c < 3; c++) {
  2135. float top = lerp(
  2136. static_cast<float>(src.buf[3 * (y_floor * src.nx + x_floor) + c]),
  2137. static_cast<float>(src.buf[3 * (y_floor * src.nx + (x_floor + 1)) + c]),
  2138. x_lerp
  2139. );
  2140. float bottom = lerp(
  2141. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + x_floor) + c]),
  2142. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + (x_floor + 1)) + c]),
  2143. x_lerp
  2144. );
  2145. dst.buf[3 * (y * target_width + x) + c] = static_cast<uint8_t>(lerp(top, bottom, y_lerp));
  2146. }
  2147. }
  2148. }
  2149. }
  2150. // Bicubic resize function
  2151. // part of image will be cropped if the aspect ratio is different
  2152. static bool resize_bicubic(const clip_image_u8 & img, clip_image_u8 & dst, int target_width, int target_height) {
  2153. const int nx = img.nx;
  2154. const int ny = img.ny;
  2155. dst.nx = target_width;
  2156. dst.ny = target_height;
  2157. dst.buf.resize(3 * target_width * target_height);
  2158. float Cc;
  2159. float C[5] = {};
  2160. float d0, d2, d3, a0, a1, a2, a3;
  2161. int i, j, k, jj;
  2162. int x, y;
  2163. float dx, dy;
  2164. float tx, ty;
  2165. tx = (float)nx / (float)target_width;
  2166. ty = (float)ny / (float)target_height;
  2167. // Bicubic interpolation; adapted from ViT.cpp, inspired from :
  2168. // -> https://github.com/yglukhov/bicubic-interpolation-image-processing/blob/master/libimage.c#L36
  2169. // -> https://en.wikipedia.org/wiki/Bicubic_interpolation
  2170. for (i = 0; i < target_height; i++) {
  2171. for (j = 0; j < target_width; j++) {
  2172. x = (int)(tx * j);
  2173. y = (int)(ty * i);
  2174. dx = tx * j - x;
  2175. dy = ty * i - y;
  2176. for (k = 0; k < 3; k++) {
  2177. for (jj = 0; jj <= 3; jj++) {
  2178. 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];
  2179. 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];
  2180. 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];
  2181. a0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  2182. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  2183. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  2184. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  2185. C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx;
  2186. d0 = C[0] - C[1];
  2187. d2 = C[2] - C[1];
  2188. d3 = C[3] - C[1];
  2189. a0 = C[1];
  2190. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  2191. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  2192. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  2193. Cc = a0 + a1 * dy + a2 * dy * dy + a3 * dy * dy * dy;
  2194. const uint8_t Cc2 = std::min(std::max(std::round(Cc), 0.0f), 255.0f);
  2195. dst.buf[(i * target_width + j) * 3 + k] = float(Cc2);
  2196. }
  2197. }
  2198. }
  2199. }
  2200. return true;
  2201. }
  2202. static inline int clip(int x, int lower, int upper) {
  2203. return std::max(lower, std::min(x, upper));
  2204. }
  2205. // Linear interpolation between two points
  2206. static inline float lerp(float s, float e, float t) {
  2207. return s + (e - s) * t;
  2208. }
  2209. };
  2210. /**
  2211. * implementation of LLaVA-UHD:
  2212. * - https://arxiv.org/pdf/2403.11703
  2213. * - https://github.com/thunlp/LLaVA-UHD
  2214. * - https://github.com/thunlp/LLaVA-UHD/blob/302301bc2175f7e717fb8548516188e89f649753/llava_uhd/train/llava-uhd/slice_logic.py#L118
  2215. *
  2216. * overview:
  2217. * - an image always have a single overview (downscaled image)
  2218. * - an image can have 0 or multiple slices, depending on the image size
  2219. * - each slice can then be considered as a separate image
  2220. *
  2221. * for example:
  2222. *
  2223. * [overview] --> [slice 1] --> [slice 2]
  2224. * | |
  2225. * +--> [slice 3] --> [slice 4]
  2226. */
  2227. struct llava_uhd {
  2228. struct slice_coordinates {
  2229. int x;
  2230. int y;
  2231. clip_image_size size;
  2232. };
  2233. struct slice_instructions {
  2234. clip_image_size overview_size; // size of downscaled image
  2235. clip_image_size refined_size; // size of image right before slicing (must be multiple of slice size)
  2236. clip_image_size grid_size; // grid_size.width * grid_size.height = number of slices
  2237. std::vector<slice_coordinates> slices;
  2238. img_tool::resize_algo interpolation_overview = img_tool::RESIZE_ALGO_BILINEAR;
  2239. bool padding_overview = false; // if true, refine image will be padded to the grid size (e.g. llava-1.6)
  2240. std::array<uint8_t, 3> pad_color_overview = {0, 0, 0};
  2241. img_tool::resize_algo interpolation_refined = img_tool::RESIZE_ALGO_BICUBIC;
  2242. bool padding_refined = false; // if true, refine image will be padded to the grid size (e.g. llava-1.6)
  2243. std::array<uint8_t, 3> pad_color_refined = {0, 0, 0};
  2244. };
  2245. static slice_instructions get_slice_instructions(struct clip_ctx * ctx, const clip_image_size & original_size) {
  2246. slice_instructions res;
  2247. const int patch_size = clip_get_patch_size(ctx);
  2248. const int slice_size = clip_get_image_size(ctx);
  2249. const int original_width = original_size.width;
  2250. const int original_height = original_size.height;
  2251. const bool has_slices = original_size.width > slice_size || original_size.height > slice_size;
  2252. const bool has_pinpoints = !ctx->model.hparams.image_res_candidates.empty();
  2253. if (!has_slices) {
  2254. // skip slicing logic
  2255. res.overview_size = clip_image_size{slice_size, slice_size};
  2256. res.refined_size = clip_image_size{0, 0};
  2257. res.grid_size = clip_image_size{0, 0};
  2258. return res;
  2259. }
  2260. if (has_pinpoints) {
  2261. // has pinpoints, use them to calculate the grid size (e.g. llava-1.6)
  2262. auto refine_size = llava_uhd::select_best_resolution(
  2263. original_size,
  2264. ctx->model.hparams.image_res_candidates);
  2265. res.overview_size = clip_image_size{slice_size, slice_size};
  2266. res.refined_size = refine_size;
  2267. res.grid_size = clip_image_size{0, 0};
  2268. res.padding_refined = true;
  2269. res.interpolation_refined = img_tool::RESIZE_ALGO_BILINEAR; // preserve old behavior when padding
  2270. LOG_DBG("%s: using pinpoints for slicing\n", __func__);
  2271. LOG_DBG("%s: original size: %d x %d, overview size: %d x %d, refined size: %d x %d\n",
  2272. __func__, original_width, original_height,
  2273. res.overview_size.width, res.overview_size.height,
  2274. res.refined_size.width, res.refined_size.height);
  2275. for (int y = 0; y < refine_size.height; y += slice_size) {
  2276. for (int x = 0; x < refine_size.width; x += slice_size) {
  2277. slice_coordinates slice;
  2278. slice.x = x;
  2279. slice.y = y;
  2280. slice.size.width = std::min(slice_size, refine_size.width - x);
  2281. slice.size.height = std::min(slice_size, refine_size.height - y);
  2282. res.slices.push_back(slice);
  2283. LOG_DBG("%s: slice %d: x=%d, y=%d, size=%dx%d\n",
  2284. __func__, (int)res.slices.size() - 1,
  2285. slice.x, slice.y, slice.size.width, slice.size.height);
  2286. }
  2287. }
  2288. res.grid_size.height = refine_size.height / slice_size;
  2289. res.grid_size.width = refine_size.width / slice_size;
  2290. LOG_DBG("%s: grid size: %d x %d\n", __func__, res.grid_size.width, res.grid_size.height);
  2291. return res;
  2292. }
  2293. // no pinpoints, dynamically calculate the grid size (e.g. minicpmv)
  2294. auto best_size = get_best_resize(original_size, slice_size, patch_size, !has_slices);
  2295. res.overview_size = best_size;
  2296. {
  2297. const int max_slice_nums = 9; // TODO: this is only used by minicpmv, maybe remove it
  2298. const float log_ratio = log((float)original_width / original_height);
  2299. const float ratio = (float)original_width * original_height / (slice_size * slice_size);
  2300. const int multiple = fmin(ceil(ratio), max_slice_nums);
  2301. auto best_grid = get_best_grid(max_slice_nums, multiple, log_ratio);
  2302. auto refine_size = get_refine_size(original_size, best_grid, slice_size, patch_size, true);
  2303. res.grid_size = best_grid;
  2304. res.refined_size = refine_size;
  2305. LOG_DBG("%s: original size: %d x %d, overview size: %d x %d, refined size: %d x %d, grid size: %d x %d\n",
  2306. __func__, original_width, original_height,
  2307. res.overview_size.width, res.overview_size.height,
  2308. res.refined_size.width, res.refined_size.height,
  2309. res.grid_size.width, res.grid_size.height);
  2310. int width = refine_size.width;
  2311. int height = refine_size.height;
  2312. int grid_x = int(width / best_grid.width);
  2313. int grid_y = int(height / best_grid.height);
  2314. for (int patches_y = 0, ic = 0;
  2315. patches_y < refine_size.height && ic < best_grid.height;
  2316. patches_y += grid_y, ic += 1) {
  2317. for (int patches_x = 0, jc = 0;
  2318. patches_x < refine_size.width && jc < best_grid.width;
  2319. patches_x += grid_x, jc += 1) {
  2320. slice_coordinates slice;
  2321. slice.x = patches_x;
  2322. slice.y = patches_y;
  2323. slice.size.width = grid_x;
  2324. slice.size.height = grid_y;
  2325. res.slices.push_back(slice);
  2326. LOG_DBG("%s: slice %d: x=%d, y=%d, size=%dx%d\n",
  2327. __func__, (int)res.slices.size() - 1,
  2328. slice.x, slice.y, slice.size.width, slice.size.height);
  2329. }
  2330. }
  2331. }
  2332. return res;
  2333. }
  2334. static std::vector<clip_image_u8_ptr> slice_image(const clip_image_u8 * img, const slice_instructions & inst) {
  2335. std::vector<clip_image_u8_ptr> output;
  2336. // resize to overview size
  2337. clip_image_u8_ptr resized_img(clip_image_u8_init());
  2338. img_tool::resize(*img, *resized_img, inst.overview_size, inst.interpolation_overview,
  2339. inst.padding_overview, inst.pad_color_overview);
  2340. output.push_back(std::move(resized_img));
  2341. if (inst.slices.empty()) {
  2342. // no slices, just return the resized image
  2343. return output;
  2344. }
  2345. // resize to refined size
  2346. clip_image_u8_ptr refined_img(clip_image_u8_init());
  2347. img_tool::resize(*img, *refined_img, inst.refined_size, inst.interpolation_refined,
  2348. inst.padding_refined, inst.pad_color_refined);
  2349. // create slices
  2350. for (const auto & slice : inst.slices) {
  2351. int x = slice.x;
  2352. int y = slice.y;
  2353. int w = slice.size.width;
  2354. int h = slice.size.height;
  2355. clip_image_u8_ptr img_slice(clip_image_u8_init());
  2356. img_tool::crop(*refined_img, *img_slice, x, y, w, h);
  2357. output.push_back(std::move(img_slice));
  2358. }
  2359. return output;
  2360. }
  2361. private:
  2362. static clip_image_size get_best_resize(const clip_image_size & original_size, int scale_resolution, int patch_size, bool allow_upscale = false) {
  2363. int width = original_size.width;
  2364. int height = original_size.height;
  2365. if ((width * height > scale_resolution * scale_resolution) || allow_upscale) {
  2366. float r = static_cast<float>(width) / height;
  2367. height = static_cast<int>(scale_resolution / std::sqrt(r));
  2368. width = static_cast<int>(height * r);
  2369. }
  2370. clip_image_size res;
  2371. res.width = ensure_divide(width, patch_size);
  2372. res.height = ensure_divide(height, patch_size);
  2373. return res;
  2374. }
  2375. static clip_image_size resize_maintain_aspect_ratio(const clip_image_size & orig, const clip_image_size & target_max) {
  2376. float scale_width = static_cast<float>(target_max.width) / orig.width;
  2377. float scale_height = static_cast<float>(target_max.height) / orig.height;
  2378. float scale = std::min(scale_width, scale_height);
  2379. return clip_image_size{
  2380. static_cast<int>(orig.width * scale),
  2381. static_cast<int>(orig.height * scale),
  2382. };
  2383. }
  2384. /**
  2385. * Selects the best resolution from a list of possible resolutions based on the original size.
  2386. *
  2387. * For example, when given a list of resolutions:
  2388. * - 100x100
  2389. * - 200x100
  2390. * - 100x200
  2391. * - 200x200
  2392. *
  2393. * And an input image of size 111x200, then 100x200 is the best fit (least wasted resolution).
  2394. *
  2395. * @param original_size The original size of the image
  2396. * @param possible_resolutions A list of possible resolutions
  2397. * @return The best fit resolution
  2398. */
  2399. static clip_image_size select_best_resolution(const clip_image_size & original_size, const std::vector<clip_image_size> & possible_resolutions) {
  2400. clip_image_size best_fit;
  2401. int min_wasted_area = std::numeric_limits<int>::max();
  2402. int max_effective_resolution = 0;
  2403. for (const clip_image_size & candidate : possible_resolutions) {
  2404. auto target_size = resize_maintain_aspect_ratio(original_size, candidate);
  2405. int effective_resolution = std::min(
  2406. target_size.width * target_size.height,
  2407. original_size.width * original_size.height);
  2408. int wasted_area = (candidate.width * candidate.height) - effective_resolution;
  2409. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_area < min_wasted_area)) {
  2410. max_effective_resolution = effective_resolution;
  2411. min_wasted_area = wasted_area;
  2412. best_fit = candidate;
  2413. }
  2414. LOG_DBG("%s: candidate: %d x %d, target: %d x %d, wasted: %d, effective: %d\n", __func__, candidate.width, candidate.height, target_size.width, target_size.height, wasted_area, effective_resolution);
  2415. }
  2416. return best_fit;
  2417. }
  2418. static int ensure_divide(int length, int patch_size) {
  2419. return std::max(static_cast<int>(std::round(static_cast<float>(length) / patch_size) * patch_size), patch_size);
  2420. }
  2421. 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) {
  2422. int width = original_size.width;
  2423. int height = original_size.height;
  2424. int grid_x = grid.width;
  2425. int grid_y = grid.height;
  2426. int refine_width = ensure_divide(width, grid_x);
  2427. int refine_height = ensure_divide(height, grid_y);
  2428. clip_image_size grid_size;
  2429. grid_size.width = refine_width / grid_x;
  2430. grid_size.height = refine_height / grid_y;
  2431. auto best_grid_size = get_best_resize(grid_size, scale_resolution, patch_size, allow_upscale);
  2432. int best_grid_width = best_grid_size.width;
  2433. int best_grid_height = best_grid_size.height;
  2434. clip_image_size refine_size;
  2435. refine_size.width = best_grid_width * grid_x;
  2436. refine_size.height = best_grid_height * grid_y;
  2437. return refine_size;
  2438. }
  2439. static clip_image_size get_best_grid(const int max_slice_nums, const int multiple, const float log_ratio) {
  2440. std::vector<int> candidate_split_grids_nums;
  2441. for (int i : {multiple - 1, multiple, multiple + 1}) {
  2442. if (i == 1 || i > max_slice_nums) {
  2443. continue;
  2444. }
  2445. candidate_split_grids_nums.push_back(i);
  2446. }
  2447. std::vector<clip_image_size> candidate_grids;
  2448. for (int split_grids_nums : candidate_split_grids_nums) {
  2449. int m = 1;
  2450. while (m <= split_grids_nums) {
  2451. if (split_grids_nums % m == 0) {
  2452. candidate_grids.push_back(clip_image_size{m, split_grids_nums / m});
  2453. }
  2454. ++m;
  2455. }
  2456. }
  2457. clip_image_size best_grid{1, 1};
  2458. float min_error = std::numeric_limits<float>::infinity();
  2459. for (const auto& grid : candidate_grids) {
  2460. float error = std::abs(log_ratio - std::log(1.0 * grid.width / grid.height));
  2461. if (error < min_error) {
  2462. best_grid = grid;
  2463. min_error = error;
  2464. }
  2465. }
  2466. return best_grid;
  2467. }
  2468. };
  2469. // 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
  2470. // res_imgs memory is being allocated here, previous allocations will be freed if found
  2471. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, struct clip_image_f32_batch * res_imgs) {
  2472. clip_image_size original_size{img->nx, img->ny};
  2473. auto & params = ctx->model.hparams;
  2474. switch (ctx->proj_type()) {
  2475. case PROJECTOR_TYPE_MINICPMV:
  2476. {
  2477. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2478. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2479. for (size_t i = 0; i < imgs.size(); ++i) {
  2480. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2481. clip_image_f32_ptr res(clip_image_f32_init());
  2482. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2483. res_imgs->entries.push_back(std::move(res));
  2484. }
  2485. res_imgs->grid_x = inst.grid_size.width;
  2486. res_imgs->grid_y = inst.grid_size.height;
  2487. } break;
  2488. case PROJECTOR_TYPE_QWEN2VL:
  2489. case PROJECTOR_TYPE_QWEN25VL:
  2490. case PROJECTOR_TYPE_QWEN3VL:
  2491. case PROJECTOR_TYPE_GLM4V:
  2492. {
  2493. GGML_ASSERT(params.image_min_pixels > 0 && params.image_max_pixels > 0);
  2494. clip_image_u8 resized;
  2495. const clip_image_size new_size = img_tool::calc_size_preserved_ratio(
  2496. original_size,
  2497. params.patch_size * 2,
  2498. params.image_min_pixels,
  2499. params.image_max_pixels);
  2500. img_tool::resize(*img, resized, new_size, img_tool::RESIZE_ALGO_BILINEAR, false);
  2501. // clip_image_save_to_bmp(resized, "preproc.bmp");
  2502. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2503. // clip_image_f32_ptr res(clip_image_f32_init());
  2504. normalize_image_u8_to_f32(resized, *img_f32, params.image_mean, params.image_std);
  2505. // res_imgs->data[0] = *res;
  2506. res_imgs->entries.push_back(std::move(img_f32));
  2507. } break;
  2508. case PROJECTOR_TYPE_YOUTUVL:
  2509. {
  2510. const int patch_size = params.patch_size; // typically 16
  2511. const int merge_size = params.n_merge; // typically 2
  2512. const int align_size = patch_size * merge_size; // 32
  2513. const int max_num_patches = params.image_max_pixels > 0 ?
  2514. params.image_max_pixels / (patch_size * patch_size) : 256;
  2515. // Linear search for optimal scale to fit within max_num_patches
  2516. float scale = 1.0f;
  2517. int target_height = original_size.height;
  2518. int target_width = original_size.width;
  2519. auto get_scaled_image_size = [align_size](float scale, int size) -> int {
  2520. float scaled_size = size * scale;
  2521. // Round up to nearest multiple of align_size
  2522. int aligned = static_cast<int>(std::ceil(scaled_size / align_size)) * align_size;
  2523. // Ensure at least one patch
  2524. return std::max(align_size, aligned);
  2525. };
  2526. // Linear search with 0.02 step size
  2527. while (scale > 0.0f) {
  2528. target_height = get_scaled_image_size(scale, original_size.height);
  2529. target_width = get_scaled_image_size(scale, original_size.width);
  2530. int num_patches_h = target_height / patch_size;
  2531. int num_patches_w = target_width / patch_size;
  2532. int num_patches = num_patches_h * num_patches_w;
  2533. if (num_patches > max_num_patches) {
  2534. scale -= 0.02f;
  2535. } else {
  2536. break;
  2537. }
  2538. }
  2539. clip_image_size new_size = {target_width, target_height};
  2540. // Resize the image
  2541. clip_image_u8 resized;
  2542. img_tool::resize(*img, resized, new_size, img_tool::RESIZE_ALGO_BILINEAR, false);
  2543. // Normalize to float32
  2544. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2545. normalize_image_u8_to_f32(resized, *img_f32, params.image_mean, params.image_std);
  2546. // Add to results
  2547. res_imgs->entries.push_back(std::move(img_f32));
  2548. } break;
  2549. case PROJECTOR_TYPE_IDEFICS3:
  2550. {
  2551. // The refined size has two steps:
  2552. // 1. Resize w/ aspect-ratio preserving such that the longer side is
  2553. // the preprocessor longest size
  2554. // 2. Resize w/out preserving aspect ratio such that both sides are
  2555. // multiples of image_size (always rounding up)
  2556. //
  2557. // CITE: https://github.com/huggingface/transformers/blob/main/src/transformers/models/idefics3/image_processing_idefics3.py#L737
  2558. const clip_image_size refined_size = img_tool::calc_size_preserved_ratio(
  2559. original_size, params.image_size, params.image_longest_edge);
  2560. // LOG_INF("%s: original size: %d x %d, refined size: %d x %d\n",
  2561. // __func__, original_size.width, original_size.height,
  2562. // refined_size.width, refined_size.height);
  2563. llava_uhd::slice_instructions instructions;
  2564. instructions.overview_size = clip_image_size{params.image_size, params.image_size};
  2565. instructions.refined_size = refined_size;
  2566. instructions.grid_size = clip_image_size{
  2567. static_cast<int>(std::ceil(static_cast<float>(refined_size.width) / params.image_size)),
  2568. static_cast<int>(std::ceil(static_cast<float>(refined_size.height) / params.image_size)),
  2569. };
  2570. for (int y = 0; y < refined_size.height; y += params.image_size) {
  2571. for (int x = 0; x < refined_size.width; x += params.image_size) {
  2572. // LOG_INF("%s: adding slice at x=%d, y=%d\n", __func__, x, y);
  2573. instructions.slices.push_back(llava_uhd::slice_coordinates{
  2574. /* x */x,
  2575. /* y */y,
  2576. /* size */clip_image_size{
  2577. std::min(params.image_size, refined_size.width - x),
  2578. std::min(params.image_size, refined_size.height - y)
  2579. }
  2580. });
  2581. }
  2582. }
  2583. auto imgs = llava_uhd::slice_image(img, instructions);
  2584. // cast and normalize to f32
  2585. for (size_t i = 0; i < imgs.size(); ++i) {
  2586. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2587. clip_image_f32_ptr res(clip_image_f32_init());
  2588. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2589. res_imgs->entries.push_back(std::move(res));
  2590. }
  2591. res_imgs->grid_x = instructions.grid_size.width;
  2592. res_imgs->grid_y = instructions.grid_size.height;
  2593. } break;
  2594. case PROJECTOR_TYPE_GLM_EDGE:
  2595. case PROJECTOR_TYPE_GEMMA3:
  2596. case PROJECTOR_TYPE_INTERNVL: // TODO @ngxson : support dynamic resolution
  2597. {
  2598. clip_image_u8 resized_image;
  2599. int sz = params.image_size;
  2600. img_tool::resize(*img, resized_image, {sz, sz}, img_tool::RESIZE_ALGO_BILINEAR);
  2601. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2602. //clip_image_save_to_bmp(resized_image, "resized.bmp");
  2603. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2604. res_imgs->entries.push_back(std::move(img_f32));
  2605. } break;
  2606. case PROJECTOR_TYPE_GEMMA3NV:
  2607. {
  2608. clip_image_u8 resized_image;
  2609. int sz = params.image_size;
  2610. img_tool::resize(*img, resized_image, {sz, sz}, img_tool::RESIZE_ALGO_BILINEAR, false);
  2611. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2612. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2613. res_imgs->entries.push_back(std::move(img_f32));
  2614. } break;
  2615. case PROJECTOR_TYPE_JANUS_PRO:
  2616. {
  2617. // Janus Pro preprocessing: pad to square with gray(127), resize to 384x384
  2618. const std::array<uint8_t, 3> pad_color = {127, 127, 127};
  2619. clip_image_u8 resized_image;
  2620. int sz = params.image_size;
  2621. img_tool::resize(*img, resized_image, {sz, sz}, img_tool::RESIZE_ALGO_BILINEAR, true, pad_color);
  2622. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2623. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2624. res_imgs->entries.push_back(std::move(img_f32));
  2625. } break;
  2626. case PROJECTOR_TYPE_PIXTRAL:
  2627. case PROJECTOR_TYPE_LIGHTONOCR:
  2628. {
  2629. GGML_ASSERT(params.image_min_pixels > 0 && params.image_max_pixels > 0);
  2630. clip_image_u8 resized_image;
  2631. // the original pixtral model doesn't have n_merge
  2632. const int cur_merge = params.n_merge == 0 ? 1 : params.n_merge;
  2633. const clip_image_size target_size = img_tool::calc_size_preserved_ratio(
  2634. original_size,
  2635. params.patch_size * cur_merge,
  2636. params.image_min_pixels,
  2637. params.image_max_pixels);
  2638. img_tool::resize(*img, resized_image, target_size, img_tool::RESIZE_ALGO_BILINEAR);
  2639. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2640. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2641. res_imgs->entries.push_back(std::move(img_f32));
  2642. } break;
  2643. case PROJECTOR_TYPE_LLAMA4:
  2644. {
  2645. GGML_ASSERT(!params.image_res_candidates.empty());
  2646. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2647. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2648. for (size_t i = 0; i < imgs.size(); ++i) {
  2649. clip_image_f32_ptr res(clip_image_f32_init());
  2650. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2651. res_imgs->entries.push_back(std::move(res));
  2652. }
  2653. res_imgs->grid_x = inst.grid_size.width;
  2654. res_imgs->grid_y = inst.grid_size.height;
  2655. } break;
  2656. case PROJECTOR_TYPE_LFM2:
  2657. case PROJECTOR_TYPE_KIMIVL:
  2658. {
  2659. GGML_ASSERT(params.image_min_pixels > 0 && params.image_max_pixels > 0);
  2660. const clip_image_size target_size = img_tool::calc_size_preserved_ratio(
  2661. original_size,
  2662. params.patch_size * params.n_merge,
  2663. params.image_min_pixels,
  2664. params.image_max_pixels);
  2665. const std::array<uint8_t, 3> pad_color = {122, 116, 104};
  2666. clip_image_u8 resized_img;
  2667. const bool pad = (ctx->proj_type() != PROJECTOR_TYPE_LFM2);
  2668. img_tool::resize(*img, resized_img, target_size, img_tool::RESIZE_ALGO_BILINEAR, pad, pad_color);
  2669. clip_image_f32_ptr res(clip_image_f32_init());
  2670. normalize_image_u8_to_f32(resized_img, *res, params.image_mean, params.image_std);
  2671. res_imgs->entries.push_back(std::move(res));
  2672. } break;
  2673. case PROJECTOR_TYPE_MLP:
  2674. case PROJECTOR_TYPE_MLP_NORM:
  2675. case PROJECTOR_TYPE_LDP:
  2676. case PROJECTOR_TYPE_LDPV2:
  2677. case PROJECTOR_TYPE_COGVLM: // TODO @ngxson : is this correct for cogvlm?
  2678. {
  2679. // TODO @ngxson : refactor the code below to avoid duplicated logic
  2680. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  2681. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  2682. clip_image_u8_ptr temp(clip_image_u8_init()); // we will keep the input image data here temporarily
  2683. // 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
  2684. if (params.image_res_candidates.empty()) { // pad_to_square
  2685. // for llava-1.5, we resize image to a square, and pad the shorter side with a background color
  2686. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  2687. const int longer_side = std::max(img->nx, img->ny);
  2688. temp->nx = longer_side;
  2689. temp->ny = longer_side;
  2690. temp->buf.resize(3 * longer_side * longer_side);
  2691. // background color in RGB from LLaVA (this is the mean rgb color * 255)
  2692. const std::array<uint8_t, 3> pad_color = {122, 116, 104};
  2693. // resize the image to the target_size
  2694. img_tool::resize(*img, *temp, clip_image_size{params.image_size, params.image_size}, img_tool::RESIZE_ALGO_BILINEAR, true, pad_color);
  2695. clip_image_f32_ptr res(clip_image_f32_init());
  2696. normalize_image_u8_to_f32(*temp, *res, params.image_mean, params.image_std);
  2697. res_imgs->entries.push_back(std::move(res));
  2698. } else {
  2699. // "spatial_unpad" with "anyres" processing for llava-1.6
  2700. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2701. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2702. for (size_t i = 0; i < imgs.size(); ++i) {
  2703. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2704. clip_image_f32_ptr res(clip_image_f32_init());
  2705. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2706. res_imgs->entries.push_back(std::move(res));
  2707. }
  2708. }
  2709. } break;
  2710. default:
  2711. LOG_ERR("%s: unsupported projector type %d\n", __func__, ctx->proj_type());
  2712. return false;
  2713. }
  2714. return true;
  2715. }
  2716. ggml_tensor * clip_get_newline_tensor(const struct clip_ctx * ctx) {
  2717. return ctx->model.image_newline;
  2718. }
  2719. void clip_free(clip_ctx * ctx) {
  2720. if (ctx == nullptr) {
  2721. return;
  2722. }
  2723. delete ctx;
  2724. }
  2725. // deprecated
  2726. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  2727. const int32_t nx = ctx->model.hparams.image_size;
  2728. const int32_t ny = ctx->model.hparams.image_size;
  2729. return clip_embd_nbytes_by_img(ctx, nx, ny);
  2730. }
  2731. size_t clip_embd_nbytes_by_img(const struct clip_ctx * ctx, int img_w, int img_h) {
  2732. clip_image_f32 img;
  2733. img.nx = img_w;
  2734. img.ny = img_h;
  2735. return clip_n_output_tokens(ctx, &img) * clip_n_mmproj_embd(ctx) * sizeof(float);
  2736. }
  2737. int32_t clip_get_image_size(const struct clip_ctx * ctx) {
  2738. return ctx->model.hparams.image_size;
  2739. }
  2740. int32_t clip_get_patch_size(const struct clip_ctx * ctx) {
  2741. return ctx->model.hparams.patch_size;
  2742. }
  2743. int32_t clip_get_hidden_size(const struct clip_ctx * ctx) {
  2744. return ctx->model.hparams.n_embd;
  2745. }
  2746. const char * clip_patch_merge_type(const struct clip_ctx * ctx) {
  2747. return ctx->model.hparams.mm_patch_merge_type == PATCH_MERGE_SPATIAL_UNPAD ? "spatial_unpad" : "flat";
  2748. }
  2749. int clip_n_output_tokens_x(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2750. const auto & params = ctx->model.hparams;
  2751. const int n_total = clip_n_output_tokens(ctx, img);
  2752. const auto & proj = ctx->proj_type();
  2753. switch (proj) {
  2754. case PROJECTOR_TYPE_QWEN2VL:
  2755. case PROJECTOR_TYPE_QWEN25VL:
  2756. case PROJECTOR_TYPE_QWEN3VL:
  2757. case PROJECTOR_TYPE_GLM4V:
  2758. case PROJECTOR_TYPE_YOUTUVL:
  2759. return (img->nx / params.patch_size) / 2;
  2760. default:
  2761. break;
  2762. }
  2763. return n_total;
  2764. }
  2765. int clip_n_output_tokens_y(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2766. const auto & params = ctx->model.hparams;
  2767. const auto & proj = ctx->proj_type();
  2768. switch (proj) {
  2769. case PROJECTOR_TYPE_QWEN2VL:
  2770. case PROJECTOR_TYPE_QWEN25VL:
  2771. case PROJECTOR_TYPE_QWEN3VL:
  2772. case PROJECTOR_TYPE_GLM4V:
  2773. case PROJECTOR_TYPE_YOUTUVL:
  2774. return (img->ny / params.patch_size) / 2;
  2775. default:
  2776. break;
  2777. }
  2778. return 1;
  2779. }
  2780. int clip_n_output_tokens(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2781. const auto & params = ctx->model.hparams;
  2782. // for models with fixed size image, the input image is already pre-processed and resized to square
  2783. int patch_size = params.patch_size;
  2784. int n_patches = (img->nx / patch_size) * (img->ny / patch_size);
  2785. projector_type proj = ctx->proj_type();
  2786. switch (proj) {
  2787. case PROJECTOR_TYPE_MLP:
  2788. case PROJECTOR_TYPE_MLP_NORM:
  2789. case PROJECTOR_TYPE_JANUS_PRO:
  2790. {
  2791. // do nothing
  2792. } break;
  2793. case PROJECTOR_TYPE_LDP:
  2794. case PROJECTOR_TYPE_LDPV2:
  2795. case PROJECTOR_TYPE_GLM_EDGE:
  2796. {
  2797. n_patches /= 4;
  2798. if (ctx->model.mm_boi) {
  2799. n_patches += 2; // for BOI and EOI token embeddings
  2800. }
  2801. } break;
  2802. case PROJECTOR_TYPE_MINICPMV:
  2803. {
  2804. // Use actual config value if available, otherwise fall back to hardcoded values
  2805. if (params.minicpmv_query_num > 0) {
  2806. n_patches = params.minicpmv_query_num;
  2807. } else {
  2808. // Fallback to hardcoded values for legacy models
  2809. if (params.minicpmv_version == 2) {
  2810. n_patches = 96;
  2811. } else if (params.minicpmv_version == 3) {
  2812. n_patches = 64;
  2813. } else if (params.minicpmv_version == 4) {
  2814. n_patches = 64;
  2815. } else if (params.minicpmv_version == 5) {
  2816. // MiniCPM-V 4.0
  2817. n_patches = 64;
  2818. } else if (params.minicpmv_version == 6) {
  2819. // MiniCPM-V 4.5
  2820. n_patches = 64;
  2821. } else {
  2822. GGML_ABORT("Unknown minicpmv version");
  2823. }
  2824. }
  2825. } break;
  2826. case PROJECTOR_TYPE_QWEN2VL:
  2827. case PROJECTOR_TYPE_QWEN25VL:
  2828. case PROJECTOR_TYPE_QWEN3VL:
  2829. case PROJECTOR_TYPE_GLM4V:
  2830. case PROJECTOR_TYPE_YOUTUVL:
  2831. {
  2832. // dynamic size (2 conv, so double patch size)
  2833. int x_patch = img->nx / (params.patch_size * 2);
  2834. int y_patch = img->ny / (params.patch_size * 2);
  2835. n_patches = x_patch * y_patch;
  2836. } break;
  2837. case PROJECTOR_TYPE_GEMMA3:
  2838. case PROJECTOR_TYPE_IDEFICS3:
  2839. case PROJECTOR_TYPE_INTERNVL:
  2840. case PROJECTOR_TYPE_LLAMA4:
  2841. {
  2842. // both X and Y are downscaled by the scale factor
  2843. int scale_factor = ctx->model.hparams.n_merge;
  2844. n_patches /= (scale_factor * scale_factor);
  2845. } break;
  2846. case PROJECTOR_TYPE_GEMMA3NV:
  2847. {
  2848. // MobileNetV5 MSFA adapter always outputs fixed 16x16 resolution
  2849. // regardless of input size (see architecture description)
  2850. n_patches = ctx->model.hparams.image_size / ctx->model.hparams.patch_size;
  2851. } break;
  2852. case PROJECTOR_TYPE_LFM2:
  2853. case PROJECTOR_TYPE_KIMIVL:
  2854. {
  2855. // dynamic size
  2856. int out_patch_size = params.patch_size * ctx->model.hparams.n_merge;
  2857. int x_patch = CLIP_ALIGN(img->nx, out_patch_size) / out_patch_size;
  2858. int y_patch = CLIP_ALIGN(img->ny, out_patch_size) / out_patch_size;
  2859. n_patches = x_patch * y_patch;
  2860. } break;
  2861. case PROJECTOR_TYPE_PIXTRAL:
  2862. case PROJECTOR_TYPE_LIGHTONOCR:
  2863. {
  2864. // dynamic size
  2865. int n_merge = ctx->model.hparams.n_merge;
  2866. int n_patches_x = img->nx / patch_size / (n_merge > 0 ? n_merge : 1);
  2867. int n_patches_y = img->ny / patch_size / (n_merge > 0 ? n_merge : 1);
  2868. if (ctx->model.token_embd_img_break) {
  2869. n_patches = n_patches_y * n_patches_x + n_patches_y - 1; // + one [IMG_BREAK] per row, except the last row
  2870. } else {
  2871. n_patches = n_patches_y * n_patches_x;
  2872. }
  2873. } break;
  2874. case PROJECTOR_TYPE_VOXTRAL:
  2875. case PROJECTOR_TYPE_ULTRAVOX:
  2876. case PROJECTOR_TYPE_QWEN2A:
  2877. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  2878. {
  2879. n_patches = img->nx;
  2880. const int proj_stack_factor = ctx->model.hparams.proj_stack_factor;
  2881. if (ctx->model.audio_has_stack_frames()) {
  2882. GGML_ASSERT(proj_stack_factor > 0);
  2883. const int n_len = CLIP_ALIGN(n_patches, proj_stack_factor);
  2884. n_patches = n_len / proj_stack_factor;
  2885. }
  2886. // whisper downscales input token by half after conv1d
  2887. n_patches /= 2;
  2888. if (ctx->model.audio_has_avgpool()) {
  2889. // divide by 2 because of nn.AvgPool1d(2, stride=2)
  2890. n_patches /= 2;
  2891. }
  2892. } break;
  2893. case PROJECTOR_TYPE_GLMA:
  2894. {
  2895. n_patches = img->nx;
  2896. // whisper downscales input token by half after conv1d
  2897. n_patches /= 2;
  2898. // reshape by merge_factor
  2899. n_patches /= ctx->model.hparams.proj_stack_factor;
  2900. // for BOI and EOI token embeddings
  2901. n_patches += 2;
  2902. } break;
  2903. case PROJECTOR_TYPE_COGVLM:
  2904. {
  2905. n_patches += 2; // for BOI and EOI token embeddings
  2906. } break;
  2907. case PROJECTOR_TYPE_LFM2A:
  2908. {
  2909. n_patches = ((((img->nx + 1) / 2) + 1) / 2 + 1) / 2;
  2910. } break;
  2911. default:
  2912. GGML_ABORT("unsupported projector type");
  2913. }
  2914. return n_patches;
  2915. }
  2916. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  2917. clip_image_f32_batch imgs;
  2918. clip_image_f32_ptr img_copy(clip_image_f32_init());
  2919. *img_copy = *img;
  2920. imgs.entries.push_back(std::move(img_copy));
  2921. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  2922. }
  2923. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs_c_ptr, float * vec) {
  2924. const clip_image_f32_batch & imgs = *imgs_c_ptr;
  2925. int batch_size = imgs.entries.size();
  2926. // TODO @ngxson : implement batch size > 1 as a loop
  2927. // we don't need true batching support because the cgraph will gonna be big anyway
  2928. if (batch_size != 1) {
  2929. return false; // only support batch size of 1
  2930. }
  2931. // if buffers are not allocated, we need to do a warmup run to allocate them
  2932. if (!ctx->is_allocated) {
  2933. clip_model_loader::warmup(*ctx, *imgs_c_ptr);
  2934. }
  2935. // build the inference graph
  2936. ggml_backend_sched_reset(ctx->sched.get());
  2937. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs);
  2938. ggml_backend_sched_alloc_graph(ctx->sched.get(), gf);
  2939. // set inputs
  2940. const auto & model = ctx->model;
  2941. const auto & hparams = model.hparams;
  2942. const int image_size_width = imgs.entries[0]->nx;
  2943. const int image_size_height = imgs.entries[0]->ny;
  2944. const int patch_size = hparams.patch_size;
  2945. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  2946. const int n_pos = num_patches + (model.class_embedding ? 1 : 0);
  2947. const int pos_w = image_size_width / patch_size;
  2948. const int pos_h = image_size_height / patch_size;
  2949. auto get_inp_tensor = [&gf](const char * name) {
  2950. ggml_tensor * inp = ggml_graph_get_tensor(gf, name);
  2951. if (inp == nullptr) {
  2952. GGML_ABORT("Failed to get tensor %s", name);
  2953. }
  2954. if (!(inp->flags & GGML_TENSOR_FLAG_INPUT)) {
  2955. GGML_ABORT("Tensor %s is not an input tensor", name);
  2956. }
  2957. return inp;
  2958. };
  2959. auto set_input_f32 = [&get_inp_tensor](const char * name, std::vector<float> & values) {
  2960. ggml_tensor * cur = get_inp_tensor(name);
  2961. GGML_ASSERT(cur->type == GGML_TYPE_F32);
  2962. GGML_ASSERT(ggml_nelements(cur) == (int64_t)values.size());
  2963. ggml_backend_tensor_set(cur, values.data(), 0, ggml_nbytes(cur));
  2964. };
  2965. auto set_input_i32 = [&get_inp_tensor](const char * name, std::vector<int32_t> & values) {
  2966. ggml_tensor * cur = get_inp_tensor(name);
  2967. GGML_ASSERT(cur->type == GGML_TYPE_I32);
  2968. GGML_ASSERT(ggml_nelements(cur) == (int64_t)values.size());
  2969. ggml_backend_tensor_set(cur, values.data(), 0, ggml_nbytes(cur));
  2970. };
  2971. // set input pixel values
  2972. if (!imgs.is_audio) {
  2973. size_t nelem = 0;
  2974. for (const auto & img : imgs.entries) {
  2975. nelem += img->nx * img->ny * 3;
  2976. }
  2977. std::vector<float> inp_raw(nelem);
  2978. // layout of data (note: the channel dim is unrolled to better visualize the layout):
  2979. //
  2980. // ┌──W──┐
  2981. // │ H │ channel = R
  2982. // ├─────┤ │
  2983. // │ H │ channel = G
  2984. // ├─────┤ │
  2985. // │ H │ channel = B
  2986. // └─────┘ │
  2987. // ──────┘ x B
  2988. for (size_t i = 0; i < imgs.entries.size(); i++) {
  2989. const int nx = imgs.entries[i]->nx;
  2990. const int ny = imgs.entries[i]->ny;
  2991. const int n = nx * ny;
  2992. for (int b = 0; b < batch_size; b++) {
  2993. float * batch_entry = inp_raw.data() + b * (3*n);
  2994. for (int y = 0; y < ny; y++) {
  2995. for (int x = 0; x < nx; x++) {
  2996. size_t base_src = 3*(y * nx + x); // idx of the first channel
  2997. size_t base_dst = y * nx + x; // idx of the first channel
  2998. batch_entry[ base_dst] = imgs.entries[b]->buf[base_src ];
  2999. batch_entry[1*n + base_dst] = imgs.entries[b]->buf[base_src + 1];
  3000. batch_entry[2*n + base_dst] = imgs.entries[b]->buf[base_src + 2];
  3001. }
  3002. }
  3003. }
  3004. }
  3005. set_input_f32("inp_raw", inp_raw);
  3006. } else {
  3007. // audio input
  3008. GGML_ASSERT(imgs.entries.size() == 1);
  3009. const auto & mel_inp = imgs.entries[0];
  3010. const int n_step = mel_inp->nx;
  3011. const int n_mel = mel_inp->ny;
  3012. std::vector<float> inp_raw(n_step * n_mel);
  3013. std::memcpy(inp_raw.data(), mel_inp->buf.data(), n_step * n_mel * sizeof(float));
  3014. set_input_f32("inp_raw", inp_raw);
  3015. }
  3016. // set input per projector
  3017. switch (ctx->model.proj_type) {
  3018. case PROJECTOR_TYPE_MINICPMV:
  3019. {
  3020. // inspired from siglip:
  3021. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit
  3022. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit/blob/d66538faeba44480d0bfaa42145eef26f9423199/modeling_siglip.py#L316
  3023. std::vector<int32_t> positions(pos_h * pos_w);
  3024. int bucket_coords_h[1024];
  3025. int bucket_coords_w[1024];
  3026. for (int i = 0; i < pos_h; i++){
  3027. bucket_coords_h[i] = std::floor(70.0*i/pos_h);
  3028. }
  3029. for (int i = 0; i < pos_w; i++){
  3030. bucket_coords_w[i] = std::floor(70.0*i/pos_w);
  3031. }
  3032. for (int i = 0, id = 0; i < pos_h; i++){
  3033. for (int j = 0; j < pos_w; j++){
  3034. positions[id++] = bucket_coords_h[i]*70 + bucket_coords_w[j];
  3035. }
  3036. }
  3037. set_input_i32("positions", positions);
  3038. // inputs for resampler projector
  3039. // set the 2D positions (using float for sinusoidal embedding)
  3040. int n_patches_per_col = image_size_width / patch_size;
  3041. std::vector<float> pos_data(n_pos);
  3042. // dimension H
  3043. for (int i = 0; i < n_pos; i++) {
  3044. pos_data[i] = static_cast<float>(i / n_patches_per_col);
  3045. }
  3046. set_input_f32("pos_h", pos_data);
  3047. // dimension W
  3048. for (int i = 0; i < n_pos; i++) {
  3049. pos_data[i] = static_cast<float>(i % n_patches_per_col);
  3050. }
  3051. set_input_f32("pos_w", pos_data);
  3052. // base frequency omega
  3053. const float base_freq = 10000.0f;
  3054. const int n_embd_proj = clip_n_mmproj_embd(ctx);
  3055. std::vector<float> omega(n_embd_proj / 4);
  3056. for (int i = 0; i < n_embd_proj / 4; ++i) {
  3057. omega[i] = 1.0f / std::pow(base_freq, static_cast<float>(i) / (n_embd_proj / 4));
  3058. }
  3059. set_input_f32("omega", omega);
  3060. } break;
  3061. case PROJECTOR_TYPE_QWEN2VL:
  3062. case PROJECTOR_TYPE_QWEN3VL:
  3063. case PROJECTOR_TYPE_GLM4V:
  3064. {
  3065. const int merge_ratio = hparams.n_merge;
  3066. const int pw = image_size_width / patch_size;
  3067. const int ph = image_size_height / patch_size;
  3068. std::vector<int> positions(n_pos * 4);
  3069. int ptr = 0;
  3070. for (int y = 0; y < ph; y += merge_ratio) {
  3071. for (int x = 0; x < pw; x += merge_ratio) {
  3072. for (int dy = 0; dy < 2; dy++) {
  3073. for (int dx = 0; dx < 2; dx++) {
  3074. positions[ ptr] = y + dy;
  3075. positions[ num_patches + ptr] = x + dx;
  3076. positions[2 * num_patches + ptr] = y + dy;
  3077. positions[3 * num_patches + ptr] = x + dx;
  3078. ptr++;
  3079. }
  3080. }
  3081. }
  3082. }
  3083. set_input_i32("positions", positions);
  3084. } break;
  3085. case PROJECTOR_TYPE_QWEN25VL:
  3086. case PROJECTOR_TYPE_YOUTUVL:
  3087. {
  3088. // pw * ph = number of tokens output by ViT after apply patch merger
  3089. // ipw * ipw = number of vision token been processed inside ViT
  3090. const bool use_window_attn = ctx->model.proj_type == PROJECTOR_TYPE_QWEN25VL ? hparams.n_wa_pattern > 0 : !hparams.wa_layer_indexes.empty();
  3091. const int merge_ratio = 2;
  3092. const int pw = image_size_width / patch_size / merge_ratio;
  3093. const int ph = image_size_height / patch_size / merge_ratio;
  3094. const int ipw = image_size_width / patch_size;
  3095. const int iph = image_size_height / patch_size;
  3096. std::vector<int> idx (ph * pw);
  3097. std::vector<int> inv_idx(ph * pw);
  3098. if (use_window_attn) {
  3099. const int attn_window_size = hparams.attn_window_size > 0 ? hparams.attn_window_size : 112;
  3100. const int grid_window = attn_window_size / patch_size / merge_ratio;
  3101. int dst = 0;
  3102. // [num_vision_tokens, num_vision_tokens] attention mask tensor
  3103. std::vector<float> mask(pow(ipw * iph, 2), std::numeric_limits<float>::lowest());
  3104. int mask_row = 0;
  3105. for (int y = 0; y < ph; y += grid_window) {
  3106. for (int x = 0; x < pw; x += grid_window) {
  3107. const int win_h = std::min(grid_window, ph - y);
  3108. const int win_w = std::min(grid_window, pw - x);
  3109. const int dst_0 = dst;
  3110. // group all tokens belong to the same window togather (to a continue range)
  3111. for (int dy = 0; dy < win_h; dy++) {
  3112. for (int dx = 0; dx < win_w; dx++) {
  3113. const int src = (y + dy) * pw + (x + dx);
  3114. GGML_ASSERT(src < (int)idx.size());
  3115. GGML_ASSERT(dst < (int)inv_idx.size());
  3116. idx [src] = dst;
  3117. inv_idx[dst] = src;
  3118. dst++;
  3119. }
  3120. }
  3121. for (int r=0; r < win_h * win_w * merge_ratio * merge_ratio; r++) {
  3122. int row_offset = mask_row * (ipw * iph);
  3123. std::fill(
  3124. mask.begin() + row_offset + (dst_0 * merge_ratio * merge_ratio),
  3125. mask.begin() + row_offset + (dst * merge_ratio * merge_ratio),
  3126. 0.0);
  3127. mask_row++;
  3128. }
  3129. }
  3130. }
  3131. set_input_i32("window_idx", idx);
  3132. set_input_i32("inv_window_idx", inv_idx);
  3133. set_input_f32("window_mask", mask);
  3134. } else {
  3135. for (int i = 0; i < ph * pw; i++) {
  3136. idx[i] = i;
  3137. }
  3138. }
  3139. const int mpow = merge_ratio * merge_ratio;
  3140. std::vector<int> positions(n_pos * 4);
  3141. int ptr = 0;
  3142. for (int y = 0; y < iph; y += merge_ratio) {
  3143. for (int x = 0; x < ipw; x += merge_ratio) {
  3144. for (int dy = 0; dy < 2; dy++) {
  3145. for (int dx = 0; dx < 2; dx++) {
  3146. auto remap = idx[ptr / mpow];
  3147. remap = (remap * mpow) + (ptr % mpow);
  3148. positions[ remap] = y + dy;
  3149. positions[ num_patches + remap] = x + dx;
  3150. positions[2 * num_patches + remap] = y + dy;
  3151. positions[3 * num_patches + remap] = x + dx;
  3152. ptr++;
  3153. }
  3154. }
  3155. }
  3156. }
  3157. set_input_i32("positions", positions);
  3158. } break;
  3159. case PROJECTOR_TYPE_PIXTRAL:
  3160. case PROJECTOR_TYPE_KIMIVL:
  3161. case PROJECTOR_TYPE_LIGHTONOCR:
  3162. {
  3163. // set the 2D positions
  3164. int n_patches_per_col = image_size_width / patch_size;
  3165. std::vector<int> pos_data(n_pos);
  3166. // dimension H
  3167. for (int i = 0; i < n_pos; i++) {
  3168. pos_data[i] = i / n_patches_per_col;
  3169. }
  3170. set_input_i32("pos_h", pos_data);
  3171. // dimension W
  3172. for (int i = 0; i < n_pos; i++) {
  3173. pos_data[i] = i % n_patches_per_col;
  3174. }
  3175. set_input_i32("pos_w", pos_data);
  3176. } break;
  3177. case PROJECTOR_TYPE_GLM_EDGE:
  3178. {
  3179. // llava and other models
  3180. std::vector<int32_t> positions(n_pos);
  3181. for (int i = 0; i < n_pos; i++) {
  3182. positions[i] = i;
  3183. }
  3184. set_input_i32("positions", positions);
  3185. } break;
  3186. case PROJECTOR_TYPE_MLP:
  3187. case PROJECTOR_TYPE_MLP_NORM:
  3188. case PROJECTOR_TYPE_LDP:
  3189. case PROJECTOR_TYPE_LDPV2:
  3190. {
  3191. // llava and other models
  3192. std::vector<int32_t> positions(n_pos);
  3193. for (int i = 0; i < n_pos; i++) {
  3194. positions[i] = i;
  3195. }
  3196. set_input_i32("positions", positions);
  3197. // The patches vector is used to get rows to index into the embeds with;
  3198. // we should skip dim 0 only if we have CLS to avoid going out of bounds
  3199. // when retrieving the rows.
  3200. int patch_offset = model.class_embedding ? 1 : 0;
  3201. std::vector<int32_t> patches(num_patches);
  3202. for (int i = 0; i < num_patches; i++) {
  3203. patches[i] = i + patch_offset;
  3204. }
  3205. set_input_i32("patches", patches);
  3206. } break;
  3207. case PROJECTOR_TYPE_GEMMA3:
  3208. case PROJECTOR_TYPE_GEMMA3NV:
  3209. case PROJECTOR_TYPE_IDEFICS3:
  3210. case PROJECTOR_TYPE_INTERNVL:
  3211. case PROJECTOR_TYPE_QWEN2A:
  3212. case PROJECTOR_TYPE_GLMA:
  3213. case PROJECTOR_TYPE_ULTRAVOX:
  3214. case PROJECTOR_TYPE_LFM2:
  3215. case PROJECTOR_TYPE_VOXTRAL:
  3216. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  3217. case PROJECTOR_TYPE_JANUS_PRO:
  3218. case PROJECTOR_TYPE_COGVLM:
  3219. {
  3220. // do nothing
  3221. } break;
  3222. case PROJECTOR_TYPE_LLAMA4:
  3223. {
  3224. // set the 2D positions
  3225. int n_patches_per_col = image_size_width / patch_size;
  3226. std::vector<int> pos_data(num_patches + 1, 0); // +1 for the [CLS] token
  3227. // last pos is always kept 0, it's for CLS
  3228. // dimension H
  3229. for (int i = 0; i < num_patches; i++) {
  3230. pos_data[i] = (i / n_patches_per_col) + 1;
  3231. }
  3232. set_input_i32("pos_h", pos_data);
  3233. // dimension W
  3234. for (int i = 0; i < num_patches; i++) {
  3235. pos_data[i] = (i % n_patches_per_col) + 1;
  3236. }
  3237. set_input_i32("pos_w", pos_data);
  3238. } break;
  3239. case PROJECTOR_TYPE_LFM2A:
  3240. {
  3241. GGML_ASSERT(imgs.entries.size() == 1);
  3242. const auto n_frames = clip_n_output_tokens(ctx, imgs.entries.front().get());
  3243. auto d_model = 512;
  3244. auto seq_len = n_frames * 2 - 1;
  3245. std::vector<float> pos_emb(d_model*seq_len);
  3246. std::vector<double> inv_freq(d_model / 2);
  3247. for (size_t i = 0; i < inv_freq.size(); ++i) {
  3248. inv_freq[i] = std::exp(-(std::log(10000.0) / (float)d_model) * (2.0f * (float)(i)));
  3249. }
  3250. for (int64_t pos = 0; pos < seq_len; ++pos) {
  3251. for (size_t i = 0; i < inv_freq.size(); ++i) {
  3252. const float ang = (n_frames - pos - 1) * inv_freq[i];
  3253. pos_emb[pos*d_model + 2*i + 0] = sinf(ang); // even
  3254. pos_emb[pos*d_model + 2*i + 1] = cosf(ang); // odd
  3255. }
  3256. }
  3257. set_input_f32("pos_emb", pos_emb);
  3258. } break;
  3259. default:
  3260. GGML_ABORT("Unknown projector type");
  3261. }
  3262. // ggml_backend_cpu_set_n_threads(ctx->backend_cpu, n_threads);
  3263. ggml_backend_dev_t dev = ggml_backend_get_device(ctx->backend_cpu);
  3264. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  3265. if (reg) {
  3266. 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");
  3267. if (ggml_backend_set_n_threads_fn) {
  3268. ggml_backend_set_n_threads_fn(ctx->backend_cpu, n_threads);
  3269. }
  3270. }
  3271. auto status = ggml_backend_sched_graph_compute(ctx->sched.get(), gf);
  3272. if (status != GGML_STATUS_SUCCESS) {
  3273. LOG_ERR("%s: ggml_backend_sched_graph_compute failed with error %d\n", __func__, status);
  3274. return false;
  3275. }
  3276. // the last node is the embedding tensor
  3277. ggml_tensor * embeddings = ggml_graph_node(gf, -1);
  3278. // sanity check (only support batch size of 1 for now)
  3279. const int n_tokens_out = embeddings->ne[1];
  3280. const int expected_n_tokens_out = clip_n_output_tokens(ctx, imgs.entries[0].get());
  3281. if (n_tokens_out != expected_n_tokens_out) {
  3282. LOG_ERR("%s: expected output %d tokens, got %d\n", __func__, expected_n_tokens_out, n_tokens_out);
  3283. GGML_ABORT("Invalid number of output tokens");
  3284. }
  3285. // copy the embeddings to the location passed by the user
  3286. if (vec != nullptr) {
  3287. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  3288. }
  3289. return true;
  3290. }
  3291. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  3292. switch (ctx->model.proj_type) {
  3293. case PROJECTOR_TYPE_LDP:
  3294. return ctx->model.mm_model_block_1_block_2_1_b->ne[0];
  3295. case PROJECTOR_TYPE_LDPV2:
  3296. return ctx->model.mm_model_peg_0_b->ne[0];
  3297. case PROJECTOR_TYPE_MLP:
  3298. case PROJECTOR_TYPE_PIXTRAL:
  3299. case PROJECTOR_TYPE_LIGHTONOCR:
  3300. return ctx->model.mm_2_w->ne[1];
  3301. case PROJECTOR_TYPE_MLP_NORM:
  3302. return ctx->model.mm_3_b->ne[0];
  3303. case PROJECTOR_TYPE_MINICPMV:
  3304. return ctx->model.mm_model_proj->ne[0];
  3305. case PROJECTOR_TYPE_GLM_EDGE:
  3306. return ctx->model.mm_model_mlp_3_w->ne[1];
  3307. case PROJECTOR_TYPE_QWEN2VL:
  3308. case PROJECTOR_TYPE_QWEN25VL:
  3309. case PROJECTOR_TYPE_JANUS_PRO:
  3310. case PROJECTOR_TYPE_YOUTUVL:
  3311. return ctx->model.mm_1_b->ne[0];
  3312. case PROJECTOR_TYPE_QWEN3VL:
  3313. // main path + deepstack paths
  3314. return ctx->model.mm_1_b->ne[0] * (1 + ctx->model.n_deepstack_layers);
  3315. case PROJECTOR_TYPE_GEMMA3:
  3316. case PROJECTOR_TYPE_GEMMA3NV:
  3317. return ctx->model.mm_input_proj_w->ne[0];
  3318. case PROJECTOR_TYPE_IDEFICS3:
  3319. return ctx->model.projection->ne[1];
  3320. case PROJECTOR_TYPE_ULTRAVOX:
  3321. case PROJECTOR_TYPE_VOXTRAL:
  3322. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  3323. return ctx->model.mm_2_w->ne[1];
  3324. case PROJECTOR_TYPE_INTERNVL:
  3325. return ctx->model.mm_3_w->ne[1];
  3326. case PROJECTOR_TYPE_LLAMA4:
  3327. return ctx->model.mm_model_proj->ne[1];
  3328. case PROJECTOR_TYPE_QWEN2A:
  3329. return ctx->model.mm_fc_w->ne[1];
  3330. case PROJECTOR_TYPE_GLMA:
  3331. return ctx->model.mm_2_w->ne[1];
  3332. case PROJECTOR_TYPE_LFM2:
  3333. case PROJECTOR_TYPE_KIMIVL:
  3334. return ctx->model.mm_2_w->ne[1];
  3335. case PROJECTOR_TYPE_COGVLM:
  3336. return ctx->model.mm_4h_to_h_w->ne[1];
  3337. case PROJECTOR_TYPE_LFM2A:
  3338. return ctx->model.position_embeddings->ne[0];
  3339. case PROJECTOR_TYPE_GLM4V:
  3340. return ctx->model.mm_ffn_down_w->ne[1];
  3341. default:
  3342. GGML_ABORT("Unknown projector type");
  3343. }
  3344. }
  3345. int clip_is_minicpmv(const struct clip_ctx * ctx) {
  3346. // TODO: remove this function
  3347. if (ctx->proj_type() == PROJECTOR_TYPE_MINICPMV) {
  3348. return ctx->model.hparams.minicpmv_version;
  3349. }
  3350. return 0;
  3351. }
  3352. bool clip_is_glm(const struct clip_ctx * ctx) {
  3353. // TODO: remove this function
  3354. return ctx->proj_type() == PROJECTOR_TYPE_GLM_EDGE;
  3355. }
  3356. bool clip_is_llava(const struct clip_ctx * ctx) {
  3357. return ctx->model.hparams.has_llava_projector;
  3358. }
  3359. bool clip_has_vision_encoder(const struct clip_ctx * ctx) {
  3360. return ctx->model.modality == CLIP_MODALITY_VISION;
  3361. }
  3362. bool clip_has_audio_encoder(const struct clip_ctx * ctx) {
  3363. return ctx->model.modality == CLIP_MODALITY_AUDIO;
  3364. }
  3365. bool clip_has_whisper_encoder(const struct clip_ctx * ctx) {
  3366. switch (ctx->proj_type()) {
  3367. case PROJECTOR_TYPE_ULTRAVOX:
  3368. case PROJECTOR_TYPE_QWEN2A:
  3369. case PROJECTOR_TYPE_GLMA:
  3370. case PROJECTOR_TYPE_VOXTRAL:
  3371. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  3372. return true;
  3373. default:
  3374. return false;
  3375. }
  3376. }
  3377. bool clip_encode_float_image (struct clip_ctx * ctx, int n_threads, float * img, int h, int w, float * vec) {
  3378. clip_image_f32 clip_img;
  3379. clip_img.buf.resize(h * w * 3);
  3380. for (int i = 0; i < h*w*3; i++)
  3381. {
  3382. clip_img.buf[i] = img[i];
  3383. }
  3384. clip_img.nx = w;
  3385. clip_img.ny = h;
  3386. clip_image_encode(ctx, n_threads, &clip_img, vec);
  3387. return true;
  3388. }
  3389. //
  3390. // API used internally with mtmd
  3391. //
  3392. projector_type clip_get_projector_type(const struct clip_ctx * ctx) {
  3393. return ctx->proj_type();
  3394. }
  3395. void clip_image_f32_batch_add_mel(struct clip_image_f32_batch * batch, int n_mel, int n_frames, float * mel) {
  3396. clip_image_f32 * audio = new clip_image_f32;
  3397. audio->nx = n_frames;
  3398. audio->ny = n_mel;
  3399. audio->buf.resize(n_frames * n_mel);
  3400. std::memcpy(audio->buf.data(), mel, n_frames * n_mel * sizeof(float));
  3401. batch->entries.push_back(clip_image_f32_ptr(audio));
  3402. batch->is_audio = true;
  3403. }
  3404. const clip_hparams * clip_get_hparams(const struct clip_ctx * ctx) {
  3405. return &ctx->model.hparams;
  3406. }
  3407. //
  3408. // API for debugging
  3409. //
  3410. void clip_debug_encode(clip_ctx * ctx, int h, int w, float fill_value) {
  3411. clip_image_f32 img;
  3412. img.nx = w;
  3413. img.ny = h;
  3414. img.buf.resize(h * w * 3);
  3415. for (int i = 0; i < h * w * 3; i++) {
  3416. img.buf[i] = static_cast<float>(fill_value);
  3417. }
  3418. clip_image_encode(ctx, 1, &img, nullptr);
  3419. GGML_ASSERT(img.buf.empty() && "expected, always stop here");
  3420. }