clip.cpp 124 KB

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