Skip to content

Commit a8cc3ea

Browse files
committed
Merge branch 'master' into esocrok
2 parents 190da3e + a2e0088 commit a8cc3ea

File tree

71 files changed

+3434
-442
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+3434
-442
lines changed

convert_hf_to_gguf.py

Lines changed: 99 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -895,8 +895,8 @@ def get_vocab_base_pre(self, tokenizer) -> str:
895895
# ref: https://huggingface.co/JetBrains/Mellum-4b-base
896896
res = "mellum"
897897
if chkhsh == "9b1be57e70d20d9501b2b3186e792d81181ae36ada3903c26f9fea418cf87206":
898-
# ref: https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Base
899-
res = "llada-moe"
898+
# ref: https://huggingface.co/inclusionAI/Ling-mini-base-2.0
899+
res = "bailingmoe2"
900900
if chkhsh == "53e325976a6e142379c19b09afcae354f2f496f147afa8f9e189a33fe4e3024e":
901901
# ref: https://huggingface.co/ibm-granite/granite-docling-258M
902902
res = "granite-docling"
@@ -8060,6 +8060,103 @@ def prepare_tensors(self):
80608060
raise ValueError(f"Unprocessed experts: {experts}")
80618061

80628062

8063+
@ModelBase.register("BailingMoeV2ForCausalLM")
8064+
class BailingMoeV2Model(TextModel):
8065+
model_arch = gguf.MODEL_ARCH.BAILINGMOE2
8066+
8067+
def __init__(self, *args, **kwargs):
8068+
super().__init__(*args, **kwargs)
8069+
if nextn_layers := self.hparams.get("num_nextn_predict_layers", 0):
8070+
self.block_count = self.hparams["num_hidden_layers"] + nextn_layers
8071+
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
8072+
8073+
def set_vocab(self):
8074+
self._set_vocab_gpt2()
8075+
8076+
def set_gguf_parameters(self):
8077+
super().set_gguf_parameters()
8078+
hparams = self.hparams
8079+
if (rope_dim := hparams.get("head_dim")) is None:
8080+
rope_dim = hparams["hidden_size"] // hparams["num_attention_heads"]
8081+
8082+
self.gguf_writer.add_rope_dimension_count(int(rope_dim * self.hparams.get("partial_rotary_factor", 0.5)))
8083+
rope_scaling = self.hparams.get("rope_scaling") or {}
8084+
if rope_scaling.get("rope_type", rope_scaling.get("type")) == "yarn" and "factor" in rope_scaling:
8085+
self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.YARN)
8086+
self.gguf_writer.add_rope_scaling_factor(rope_scaling["factor"])
8087+
self.gguf_writer.add_rope_scaling_orig_ctx_len(rope_scaling["original_max_position_embeddings"])
8088+
else:
8089+
self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
8090+
self.gguf_writer.add_leading_dense_block_count(hparams["first_k_dense_replace"])
8091+
self.gguf_writer.add_vocab_size(hparams["vocab_size"])
8092+
self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"])
8093+
self.gguf_writer.add_expert_shared_feed_forward_length(hparams.get("moe_shared_expert_intermediate_size", hparams["moe_intermediate_size"] * hparams["num_shared_experts"]))
8094+
self.gguf_writer.add_expert_weights_scale(hparams["routed_scaling_factor"])
8095+
self.gguf_writer.add_expert_count(hparams["num_experts"])
8096+
self.gguf_writer.add_expert_shared_count(hparams["num_shared_experts"])
8097+
self.gguf_writer.add_expert_group_count(hparams["n_group"])
8098+
self.gguf_writer.add_expert_group_used_count(hparams["topk_group"])
8099+
self.gguf_writer.add_expert_weights_norm(hparams["norm_topk_prob"])
8100+
8101+
if hparams["score_function"] == "sigmoid":
8102+
self.gguf_writer.add_expert_gating_func(gguf.ExpertGatingFuncType.SIGMOID)
8103+
elif hparams["score_function"] == "softmax":
8104+
self.gguf_writer.add_expert_gating_func(gguf.ExpertGatingFuncType.SOFTMAX)
8105+
else:
8106+
raise ValueError(f"Unsupported score_function value: {hparams['score_function']}")
8107+
8108+
if (nextn_layers := self.hparams.get("num_nextn_predict_layers")) is not None:
8109+
self.gguf_writer.add_nextn_predict_layers(nextn_layers)
8110+
8111+
_experts: list[dict[str, Tensor]] | None = None
8112+
8113+
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
8114+
if "mlp.experts" in name:
8115+
n_experts = self.hparams["num_experts"]
8116+
assert bid is not None
8117+
8118+
tensors: list[tuple[str, Tensor]] = []
8119+
8120+
if self._experts is None:
8121+
self._experts = [{} for _ in range(self.block_count)]
8122+
8123+
self._experts[bid][name] = data_torch
8124+
8125+
if len(self._experts[bid]) >= n_experts * 3:
8126+
# merge the experts into a single 3d tensor
8127+
for w_name in ["down_proj", "gate_proj", "up_proj"]:
8128+
datas: list[Tensor] = []
8129+
8130+
for xid in range(n_experts):
8131+
ename = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
8132+
datas.append(self._experts[bid][ename])
8133+
del self._experts[bid][ename]
8134+
8135+
data_torch = torch.stack(datas, dim=0)
8136+
8137+
merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
8138+
8139+
new_name = self.map_tensor_name(merged_name)
8140+
8141+
tensors.append((new_name, data_torch))
8142+
8143+
return tensors
8144+
8145+
if name.endswith(".expert_bias"):
8146+
name = name.replace(".expert_bias", ".expert_bias.bias")
8147+
8148+
return [(self.map_tensor_name(name), data_torch)]
8149+
8150+
def prepare_tensors(self):
8151+
super().prepare_tensors()
8152+
8153+
if self._experts is not None:
8154+
# flatten `list[dict[str, Tensor]]` into `list[str]`
8155+
experts = [k for d in self._experts for k in d.keys()]
8156+
if len(experts) > 0:
8157+
raise ValueError(f"Unprocessed experts: {experts}")
8158+
8159+
80638160
@ModelBase.register("GroveMoeForCausalLM", "modeling_grove_moe.GroveMoeForCausalLM")
80648161
class GroveMoeModel(TextModel):
80658162
model_arch = gguf.MODEL_ARCH.GROVEMOE

