clip.cpp 126 KB

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