clip.cpp 124 KB

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