-
Notifications
You must be signed in to change notification settings - Fork 24.1k
llama: add Maple 20B-A1B ternary MoE architecture (CPU) #27000
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+285
−2
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
60a211f
gguf-py: add Maple tensor constants
AlexGabbia af0c496
convert: add Maple HF->GGUF converter
AlexGabbia d0e002d
llama: add Maple architecture (20B-A1B ternary MoE)
AlexGabbia 4ac3469
tests: mark Maple as MoE-mandatory
AlexGabbia dd4543e
maple: apply review feedback (n_ff_exp_arr, get_arr, rope params)
AlexGabbia b92b8bf
tests: add Maple to the SWA pattern array list
AlexGabbia 8e3842b
maple: move swiglu_clamp_exp to the converter
AlexGabbia 0d0b53c
convert: fix the LazyBase func signature in the Maple converter
AlexGabbia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Iterable, TYPE_CHECKING, cast | ||
|
|
||
| import torch | ||
|
|
||
| if TYPE_CHECKING: | ||
| from torch import Tensor | ||
|
|
||
| from .base import LazyTorchTensor, ModelBase, TextModel, gguf | ||
|
|
||
|
|
||
| @ModelBase.register("MapleForCausalLM") | ||
| @ModelBase.example("deepgrove/maple-preview") | ||
| class MapleModel(TextModel): | ||
| model_arch = gguf.MODEL_ARCH.MAPLE | ||
|
|
||
| def set_gguf_parameters(self): | ||
| super().set_gguf_parameters() | ||
| hparams = self.hparams | ||
|
|
||
| assert hparams["hidden_act"] == "silu" | ||
| assert hparams.get("num_shared_experts", 0) == 0 | ||
| assert hparams.get("norm_topk_prob", True) | ||
| assert hparams.get("nope_on_global_attention", False) | ||
|
|
||
| head_dim = hparams.get("head_dim", hparams["hidden_size"] // hparams["num_attention_heads"]) | ||
| partial_rotary_factor = self.rope_parameters.get("partial_rotary_factor", 1.0) | ||
|
|
||
| self.gguf_writer.add_vocab_size(hparams["vocab_size"]) | ||
| self.gguf_writer.add_rope_dimension_count(int(head_dim * partial_rotary_factor)) | ||
| self.gguf_writer.add_sliding_window(hparams["sliding_window"]) | ||
| self.gguf_writer.add_sliding_window_pattern([layer_type == "sliding_attention" for layer_type in hparams["layer_types"]]) | ||
| self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"]) | ||
| # the reference clamps the MoE SwiGLU gate/up at 7.0 (modeling_maple.py) | ||
| self.gguf_writer.add_swiglu_clamp_exp([7.0] * self.block_count) | ||
|
|
||
| _experts: list[dict[str, Tensor]] | None = None | ||
|
|
||
| @staticmethod | ||
| def _stack_experts(tensors: list[Tensor]) -> Tensor: | ||
| shape = (len(tensors), *tensors[0].shape) | ||
| dtype = tensors[0].dtype | ||
| meta = LazyTorchTensor.meta_with_dtype_and_shape(dtype, shape) | ||
|
|
||
| # tensors goes through args, not the closure, so that `func` matches | ||
| # LazyBase's single-argument shape | ||
| def stack(ts: list[Tensor]) -> Tensor: | ||
| result = torch.empty(shape, dtype=dtype) | ||
| for expert_id, tensor in enumerate(ts): | ||
| result[expert_id].copy_(LazyTorchTensor.to_eager(tensor)) | ||
| ts.clear() | ||
| return result | ||
|
|
||
| return cast(torch.Tensor, LazyTorchTensor(meta=meta, args=(tensors,), func=stack)) | ||
|
|
||
| def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: | ||
| if "mlp.experts" in name: | ||
| n_experts = self.hparams["num_experts"] | ||
| assert bid is not None | ||
|
|
||
| if self._experts is None: | ||
| self._experts = [{} for _ in range(self.block_count)] | ||
|
|
||
| self._experts[bid][name] = data_torch | ||
|
|
||
| if len(self._experts[bid]) >= n_experts * 3: | ||
| for weight_name in ("down_proj", "gate_proj", "up_proj"): | ||
| tensors = [] | ||
|
|
||
| for expert_id in range(n_experts): | ||
| expert_name = f"model.layers.{bid}.mlp.experts.{expert_id}.{weight_name}.weight" | ||
| tensors.append(self._experts[bid].pop(expert_name)) | ||
|
|
||
| merged_name = f"model.layers.{bid}.mlp.experts.{weight_name}.weight" | ||
| yield from super().modify_tensors(self._stack_experts(tensors), merged_name, bid) | ||
| return | ||
|
|
||
| yield from super().modify_tensors(data_torch, name, bid) | ||
|
|
||
| def prepare_tensors(self): | ||
| super().prepare_tensors() | ||
|
|
||
| if self._experts is not None: | ||
| experts = [name for layer in self._experts for name in layer] | ||
| if experts: | ||
| raise ValueError(f"Unprocessed experts: {experts}") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,6 +33,7 @@ bool llama_model_saver_supports_arch(llm_arch arch) { | |
| case LLM_ARCH_LAGUNA: | ||
| case LLM_ARCH_GRANITE_SWA: | ||
| case LLM_ARCH_DOTS3NOTE: // TODO: need to handle SWA pattern and MLA+SWA config | ||
| case LLM_ARCH_MAPLE: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Any reason to not implement the model saver for this model?
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same reason as the others, the SWA pattern. |
||
| return false; | ||
| default: | ||
| return true; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| #include "models.h" | ||
|
|
||
| void llama_model_maple::load_arch_hparams(llama_model_loader & ml) { | ||
| hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; | ||
|
|
||
| ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); | ||
| ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); | ||
| ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); | ||
|
|
||
| ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); | ||
|
|
||
| hparams.rope_freq_base_train_swa = hparams.rope_freq_base_train; | ||
| hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; | ||
| ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa, false); | ||
|
|
||
| ml.get_key_or_arr(LLM_KV_SWIGLU_CLAMP_EXP, hparams.swiglu_clamp_exp, hparams.n_layer_all); | ||
|
|
||
| switch (hparams.n_layer()) { | ||
| case 24: type = LLM_TYPE_20B; break; | ||
| default: type = LLM_TYPE_UNKNOWN; | ||
| } | ||
| } | ||
|
|
||
| void llama_model_maple::load_arch_tensors(llama_model_loader &) { | ||
| LLAMA_LOAD_LOCALS; | ||
|
|
||
| const int64_t n_ff_exp = hparams.n_ff_exp(); | ||
| const int64_t head_dim = hparams.n_embd_head_k(); | ||
|
|
||
| tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); | ||
|
|
||
| output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); | ||
| output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0); | ||
|
|
||
| if (n_expert == 0) { | ||
| throw std::runtime_error("n_expert must be > 0 for Maple"); | ||
| } | ||
| if (n_expert_used == 0) { | ||
| throw std::runtime_error("n_expert_used must be > 0 for Maple"); | ||
| } | ||
|
|
||
| for (int i = 0; i < n_layer; ++i) { | ||
| auto & layer = layers[i]; | ||
|
|
||
| layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); | ||
|
|
||
| create_tensor_qkv(layer, i, n_embd, n_head * head_dim, n_head_kv * head_dim, n_head_kv * head_dim, 0); | ||
| layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head * head_dim, n_embd}, 0); | ||
|
|
||
| layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {head_dim}, 0); | ||
| layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {head_dim}, 0); | ||
| layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); | ||
|
|
||
| layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); | ||
| layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); | ||
| layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); | ||
| layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); | ||
| } | ||
| } | ||
|
|
||
| std::unique_ptr<llm_graph_context> llama_model_maple::build_arch_graph(const llm_graph_params & params) const { | ||
| return std::make_unique<graph>(*this, params); | ||
| } | ||
|
|
||
| llama_model_maple::graph::graph(const llama_model & model, const llm_graph_params & params) : | ||
| llm_graph_context(params) { | ||
| const int64_t n_embd_head = hparams.n_embd_head_k(); | ||
|
|
||
| GGML_ASSERT(n_embd_head == hparams.n_embd_head_v()); | ||
|
|
||
| ggml_tensor * inpL = build_inp_embd(model.tok_embd); | ||
| ggml_tensor * inp_pos = build_inp_pos(); | ||
| auto * inp_attn = build_attn_inp_kv_iswa(); | ||
| ggml_tensor * inp_out_ids = build_inp_out_ids(); | ||
|
|
||
| for (int il = 0; il < n_layer; ++il) { | ||
| ggml_tensor * inpSA = inpL; | ||
|
|
||
| ggml_tensor * cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il); | ||
| cb(cur, "attn_norm", il); | ||
|
|
||
| { | ||
| auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il); | ||
|
|
||
| Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, nullptr, LLM_NORM_RMS, il); | ||
| Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, nullptr, LLM_NORM_RMS, il); | ||
| cb(Qcur, "Qcur_normed", il); | ||
| cb(Kcur, "Kcur_normed", il); | ||
|
|
||
| if (hparams.is_swa(il)) { | ||
| const int64_t n_rot_l = hparams.n_rot(il); | ||
| const float freq_base_l = model.get_rope_freq_base(cparams, il); | ||
| const float freq_scale_l = model.get_rope_freq_scale(cparams, il); | ||
|
|
||
| Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, n_rot_l, rope_type, n_ctx_orig, freq_base_l, | ||
| freq_scale_l, ext_factor, attn_factor, beta_fast, beta_slow); | ||
| Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, n_rot_l, rope_type, n_ctx_orig, freq_base_l, | ||
| freq_scale_l, ext_factor, attn_factor, beta_fast, beta_slow); | ||
| } | ||
| cb(Qcur, "Qcur", il); | ||
| cb(Kcur, "Kcur", il); | ||
| cb(Vcur, "Vcur", il); | ||
|
|
||
| cur = build_attn(inp_attn, | ||
| model.layers[il].wo, nullptr, model.layers[il].wo_s, | ||
| Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il); | ||
| cb(cur, "attn_out", il); | ||
| } | ||
|
|
||
| if (il == n_layer - 1 && inp_out_ids) { | ||
| cur = ggml_get_rows(ctx0, cur, inp_out_ids); | ||
| inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids); | ||
| } | ||
|
|
||
| ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); | ||
| cb(ffn_inp, "ffn_inp", il); | ||
|
|
||
| cur = build_norm(ffn_inp, model.layers[il].ffn_norm, nullptr, LLM_NORM_RMS, il); | ||
| cb(cur, "ffn_norm", il); | ||
|
|
||
| cur = build_moe_ffn(cur, | ||
| model.layers[il].ffn_gate_inp, | ||
| model.layers[il].ffn_up_exps, | ||
| model.layers[il].ffn_gate_exps, | ||
| model.layers[il].ffn_down_exps, | ||
| nullptr, | ||
| n_expert, n_expert_used, | ||
| LLM_FFN_SILU, true, | ||
| 1.0f, | ||
| LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, | ||
| il); | ||
| cb(cur, "ffn_moe_out", il); | ||
|
|
||
| cur = ggml_add(ctx0, cur, ffn_inp); | ||
| cur = build_cvec(cur, il); | ||
| cb(cur, "l_out", il); | ||
|
|
||
| inpL = cur; | ||
| } | ||
|
|
||
| ggml_tensor * cur = build_norm(inpL, model.output_norm, nullptr, LLM_NORM_RMS, -1); | ||
| cb(cur, "result_norm", -1); | ||
| res->t_embd = cur; | ||
|
|
||
| cur = build_lora_mm(model.output, cur, model.output_s); | ||
| cb(cur, "result_output", -1); | ||
| res->t_logits = cur; | ||
|
|
||
| ggml_build_forward_expand(gf, cur); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.