clip.cpp 174 KB

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