clip.cpp 86 KB

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