0010-add-mllama-support.patch 33 KB

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