clip.cpp 112 KB

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