mllama.cpp 33 KB

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