Skip to content

Commit b605bb9

Browse files
committed
Merge remote-tracking branch 'origin/compilade/mamba2' into mamba2-sync
* origin/compilade/mamba2: (28 commits) cuda : implement ssm scan for Mamba2 ggml-cpu : reorder SVE FMA for consistency with other SIMD arches ggml : fix mamba2 ssm scan when compiled with SVE graph : fix recurrent state copies when avoiding copies kv-cache : allow context shift for recurrent models convert : avoid AutoConfig for Mamba and Mamba2 hparams kv-cache : remove const_cast when setting inputs for s_copy metal : single-user mamba2 inference works metal : add missing args for nb references in ssm_scan_f32_group metal : fix confusion between ; and , convert : fix flake8 lint ggml : avoid multiply by D in GGML_OP_SSM_SCAN ggml : remove unused fast broadcast path in GGML_MUL metal : fix wrong number of tokens per sequence in SSM_SCAN metal : fix SSM_SCAN state head offset metal : add back n_seqs to SSM_SCAN args metal : remove unused arguments for SSM_SCAN metal : use log and exp instead of log1pf and expf in SSM_SCAN metal : fix SSM_SCAN pipeline scope metal : attempt to adapt SSM_SCAN for Mamba-2 ...
2 parents 06cbedf + 830e554 commit b605bb9

24 files changed

+1076
-313
lines changed

convert_hf_to_gguf.py

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4623,6 +4623,14 @@ def set_gguf_parameters(self):
46234623
class MambaModel(TextModel):
46244624
model_arch = gguf.MODEL_ARCH.MAMBA
46254625

4626+
def __init__(self, dir_model: Path, *args, **kwargs):
4627+
# Avoid using AutoConfig for hparams
4628+
hparams = kwargs.pop("hparams", None)
4629+
if hparams is None:
4630+
with open(dir_model / "config.json", "r", encoding="utf-8") as f:
4631+
hparams = json.load(f)
4632+
super().__init__(dir_model, *args, hparams=hparams, **kwargs)
4633+
46264634
def set_vocab(self):
46274635
vocab_size = self.hparams["vocab_size"]
46284636
# Round vocab size to next multiple of 8
@@ -4697,6 +4705,100 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter
46974705
return [(new_name, data_torch)]
46984706

46994707

