Skip to content

Commit d12d4a4

Browse files
committed
Merge branch 'compilade/mamba2' into GraniteFour
* compilade/mamba2: (24 commits) 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 llama : avoid redundant state copy for Mamba 1 and 2 convert_hf : prefer SentencePiece tokenizer for Mamba-2 when present llama : add missing break llama : remove unused variable ...
2 parents 0893b4c + e94f393 commit d12d4a4

22 files changed

+851
-294
lines changed

convert_hf_to_gguf.py

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

4595+
def __init__(self, dir_model: Path, *args, **kwargs):
4596+
# Avoid using AutoConfig for hparams
4597+
hparams = kwargs.pop("hparams", None)
4598+
if hparams is None:
4599+
with open(dir_model / "config.json", "r", encoding="utf-8") as f:
4600+
hparams = json.load(f)
4601+
super().__init__(dir_model, *args, hparams=hparams, **kwargs)
4602+
45954603
def set_vocab(self):
45964604
vocab_size = self.hparams["vocab_size"]
45974605
# Round vocab size to next multiple of 8
@@ -4666,6 +4674,100 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter
46664674
return [(new_name, data_torch)]
46674675

46684676

4677+
@ModelBase.register("Mamba2ForCausalLM")
4678+
class Mamba2Model(TextModel):
4679+
model_arch = gguf.MODEL_ARCH.MAMBA2
4680+
4681+
def __init__(self, dir_model: Path, *args, **kwargs):
4682+
# Avoid using AutoConfig for hparams
4683+
# It wrongly assumes all Mamba2 models are Mamba-Codestral-7B-v0.1
4684+
hparams = kwargs.pop("hparams", None)
4685+
if hparams is None:
4686+
with open(dir_model / "config.json", "r", encoding="utf-8") as f:
4687+
hparams = json.load(f)
4688+
super().__init__(dir_model, *args, hparams=hparams, **kwargs)
4689+
4690+
def set_vocab(self):
4691+
vocab_size = self.hparams["vocab_size"]
4692+
# Round vocab size to next multiple of 16
4693+
pad_vocab = self.hparams.get("pad_vocab_size_multiple", 16)
4694+
# pad using ceiling division
4695+
# ref: https://stackoverflow.com/a/17511341/22827863
4696+
vocab_size = -(vocab_size // -pad_vocab) * pad_vocab
4697+
self.hparams["vocab_size"] = vocab_size
4698+
4699+
if (self.dir_model / "tokenizer.model").is_file():
4700+
self._set_vocab_sentencepiece()
4701+
elif (self.dir_model / "tokenizer.model.v3").is_file():
4702+
# mamba-codestral
4703+
raise NotImplementedError(f"Please rename {self.dir_model / 'tokenizer.model.v3'} to {self.dir_model / 'tokenizer.model'}")
4704+
elif (self.dir_model / "tokenizer.json").is_file():
4705+
self._set_vocab_gpt2()
4706+
else:
4707+
# Use the GPT-NeoX tokenizer when no tokenizer files are present
4708+
self._set_vocab_builtin("gpt-neox", vocab_size)
4709+
4710+
def set_gguf_parameters(self):
4711+
d_model = self.find_hparam(["hidden_size", "d_model", "dim"])
4712+
d_conv = self.find_hparam(["conv_kernel", "d_conv"], optional=True) or 4
4713+
d_inner = self.find_hparam(["intermediate_size", "d_inner"], optional=True) or 2 * d_model
4714+
d_state = self.find_hparam(["state_size", "d_state"], optional=True) or 128
4715+
head_dim = self.find_hparam(["head_dim"], optional=True) or 64
4716+
n_group = self.find_hparam(["n_groups"], optional=True) or 1
4717+
4718+
rms_norm_eps = self.find_hparam(["layer_norm_epsilon", "rms_norm_eps"], optional=True) or 1e-5
4719+
4720+
# Fail early for models which don't have a block expansion factor of 2
4721+
# TODO: does this really matter?
4722+
assert d_inner == 2 * d_model
4723+
assert d_inner % head_dim == 0
4724+
4725+
self.gguf_writer.add_context_length(2**20) # arbitrary value; for those who use the default
4726+
self.gguf_writer.add_embedding_length(d_model)
4727+
self.gguf_writer.add_feed_forward_length(0) # unused, but seemingly required when loading
4728+
self.gguf_writer.add_head_count(0) # unused, but seemingly required when loading
4729+
self.gguf_writer.add_block_count(self.block_count)
4730+
self.gguf_writer.add_ssm_conv_kernel(d_conv)
4731+
self.gguf_writer.add_ssm_inner_size(d_inner)
4732+
self.gguf_writer.add_ssm_state_size(d_state)
4733+
self.gguf_writer.add_ssm_time_step_rank(d_inner // head_dim)
4734+
self.gguf_writer.add_ssm_group_count(n_group)
4735+
self.gguf_writer.add_layer_norm_rms_eps(rms_norm_eps)
4736+
self.gguf_writer.add_file_type(self.ftype)
4737+
4738+
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
4739+
4740+
if name.startswith("model.backbone") or name.startswith("model.lm_head"):
4741+
# map Mamba-Codestral-7B-v0.1 tensor names to the names used by Mamba-2
4742+
name = name.removeprefix("model.")
4743+
4744+
if name.endswith(".dt_bias"):
4745+
name = name.rpartition(".dt_bias")[0] + ".dt_proj.bias"
4746+
4747+
new_name = self.map_tensor_name(name)
4748+
4749+
if self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.SSM_CONV1D, bid):
4750+
data_torch = data_torch.squeeze()
4751+
elif any(self.match_model_tensor_name(new_name, t, bid, suffix="") for t in [
4752+
gguf.MODEL_TENSOR.SSM_A,
4753+
gguf.MODEL_TENSOR.SSM_D,
4754+
]):
4755+
# unsqueeze A to use similar shape semantics as Mamba-1
4756+
# (D is also unsqueezed, but for more straightforward broadcast internally)
4757+
data_torch = data_torch.reshape((*data_torch.shape, 1))
4758+
elif self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.SSM_NORM, bid):
4759+
d_model = self.find_hparam(["hidden_size", "d_model", "dim"])
4760+
d_inner = self.find_hparam(["intermediate_size", "d_inner"], optional=True) or 2 * d_model
4761+
n_group = self.hparams.get("n_groups", 1)
4762+
data_torch = data_torch.reshape((n_group, d_inner // n_group))
4763+
4764+
if name.endswith(".A_log"):
4765+
logger.debug("A_log --> A ==> " + new_name)
4766+
data_torch = -torch.exp(data_torch)
4767+
4768+
yield (new_name, data_torch)
4769+
4770+
46694771
@ModelBase.register("CohereForCausalLM")
46704772
class CommandR2Model(TextModel):
46714773
model_arch = gguf.MODEL_ARCH.COMMAND_R
@@ -6432,12 +6534,20 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st
64326534
# maybe we should fallback to text model's arch in that case, since not many models have both
64336535
text_config = hparams.get("text_config", {})
64346536
vision_config = hparams.get("vision_config", {})
6435-
arch = hparams["architectures"][0]
6537+
arch = None
6538+
if (arches := hparams.get("architectures")) is not None and len(arches) > 0:
6539+
arch = arches[0]
6540+
elif "ssm_cfg" in hparams:
6541+
# For non-hf Mamba and Mamba2 models
6542+
arch = hparams["ssm_cfg"].get("layer", "Mamba") + "ForCausalLM"
6543+
64366544
# if "architectures" is found in the sub-config, use that instead
64376545
if model_type == ModelType.TEXT and text_config.get("architectures") is not None:
64386546
arch = text_config["architectures"][0]
64396547
elif model_type == ModelType.MMPROJ and vision_config.get("architectures") is not None:
64406548
arch = vision_config["architectures"][0]
6549+
if arch is None:
6550+
raise ValueError("Failed to detect model architecture")
64416551
return arch
64426552

64436553

ggml/include/ggml.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1878,7 +1878,8 @@ extern "C" {
18781878
struct ggml_tensor * dt,
18791879
struct ggml_tensor * A,
18801880
struct ggml_tensor * B,
1881-
struct ggml_tensor * C);
1881+
struct ggml_tensor * C,
1882+
struct ggml_tensor * ids);
18821883

18831884
// partition into non-overlapping windows with padding if needed
18841885
// example:

0 commit comments

Comments
 (0)