clip.cpp 85 KB

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