mllama.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. // NOTE: This is modified from clip.cpp for Mllama only
  2. #include "mllama.h"
  3. #include "ggml-alloc.h"
  4. #include "ggml-backend.h"
  5. #include "ggml.h"
  6. #ifdef GGML_USE_CUDA
  7. #include "ggml-cuda.h"
  8. #endif
  9. #ifdef GGML_USE_METAL
  10. #include "ggml-metal.h"
  11. #endif
  12. #ifdef GGML_USE_CANN
  13. #include "ggml-cann.h"
  14. #endif
  15. #ifdef GGML_USE_VULKAN
  16. #include "ggml-vulkan.h"
  17. #endif
  18. #include <algorithm>
  19. #include <cmath>
  20. #include <cstdarg>
  21. #include <cstdlib>
  22. #include <cstring>
  23. #include <fstream>
  24. #include <stdexcept>
  25. #include <vector>
  26. #define REQUIRE(x) \
  27. do { \
  28. if (!(x)) { \
  29. throw std::runtime_error("REQUIRE failed: " #x); \
  30. } \
  31. } while (0)
  32. #define LOG(fmt, ...) fprintf(stderr, "%s: " fmt "\n", __func__, ##__VA_ARGS__)
  33. #if defined(_WIN32)
  34. #define WIN32_LEAN_AND_MEAN
  35. #ifndef NOMINMAX
  36. #define NOMINMAX
  37. #endif
  38. #include <windows.h>
  39. #if __GLIBCXX__
  40. #include <cstdio>
  41. #include <ext/stdio_filebuf.h>
  42. #include <fcntl.h>
  43. #endif
  44. #endif
  45. struct mllama_image {
  46. int width;
  47. int height;
  48. int num_channels = 3;
  49. int num_tiles = 4;
  50. int aspect_ratio_id;
  51. std::vector<float> data;
  52. };
  53. static std::string format(const char *fmt, ...) {
  54. va_list args;
  55. va_start(args, fmt);
  56. std::vector<char> b(128);
  57. int n = vsnprintf(b.data(), b.size(), fmt, args);
  58. REQUIRE(n >= 0 && n < b.size());
  59. va_end(args);
  60. return std::string(b.data(), b.size());
  61. }
  62. //
  63. // utilities to get data from a gguf file
  64. //
  65. static int get_key_index(const gguf_context *ctx, const char *key) {
  66. int key_index = gguf_find_key(ctx, key);
  67. REQUIRE(key_index != -1);
  68. return key_index;
  69. }
  70. static std::vector<uint32_t> get_u32_array(const gguf_context *ctx, const std::string &key) {
  71. const int i = get_key_index(ctx, key.c_str());
  72. const int n = gguf_get_arr_n(ctx, i);
  73. const uint32_t *data = (uint32_t *)gguf_get_arr_data(ctx, i);
  74. std::vector<uint32_t> s(n);
  75. for (size_t j = 0; j < s.size(); j++) {
  76. s[j] = data[j];
  77. }
  78. return s;
  79. }
  80. static uint32_t get_u32(const gguf_context *ctx, const std::string &key) {
  81. return gguf_get_val_u32(ctx, get_key_index(ctx, key.c_str()));
  82. }
  83. static float get_f32(const gguf_context *ctx, const std::string &key) {
  84. return gguf_get_val_f32(ctx, get_key_index(ctx, key.c_str()));
  85. }
  86. static std::string get_ftype(int ftype) {
  87. return ggml_type_name(static_cast<ggml_type>(ftype));
  88. }
  89. //
  90. // mllama layers
  91. //
  92. struct mllama_hparams {
  93. uint32_t image_size;
  94. uint32_t patch_size;
  95. uint32_t hidden_size;
  96. uint32_t n_intermediate;
  97. uint32_t projection_dim;
  98. uint32_t n_head;
  99. uint32_t n_layer;
  100. uint32_t n_global_layer;
  101. uint32_t n_tiles;
  102. float eps;
  103. std::vector<bool> intermediate_layers;
  104. };
  105. struct mllama_layer {
  106. // attention
  107. struct ggml_tensor *k_w;
  108. struct ggml_tensor *k_b;
  109. struct ggml_tensor *q_w;
  110. struct ggml_tensor *q_b;
  111. struct ggml_tensor *v_w;
  112. struct ggml_tensor *v_b;
  113. struct ggml_tensor *o_w;
  114. struct ggml_tensor *o_b;
  115. struct ggml_tensor *attn_gate;
  116. // layernorm 1
  117. struct ggml_tensor *ln_1_w;
  118. struct ggml_tensor *ln_1_b;
  119. // ff
  120. struct ggml_tensor *ff_i_w;
  121. struct ggml_tensor *ff_i_b;
  122. struct ggml_tensor *ff_o_w;
  123. struct ggml_tensor *ff_o_b;
  124. struct ggml_tensor *ff_gate;
  125. // layernorm 2
  126. struct ggml_tensor *ln_2_w;
  127. struct ggml_tensor *ln_2_b;
  128. };
  129. struct mllama_vision_model {
  130. struct mllama_hparams hparams;
  131. // embeddings
  132. struct ggml_tensor *class_embedding;
  133. struct ggml_tensor *patch_embeddings;
  134. struct ggml_tensor *position_embeddings;
  135. struct ggml_tensor *position_embeddings_gate;
  136. struct ggml_tensor *tile_position_embeddings;
  137. struct ggml_tensor *tile_position_embeddings_gate;
  138. struct ggml_tensor *pre_tile_position_embeddings;
  139. struct ggml_tensor *pre_tile_position_embeddings_gate;
  140. struct ggml_tensor *post_tile_position_embeddings;
  141. struct ggml_tensor *post_tile_position_embeddings_gate;
  142. struct ggml_tensor *pre_ln_w;
  143. struct ggml_tensor *pre_ln_b;
  144. std::vector<mllama_layer> layers;
  145. std::vector<mllama_layer> global_layers;
  146. struct ggml_tensor *post_ln_w;
  147. struct ggml_tensor *post_ln_b;
  148. struct ggml_tensor *mm_0_w;
  149. struct ggml_tensor *mm_0_b;
  150. };
  151. struct mllama_ctx {
  152. struct mllama_vision_model vision_model;
  153. uint32_t ftype = 1;
  154. struct gguf_context *ctx_gguf;
  155. struct ggml_context *ctx_data;
  156. std::vector<uint8_t> buf_compute_meta;
  157. // memory buffers to evaluate the model
  158. ggml_backend_buffer_t params_buffer = nullptr;
  159. ggml_backend_t backend = nullptr;
  160. ggml_gallocr_t compute_alloc = nullptr;
  161. };
  162. static ggml_tensor *mllama_image_build_encoder_layer(
  163. struct ggml_context *ctx0, const size_t il, const struct mllama_layer &layer, struct ggml_tensor *embeddings,
  164. const float eps, const int hidden_size, const int batch_size, const int n_head, const int d_head) {
  165. struct ggml_tensor *cur = embeddings;
  166. {
  167. // layernorm1
  168. cur = ggml_norm(ctx0, cur, eps);
  169. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, layer.ln_1_w), layer.ln_1_b);
  170. ggml_set_name(cur, format("%d pre layernorm", il).c_str());
  171. }
  172. {
  173. // self-attention
  174. struct ggml_tensor *Q = ggml_mul_mat(ctx0, layer.q_w, cur);
  175. if (layer.q_b != nullptr) {
  176. Q = ggml_add(ctx0, Q, layer.q_b);
  177. }
  178. Q = ggml_reshape_4d(ctx0, Q, d_head, n_head, Q->ne[1], batch_size);
  179. Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
  180. ggml_set_name(Q, format("%d query", il).c_str());
  181. struct ggml_tensor *K = ggml_mul_mat(ctx0, layer.k_w, cur);
  182. if (layer.k_b != nullptr) {
  183. K = ggml_add(ctx0, K, layer.k_b);
  184. }
  185. K = ggml_reshape_4d(ctx0, K, d_head, n_head, K->ne[1], batch_size);
  186. K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
  187. ggml_set_name(K, format("%d key", il).c_str());
  188. struct ggml_tensor *V = ggml_mul_mat(ctx0, layer.v_w, cur);
  189. if (layer.v_b != nullptr) {
  190. V = ggml_add(ctx0, V, layer.v_b);
  191. }
  192. V = ggml_reshape_4d(ctx0, V, d_head, n_head, V->ne[1], batch_size);
  193. V = ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 2, 0, 3));
  194. ggml_set_name(V, format("%d value", il).c_str());
  195. struct ggml_tensor *KQ = ggml_mul_mat(ctx0, K, Q);
  196. KQ = ggml_scale_inplace(ctx0, KQ, 1.0f / sqrtf((float)d_head));
  197. KQ = ggml_soft_max_inplace(ctx0, KQ);
  198. ggml_set_name(KQ, format("%d KQ", il).c_str());
  199. struct ggml_tensor *KQV = ggml_mul_mat(ctx0, V, KQ);
  200. KQV = ggml_reshape_4d(ctx0, KQV, d_head, KQV->ne[1], n_head, batch_size);
  201. KQV = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  202. KQV = ggml_cont_3d(ctx0, KQV, hidden_size, KQV->ne[2], batch_size);
  203. ggml_set_name(KQV, format("%d KQV", il).c_str());
  204. cur = ggml_mul_mat(ctx0, layer.o_w, KQV);
  205. if (layer.o_b != nullptr) {
  206. cur = ggml_add(ctx0, cur, layer.o_b);
  207. }
  208. ggml_set_name(cur, format("%d self attention", il).c_str());
  209. if (layer.attn_gate != nullptr) {
  210. cur = ggml_mul_inplace(ctx0, cur, layer.attn_gate);
  211. ggml_set_name(cur, format("%d self attention gate", il).c_str());
  212. }
  213. }
  214. cur = ggml_add(ctx0, cur, embeddings);
  215. ggml_set_name(cur, format("%d residual", il).c_str());
  216. embeddings = cur;
  217. {
  218. // layernorm2
  219. cur = ggml_norm(ctx0, cur, eps);
  220. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, layer.ln_2_w), layer.ln_2_b);
  221. ggml_set_name(cur, format("%d post layernorm", il).c_str());
  222. }
  223. {
  224. // feed forward
  225. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, layer.ff_i_w, cur), layer.ff_i_b);
  226. cur = ggml_gelu_inplace(ctx0, cur);
  227. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, layer.ff_o_w, cur), layer.ff_o_b);
  228. ggml_set_name(cur, format("%d feed forward", il).c_str());
  229. if (layer.ff_gate != nullptr) {
  230. cur = ggml_mul_inplace(ctx0, cur, layer.ff_gate);
  231. ggml_set_name(cur, format("%d feed forward gate", il).c_str());
  232. }
  233. }
  234. // residual 2
  235. cur = ggml_add(ctx0, cur, embeddings);
  236. ggml_set_name(cur, format("%d residual", il).c_str());
  237. embeddings = cur;
  238. return embeddings;
  239. }
  240. static ggml_cgraph *mllama_image_build_graph(mllama_ctx *ctx, const mllama_image_batch *imgs) {
  241. const auto &model = ctx->vision_model;
  242. const auto &hparams = model.hparams;
  243. const int image_size = hparams.image_size;
  244. const int image_size_width = image_size;
  245. const int image_size_height = image_size;
  246. const int patch_size = hparams.patch_size;
  247. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  248. const int num_positions = num_patches + (model.class_embedding == nullptr ? 0 : 1);
  249. const int hidden_size = hparams.hidden_size;
  250. const int n_head = hparams.n_head;
  251. const int d_head = hidden_size / n_head;
  252. const int batch_size = imgs->size;
  253. REQUIRE(batch_size == 1);
  254. int num_tiles = 4;
  255. int num_channels = 3;
  256. if (imgs->data != nullptr) {
  257. num_tiles = imgs->data[0].num_tiles > 0 ? imgs->data[0].num_tiles : num_tiles;
  258. num_channels = imgs->data[0].num_channels > 0 ? imgs->data[0].num_channels : num_channels;
  259. }
  260. struct ggml_init_params params = {
  261. ctx->buf_compute_meta.size(), // mem_size
  262. ctx->buf_compute_meta.data(), // mem_buffer
  263. true, // no_alloc
  264. };
  265. struct ggml_context *ctx0 = ggml_init(params);
  266. struct ggml_cgraph *gf = ggml_new_graph(ctx0);
  267. struct ggml_tensor *inp_raw = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, image_size_width, image_size_height, num_channels, num_tiles);
  268. ggml_set_name(inp_raw, "inp_raw");
  269. ggml_set_input(inp_raw);
  270. struct ggml_tensor *inp = ggml_conv_2d(ctx0, model.patch_embeddings, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  271. inp = ggml_reshape_3d(ctx0, inp, num_patches, hidden_size, num_tiles);
  272. inp = ggml_cont(ctx0, ggml_permute(ctx0, inp, 1, 0, 2, 3));
  273. struct ggml_tensor *aspect_ratios = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, imgs->size);
  274. ggml_set_name(aspect_ratios, "aspect_ratios");
  275. ggml_set_input(aspect_ratios);
  276. if (model.pre_tile_position_embeddings != nullptr) {
  277. struct ggml_tensor *pre_tile_position_embeddings = ggml_get_rows(ctx0, model.pre_tile_position_embeddings, aspect_ratios);
  278. ggml_set_name(pre_tile_position_embeddings, "pre_tile_position_embeddings");
  279. pre_tile_position_embeddings = ggml_reshape_3d(ctx0, pre_tile_position_embeddings, hidden_size, 1, num_tiles);
  280. if (model.pre_tile_position_embeddings_gate != nullptr) {
  281. pre_tile_position_embeddings = ggml_mul_inplace(ctx0, pre_tile_position_embeddings, model.pre_tile_position_embeddings_gate);
  282. }
  283. inp = ggml_add(ctx0, inp, pre_tile_position_embeddings);
  284. }
  285. struct ggml_tensor *embeddings = inp;
  286. if (model.class_embedding != nullptr) {
  287. // concat class_embeddings and patch_embeddings
  288. embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hidden_size, num_positions, num_tiles);
  289. ggml_set_name(embeddings, "embeddings");
  290. ggml_set_input(embeddings);
  291. for (int i = 0; i < num_tiles; ++i) {
  292. // repeat class embeddings for each tile
  293. embeddings = ggml_acc_inplace(ctx0, embeddings, model.class_embedding, embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], i * embeddings->nb[2]);
  294. }
  295. embeddings = ggml_acc_inplace(ctx0, embeddings, inp, embeddings->nb[1], embeddings->nb[2], embeddings->nb[3], model.class_embedding->nb[1]);
  296. }
  297. struct ggml_tensor *positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_positions);
  298. ggml_set_name(positions, "positions");
  299. ggml_set_input(positions);
  300. struct ggml_tensor *position_embd = ggml_get_rows(ctx0, model.position_embeddings, positions);
  301. if (model.position_embeddings_gate != nullptr) {
  302. position_embd = ggml_mul_inplace(ctx0, position_embd, model.position_embeddings_gate);
  303. }
  304. embeddings = ggml_add(ctx0, embeddings, position_embd);
  305. if (model.tile_position_embeddings != nullptr) {
  306. struct ggml_tensor *tile_position_embeddings = ggml_get_rows(ctx0, model.tile_position_embeddings, aspect_ratios);
  307. ggml_set_name(tile_position_embeddings, "tile_position_embeddings");
  308. tile_position_embeddings = ggml_reshape_3d(ctx0, tile_position_embeddings, hidden_size, num_positions, num_tiles);
  309. if (model.tile_position_embeddings_gate != nullptr) {
  310. tile_position_embeddings = ggml_mul_inplace(ctx0, tile_position_embeddings, model.tile_position_embeddings_gate);
  311. }
  312. embeddings = ggml_add(ctx0, embeddings, tile_position_embeddings);
  313. }
  314. // pre-layernorm
  315. if (model.pre_ln_w != nullptr) {
  316. embeddings = ggml_mul(ctx0, ggml_norm(ctx0, embeddings, hparams.eps), model.pre_ln_w);
  317. if (model.pre_ln_b != nullptr) {
  318. embeddings = ggml_add(ctx0, embeddings, model.pre_ln_b);
  319. }
  320. ggml_set_name(embeddings, "pre layernorm");
  321. }
  322. const int num_padding_patches = 8 - (embeddings->ne[1] % 8) % 8;
  323. embeddings = ggml_pad(ctx0, embeddings, 0, num_padding_patches, 0, 0);
  324. embeddings = ggml_view_3d(ctx0, embeddings, embeddings->ne[0], embeddings->ne[1] * embeddings->ne[2], batch_size, embeddings->nb[1], embeddings->nb[2] * embeddings->ne[3], 0);
  325. std::vector<struct ggml_tensor *> intermediate_embeddings;
  326. // encoder
  327. for (size_t il = 0; il < model.layers.size(); il++) {
  328. if (hparams.intermediate_layers[il]) {
  329. intermediate_embeddings.push_back(embeddings);
  330. }
  331. embeddings = mllama_image_build_encoder_layer(
  332. ctx0, il, model.layers[il], embeddings,
  333. hparams.eps, hidden_size, batch_size, n_head, d_head);
  334. }
  335. // post-layernorm
  336. if (model.post_ln_w != nullptr) {
  337. embeddings = ggml_mul(ctx0, ggml_norm(ctx0, embeddings, hparams.eps), model.post_ln_w);
  338. if (model.post_ln_b != nullptr) {
  339. embeddings = ggml_add(ctx0, embeddings, model.post_ln_b);
  340. }
  341. ggml_set_name(embeddings, "post layernorm");
  342. }
  343. embeddings = ggml_reshape_3d(ctx0, embeddings, hidden_size, num_positions + num_padding_patches, num_tiles);
  344. if (model.post_tile_position_embeddings != nullptr) {
  345. struct ggml_tensor *post_tile_position_embeddings = ggml_get_rows(ctx0, model.post_tile_position_embeddings, aspect_ratios);
  346. ggml_set_name(post_tile_position_embeddings, "post_tile_position_embeddings");
  347. post_tile_position_embeddings = ggml_reshape_3d(ctx0, post_tile_position_embeddings, hidden_size, 1, num_tiles);
  348. if (model.post_tile_position_embeddings_gate != nullptr) {
  349. post_tile_position_embeddings = ggml_mul(ctx0, post_tile_position_embeddings, model.post_tile_position_embeddings_gate);
  350. }
  351. embeddings = ggml_add(ctx0, embeddings, post_tile_position_embeddings);
  352. }
  353. embeddings = ggml_reshape_3d(ctx0, embeddings, hidden_size, num_tiles * (num_positions + num_padding_patches), 1);
  354. // global encoder
  355. for (size_t il = 0; il < model.global_layers.size(); il++) {
  356. embeddings = mllama_image_build_encoder_layer(
  357. ctx0, il, model.global_layers[il], embeddings,
  358. hparams.eps, hidden_size, batch_size, n_head, d_head);
  359. }
  360. struct ggml_tensor *stacked_embeddings = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 0, hidden_size, (num_positions + num_padding_patches) * num_tiles);
  361. for (size_t i = 0; i < intermediate_embeddings.size(); ++i) {
  362. stacked_embeddings = ggml_concat(ctx0, stacked_embeddings, ggml_reshape_3d(ctx0, intermediate_embeddings[i], 1, intermediate_embeddings[i]->ne[0], intermediate_embeddings[i]->ne[1]), 0);
  363. }
  364. stacked_embeddings = ggml_reshape_4d(ctx0, stacked_embeddings, intermediate_embeddings.size() * hidden_size, num_positions + num_padding_patches, num_tiles, batch_size);
  365. stacked_embeddings = ggml_unpad(ctx0, stacked_embeddings, 0, num_padding_patches, 0, 0);
  366. embeddings = ggml_reshape_3d(ctx0, embeddings, hidden_size, num_positions + num_padding_patches, num_tiles);
  367. embeddings = ggml_unpad(ctx0, embeddings, 0, num_padding_patches, 0, 0);
  368. embeddings = ggml_concat(ctx0, embeddings, stacked_embeddings, 0);
  369. // mllama projector
  370. embeddings = ggml_add(ctx0, ggml_mul_mat(ctx0, model.mm_0_w, embeddings), model.mm_0_b);
  371. ggml_set_name(embeddings, "multi modal projector");
  372. // build the graph
  373. ggml_build_forward_expand(gf, embeddings);
  374. ggml_free(ctx0);
  375. return gf;
  376. }
  377. static struct ggml_tensor *mllama_tensor_load(struct ggml_context *ctx, const char *name, const bool optional) {
  378. struct ggml_tensor *cur = ggml_get_tensor(ctx, name);
  379. REQUIRE(cur != nullptr || optional);
  380. return cur;
  381. }
  382. static std::vector<struct mllama_layer> mllama_layers_load(struct ggml_context *ctx, const char *prefix, const int n) {
  383. std::vector<struct mllama_layer> layers(n);
  384. for (size_t i = 0; i < layers.size(); i++) {
  385. auto &layer = layers[i];
  386. layer.ln_1_w = mllama_tensor_load(ctx, format("%s.blk.%d.ln1.weight", prefix, i).c_str(), false);
  387. layer.ln_1_b = mllama_tensor_load(ctx, format("%s.blk.%d.ln1.bias", prefix, i).c_str(), false);
  388. layer.ln_2_w = mllama_tensor_load(ctx, format("%s.blk.%d.ln2.weight", prefix, i).c_str(), false);
  389. layer.ln_2_b = mllama_tensor_load(ctx, format("%s.blk.%d.ln2.bias", prefix, i).c_str(), false);
  390. layer.k_w = mllama_tensor_load(ctx, format("%s.blk.%d.attn_k.weight", prefix, i).c_str(), false);
  391. layer.k_b = mllama_tensor_load(ctx, format("%s.blk.%d.attn_k.bias", prefix, i).c_str(), true);
  392. layer.q_w = mllama_tensor_load(ctx, format("%s.blk.%d.attn_q.weight", prefix, i).c_str(), false);
  393. layer.q_b = mllama_tensor_load(ctx, format("%s.blk.%d.attn_q.bias", prefix, i).c_str(), true);
  394. layer.v_w = mllama_tensor_load(ctx, format("%s.blk.%d.attn_v.weight", prefix, i).c_str(), false);
  395. layer.v_b = mllama_tensor_load(ctx, format("%s.blk.%d.attn_v.bias", prefix, i).c_str(), true);
  396. layer.o_w = mllama_tensor_load(ctx, format("%s.blk.%d.attn_out.weight", prefix, i).c_str(), false);
  397. layer.o_b = mllama_tensor_load(ctx, format("%s.blk.%d.attn_out.bias", prefix, i).c_str(), true);
  398. layer.ff_i_w = mllama_tensor_load(ctx, format("%s.blk.%d.ffn_down.weight", prefix, i).c_str(), false);
  399. layer.ff_i_b = mllama_tensor_load(ctx, format("%s.blk.%d.ffn_down.bias", prefix, i).c_str(), false);
  400. layer.ff_o_w = mllama_tensor_load(ctx, format("%s.blk.%d.ffn_up.weight", prefix, i).c_str(), false);
  401. layer.ff_o_b = mllama_tensor_load(ctx, format("%s.blk.%d.ffn_up.bias", prefix, i).c_str(), false);
  402. layer.attn_gate = mllama_tensor_load(ctx, format("%s.blk.%d.attn_gate", prefix, i).c_str(), true);
  403. layer.ff_gate = mllama_tensor_load(ctx, format("%s.blk.%d.ffn_gate", prefix, i).c_str(), true);
  404. }
  405. return layers;
  406. }
  407. // read and create ggml_context containing the tensors and their data
  408. struct mllama_ctx *mllama_model_load(const char *fname, const int verbosity = 1) {
  409. struct ggml_context *meta = nullptr;
  410. struct gguf_init_params params = {
  411. true, // no_alloc
  412. &meta, // ctx
  413. };
  414. struct gguf_context *ctx = gguf_init_from_file(fname, params);
  415. REQUIRE(ctx != nullptr);
  416. if (verbosity >= 1) {
  417. const int n_tensors = gguf_get_n_tensors(ctx);
  418. const int n_kv = gguf_get_n_kv(ctx);
  419. const std::string ftype = get_ftype(get_u32(ctx, "general.file_type"));
  420. const int idx_desc = get_key_index(ctx, "general.description");
  421. const std::string description = gguf_get_val_str(ctx, idx_desc);
  422. const int idx_name = gguf_find_key(ctx, "general.name");
  423. if (idx_name != -1) { // make name optional temporarily as some of the uploaded models missing it due to a bug
  424. const std::string name = gguf_get_val_str(ctx, idx_name);
  425. LOG("model name: %s", name.c_str());
  426. }
  427. LOG("description: %s", description.c_str());
  428. LOG("GGUF version: %d", gguf_get_version(ctx));
  429. LOG("alignment: %zu", gguf_get_alignment(ctx));
  430. LOG("n_tensors: %d", n_tensors);
  431. LOG("n_kv: %d", n_kv);
  432. LOG("ftype: %s", ftype.c_str());
  433. LOG("");
  434. }
  435. const int n_tensors = gguf_get_n_tensors(ctx);
  436. mllama_ctx *new_mllama = new mllama_ctx{};
  437. #ifdef GGML_USE_CUDA
  438. new_mllama->backend = ggml_backend_cuda_init(0);
  439. LOG("vision using CUDA backend");
  440. #endif
  441. #ifdef GGML_USE_METAL
  442. new_mllama->backend = ggml_backend_metal_init();
  443. LOG("vision using Metal backend");
  444. #endif
  445. #ifdef GGML_USE_CANN
  446. new_mllama->backend = ggml_backend_cann_init(0);
  447. LOG("vision using CANN backend");
  448. #endif
  449. #ifdef GGML_USE_VULKAN
  450. new_mllama->backend = ggml_backend_vk_init(0);
  451. LOG("vision using Vulkan backend");
  452. #endif
  453. if (!new_mllama->backend) {
  454. new_mllama->backend = ggml_backend_cpu_init();
  455. LOG("vision using CPU backend");
  456. }
  457. // load tensors
  458. {
  459. std::vector<uint8_t> read_buf;
  460. struct ggml_init_params params = {
  461. (n_tensors + 1) * ggml_tensor_overhead(), // mem_size
  462. nullptr, // mem_buffer
  463. true, // no_alloc
  464. };
  465. new_mllama->ctx_data = ggml_init(params);
  466. if (!new_mllama->ctx_data) {
  467. LOG("ggml_init() failed");
  468. mllama_free(new_mllama);
  469. gguf_free(ctx);
  470. return nullptr;
  471. }
  472. #ifdef _WIN32
  473. int wlen = MultiByteToWideChar(CP_UTF8, 0, fname, -1, NULL, 0);
  474. if (!wlen) {
  475. return NULL;
  476. }
  477. wchar_t * wbuf = (wchar_t *) malloc(wlen * sizeof(wchar_t));
  478. wlen = MultiByteToWideChar(CP_UTF8, 0, fname, -1, wbuf, wlen);
  479. if (!wlen) {
  480. free(wbuf);
  481. return NULL;
  482. }
  483. #if __GLIBCXX__
  484. int fd = _wopen(wbuf, _O_RDONLY | _O_BINARY);
  485. __gnu_cxx::stdio_filebuf<char> buffer(fd, std::ios_base::in);
  486. std::istream fin(&buffer);
  487. #else // MSVC
  488. // unused in our current build
  489. auto fin = std::ifstream(wbuf, std::ios::binary);
  490. #endif
  491. free(wbuf);
  492. #else
  493. auto fin = std::ifstream(fname, std::ios::binary);
  494. #endif
  495. if (!fin) {
  496. LOG("cannot open model file for loading tensors\n");
  497. mllama_free(new_mllama);
  498. gguf_free(ctx);
  499. return nullptr;
  500. }
  501. // add tensors to context
  502. for (int i = 0; i < n_tensors; ++i) {
  503. const char *name = gguf_get_tensor_name(ctx, i);
  504. struct ggml_tensor *t = ggml_get_tensor(meta, name);
  505. struct ggml_tensor *cur = ggml_dup_tensor(new_mllama->ctx_data, t);
  506. ggml_set_name(cur, name);
  507. }
  508. // alloc memory and offload data
  509. new_mllama->params_buffer = ggml_backend_alloc_ctx_tensors(new_mllama->ctx_data, new_mllama->backend);
  510. for (int i = 0; i < n_tensors; ++i) {
  511. const char *name = gguf_get_tensor_name(ctx, i);
  512. struct ggml_tensor *cur = ggml_get_tensor(new_mllama->ctx_data, name);
  513. const size_t offset = gguf_get_data_offset(ctx) + gguf_get_tensor_offset(ctx, i);
  514. fin.seekg(offset, std::ios::beg);
  515. if (!fin) {
  516. LOG("failed to seek for tensor %s\n", name);
  517. mllama_free(new_mllama);
  518. gguf_free(ctx);
  519. return nullptr;
  520. }
  521. int num_bytes = ggml_nbytes(cur);
  522. if (ggml_backend_buffer_is_host(new_mllama->params_buffer)) {
  523. // for the CPU and Metal backend, we can read directly into the tensor
  524. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  525. } else {
  526. // read into a temporary buffer first, then copy to device memory
  527. read_buf.resize(num_bytes);
  528. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  529. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  530. }
  531. }
  532. #if defined(_WIN32) && defined(__GLIBCXX__)
  533. close(fd);
  534. #else
  535. fin.close();
  536. #endif
  537. }
  538. // vision model
  539. // load vision model
  540. auto &vision_model = new_mllama->vision_model;
  541. auto &hparams = vision_model.hparams;
  542. hparams.hidden_size = get_u32(ctx, "mllama.vision.embedding_length");
  543. hparams.n_head = get_u32(ctx, "mllama.vision.attention.head_count");
  544. hparams.n_intermediate = get_u32(ctx, "mllama.vision.feed_forward_length");
  545. hparams.n_layer = get_u32(ctx, "mllama.vision.block_count");
  546. hparams.n_global_layer = get_u32(ctx, "mllama.vision.global.block_count");
  547. hparams.n_tiles = get_u32(ctx, "mllama.vision.max_num_tiles");
  548. hparams.image_size = get_u32(ctx, "mllama.vision.image_size");
  549. hparams.patch_size = get_u32(ctx, "mllama.vision.patch_size");
  550. hparams.projection_dim = get_u32(ctx, "mllama.vision.projection_dim");
  551. hparams.eps = get_f32(ctx, "mllama.vision.attention.layer_norm_epsilon");
  552. std::vector<uint32_t> intermediate_layers_indices = get_u32_array(ctx, "mllama.vision.intermediate_layers_indices");
  553. hparams.intermediate_layers.resize(hparams.n_layer);
  554. for (size_t i = 0; i < intermediate_layers_indices.size(); i++) {
  555. hparams.intermediate_layers[intermediate_layers_indices[i]] = true;
  556. }
  557. if (verbosity >= 2) {
  558. LOG("");
  559. LOG("vision model hparams");
  560. LOG("image_size %d", hparams.image_size);
  561. LOG("patch_size %d", hparams.patch_size);
  562. LOG("v_hidden_size %d", hparams.hidden_size);
  563. LOG("v_n_intermediate %d", hparams.n_intermediate);
  564. LOG("v_projection_dim %d", hparams.projection_dim);
  565. LOG("v_n_head %d", hparams.n_head);
  566. LOG("v_n_layer %d", hparams.n_layer);
  567. LOG("v_n_global_layer %d", hparams.n_global_layer);
  568. LOG("v_eps %f", hparams.eps);
  569. }
  570. vision_model.class_embedding = mllama_tensor_load(new_mllama->ctx_data, "v.class_embd", true);
  571. vision_model.patch_embeddings = mllama_tensor_load(new_mllama->ctx_data, "v.patch_embd.weight", true);
  572. vision_model.position_embeddings = mllama_tensor_load(new_mllama->ctx_data, "v.position_embd.weight", true);
  573. vision_model.position_embeddings_gate = mllama_tensor_load(new_mllama->ctx_data, "v.position_embd.gate", true);
  574. vision_model.pre_ln_w = mllama_tensor_load(new_mllama->ctx_data, "v.pre_ln.weight", true);
  575. vision_model.pre_ln_b = mllama_tensor_load(new_mllama->ctx_data, "v.pre_ln.bias", true);
  576. vision_model.post_ln_w = mllama_tensor_load(new_mllama->ctx_data, "v.post_ln.weight", true);
  577. vision_model.post_ln_b = mllama_tensor_load(new_mllama->ctx_data, "v.post_ln.bias", true);
  578. vision_model.tile_position_embeddings = mllama_tensor_load(new_mllama->ctx_data, "v.tile_position_embd.weight", true);
  579. vision_model.tile_position_embeddings_gate = mllama_tensor_load(new_mllama->ctx_data, "v.tile_position_embd.gate", true);
  580. vision_model.pre_tile_position_embeddings = mllama_tensor_load(new_mllama->ctx_data, "v.pre_tile_position_embd.weight", true);
  581. vision_model.pre_tile_position_embeddings_gate = mllama_tensor_load(new_mllama->ctx_data, "v.pre_tile_position_embd.gate", true);
  582. vision_model.post_tile_position_embeddings = mllama_tensor_load(new_mllama->ctx_data, "v.post_tile_position_embd.weight", true);
  583. vision_model.post_tile_position_embeddings_gate = mllama_tensor_load(new_mllama->ctx_data, "v.post_tile_position_embd.gate", true);
  584. vision_model.mm_0_w = mllama_tensor_load(new_mllama->ctx_data, "mm.0.weight", false);
  585. vision_model.mm_0_b = mllama_tensor_load(new_mllama->ctx_data, "mm.0.bias", false);
  586. vision_model.layers = mllama_layers_load(new_mllama->ctx_data, "v", hparams.n_layer);
  587. vision_model.global_layers = mllama_layers_load(new_mllama->ctx_data, "v.global", hparams.n_global_layer);
  588. ggml_free(meta);
  589. new_mllama->ctx_gguf = ctx;
  590. {
  591. // measure mem requirement and allocate
  592. new_mllama->buf_compute_meta.resize(GGML_DEFAULT_GRAPH_SIZE * ggml_tensor_overhead() + ggml_graph_overhead());
  593. new_mllama->compute_alloc = ggml_gallocr_new(ggml_backend_get_default_buffer_type(new_mllama->backend));
  594. struct mllama_image_batch batch;
  595. batch.size = 1;
  596. ggml_cgraph *gf = mllama_image_build_graph(new_mllama, &batch);
  597. ggml_gallocr_reserve(new_mllama->compute_alloc, gf);
  598. size_t compute_memory_buffer_size = ggml_gallocr_get_buffer_size(new_mllama->compute_alloc, 0);
  599. LOG("compute allocated memory: %.2f MB", compute_memory_buffer_size / 1024.0 / 1024.0);
  600. }
  601. return new_mllama;
  602. }
  603. struct mllama_image *mllama_image_init() {
  604. return new mllama_image();
  605. }
  606. void mllama_image_free(struct mllama_image *img) { delete img; }
  607. void mllama_image_batch_free(struct mllama_image_batch *batch) {
  608. if (batch->size > 0) {
  609. delete[] batch->data;
  610. batch->size = 0;
  611. }
  612. }
  613. bool mllama_image_load_from_data(const void *data, const int n, const int width, const int height, const int num_channels, const int num_tiles, const int aspect_ratio_id, struct mllama_image *img) {
  614. img->width = width;
  615. img->height = height;
  616. img->num_channels = num_channels;
  617. img->num_tiles = num_tiles;
  618. img->aspect_ratio_id = aspect_ratio_id;
  619. img->data.resize(n);
  620. memcpy(img->data.data(), data, n);
  621. return true;
  622. }
  623. inline int mllama(int x, int lower, int upper) {
  624. return std::max(lower, std::min(x, upper));
  625. }
  626. void mllama_free(mllama_ctx *ctx) {
  627. ggml_free(ctx->ctx_data);
  628. gguf_free(ctx->ctx_gguf);
  629. ggml_backend_buffer_free(ctx->params_buffer);
  630. ggml_backend_free(ctx->backend);
  631. ggml_gallocr_free(ctx->compute_alloc);
  632. delete ctx;
  633. }
  634. bool mllama_image_encode(struct mllama_ctx *ctx, const int n_threads, mllama_image *img, float *vec) {
  635. mllama_image_batch imgs{};
  636. imgs.size = 1;
  637. imgs.data = img;
  638. return mllama_image_batch_encode(ctx, n_threads, &imgs, vec);
  639. }
  640. bool mllama_image_batch_encode(mllama_ctx *ctx, const int n_threads, const mllama_image_batch *imgs, float *vec) {
  641. int batch_size = imgs->size;
  642. REQUIRE(batch_size == 1);
  643. // build the inference graph
  644. ggml_cgraph *gf = mllama_image_build_graph(ctx, imgs);
  645. ggml_gallocr_alloc_graph(ctx->compute_alloc, gf);
  646. // set inputs
  647. const auto &model = ctx->vision_model;
  648. const auto &hparams = model.hparams;
  649. const int image_size = hparams.image_size;
  650. int image_size_width = image_size;
  651. int image_size_height = image_size;
  652. const int patch_size = hparams.patch_size;
  653. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  654. const int num_positions = num_patches + (model.class_embedding == nullptr ? 0 : 1);
  655. {
  656. struct ggml_tensor *inp_raw = ggml_graph_get_tensor(gf, "inp_raw");
  657. ggml_backend_tensor_set(inp_raw, imgs->data[0].data.data(), 0, ggml_nbytes(inp_raw));
  658. }
  659. {
  660. struct ggml_tensor *embeddings = ggml_graph_get_tensor(gf, "embeddings");
  661. if (embeddings != nullptr) {
  662. void *zeros = malloc(ggml_nbytes(embeddings));
  663. memset(zeros, 0, ggml_nbytes(embeddings));
  664. ggml_backend_tensor_set(embeddings, zeros, 0, ggml_nbytes(embeddings));
  665. free(zeros);
  666. }
  667. }
  668. {
  669. struct ggml_tensor *positions = ggml_graph_get_tensor(gf, "positions");
  670. if (positions != nullptr) {
  671. int *positions_data = (int *)malloc(ggml_nbytes(positions));
  672. for (int i = 0; i < num_positions; i++) {
  673. positions_data[i] = i;
  674. }
  675. ggml_backend_tensor_set(positions, positions_data, 0, ggml_nbytes(positions));
  676. free(positions_data);
  677. }
  678. }
  679. {
  680. struct ggml_tensor *aspect_ratios = ggml_graph_get_tensor(gf, "aspect_ratios");
  681. if (aspect_ratios != nullptr) {
  682. int *aspect_ratios_data = (int *)malloc(ggml_nbytes(aspect_ratios));
  683. aspect_ratios_data[0] = imgs->data[0].aspect_ratio_id;
  684. ggml_backend_tensor_set(aspect_ratios, aspect_ratios_data, 0, ggml_nbytes(aspect_ratios));
  685. free(aspect_ratios_data);
  686. }
  687. }
  688. if (ggml_backend_is_cpu(ctx->backend)) {
  689. ggml_backend_cpu_set_n_threads(ctx->backend, n_threads);
  690. }
  691. ggml_backend_graph_compute(ctx->backend, gf);
  692. // the last node is the embedding tensor
  693. struct ggml_tensor *embeddings = ggml_graph_node(gf, ggml_graph_n_nodes(gf) - 1);
  694. // copy the embeddings to the location passed by the user
  695. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  696. return true;
  697. }
  698. int32_t mllama_image_size(const struct mllama_ctx *ctx) {
  699. return ctx->vision_model.hparams.image_size;
  700. }
  701. int32_t mllama_patch_size(const struct mllama_ctx *ctx) {
  702. return ctx->vision_model.hparams.patch_size;
  703. }
  704. int32_t mllama_hidden_size(const struct mllama_ctx *ctx) {
  705. return ctx->vision_model.hparams.hidden_size;
  706. }
  707. int mllama_n_patches(const struct mllama_ctx *ctx) {
  708. const auto &hparams = ctx->vision_model.hparams;
  709. return (hparams.image_size / hparams.patch_size) * (hparams.image_size / hparams.patch_size);
  710. }
  711. int mllama_n_positions(const struct mllama_ctx *ctx) {
  712. return mllama_n_patches(ctx) + (ctx->vision_model.class_embedding == nullptr ? 0 : 1);
  713. }
  714. int mllama_n_tiles(const struct mllama_ctx *ctx) {
  715. return ctx->vision_model.hparams.n_tiles;
  716. }
  717. int mllama_n_embd(const struct mllama_ctx *ctx) {
  718. return ctx->vision_model.hparams.projection_dim;
  719. }
  720. size_t mllama_n_embd_bytes(const struct mllama_ctx *ctx) {
  721. return mllama_n_positions(ctx) * mllama_n_embd(ctx) * mllama_n_tiles(ctx) * sizeof(float);
  722. }