clip.cpp 118 KB

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