mllama.cpp 33 KB

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