0008-add-mllama-support.patch 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
  2. From: jmorganca <jmorganca@gmail.com>
  3. Date: Thu, 17 Oct 2024 15:18:22 -0700
  4. Subject: [PATCH] add mllama support
  5. mllama adds cross-attention layers to the standard llama architecture
  6. it also requires a way to input a new tensor: cross_attention_state
  7. once per generation
  8. cross-attention layers don't change and so they are cached in the
  9. kv cache once per run
  10. remaining is to implement the cross attention mask
  11. ---
  12. examples/llava/llava.cpp | 5 +-
  13. include/llama.h | 5 +
  14. src/llama.cpp | 477 +++++++++++++++++++++++++++++++++++++--
  15. 3 files changed, 467 insertions(+), 20 deletions(-)
  16. diff --git a/examples/llava/llava.cpp b/examples/llava/llava.cpp
  17. index 16f30c56..0f0f3f62 100644
  18. --- a/examples/llava/llava.cpp
  19. +++ b/examples/llava/llava.cpp
  20. @@ -429,7 +429,7 @@ struct llava_embd_batch {
  21. std::vector<llama_seq_id *> seq_ids;
  22. std::vector<int8_t> logits;
  23. llama_batch batch;
  24. - llava_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  25. + llava_embd_batch(float * embd, int32_t n_embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  26. pos .resize(n_tokens);
  27. n_seq_id.resize(n_tokens);
  28. seq_ids .resize(n_tokens + 1);
  29. @@ -441,6 +441,7 @@ struct llava_embd_batch {
  30. /*n_tokens =*/ n_tokens,
  31. /*tokens =*/ nullptr,
  32. /*embd =*/ embd,
  33. + /*n_embd =*/ n_embd,
  34. /*pos =*/ pos.data(),
  35. /*n_seq_id =*/ n_seq_id.data(),
  36. /*seq_id =*/ seq_ids.data(),
  37. @@ -464,7 +465,7 @@ bool llava_eval_image_embed(llama_context * ctx_llama, const struct llava_image_
  38. n_eval = n_batch;
  39. }
  40. float * embd = image_embed->embed+i*n_embd;
  41. - llava_embd_batch llava_batch = llava_embd_batch(embd, n_eval, *n_past, 0);
  42. + llava_embd_batch llava_batch = llava_embd_batch(embd, n_embd, n_eval, *n_past, 0);
  43. if (llama_decode(ctx_llama, llava_batch.batch)) {
  44. LOG_ERR("%s : failed to eval\n", __func__);
  45. return false;
  46. diff --git a/include/llama.h b/include/llama.h
  47. index c67988a3..0f266283 100644
  48. --- a/include/llama.h
  49. +++ b/include/llama.h
  50. @@ -249,6 +249,7 @@ extern "C" {
  51. llama_token * token;
  52. float * embd;
  53. + int32_t n_embd;
  54. llama_pos * pos;
  55. int32_t * n_seq_id;
  56. llama_seq_id ** seq_id;
  57. @@ -423,6 +424,10 @@ extern "C" {
  58. struct llama_model * model,
  59. struct llama_context_params params);
  60. + // TODO (jmorganca): this should most likely be passed in as part of a batch
  61. + // and not set on the context for all batches.
  62. + LLAMA_API void llama_set_cross_attention(struct llama_context * ctx, bool cross_attn_state);
  63. +
  64. // Frees all allocated memory
  65. LLAMA_API void llama_free(struct llama_context * ctx);
  66. diff --git a/src/llama.cpp b/src/llama.cpp
  67. index 26be6254..4778a9ed 100644
  68. --- a/src/llama.cpp
  69. +++ b/src/llama.cpp
  70. @@ -146,6 +146,7 @@ static std::string format(const char * fmt, ...) {
  71. enum llm_arch {
  72. LLM_ARCH_LLAMA,
  73. + LLM_ARCH_MLLAMA,
  74. LLM_ARCH_FALCON,
  75. LLM_ARCH_BAICHUAN,
  76. LLM_ARCH_GROK,
  77. @@ -202,6 +203,7 @@ enum llm_arch {
  78. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  79. { LLM_ARCH_LLAMA, "llama" },
  80. + { LLM_ARCH_MLLAMA, "mllama" },
  81. { LLM_ARCH_FALCON, "falcon" },
  82. { LLM_ARCH_GROK, "grok" },
  83. { LLM_ARCH_GPT2, "gpt2" },
  84. @@ -311,6 +313,7 @@ enum llm_kv {
  85. LLM_KV_ATTENTION_SLIDING_WINDOW,
  86. LLM_KV_ATTENTION_SCALE,
  87. LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION,
  88. + LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS,
  89. LLM_KV_ROPE_DIMENSION_COUNT,
  90. LLM_KV_ROPE_DIMENSION_SECTIONS,
  91. @@ -429,6 +432,7 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  92. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  93. { LLM_KV_ATTENTION_SCALE, "%s.attention.scale" },
  94. { LLM_KV_ATTENTION_BLOCK_SKIP_CONNECTION, "%s.attention.block_skip_connection.%d" },
  95. + { LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, "%s.attention.cross_attention_layers" },
  96. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  97. { LLM_KV_ROPE_DIMENSION_SECTIONS, "%s.rope.dimension_sections" },
  98. @@ -612,6 +616,14 @@ enum llm_tensor {
  99. LLM_TENSOR_CLS,
  100. LLM_TENSOR_CLS_OUT,
  101. LLM_TENSOR_BSKCN_TV,
  102. + LLM_TENSOR_CROSS_ATTN_K_NORM,
  103. + LLM_TENSOR_CROSS_ATTN_K_PROJ,
  104. + LLM_TENSOR_CROSS_ATTN_O_PROJ,
  105. + LLM_TENSOR_CROSS_ATTN_Q_NORM,
  106. + LLM_TENSOR_CROSS_ATTN_Q_PROJ,
  107. + LLM_TENSOR_CROSS_ATTN_V_PROJ,
  108. + LLM_TENSOR_CROSS_ATTN_ATTN_GATE,
  109. + LLM_TENSOR_CROSS_ATTN_MLP_GATE,
  110. };
  111. static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_NAMES = {
  112. @@ -641,6 +653,40 @@ static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_N
  113. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  114. },
  115. },
  116. + {
  117. + LLM_ARCH_MLLAMA,
  118. + {
  119. + { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  120. + { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  121. + { LLM_TENSOR_OUTPUT, "output" },
  122. + { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  123. + { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  124. + { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  125. + { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  126. + { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  127. + { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  128. + { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  129. + { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  130. + { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  131. + { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  132. + { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  133. + { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  134. + { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  135. + { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  136. + { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  137. + { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  138. + { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  139. + { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  140. + { LLM_TENSOR_CROSS_ATTN_K_NORM, "blk.%d.cross_attn_k_norm" },
  141. + { LLM_TENSOR_CROSS_ATTN_K_PROJ, "blk.%d.cross_attn_k_proj" },
  142. + { LLM_TENSOR_CROSS_ATTN_O_PROJ, "blk.%d.cross_attn_o_proj" },
  143. + { LLM_TENSOR_CROSS_ATTN_Q_NORM, "blk.%d.cross_attn_q_norm" },
  144. + { LLM_TENSOR_CROSS_ATTN_Q_PROJ, "blk.%d.cross_attn_q_proj" },
  145. + { LLM_TENSOR_CROSS_ATTN_V_PROJ, "blk.%d.cross_attn_v_proj" },
  146. + { LLM_TENSOR_CROSS_ATTN_ATTN_GATE, "blk.%d.cross_attn_attn_gate" },
  147. + { LLM_TENSOR_CROSS_ATTN_MLP_GATE, "blk.%d.cross_attn_mlp_gate" },
  148. + },
  149. + },
  150. {
  151. LLM_ARCH_BAICHUAN,
  152. {
  153. @@ -2456,6 +2502,7 @@ enum e_model {
  154. MODEL_40B,
  155. MODEL_65B,
  156. MODEL_70B,
  157. + MODEL_90B,
  158. MODEL_236B,
  159. MODEL_314B,
  160. MODEL_SMALL,
  161. @@ -2500,6 +2547,7 @@ struct llama_hparams {
  162. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  163. std::array<std::array<uint32_t, LLAMA_MAX_LAYERS>, 4> n_bskcn_arr;
  164. + std::array<uint32_t, LLAMA_MAX_LAYERS> cross_attn_layers;
  165. uint32_t n_layer_dense_lead = 0;
  166. uint32_t n_lora_q = 0;
  167. @@ -2569,10 +2617,11 @@ struct llama_hparams {
  168. if (this->n_expert != other.n_expert) return true;
  169. if (this->n_expert_used != other.n_expert_used) return true;
  170. - if (this->n_head_arr != other.n_head_arr) return true;
  171. - if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  172. - if (this->n_ff_arr != other.n_ff_arr) return true;
  173. - if (this->n_bskcn_arr != other.n_bskcn_arr) return true;
  174. + if (this->n_head_arr != other.n_head_arr) return true;
  175. + if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  176. + if (this->n_ff_arr != other.n_ff_arr) return true;
  177. + if (this->n_bskcn_arr != other.n_bskcn_arr) return true;
  178. + if (this->cross_attn_layers != other.cross_attn_layers) return true;
  179. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  180. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  181. @@ -2693,6 +2742,10 @@ struct llama_hparams {
  182. GGML_ABORT("fatal error");
  183. }
  184. +
  185. + bool cross_attention_layers(uint32_t il) const {
  186. + return std::find(cross_attn_layers.begin(), cross_attn_layers.end(), il) != cross_attn_layers.end();
  187. + }
  188. };
  189. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  190. @@ -2722,6 +2775,9 @@ struct llama_cparams {
  191. bool offload_kqv;
  192. bool flash_attn;
  193. bool no_perf;
  194. + // TODO (jmorganca): this should most likely be passed in as part of a batch
  195. + // and not set on the context for all batches.
  196. + bool cross_attn = false;
  197. enum llama_pooling_type pooling_type;
  198. @@ -2881,6 +2937,16 @@ struct llama_layer {
  199. struct ggml_tensor * ffn_down_scale;
  200. struct ggml_tensor * bskcn_tv;
  201. +
  202. + // cross attention
  203. + struct ggml_tensor * cross_attn_k_norm;
  204. + struct ggml_tensor * cross_attn_k_proj;
  205. + struct ggml_tensor * cross_attn_o_proj;
  206. + struct ggml_tensor * cross_attn_q_norm;
  207. + struct ggml_tensor * cross_attn_q_proj;
  208. + struct ggml_tensor * cross_attn_v_proj;
  209. + struct ggml_tensor * cross_attn_attn_gate;
  210. + struct ggml_tensor * cross_attn_mlp_gate;
  211. };
  212. // very similar to llama_batch,
  213. @@ -3472,6 +3538,8 @@ struct llama_context {
  214. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  215. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  216. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  217. +
  218. + struct ggml_tensor * inp_cross_attn_state; // F32 [4, n_embd, 1061]
  219. };
  220. struct llama_lora_weight {
  221. @@ -3610,6 +3678,39 @@ static bool llama_kv_cache_init(
  222. cache.v_l.reserve(n_layer);
  223. for (int i = 0; i < (int) n_layer; i++) {
  224. + // for cross attention layers
  225. + if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layers(i)) {
  226. + const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  227. + const llama_model::buft_list_t * buft_list;
  228. + if (offload) {
  229. + buft_list = model.dev_layer.at(i).buft_list;
  230. + } else {
  231. + buft_list = &model.cpu_buft_list;
  232. + }
  233. + ggml_backend_buffer_type_t buft = select_buft(*buft_list,
  234. + [&](ggml_context * ctx) {
  235. + ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  236. + if (hparams.rope_type == LLAMA_ROPE_TYPE_NONE) {
  237. + return k;
  238. + }
  239. + ggml_tensor * p = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  240. + return ggml_rope(ctx, k, p, hparams.n_rot, hparams.rope_type);
  241. + });
  242. + ggml_context * ctx = ctx_for_buft(buft);
  243. +
  244. + if (!ctx) {
  245. + LLAMA_LOG_ERROR("%s: failed to create ggml context for kv cache\n", __func__);
  246. + return false;
  247. + }
  248. + ggml_tensor * k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  249. + ggml_tensor * v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  250. + ggml_format_name(k, "cache_k_l%d", i);
  251. + ggml_format_name(v, "cache_v_l%d", i);
  252. + cache.k_l.push_back(k);
  253. + cache.v_l.push_back(v);
  254. + continue;
  255. + }
  256. +
  257. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  258. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  259. @@ -5547,12 +5648,14 @@ static void llm_load_hparams(
  260. }
  261. // zero-out the per-layer hparams
  262. - std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  263. - std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  264. - std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  265. + std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  266. + std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  267. + std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  268. + std::fill(hparams.cross_attn_layers.begin(), hparams.cross_attn_layers.end(), -1);
  269. - ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  270. - ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  271. + ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  272. + ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  273. + ml.get_arr(LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, hparams.cross_attn_layers, false);
  274. // n_head_kv is optional, default to n_head
  275. hparams.n_head_kv_arr = hparams.n_head_arr;
  276. @@ -5601,7 +5704,7 @@ static void llm_load_hparams(
  277. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  278. - if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  279. + if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_MLLAMA || model.arch == LLM_ARCH_FALCON) {
  280. if (hparams.n_rot != hparams.n_embd_head_k) {
  281. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  282. }
  283. @@ -5641,6 +5744,16 @@ static void llm_load_hparams(
  284. }
  285. }
  286. } break;
  287. + case LLM_ARCH_MLLAMA:
  288. + {
  289. + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  290. +
  291. + switch (hparams.n_layer) {
  292. + case 40: model.type = e_model::MODEL_11B; break;
  293. + case 100: model.type = e_model::MODEL_90B; break;
  294. + default: model.type = e_model::MODEL_UNKNOWN;
  295. + }
  296. + } break;
  297. case LLM_ARCH_MINICPM:
  298. {
  299. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  300. @@ -7291,7 +7404,15 @@ static const std::map<llm_tensor, llm_tensor_info> llm_tensor_info_mapping = {
  301. {LLM_TENSOR_FFN_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
  302. // this tensor is loaded for T5, but never used
  303. {LLM_TENSOR_DEC_CROSS_ATTN_REL_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_NONE}},
  304. - {LLM_TENSOR_BSKCN_TV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}
  305. + {LLM_TENSOR_BSKCN_TV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  306. + {LLM_TENSOR_CROSS_ATTN_K_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  307. + {LLM_TENSOR_CROSS_ATTN_K_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  308. + {LLM_TENSOR_CROSS_ATTN_O_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  309. + {LLM_TENSOR_CROSS_ATTN_Q_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  310. + {LLM_TENSOR_CROSS_ATTN_Q_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  311. + {LLM_TENSOR_CROSS_ATTN_V_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
  312. + {LLM_TENSOR_CROSS_ATTN_ATTN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  313. + {LLM_TENSOR_CROSS_ATTN_MLP_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
  314. };
  315. // checks if the weight tensor can be used with the specified buffer type and device
  316. @@ -7801,6 +7922,53 @@ static bool llm_load_tensors(
  317. }
  318. }
  319. } break;
  320. + case LLM_ARCH_MLLAMA:
  321. + {
  322. + model.tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab+8}, 0);
  323. +
  324. + // output
  325. + {
  326. + model.output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
  327. + model.output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  328. +
  329. + // if output is NULL, init from the input tok embed
  330. + if (model.output == NULL) {
  331. + model.output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  332. + }
  333. + }
  334. +
  335. + for (int i = 0; i < n_layer; ++i) {
  336. +
  337. + auto & layer = model.layers[i];
  338. +
  339. + if (hparams.cross_attention_layers(i)) {
  340. + layer.cross_attn_k_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_NORM, "weight", i), {128}, 0);
  341. + layer.cross_attn_k_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_K_PROJ, "weight", i), {n_embd, 1024}, 0);
  342. + layer.cross_attn_o_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_O_PROJ, "weight", i), {n_embd, n_embd}, 0);
  343. + layer.cross_attn_q_norm = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_NORM, "weight", i), {128}, 0);
  344. + layer.cross_attn_q_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_Q_PROJ, "weight", i), {n_embd, n_embd}, 0);
  345. + layer.cross_attn_v_proj = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_V_PROJ, "weight", i), {n_embd, 1024}, 0);
  346. + layer.cross_attn_attn_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_ATTN_GATE, i), {1}, 0);
  347. + layer.cross_attn_mlp_gate = create_tensor(tn(LLM_TENSOR_CROSS_ATTN_MLP_GATE, i), {1}, 0);
  348. + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  349. + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
  350. + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  351. + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  352. + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  353. + } else {
  354. + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
  355. + layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
  356. + layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa}, 0);
  357. + layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa}, 0);
  358. + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
  359. + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
  360. + layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  361. + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
  362. + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, 0);
  363. + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
  364. + }
  365. + }
  366. + } break;
  367. case LLM_ARCH_MINICPM3:
  368. {
  369. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  370. @@ -9511,7 +9679,7 @@ static int llama_model_load(const std::string & fname, llama_model & model, llam
  371. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  372. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  373. - throw std::runtime_error("vocab size mismatch");
  374. + LLAMA_LOG_WARN("%s: vocab mismatch %u !- %zu ...\n", __func__, model.hparams.n_vocab, model.vocab.id_to_token.size());
  375. }
  376. if (params.vocab_only) {
  377. @@ -9594,6 +9762,21 @@ static struct ggml_tensor * llm_build_inp_embd(
  378. return inpL;
  379. }
  380. +static struct ggml_tensor * llm_build_inp_cross_attn_state(
  381. + struct ggml_context * ctx,
  382. + struct llama_context & lctx,
  383. + const llama_hparams & hparams,
  384. + const llm_build_cb & cb) {
  385. + const int64_t n_embd = hparams.n_embd;
  386. +
  387. + struct ggml_tensor * inpCAS = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, 1601, 4);
  388. + cb(inpCAS, "inp_cross_attn_state", -1);
  389. + ggml_set_input(inpCAS);
  390. + lctx.inp_cross_attn_state = inpCAS;
  391. +
  392. + return inpCAS;
  393. +}
  394. +
  395. static void llm_build_kv_store(
  396. struct ggml_context * ctx,
  397. const llama_hparams & hparams,
  398. @@ -10561,6 +10744,7 @@ struct llm_build_context {
  399. lctx.inp_pos_bucket = nullptr;
  400. lctx.inp_embd_enc = nullptr;
  401. lctx.inp_KQ_mask_cross = nullptr;
  402. + lctx.inp_cross_attn_state = nullptr;
  403. }
  404. void free() {
  405. @@ -11040,6 +11224,240 @@ struct llm_build_context {
  406. return gf;
  407. }
  408. + struct ggml_cgraph * build_mllama() {
  409. + struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  410. +
  411. + // mutable variable, needed during the last layer of the computation to skip unused tokens
  412. + int32_t n_tokens = this->n_tokens;
  413. +
  414. + const int64_t n_embd_head = hparams.n_embd_head_v;
  415. + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  416. + GGML_ASSERT(n_embd_head == hparams.n_rot);
  417. +
  418. + struct ggml_tensor * cur;
  419. + struct ggml_tensor * inpL;
  420. + struct ggml_tensor * inpCAS;
  421. +
  422. + inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  423. + inpCAS = llm_build_inp_cross_attn_state(ctx0, lctx, hparams, cb);
  424. +
  425. + // inp_pos - contains the positions
  426. + struct ggml_tensor * inp_pos = build_inp_pos();
  427. +
  428. + // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  429. + struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  430. +
  431. + for (int il = 0; il < n_layer; ++il) {
  432. + struct ggml_tensor * inpSA = inpL;
  433. +
  434. + // norm
  435. + cur = llm_build_norm(ctx0, inpL, hparams,
  436. + model.layers[il].attn_norm, NULL,
  437. + LLM_NORM_RMS, cb, il);
  438. + cb(cur, "attn_norm", il);
  439. +
  440. + if (hparams.cross_attention_layers(il)) {
  441. + if (!ubatch.embd && !cparams.cross_attn) {
  442. + continue;
  443. + }
  444. +
  445. + // cross attention layer
  446. + struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_q_proj, cur);
  447. + cb(Qcur, "Qcur", il);
  448. +
  449. + Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  450. + cb(Qcur, "Qcur", il);
  451. +
  452. + Qcur = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 0, 2, 1, 3));
  453. + cb(Qcur, "Qcur", il);
  454. +
  455. + Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].cross_attn_q_norm, NULL, LLM_NORM_RMS, cb, il);
  456. + cb(Qcur, "Qcur", il);
  457. +
  458. + struct ggml_tensor * Kcur, * Vcur;
  459. + if (ubatch.embd) {
  460. + Kcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_k_proj, inpCAS);
  461. + cb(Kcur, "Kcur", il);
  462. +
  463. + Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 6404);
  464. + cb(Kcur, "Kcur", il);
  465. +
  466. + Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  467. + cb(Kcur, "Kcur", il);
  468. +
  469. + Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].cross_attn_k_norm, NULL, LLM_NORM_RMS, cb, il);
  470. + cb(Kcur, "Kcur", il);
  471. +
  472. + ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, kv_self.k_l[il]));
  473. +
  474. + Vcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_v_proj, inpCAS);
  475. + cb(Vcur, "Vcur", il);
  476. +
  477. + Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, 6404);
  478. + cb(Vcur, "Vcur", il);
  479. +
  480. + Vcur = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
  481. + cb(Vcur, "Vcur", il);
  482. +
  483. + ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, kv_self.v_l[il]));
  484. + } else {
  485. + Kcur = ggml_view_tensor(ctx0, kv_self.k_l[il]);
  486. + cb(Kcur, "Kcur (view)", il);
  487. +
  488. + Vcur = ggml_view_tensor(ctx0, kv_self.v_l[il]);
  489. + cb(Vcur, "Vcur (view)", il);
  490. + }
  491. +
  492. + struct ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur);
  493. + cb(kq, "kq", il);
  494. +
  495. + // TODO: apply causal masks
  496. + struct ggml_tensor * kq_soft_max = ggml_soft_max_ext(ctx0, kq, nullptr, 1.f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  497. + cb(kq_soft_max, "kq_soft_max", il);
  498. +
  499. + Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, Vcur));
  500. + cb(Vcur, "Vcur", il);
  501. +
  502. + struct ggml_tensor * kqv = ggml_mul_mat(ctx0, Vcur, kq_soft_max);
  503. + cb(kqv, "kqv", il);
  504. +
  505. + struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  506. + cb(kqv_merged, "kqv_merged", il);
  507. +
  508. + cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_head_v*n_head, n_tokens);
  509. + cb(cur, "kqv_merged_cont", il);
  510. +
  511. + cur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_o_proj, cur);
  512. + cb(cur, "cur", il);
  513. +
  514. + // TODO: do this in place once?
  515. + cur = ggml_mul(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_attn_gate));
  516. +
  517. + struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  518. + cb(ffn_inp, "ffn_inp", il);
  519. +
  520. + // feed-forward network
  521. + cur = llm_build_norm(ctx0, ffn_inp, hparams,
  522. + model.layers[il].ffn_norm, NULL,
  523. + LLM_NORM_RMS, cb, il);
  524. + cb(cur, "ffn_norm", il);
  525. +
  526. + cur = llm_build_ffn(ctx0, lctx, cur,
  527. + model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  528. + model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  529. + model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  530. + NULL,
  531. + LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  532. + cb(cur, "ffn_out", il);
  533. +
  534. + // TODO: do this inplace once?
  535. + cur = ggml_add_inplace(ctx0, ggml_mul_inplace(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_mlp_gate)), ffn_inp);
  536. + cb(cur, "ffn_out", il);
  537. +
  538. + cur = lctx.cvec.apply_to(ctx0, cur, il);
  539. + cb(cur, "l_out", il);
  540. +
  541. + // input for next layer
  542. + inpL = cur;
  543. + } else {
  544. + // self attention layer
  545. +
  546. + // rope freq factors for llama3; may return nullptr for llama2 and other models
  547. + struct ggml_tensor * rope_factors = build_rope_factors(il);
  548. +
  549. + // compute Q and K and RoPE them
  550. + struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  551. + cb(Qcur, "Qcur", il);
  552. + if (model.layers[il].bq) {
  553. + Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  554. + cb(Qcur, "Qcur", il);
  555. + }
  556. +
  557. + struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  558. + cb(Kcur, "Kcur", il);
  559. + if (model.layers[il].bk) {
  560. + Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  561. + cb(Kcur, "Kcur", il);
  562. + }
  563. +
  564. + struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  565. + cb(Vcur, "Vcur", il);
  566. + if (model.layers[il].bv) {
  567. + Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  568. + cb(Vcur, "Vcur", il);
  569. + }
  570. +
  571. + Qcur = ggml_rope_ext(
  572. + ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  573. + n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  574. + ext_factor, attn_factor, beta_fast, beta_slow
  575. + );
  576. + cb(Qcur, "Qcur", il);
  577. +
  578. + Kcur = ggml_rope_ext(
  579. + ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  580. + n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  581. + ext_factor, attn_factor, beta_fast, beta_slow
  582. + );
  583. + cb(Kcur, "Kcur", il);
  584. +
  585. + cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  586. + model.layers[il].wo, model.layers[il].bo,
  587. + Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  588. +
  589. +
  590. + if (il == n_layer - 1) {
  591. + // skip computing output for unused tokens
  592. + struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  593. + n_tokens = n_outputs;
  594. + cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  595. + inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  596. + }
  597. +
  598. + struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  599. + cb(ffn_inp, "ffn_inp", il);
  600. +
  601. + // feed-forward network
  602. + cur = llm_build_norm(ctx0, ffn_inp, hparams,
  603. + model.layers[il].ffn_norm, NULL,
  604. + LLM_NORM_RMS, cb, il);
  605. + cb(cur, "ffn_norm", il);
  606. +
  607. + cur = llm_build_ffn(ctx0, lctx, cur,
  608. + model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  609. + model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  610. + model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  611. + NULL,
  612. + LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  613. + cb(cur, "ffn_out", il);
  614. +
  615. + cur = ggml_add(ctx0, cur, ffn_inp);
  616. + cb(cur, "ffn_out", il);
  617. +
  618. + cur = lctx.cvec.apply_to(ctx0, cur, il);
  619. + cb(cur, "l_out", il);
  620. +
  621. + // input for next layer
  622. + inpL = cur;
  623. + }
  624. + }
  625. +
  626. + cur = inpL;
  627. +
  628. + cur = llm_build_norm(ctx0, cur, hparams,
  629. + model.output_norm, NULL,
  630. + LLM_NORM_RMS, cb, -1);
  631. + cb(cur, "result_norm", -1);
  632. +
  633. + // lm_head
  634. + cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  635. + cb(cur, "result_output", -1);
  636. +
  637. + ggml_build_forward_expand(gf, cur);
  638. +
  639. + return gf;
  640. + }
  641. +
  642. struct ggml_cgraph * build_baichuan() {
  643. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  644. @@ -16993,6 +17411,10 @@ static struct ggml_cgraph * llama_build_graph(
  645. {
  646. result = llm.build_llama();
  647. } break;
  648. + case LLM_ARCH_MLLAMA:
  649. + {
  650. + result = llm.build_mllama();
  651. + } break;
  652. case LLM_ARCH_BAICHUAN:
  653. {
  654. result = llm.build_baichuan();
  655. @@ -17258,10 +17680,19 @@ static void llama_set_inputs(llama_context & lctx, const llama_ubatch & ubatch)
  656. }
  657. if (ubatch.embd) {
  658. - const int64_t n_embd = hparams.n_embd;
  659. - const int64_t n_tokens = ubatch.n_tokens;
  660. + if (lctx.inp_cross_attn_state && lctx.inp_cross_attn_state->buffer) {
  661. + ggml_backend_tensor_set(lctx.inp_cross_attn_state, ubatch.embd, 0, ggml_nbytes(lctx.inp_cross_attn_state));
  662. + // zero out inp_embd since it's not used
  663. + float * inp_embd_data = (float *)lctx.inp_embd->data;
  664. + for (int i = 0; i < ggml_nelements(lctx.inp_embd); ++i) {
  665. + inp_embd_data[i] = 0.0f;
  666. + }
  667. + } else {
  668. + const int64_t n_embd = hparams.n_embd;
  669. + const int64_t n_tokens = ubatch.n_tokens;
  670. - ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  671. + ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  672. + }
  673. }
  674. if (ubatch.pos && lctx.inp_pos) {
  675. @@ -17862,7 +18293,7 @@ static int llama_decode_internal(
  676. n_outputs = 1;
  677. }
  678. - lctx.sbatch.from_batch(batch, n_embd,
  679. + lctx.sbatch.from_batch(batch, batch.n_embd,
  680. /* simple_split */ !kv_self.recurrent,
  681. /* logits_all */ n_outputs == n_tokens_all);
  682. @@ -18172,7 +18603,7 @@ static int llama_encode_internal(
  683. const int64_t n_embd = hparams.n_embd;
  684. - lctx.sbatch.from_batch(batch, n_embd, /* simple_split */ true, /* logits_all */ true);
  685. + lctx.sbatch.from_batch(batch, batch.n_embd, /* simple_split */ true, /* logits_all */ true);
  686. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  687. @@ -19203,7 +19634,9 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
  688. if (llama_model_has_encoder(&model)) {
  689. n_attn_layer *= 3;
  690. }
  691. - GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
  692. + if (qs.n_attention_wv != n_attn_layer) {
  693. + LLAMA_LOG_WARN("%s: n_attention_wv is unexpected, expected: %d, found: %d\n", __func__, n_attn_layer, qs.n_attention_wv);
  694. + }
  695. }
  696. size_t total_size_org = 0;
  697. @@ -20360,6 +20793,7 @@ enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  698. // use what we call a normal RoPE, operating on pairs of consecutive head values
  699. case LLM_ARCH_LLAMA:
  700. + case LLM_ARCH_MLLAMA:
  701. case LLM_ARCH_BAICHUAN:
  702. case LLM_ARCH_STARCODER:
  703. case LLM_ARCH_PLAMO:
  704. @@ -21790,6 +22224,10 @@ void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  705. ctx->cparams.causal_attn = causal_attn;
  706. }
  707. +void llama_set_cross_attention(struct llama_context * ctx, bool cross_attention) {
  708. + ctx->cparams.cross_attn = cross_attention;
  709. +}
  710. +
  711. struct llama_batch llama_batch_get_one(
  712. llama_token * tokens,
  713. int32_t n_tokens) {
  714. @@ -21797,6 +22235,7 @@ struct llama_batch llama_batch_get_one(
  715. /*n_tokens =*/ n_tokens,
  716. /*tokens =*/ tokens,
  717. /*embd =*/ nullptr,
  718. + /*n_embd =*/ 0,
  719. /*pos =*/ nullptr,
  720. /*n_seq_id =*/ nullptr,
  721. /*seq_id =*/ nullptr,
  722. @@ -21809,6 +22248,7 @@ struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_
  723. /*n_tokens =*/ 0,
  724. /*tokens =*/ nullptr,
  725. /*embd =*/ nullptr,
  726. + /*n_embd =*/ 0,
  727. /*pos =*/ nullptr,
  728. /*n_seq_id =*/ nullptr,
  729. /*seq_id =*/ nullptr,
  730. @@ -21817,6 +22257,7 @@ struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_
  731. if (embd) {
  732. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  733. + batch.n_embd = embd;
  734. } else {
  735. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  736. }