clip.cpp 124 KB

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