convert_hf_to_gguf_update.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ class TOKENIZER_TYPE(IntEnum):
139139
{"name": "lfm2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LiquidAI/LFM2-Tokenizer"},
140140
{"name": "exaone4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-32B", },
141141
{"name": "mellum", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/JetBrains/Mellum-4b-base", },
142-
{"name": "llada-moe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Base", },
142+
{"name": "bailingmoe2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/inclusionAI/Ling-mini-base-2.0", },
143143
{"name": "granite-docling", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/ibm-granite/granite-docling-258M", },
144144
]
145145

ggml/src/ggml-alloc.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,26 @@ static bool ggml_gallocr_is_allocated(ggml_gallocr_t galloc, struct ggml_tensor
598598
return t->data != NULL || ggml_gallocr_hash_get(galloc, t)->allocated;
599599
}
600600

601+
// free the extra space at the end if the new tensor is smaller
602+
static void ggml_gallocr_free_extra_space(ggml_gallocr_t galloc, struct ggml_tensor * node, struct ggml_tensor * parent) {
603+
struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
604+
struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
605+
606+
size_t parent_size = ggml_backend_buft_get_alloc_size(galloc->bufts[p_hn->buffer_id], parent);
607+
size_t node_size = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], node);
608+
609+
GGML_ASSERT(parent_size >= node_size);
610+
611+
if (parent_size > node_size) {
612+
struct ggml_dyn_tallocr * p_alloc = galloc->buf_tallocs[p_hn->buffer_id];
613+
struct buffer_address p_addr = p_hn->addr;
614+
p_addr.offset += node_size;
615+
size_t extra_size = parent_size - node_size;
616+
AT_PRINTF("freeing extra %zu bytes from parent %s for %s\n", extra_size, parent->name, node->name);
617+
ggml_dyn_tallocr_free_tensor(p_alloc, p_addr, extra_size, parent);
618+
}
619+
}
620+
601621
static void ggml_gallocr_allocate_node(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id) {
602622
GGML_ASSERT(buffer_id >= 0);
603623
struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
@@ -643,13 +663,15 @@ static void ggml_gallocr_allocate_node(ggml_gallocr_t galloc, struct ggml_tensor
643663
hn->addr = p_hn->addr;
644664
p_hn->allocated = false; // avoid freeing the parent
645665
view_src_hn->allocated = false;
666+
ggml_gallocr_free_extra_space(galloc, node, view_src);
646667
return;
647668
}
648669
} else {
649670
AT_PRINTF("reusing parent %s for %s\n", parent->name, node->name);
650671
hn->buffer_id = p_hn->buffer_id;
651672
hn->addr = p_hn->addr;
652673
p_hn->allocated = false; // avoid freeing the parent
674+
ggml_gallocr_free_extra_space(galloc, node, parent);
653675
return;
654676
}
655677
}

