clip.cpp 128 KB

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