clip.cpp 135 KB

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