Skip to content

Commit 59928ec

Browse files
committed
Merge remote-tracking branch 'origin/compilade/mamba2' into GraniteFour
* origin/compilade/mamba2: (22 commits) 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 llama : fix Mamba-2 conv state saving llama : support running Mamba-Codestral-7B-v0.1 ...
2 parents 074e42a + 929fe85 commit 59928ec

22 files changed

+834
-322
lines changed

convert_hf_to_gguf.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4279,6 +4279,91 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter
42794279
return [(new_name, data_torch)]
42804280

42814281

4282+
@ModelBase.register("Mamba2ForCausalLM")
4283+
class Mamba2Model(TextModel):
4284+
model_arch = gguf.MODEL_ARCH.MAMBA2
4285+
4286+
def set_vocab(self):
4287+
vocab_size = self.hparams["vocab_size"]
4288+
# Round vocab size to next multiple of 16
4289+
pad_vocab = self.hparams.get("pad_vocab_size_multiple", 16)
4290+
# pad using ceiling division
4291+
# ref: https://stackoverflow.com/a/17511341/22827863
4292+
vocab_size = -(vocab_size // -pad_vocab) * pad_vocab
4293+
self.hparams["vocab_size"] = vocab_size
4294+
4295+
if (self.dir_model / "tokenizer.model").is_file():
4296+
self._set_vocab_sentencepiece()
4297+
elif (self.dir_model / "tokenizer.model.v3").is_file():
4298+
# mamba-codestral
4299+
raise NotImplementedError(f"Please rename {self.dir_model / 'tokenizer.model.v3'} to {self.dir_model / 'tokenizer.model'}")
4300+
elif (self.dir_model / "tokenizer.json").is_file():
4301+
self._set_vocab_gpt2()
4302+
else:
4303+
# Use the GPT-NeoX tokenizer when no tokenizer files are present
4304+
self._set_vocab_builtin("gpt-neox", vocab_size)
4305+
4306+
def set_gguf_parameters(self):
4307+
d_model = self.find_hparam(["hidden_size", "d_model", "dim"])
4308+
d_conv = self.find_hparam(["conv_kernel", "d_conv"], optional=True) or 4
4309+
d_inner = self.find_hparam(["intermediate_size", "d_inner"], optional=True) or 2 * d_model
4310+
d_state = self.find_hparam(["state_size", "d_state"], optional=True) or 128
4311+
head_dim = self.find_hparam(["head_dim"], optional=True) or 64
4312+
n_group = self.find_hparam(["n_groups"], optional=True) or 1
4313+
4314+
rms_norm_eps = self.find_hparam(["layer_norm_epsilon", "rms_norm_eps"], optional=True) or 1e-5
4315+
4316+
# Fail early for models which don't have a block expansion factor of 2
4317+
# TODO: does this really matter?
4318+
assert d_inner == 2 * d_model
4319+
assert d_inner % head_dim == 0
4320+
4321+
self.gguf_writer.add_context_length(2**20) # arbitrary value; for those who use the default
4322+
self.gguf_writer.add_embedding_length(d_model)
4323+
self.gguf_writer.add_feed_forward_length(0) # unused, but seemingly required when loading
4324+
self.gguf_writer.add_head_count(0) # unused, but seemingly required when loading
4325+
self.gguf_writer.add_block_count(self.block_count)
4326+
self.gguf_writer.add_ssm_conv_kernel(d_conv)
4327+
self.gguf_writer.add_ssm_inner_size(d_inner)
4328+
self.gguf_writer.add_ssm_state_size(d_state)
4329+
self.gguf_writer.add_ssm_time_step_rank(d_inner // head_dim)
4330+
self.gguf_writer.add_ssm_group_count(n_group)
4331+
self.gguf_writer.add_layer_norm_rms_eps(rms_norm_eps)
4332+
self.gguf_writer.add_file_type(self.ftype)
4333+
4334+
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
4335+
4336+
if name.startswith("model.backbone") or name.startswith("model.lm_head"):
4337+
# map Mamba-Codestral-7B-v0.1 tensor names to the names used by Mamba-2
4338+
name = name.removeprefix("model.")
4339+
4340+
if name.endswith(".dt_bias"):
4341+
name = name.rpartition(".dt_bias")[0] + ".dt_proj.bias"
4342+
4343+
new_name = self.map_tensor_name(name)
4344+
4345+
if self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.SSM_CONV1D, bid):
4346+
data_torch = data_torch.squeeze()
4347+
elif any(self.match_model_tensor_name(new_name, t, bid, suffix="") for t in [
4348+
gguf.MODEL_TENSOR.SSM_A,
4349+
gguf.MODEL_TENSOR.SSM_D,
4350+
]):
4351+
# unsqueeze A to use similar shape semantics as Mamba-1
4352+
# (D is also unsqueezed, but for more straightforward broadcast internally)
4353+
data_torch = data_torch.reshape((*data_torch.shape, 1))
4354+
elif self.match_model_tensor_name(new_name, gguf.MODEL_TENSOR.SSM_NORM, bid):
4355+
d_model = self.find_hparam(["hidden_size", "d_model", "dim"])
4356+
d_inner = self.find_hparam(["intermediate_size", "d_inner"], optional=True) or 2 * d_model
4357+
n_group = self.hparams.get("n_groups", 1)
4358+
data_torch = data_torch.reshape((n_group, d_inner // n_group))
4359+
4360+
if name.endswith(".A_log"):
4361+
logger.debug("A_log --> A ==> " + new_name)
4362+
data_torch = -torch.exp(data_torch)
4363+
4364+
yield (new_name, data_torch)
4365+
4366+
42824367
@ModelBase.register("CohereForCausalLM")
42834368
class CommandR2Model(TextModel):
42844369
model_arch = gguf.MODEL_ARCH.COMMAND_R

ggml/include/ggml.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1854,7 +1854,8 @@ extern "C" {
18541854
struct ggml_tensor * dt,
18551855
struct ggml_tensor * A,
18561856
struct ggml_tensor * B,
1857-
struct ggml_tensor * C);
1857+
struct ggml_tensor * C,
1858+
struct ggml_tensor * ids);
18581859

18591860
// partition into non-overlapping windows with padding if needed
18601861
// example:

ggml/src/ggml-cpu/ops.cpp

Lines changed: 128 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -7506,74 +7506,151 @@ void ggml_compute_forward_ssm_conv(
75067506
static void ggml_compute_forward_ssm_scan_f32(
75077507
const ggml_compute_params * params,
75087508
ggml_tensor * dst) {
7509-
const ggml_tensor * src0 = dst->src[0]; // s
7510-
const ggml_tensor * src1 = dst->src[1]; // x
7511-
const ggml_tensor * src2 = dst->src[2]; // dt
7512-
const ggml_tensor * src3 = dst->src[3]; // A
7513-
const ggml_tensor * src4 = dst->src[4]; // B
7514-
const ggml_tensor * src5 = dst->src[5]; // C
7509+
const ggml_tensor * src0 = dst->src[0]; // s {d_state, dim, n_head, n_seqs+}
7510+
const ggml_tensor * src1 = dst->src[1]; // x {dim, n_head, n_seq_tokens, n_seqs}
7511+
const ggml_tensor * src2 = dst->src[2]; // dt {n_head, n_seq_tokens, n_seqs}
7512+
const ggml_tensor * src3 = dst->src[3]; // A {d_state, n_head} or {1, n_head}
7513+
const ggml_tensor * src4 = dst->src[4]; // B {d_state, n_group, n_seq_tokens, n_seqs}
7514+
const ggml_tensor * src5 = dst->src[5]; // C {d_state, n_group, n_seq_tokens, n_seqs}
7515+
const ggml_tensor * src6 = dst->src[6]; // ids {n_seqs}
75157516

75167517
const int ith = params->ith;
75177518
const int nth = params->nth;
75187519

7519-
const int64_t nc = src0->ne[0]; // d_state
7520-
const int64_t nr = src0->ne[1]; // d_inner
7521-
const int64_t n_t = src1->ne[1]; // number of tokens per sequence
7522-
const int64_t n_s = src0->ne[2]; // number of sequences in the batch
7520+
const int64_t nc = src0->ne[0]; // d_state
7521+
const int64_t nr = src0->ne[1]; // dim
7522+
const int64_t nh = src1->ne[1]; // n_head
7523+
const int64_t ng = src4->ne[1];
7524+
const int64_t nt = src1->ne[2]; // number of tokens per sequence
7525+
const int64_t ns = src1->ne[3]; // number of sequences in the batch
75237526

7524-
GGML_ASSERT(ggml_nelements(src1) + ggml_nelements(src0) == ggml_nelements(dst));
7527+
// can't use ggml_nbytes because src1 is not necessarily contiguous
7528+
const int64_t s_off = ggml_nelements(src1) * ggml_element_size(src1);
7529+
7530+
GGML_ASSERT(ggml_nelements(src1) + nc*nr*nh*ns == ggml_nelements(dst));
75257531
GGML_ASSERT(src0->nb[0] == sizeof(float));
75267532
GGML_ASSERT(src1->nb[0] == sizeof(float));
75277533
GGML_ASSERT(src2->nb[0] == sizeof(float));
75287534
GGML_ASSERT(src3->nb[0] == sizeof(float));
75297535
GGML_ASSERT(src4->nb[0] == sizeof(float));
75307536
GGML_ASSERT(src5->nb[0] == sizeof(float));
7531-
// required for the dot product between s and C
7532-
GGML_ASSERT(src0->nb[1] == src0->ne[0]*sizeof(float));
7533-
// required for per-sequence offsets for states
7534-
GGML_ASSERT(src0->nb[2] == src0->ne[0]*src0->ne[1]*sizeof(float));
7535-
// required to get correct offset for state destination (i.e. src1->nb[3])
7536-
GGML_ASSERT(src1->nb[3] == src1->ne[0]*src1->ne[1]*src1->ne[2]*sizeof(float));
7537+
GGML_ASSERT(src6->nb[0] == sizeof(int32_t));
7538+
// allows optimizing the modulo since n_group should be a power of 2
7539+
GGML_ASSERT((ng & -ng) == ng);
7540+
7541+
// heads per thread
7542+
const int dh = (nh + nth - 1)/nth;
7543+
7544+
// head range for this thread
7545+
const int ih0 = dh*ith;
7546+
const int ih1 = MIN(ih0 + dh, nh);
7547+
7548+
const int32_t * ids = (const int32_t *) src6->data;
7549+
7550+
for (int i3 = 0; i3 < ns; ++i3) {
7551+
const float * s0 = (const float *) ((const char *) src0->data + ids[i3]*(src0->nb[3])); // {d_state, dim, nh, ns}
7552+
float * s = ( float *) (( char *) dst->data + i3*(src0->nb[3]) + s_off); // {d_state, dim, nh, ns}
7553+
7554+
for (int i2 = 0; i2 < nt; ++i2) {
7555+
const float * x = (const float *) ((const char *) src1->data + i2*(src1->nb[2]) + i3*(src1->nb[3])); // {dim, nh, nt, ns}
7556+
const float * dt = (const float *) ((const char *) src2->data + i2*(src2->nb[1]) + i3*(src2->nb[2])); // {nh, nt, ns}
7557+
const float * A = (const float *) ((const char *) src3->data); // {d_state, nh} or {1, nh}
7558+
const float * B = (const float *) ((const char *) src4->data + i2*(src4->nb[2]) + i3*(src4->nb[3])); // {d_state, ng, nt, ns}
7559+
const float * C = (const float *) ((const char *) src5->data + i2*(src5->nb[2]) + i3*(src5->nb[3])); // {d_state, ng, nt, ns}
7560+
float * y = ( float *) (( char *) dst->data + i2*(nh*nr*sizeof(float)) + i3*(nt*nh*nr*sizeof(float))); // {dim, nh, nt, ns}
7561+
7562+
if (src3->ne[0] == 1) {
7563+
// Mamba-2 has a scalar decay factor per head; dA can be outside the state-wise loop
7564+
7565+
// n_head
7566+
for (int h = ih0; h < ih1; ++h) {
7567+
// ref: https://github.com/state-spaces/mamba/blob/62db608da60f6fc790b8ed9f4b3225e95ca15fde/mamba_ssm/ops/triton/softplus.py#L16
7568+
const float dt_soft_plus = dt[h] <= 20.0f ? log1pf(expf(dt[h])) : dt[h];
7569+
const float dA = expf(dt_soft_plus * A[h]);
7570+
7571+
// dim
7572+
for (int i1 = 0; i1 < nr; ++i1) {
7573+
const int ii = i1 + h*nr;
7574+
const float x_dt = x[ii] * dt_soft_plus;
7575+
float sumf = 0.0f;
7576+
#if defined(GGML_SIMD)
7577+
const int np = (nc & ~(GGML_F32_STEP - 1));
75377578

7538-
// rows per thread
7539-
const int dr = (nr + nth - 1)/nth;
7579+
GGML_F32_VEC sum[GGML_F32_ARR] = { GGML_F32_VEC_ZERO };
75407580

7541-
// row range for this thread
7542-
const int ir0 = dr*ith;
7543-
const int ir1 = MIN(ir0 + dr, nr);
7544-
const int ir = ir1 - ir0;
7581+
GGML_F32_VEC adA = GGML_F32_VEC_SET1(dA);
7582+
GGML_F32_VEC axdt = GGML_F32_VEC_SET1(x_dt);
75457583

7546-
for (int i3 = 0; i3 < n_s; ++i3) {
7547-
for (int i2 = 0; i2 < n_t; ++i2) {
7548-
const float * s0 = (const float *) ((const char *) src0->data + ir0*(src0->nb[1]) + i3*(src0->nb[2])); // {d_state, d_inner, n_s}
7549-
const float * x = (const float *) ((const char *) src1->data + ir0*(src1->nb[0]) + i2*(src1->nb[1]) + i3*(src1->nb[2])); // {d_inner, n_t, n_s}
7550-
const float * dt = (const float *) ((const char *) src2->data + ir0*(src2->nb[0]) + i2*(src2->nb[1]) + i3*(src2->nb[2])); // {d_inner, n_t, n_s}
7551-
const float * A = (const float *) ((const char *) src3->data + ir0*(src3->nb[1])); // {d_state, d_inner}
7552-
const float * B = (const float *) ((const char *) src4->data + i2*(src4->nb[1]) + i3*(src4->nb[2])); // {d_state, n_t, n_s}
7553-
const float * C = (const float *) ((const char *) src5->data + i2*(src5->nb[1]) + i3*(src5->nb[2])); // {d_state, n_t, n_s}
7554-
float * y = ( float *) (( char *) dst->data + ir0*(src1->nb[0]) + i2*(src1->nb[1]) + i3*(src1->nb[2])); // {d_inner, n_t, n_s}
7555-
float * s = ( float *) (( char *) dst->data + ir0*(src0->nb[1]) + i3*(src0->nb[2]) + src1->nb[3]); // {d_state, d_inner, n_s}
7556-
7557-
// use the output as the source for the next token-wise iterations
7558-
if (i2 > 0) { s0 = s; }
7584+
GGML_F32_VEC ax[GGML_F32_ARR];
7585+
GGML_F32_VEC ay[GGML_F32_ARR];
7586+
GGML_F32_VEC az[GGML_F32_ARR];
75597587

7560-
// d_inner
7561-
for (int i1 = 0; i1 < ir; ++i1) {
7562-
// ref: https://github.com/state-spaces/mamba/blob/34076d664838588a3c97727b263478ab9f621a07/mamba_ssm/ops/triton/selective_state_update.py#L78
7563-
float dt_soft_plus = dt[i1] <= 20.0f ? log1pf(expf(dt[i1])) : dt[i1];
7564-
float x_dt = x[i1] * dt_soft_plus;
7565-
float sumf = 0.0f;
7566-
// d_state
7567-
for (int i0 = 0; i0 < nc; ++i0) {
7568-
int i = i0 + i1*nc;
7569-
// state = prev_state * dA + dB * x
7570-
float state = (s0[i] * expf(dt_soft_plus * A[i])) + (B[i0] * x_dt);
7571-
// y = rowwise_dotprod(state, C)
7572-
sumf += state * C[i0];
7573-
s[i] = state;
7588+
for (int i = 0; i < np; i += GGML_F32_STEP) {
7589+
for (int j = 0; j < GGML_F32_ARR; j++) {
7590+
ax[j] = GGML_F32_VEC_LOAD(s0 + i + j*GGML_F32_EPR + ii*nc);
7591+
ay[j] = GGML_F32_VEC_LOAD(B + i + j*GGML_F32_EPR + (h & (ng - 1))*nc);
7592+
az[j] = GGML_F32_VEC_LOAD(C + i + j*GGML_F32_EPR + (h & (ng - 1))*nc);
7593+
7594+
ax[j] = GGML_F32_VEC_MUL(ax[j], adA);
7595+
ay[j] = GGML_F32_VEC_MUL(ay[j], axdt);
7596+
7597+
ax[j] = GGML_F32_VEC_ADD(ax[j], ay[j]);
7598+
7599+
sum[j] = GGML_F32_VEC_FMA(sum[j], ax[j], az[j]);
7600+
7601+
GGML_F32_VEC_STORE(s + i + j*GGML_F32_EPR + ii*nc, ax[j]);
7602+
}
7603+
}
7604+
7605+
// reduce sum0..sum3 to sum0
7606+
GGML_F32_VEC_REDUCE(sumf, sum);
7607+
#else
7608+
const int np = 0;
7609+
#endif
7610+
// d_state
7611+
for (int i0 = np; i0 < nc; ++i0) {
7612+
const int i = i0 + ii*nc;
7613+
const int ig = i0 + (h & (ng - 1))*nc;
7614+
// state = prev_state * dA + dB * x
7615+
const float state = (s0[i] * dA) + (B[ig] * x_dt);
7616+
// y = rowwise_dotprod(state, C)
7617+
sumf += state * C[ig];
7618+
s[i] = state;
7619+
}
7620+
y[ii] = sumf;
7621+
}
7622+
}
7623+
} else {
7624+
// Mamba-1 has an element-wise decay factor for the states
7625+
7626+
// n_head
7627+
for (int h = ih0; h < ih1; ++h) {
7628+
// ref: https://github.com/state-spaces/mamba/blob/62db608da60f6fc790b8ed9f4b3225e95ca15fde/mamba_ssm/ops/triton/softplus.py#L16
7629+
const float dt_soft_plus = dt[h] <= 20.0f ? log1pf(expf(dt[h])) : dt[h];
7630+
7631+
// dim
7632+
for (int i1 = 0; i1 < nr; ++i1) {
7633+
const int ii = i1 + h*nr;
7634+
const float x_dt = x[ii] * dt_soft_plus;
7635+
float sumf = 0.0f;
7636+
// NOTE: can't really use GGML_SIMD here because d_state is usually 16
7637+
// and also because expf is used within the loop.
7638+
// d_state
7639+
for (int i0 = 0; i0 < nc; ++i0) {
7640+
const int i = i0 + ii*nc;
7641+
const int ig = i0 + (h & (ng - 1))*nc;
7642+
// state = prev_state * dA + dB * x
7643+
const float state = (s0[i] * expf(dt_soft_plus * A[i0 + h*nc])) + (B[ig] * x_dt);
7644+
// y = rowwise_dotprod(state, C)
7645+
sumf += state * C[ig];
7646+
s[i] = state;
7647+
}
7648+
y[ii] = sumf;
7649+
}
75747650
}
7575-
y[i1] = sumf;
75767651
}
7652+
// use the output as the source when it's not the first token-wise iteration
7653+
s0 = s;
75777654
}
75787655
}
75797656
}

ggml/src/ggml-metal/ggml-metal-impl.h

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -463,26 +463,25 @@ typedef struct {
463463
typedef struct {
464464
int64_t d_state;
465465
int64_t d_inner;
466+
int64_t n_head;
467+
int64_t n_group;
466468
int64_t n_seq_tokens;
467469
int64_t n_seqs;
468-
uint64_t nb00;
469470
uint64_t nb01;
470471
uint64_t nb02;
471-
uint64_t nb10;
472+
uint64_t nb03;
472473
uint64_t nb11;
473474
uint64_t nb12;
474475
uint64_t nb13;
475-
uint64_t nb20;
476476
uint64_t nb21;
477477
uint64_t nb22;
478-
uint64_t nb30;
479478
uint64_t nb31;
480-
uint64_t nb40;
481479
uint64_t nb41;
482480
uint64_t nb42;
483-
uint64_t nb50;
481+
uint64_t nb43;
484482
uint64_t nb51;
485483
uint64_t nb52;
484+
uint64_t nb53;
486485
} ggml_metal_kargs_ssm_scan;
487486

488487
typedef struct {

0 commit comments

Comments
 (0)