clip.cpp 173 KB

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