clip.cpp 153 KB

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