clip.cpp 156 KB

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