ggml/src/ggml-cuda/fattn-common.cuh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,7 @@ void launch_fattn(
895895
const dim3 block_dim(warp_size, nwarps, 1);
896896
int max_blocks_per_sm = 1; // Max. number of active blocks limited by occupancy.
897897
CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_blocks_per_sm, fattn_kernel, block_dim.x * block_dim.y * block_dim.z, nbytes_shared));
898+
GGML_ASSERT(max_blocks_per_sm > 0);
898899
int parallel_blocks = max_blocks_per_sm;
899900

900901
dim3 blocks_num;

ggml/src/ggml-cuda/ggml-cuda.cu

Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2831,18 +2831,15 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, int node_idx,
28312831
#endif
28322832

28332833
//TODO: remove special case once ggml_can_fuse can handle empty nodes
2834-
std::initializer_list<enum ggml_op> topk_moe_ops = ggml_cuda_topk_moe_ops(false);
2835-
std::initializer_list<enum ggml_op> topk_moe_ops_with_norm = ggml_cuda_topk_moe_ops(true);
2836-
2837-
if (ops.size() == topk_moe_ops_with_norm.size() && std::equal(ops.begin(), ops.end(), topk_moe_ops_with_norm.begin())) {
2838-
2839-
if (node_idx + topk_moe_ops_with_norm.size() > (size_t)cgraph->n_nodes) {
2840-
return false;
2841-
}
2842-
2843-
for (size_t i = 0; i < topk_moe_ops_with_norm.size(); i++) {
2844-
if (cgraph->nodes[node_idx + i]->op != topk_moe_ops_with_norm.begin()[i]) return false;
2845-
}
2834+
std::initializer_list<enum ggml_op> topk_moe_ops =
2835+
ggml_cuda_topk_moe_ops(/*with_norm*/ false, /*delayed_softmax=*/false);
2836+
std::initializer_list<enum ggml_op> topk_moe_ops_with_norm =
2837+
ggml_cuda_topk_moe_ops(/*with_norm=*/true, /*delayed_softmax=*/false);
2838+
std::initializer_list<enum ggml_op> topk_moe_ops_delayed_softmax =
2839+
ggml_cuda_topk_moe_ops(/*with_norm=*/false, /*delayed_softmax=*/true);
2840+
2841+
if (ops.size() == topk_moe_ops_with_norm.size() &&
2842+
ggml_can_fuse_subgraph(cgraph, node_idx, topk_moe_ops_with_norm, { node_idx + 3, node_idx + 8 })) {
28462843
ggml_tensor * softmax = cgraph->nodes[node_idx];
28472844
ggml_tensor * weights = cgraph->nodes[node_idx+8];
28482845

@@ -2851,18 +2848,20 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, int node_idx,
28512848
}
28522849
}
28532850