4708+
@ModelBase.register("Mamba2ForCausalLM")
4709+
class Mamba2Model(TextModel):
4710+
model_arch = gguf.MODEL_ARCH.MAMBA2
4711+
4712+
def __init__(self, dir_model: Path, *args, **kwargs):
4713+
# Avoid using AutoConfig for hparams
4714+
# It wrongly assumes all Mamba2 models are Mamba-Codestral-7B-v0.1
4715+
hparams = kwargs.pop("hparams", None)
4716+
if hparams is None:
4717+
with open(dir_model / "config.json", "r", encoding="utf-8") as f:
4718+
hparams = json.load(f)
4719+
super().__init__(dir_model, *args, hparams=hparams, **kwargs)
4720+
4721+
def set_vocab(self):
4722+
vocab_size = self.hparams["vocab_size"]
4723+
# Round vocab size to next multiple of 16
4724+
pad_vocab = self.hparams.get("pad_vocab_size_multiple", 16)
4725+
# pad using ceiling division
4726+
# ref: https://stackoverflow.com/a/17511341/22827863
4727+
vocab_size = -(vocab_size // -pad_vocab) * pad_vocab
4728+
self.hparams["vocab_size"] = vocab_size
4729+
4730+
if (self.dir_model / "tokenizer.model").is_file():
4731+
self._set_vocab_sentencepiece()
4732+
elif (self.dir_model / "tokenizer.model.v3").is_file():
4733+
# mamba-codestral
4734+
raise NotImplementedError(f"Please rename {self.dir_model / 'tokenizer.model.v3'} to {self.dir_model / 'tokenizer.model'}")
4735+
elif (self.dir_model / "tokenizer.json").is_file():
4736+
self._set_vocab_gpt2()
4737+
else:
4738+
# Use the GPT-NeoX tokenizer when no tokenizer files are present
4739+
self._set_vocab_builtin("gpt-neox", vocab_size)
4740+
4741+
def set_gguf_parameters(self):
4742+
d_model = self.find_hparam(["hidden_size", "d_model", "dim"])
4743+
d_conv = self.find_hparam(["conv_kernel", "d_conv"], optional=True) or 4
4744+
d_inner = self.find_hparam(["intermediate_size", "d_inner"], optional=True) or 2 * d_model
4745+
d_state = self.find_hparam(["state_size", "d_state"], optional=True) or 128
4746+
head_dim = self.find_hparam(["head_dim"], optional=True) or 64
4747+
n_group = self.find_hparam(["n_groups"], optional=True) or 1
4748+
4749+
rms_norm_eps = self.find_hparam(["layer_norm_epsilon", "rms_norm_eps"], optional=True) or 1e-5
4750+
4751+
# Fail early for models which don't have a block expansion factor of 2
4752+
# TODO: does this really matter?
4753+
assert d_inner == 2 * d_model
4754+
assert d_inner % head_dim == 0
4755+
4756+
self.gguf_writer.add_context_length(2**20) # arbitrary value; for those who use the default
4757+
self.gguf_writer.add_embedding_length(d_model)
4758+
self.gguf_writer.add_feed_forward_length(0) # unused, but seemingly required when loading
4759+
self.gguf_writer.add_head_count(0) # unused, but seemingly required when loading
4760+
self.gguf_writer.add_block_count(self.block_count)
4761+
self.gguf_writer.add_ssm_conv_kernel(d_conv)
4762+
self.gguf_writer.add_ssm_inner_size(d_inner)
4763+
self.gguf_writer.add_ssm_state_size(d_state)
4764+
self.gguf_writer.add_ssm_time_step_rank(d_inner // head_dim)
4765+
self.gguf_writer.add_ssm_group_count(n_group)
4766+
self.gguf_writer.add_layer_norm_rms_eps(rms_norm_eps)
4767+
self.gguf_writer.add_file_type(self.ftype)
4768+
4769+
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
4770+
4771+
if name.startswith("model.backbone") or name.startswith("model.lm_head"):
4772+
# map Mamba-Codestral-7B-v0.1 tensor names to the names used by Mamba-2
4773+
name = name.removeprefix("model.")
4774+
4775+
if name.endswith(".dt_bias"):
4776+
name = name.rpartition(".dt_bias")[0] + ".dt_proj.bias"
4777+
4778+
new_name = self.map_tensor_name(name)
4779+
4780+
if self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.SSM_CONV1D, bid):
4781+
data_torch = data_torch.squeeze()
4782+
elif any(self.match_model_tensor_name(new_name, t, bid, suffix="") for t in [
4783+
gguf.MODEL_TENSOR.SSM_A,
4784+
gguf.MODEL_TENSOR.SSM_D,
4785+
]):
4786+
# unsqueeze A to use similar shape semantics as Mamba-1
4787+
# (D is also unsqueezed, but for more straightforward broadcast internally)
4788+
data_torch = data_torch.reshape((*data_torch.shape, 1))
4789+
elif self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.SSM_NORM, bid):
4790+
d_model = self.find_hparam(["hidden_size", "d_model", "dim"])
4791+
d_inner = self.find_hparam(["intermediate_size", "d_inner"], optional=True) or 2 * d_model
4792+
n_group = self.hparams.get("n_groups", 1)
4793+
data_torch = data_torch.reshape((n_group, d_inner // n_group))
4794+
4795+
if name.endswith(".A_log"):
4796+
logger.debug("A_log --> A ==> " + new_name)
4797+
data_torch = -torch.exp(data_torch)
4798+
4799+
yield (new_name, data_torch)
4800+
4801+
47004802
@ModelBase.register("CohereForCausalLM")
47014803
class CommandR2Model(TextModel):
47024804
model_arch = gguf.MODEL_ARCH.COMMAND_R
@@ -6457,12 +6559,20 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st
64576559
# maybe we should fallback to text model's arch in that case, since not many models have both
64586560
text_config = hparams.get("text_config", {})
64596561
vision_config = hparams.get("vision_config", {})
6460-
arch = hparams["architectures"][0]
6562+
arch = None
6563+
if (arches := hparams.get("architectures")) is not None and len(arches) > 0:
6564+
arch = arches[0]
6565+
elif "ssm_cfg" in hparams:
6566+
# For non-hf Mamba and Mamba2 models
6567+
arch = hparams["ssm_cfg"].get("layer", "Mamba") + "ForCausalLM"
6568+
64616569
# if "architectures" is found in the sub-config, use that instead
64626570
if model_type == ModelType.TEXT and text_config.get("architectures") is not None:
64636571
arch = text_config["architectures"][0]
64646572
elif model_type == ModelType.MMPROJ and vision_config.get("architectures") is not None:
64656573
arch = vision_config["architectures"][0]
6574+
if arch is None:
6575+
raise ValueError("Failed to detect model architecture")
64666576
return arch
64676577

64686578

ggml/include/ggml.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1890,7 +1890,8 @@ extern "C" {
18901890
struct ggml_tensor * dt,
18911891
struct ggml_tensor * A,
18921892
struct ggml_tensor * B,
1893-
struct ggml_tensor * C);
1893+
struct ggml_tensor * C,
1894+
struct ggml_tensor * ids);
18941895

18951896
// partition into non-overlapping windows with padding if needed
18961897
// example:

0 commit comments

Comments
 (0)