clip.cpp 154 KB

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