2854-
if (ops.size() == topk_moe_ops.size() && std::equal(ops.begin(), ops.end(), topk_moe_ops.begin())) {
2855-
2856-
if (node_idx + topk_moe_ops.size() > (size_t)cgraph->n_nodes) {
2857-
return false;
2851+
if (ops.size() == topk_moe_ops.size() &&
2852+
ggml_can_fuse_subgraph(cgraph, node_idx, topk_moe_ops, { node_idx + 3, node_idx + 4 })) {
2853+
ggml_tensor * softmax = cgraph->nodes[node_idx];
2854+
ggml_tensor * weights = cgraph->nodes[node_idx+4];
2855+
if (ggml_cuda_should_use_topk_moe(softmax, weights)) {
2856+
return true;
28582857
}
2858+
}
28592859

2860-
for (size_t i = 0; i < topk_moe_ops.size(); i++) {
2861-
if (cgraph->nodes[node_idx + i]->op != topk_moe_ops.begin()[i]) return false;
2862-
}
2860+
if (ops.size() == topk_moe_ops_delayed_softmax.size() &&
2861+
ggml_can_fuse_subgraph(cgraph, node_idx, topk_moe_ops_delayed_softmax, { node_idx + 2, node_idx + 5 })) {
2862+
ggml_tensor * softmax = cgraph->nodes[node_idx + 4];
2863+
ggml_tensor * weights = cgraph->nodes[node_idx + 5];
28632864

2864-
ggml_tensor * softmax = cgraph->nodes[node_idx];
2865-
ggml_tensor * weights = cgraph->nodes[node_idx+4];
28662865
if (ggml_cuda_should_use_topk_moe(softmax, weights)) {
28672866
return true;
28682867
}
@@ -2961,19 +2960,32 @@ static void evaluate_and_capture_cuda_graph(ggml_backend_cuda_context * cuda_ctx
29612960
if (ggml_cuda_can_fuse(cgraph, i, ggml_cuda_topk_moe_ops(/*with norm*/ true), {})) {
29622961
ggml_tensor * weights = cgraph->nodes[i+8];
29632962
ggml_tensor * selected_experts = cgraph->nodes[i+3];
2964-
ggml_cuda_op_topk_moe(*cuda_ctx, node, weights, selected_experts, /*with norm*/ true);
2963+
ggml_cuda_op_topk_moe(*cuda_ctx, node->src[0], weights, selected_experts, /*with norm*/ true,
2964+
/*delayed softmax*/ false);
29652965
i += 8;
29662966
continue;
29672967
}
29682968

29692969
if (ggml_cuda_can_fuse(cgraph, i, ggml_cuda_topk_moe_ops(/*with norm*/ false), {})) {
29702970
ggml_tensor * weights = cgraph->nodes[i+4];
29712971
ggml_tensor * selected_experts = cgraph->nodes[i+3];
2972-
ggml_cuda_op_topk_moe(*cuda_ctx, node, weights, selected_experts, /*with norm*/ false);
2972+
ggml_cuda_op_topk_moe(*cuda_ctx, node->src[0], weights, selected_experts, /*with norm*/ false,
2973+
/*delayed softmax*/ false);
29732974
i += 4;
29742975
continue;
29752976
}
29762977

2978+
if (ggml_cuda_can_fuse(cgraph, i,
2979+
ggml_cuda_topk_moe_ops(/*with norm*/ false, /*delayed softmax*/ true), {})) {
2980+
ggml_tensor * weights = cgraph->nodes[i + 5];
2981+
ggml_tensor * ids = cgraph->nodes[i + 1];
2982+
2983+
ggml_cuda_op_topk_moe(*cuda_ctx, node->src[0], weights, ids, /*with norm*/ false,
2984+
/*delayed_softmax*/ true);
2985+
i += 5;
2986+
continue;
2987+
}
2988+
29772989
if (node->op == GGML_OP_ADD) {
29782990
int n_fuse = 0;
29792991
ggml_op ops[8];

0 commit comments

Comments
 (0)