clip.cpp 124 KB

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