1
0

clip.cpp 107 KB

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