clip.cpp 139 KB

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