clip.cpp 161 KB

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