Skip to content

Commit 8936784

Browse files
authored
mtmd : add **vision** support for Mistral Small 3.1 (#13231)
* convert ok * load ok, missing patch merger * ah sheet it works * update llava/readme * add test * fix test
1 parent 13c9a33 commit 8936784

File tree

9 files changed

+112
-15
lines changed

9 files changed

+112
-15
lines changed

convert_hf_to_gguf.py

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1899,7 +1899,10 @@ def prepare_tensors(self):
18991899
raise ValueError(f"Unprocessed experts: {experts}")
19001900

19011901

1902-
@ModelBase.register("LlavaForConditionalGeneration")
1902+
@ModelBase.register(
1903+
"LlavaForConditionalGeneration", # pixtral
1904+
"Mistral3ForConditionalGeneration", # mistral small 3.1
1905+
)
19031906
class LlavaVisionModel(VisionModel):
19041907
img_break_tok_id = -1
19051908

@@ -1908,17 +1911,38 @@ def __init__(self, *args, **kwargs):
19081911
if self.hparams["model_type"] == "pixtral":
19091912
# layer_norm_eps is not in config.json, it is hard-coded in modeling_pixtral.py
19101913
self.hparams["layer_norm_eps"] = self.hparams.get("layer_norm_eps", 1e-5)
1911-
self.img_break_tok_id = 12 # see tokenizer_config.json
1914+
self.img_break_tok_id = self.get_token_id("[IMG_BREAK]")
1915+
logger.info(f"Image break token id: {self.img_break_tok_id}")
19121916
else:
19131917
raise ValueError(f"Unsupported model type: {self.hparams['model_type']}")
19141918

1919+
def get_token_id(self, token: str) -> int:
1920+
tokenizer_config_file = self.dir_model / 'tokenizer_config.json'
1921+
with open(tokenizer_config_file, "r", encoding="utf-8") as f:
1922+
added_tokens_decoder = json.load(f)['added_tokens_decoder']
1923+
for id_, token_data in added_tokens_decoder.items():
1924+
if token_data["content"] == token:
1925+
return int(id_)
1926+
raise ValueError(f"Token '{token}' not found in tokenizer config.")
1927+
19151928
def set_gguf_parameters(self):
19161929
super().set_gguf_parameters()
19171930
hparams = self.hparams
19181931
if hparams["model_type"] == "pixtral":
19191932
self.gguf_writer.add_vision_projector_type(gguf.VisionProjectorType.PIXTRAL)
19201933
self.gguf_writer.add_vision_attention_layernorm_eps(hparams["layer_norm_eps"])
1921-
self.gguf_writer.add_vision_use_silu(True)
1934+
1935+
# hidden_act
1936+
if hparams["hidden_act"] == "silu":
1937+
self.gguf_writer.add_vision_use_silu(True)
1938+
elif hparams["hidden_act"] == "gelu":
1939+
self.gguf_writer.add_vision_use_gelu(True)
1940+
else:
1941+
raise ValueError(f"Unsupported hidden_act: {hparams['hidden_act']}")
1942+
1943+
# spatial_merge_size
1944+
if "spatial_merge_size" in self.global_config:
1945+
self.gguf_writer.add_vision_spatial_merge_size(self.global_config["spatial_merge_size"])
19221946

19231947
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
19241948
del bid # unused

examples/llava/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ llama-mtmd-cli -hf ggml-org/SmolVLM2-500M-Video-Instruct-GGUF
3434

3535
# Pixtral 12B
3636
llama-mtmd-cli -hf ggml-org/pixtral-12b-GGUF
37+
38+
# Mistral Small 3.1 24B (IQ2_M quantization)
39+
llama-mtmd-cli -hf ggml-org/Mistral-Small-3.1-24B-Instruct-2503-GGUF --chat-template mistral-v7
3740
```
3841

3942
## How it works and what is `mmproj`?
@@ -73,3 +76,4 @@ For the following models, you can use `convert_hf_to_gguf.py`with `--mmproj` fla
7376
- SmolVLM (from [HuggingFaceTB](https://huggingface.co/HuggingFaceTB))
7477
- SmolVLM2 (from [HuggingFaceTB](https://huggingface.co/HuggingFaceTB))
7578
- [Pixtral 12B](https://huggingface.co/mistral-community/pixtral-12b) - only works with `transformers`-compatible checkpoint
79+
- [Mistral Small 3.1 24B](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)

examples/llava/clip-impl.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#define KEY_FEATURE_LAYER "clip.vision.feature_layer"
3232
#define KEY_PROJ_SCALE_FACTOR "clip.vision.projector.scale_factor"
3333
#define KEY_PROJ_TYPE "clip.projector_type"
34+
#define KEY_SPATIAL_MERGE_SIZE "clip.vision.spatial_merge_size"
3435

3536
#define KEY_USE_GLU_MLP "clip.use_glu_mlp" // for qwen2.5vl
3637
#define KEY_USE_RMS_NORM "clip.use_rms_norm" // for qwen2.5vl
@@ -68,9 +69,11 @@
6869
#define TN_MVLM_PROJ_BLOCK "mm.model.mb_block.%d.block.%d.%s"
6970
#define TN_MVLM_PROJ_PEG "mm.model.peg.%d.%s"
7071
#define TN_IMAGE_NEWLINE "model.image_newline"
72+
#define TN_MM_INP_NORM "mm.input_norm.weight"
7173
#define TN_MM_INP_PROJ "mm.input_projection.weight" // gemma3
7274
#define TN_MM_SOFT_EMB_N "mm.soft_emb_norm.weight" // gemma3
7375
#define TN_MM_PROJECTOR "mm.model.fc.weight" // idefics3
76+
#define TN_MM_PATCH_MERGER "mm.patch_merger.weight" // mistral small 3.1
7477
#define TN_TOK_IMG_BREAK "v.token_embd.img_break" // pixtral
7578

7679
// mimicpmv

examples/llava/clip.cpp

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ struct clip_hparams {
172172
std::unordered_set<int32_t> vision_feature_layer;
173173
int32_t attn_window_size = 0;
174174
int32_t n_wa_pattern = 0;
175+
int32_t spatial_merge_size = 0;
175176
};
176177

177178
struct clip_layer {
@@ -232,6 +233,7 @@ struct clip_vision_model {
232233
struct ggml_tensor * projection;
233234

234235
// LLaVA projection
236+
struct ggml_tensor * mm_input_norm_w = nullptr;
235237
struct ggml_tensor * mm_0_w = nullptr;
236238
struct ggml_tensor * mm_0_b = nullptr;
237239
struct ggml_tensor * mm_2_w = nullptr;
@@ -311,6 +313,7 @@ struct clip_vision_model {
311313

312314
// pixtral
313315
struct ggml_tensor * token_embd_img_break = nullptr;
316+
struct ggml_tensor * mm_patch_merger_w = nullptr;
314317
};
315318

316319
struct clip_ctx {
@@ -637,6 +640,7 @@ static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_i
637640
const int d_head = hidden_size / n_head;
638641
const int n_layer = hparams.n_layer;
639642
const float eps = hparams.eps;
643+
const int n_merge = hparams.spatial_merge_size;
640644

641645
struct ggml_init_params params = {
642646
/*.mem_size =*/ ctx->buf_compute_meta.size(),
@@ -721,7 +725,13 @@ static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_i
721725
{
722726
ggml_tensor * gate_proj = ggml_mul_mat(ctx0, model.layers[il].ff_gate_w, cur);
723727
ggml_tensor * up_proj = ggml_mul_mat(ctx0, model.layers[il].ff_up_w, cur);
724-
gate_proj = ggml_silu(ctx0, gate_proj); // pixtral uses silu
728+
if (ctx->use_silu) {
729+
gate_proj = ggml_silu(ctx0, gate_proj);
730+
} else if (ctx->use_gelu) {
731+
gate_proj = ggml_gelu(ctx0, gate_proj);
732+
} else {
733+
GGML_ABORT("Pixtral: Unsupported activation");
734+
}
725735
cur = ggml_mul(ctx0, up_proj, gate_proj);
726736
cur = ggml_mul_mat(ctx0, model.layers[il].ff_down_w, cur);
727737
}
@@ -732,14 +742,42 @@ static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_i
732742
embeddings = cur;
733743
}
734744

735-
// LlavaMultiModalProjector (with GELU activation)
745+
// mistral small 3.1 patch merger
746+
// ref: https://github.com/huggingface/transformers/blob/7a3e208892c06a5e278144eaf38c8599a42f53e7/src/transformers/models/mistral3/modeling_mistral3.py#L67
747+
if (model.mm_patch_merger_w) {
748+
GGML_ASSERT(hparams.spatial_merge_size > 0);
749+
750+
ggml_tensor * cur = embeddings;
751+
cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, cur, eps), model.mm_input_norm_w);
752+
753+
// reshape image tokens to 2D grid
754+
cur = ggml_reshape_3d(ctx0, cur, hidden_size, n_patches_x, n_patches_y);
755+
cur = ggml_permute(ctx0, cur, 2, 0, 1, 3); // [x, y, hidden_size]
756+
cur = ggml_cont(ctx0, cur);
757+
758+
// torch.nn.functional.unfold is just an im2col under the hood
759+
// we just need a dummy kernel to make it work
760+
ggml_tensor * kernel = ggml_view_3d(ctx0, cur, n_merge, n_merge, cur->ne[2], 0, 0, 0);
761+
cur = ggml_im2col(ctx0, kernel, cur, n_merge, n_merge, 0, 0, 1, 1, true, inp->type);
762+
763+
// project to hidden_size
764+
cur = ggml_reshape_2d(ctx0, cur, cur->ne[0], cur->ne[1] * cur->ne[2]);
765+
cur = ggml_mul_mat(ctx0, model.mm_patch_merger_w, cur);
766+
embeddings = cur;
767+
}
768+
769+
// LlavaMultiModalProjector (always using GELU activation)
736770
{
737771
embeddings = ggml_mul_mat(ctx0, model.mm_1_w, embeddings);
738-
embeddings = ggml_add(ctx0, embeddings, model.mm_1_b);
772+
if (model.mm_1_b) {
773+
embeddings = ggml_add(ctx0, embeddings, model.mm_1_b);
774+
}
739775

740776
embeddings = ggml_gelu(ctx0, embeddings);
741777
embeddings = ggml_mul_mat(ctx0, model.mm_2_w, embeddings);
742-
embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
778+
if (model.mm_2_b) {
779+
embeddings = ggml_add(ctx0, embeddings, model.mm_2_b);
780+
}
743781
}
744782

745783
// arrangement of the [IMG_BREAK] token
@@ -749,11 +787,14 @@ static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_i
749787
// and then concatenate the [IMG_BREAK] token to the end of each row, aka n_patches_per_row dimension
750788
// after the concatenation, we have a tensor with shape [hidden_size, n_patches_per_row + 1, n_rows]
751789

790+
const int p_y = n_merge > 0 ? n_patches_y / n_merge : n_patches_y;
791+
const int p_x = n_merge > 0 ? n_patches_x / n_merge : n_patches_x;
792+
const int p_total = p_x * p_y;
752793
const int n_embd_text = embeddings->ne[0];
753-
const int n_tokens_output = num_patches + n_patches_y - 1; // one [IMG_BREAK] per row, except the last row
794+
const int n_tokens_output = p_total + p_y - 1; // one [IMG_BREAK] per row, except the last row
754795

755-
ggml_tensor * cur = ggml_reshape_3d(ctx0, embeddings, n_embd_text, n_patches_x, n_patches_y);
756-
ggml_tensor * tok = ggml_new_tensor_3d(ctx0, embeddings->type, n_embd_text, 1, n_patches_y);
796+
ggml_tensor * cur = ggml_reshape_3d(ctx0, embeddings, n_embd_text, p_x, p_y);
797+
ggml_tensor * tok = ggml_new_tensor_3d(ctx0, embeddings->type, n_embd_text, 1, p_y);
757798
tok = ggml_scale(ctx0, tok, 0.0); // clear the tensor
758799
tok = ggml_add(ctx0, tok, model.token_embd_img_break);
759800
cur = ggml_concat(ctx0, cur, tok, 1);
@@ -1734,6 +1775,7 @@ struct clip_model_loader {
17341775
case PROJECTOR_TYPE_PIXTRAL:
17351776
{
17361777
hparams.rope_theta = 10000.0f;
1778+
get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.spatial_merge_size, false);
17371779
} break;
17381780
case PROJECTOR_TYPE_QWEN25VL:
17391781
{
@@ -1957,11 +1999,14 @@ struct clip_model_loader {
19571999
case PROJECTOR_TYPE_PIXTRAL:
19582000
{
19592001
vision_model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
1960-
vision_model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"));
2002+
vision_model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
19612003
vision_model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
1962-
vision_model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
2004+
vision_model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
19632005
// [IMG_BREAK] token embedding
19642006
vision_model.token_embd_img_break = get_tensor(TN_TOK_IMG_BREAK);
2007+
// for mistral small 3.1
2008+
vision_model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
2009+
vision_model.mm_patch_merger_w = get_tensor(TN_MM_PATCH_MERGER, false);
19652010
} break;
19662011
default:
19672012
GGML_ASSERT(false && "unknown projector type");
@@ -2926,8 +2971,9 @@ int clip_n_output_tokens(const struct clip_ctx * ctx, struct clip_image_f32 * im
29262971
} else if (ctx->proj_type == PROJECTOR_TYPE_IDEFICS3) {
29272972
n_patches /= ctx->vision_model.hparams.proj_scale_factor;
29282973
} else if (ctx->proj_type == PROJECTOR_TYPE_PIXTRAL) {
2929-
int n_patches_x = img->nx / params.patch_size;
2930-
int n_patches_y = img->ny / params.patch_size;
2974+
int n_merge = ctx->vision_model.hparams.spatial_merge_size;
2975+
int n_patches_x = img->nx / params.patch_size / (n_merge > 0 ? n_merge : 1);
2976+
int n_patches_y = img->ny / params.patch_size / (n_merge > 0 ? n_merge : 1);
29312977
n_patches = n_patches_y*n_patches_x + n_patches_y - 1; // + one [IMG_BREAK] per row, except the last row
29322978
}
29332979

@@ -3484,7 +3530,7 @@ int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
34843530
return ctx->vision_model.mm_model_peg_0_b->ne[0];
34853531
case PROJECTOR_TYPE_MLP:
34863532
case PROJECTOR_TYPE_PIXTRAL:
3487-
return ctx->vision_model.mm_2_b->ne[0];
3533+
return ctx->vision_model.mm_2_w->ne[1];
34883534
case PROJECTOR_TYPE_MLP_NORM:
34893535
return ctx->vision_model.mm_3_b->ne[0];
34903536
case PROJECTOR_TYPE_MINICPMV:

examples/llava/mtmd-cli.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ struct mtmd_cli_context {
9494
LOG_ERR("Model does not have chat template.\n");
9595
LOG_ERR(" For old llava models, you may need to use '--chat-template vicuna'\n");
9696
LOG_ERR(" For MobileVLM models, use '--chat-template deepseek'\n");
97+
LOG_ERR(" For Mistral Small 3.1, use '--chat-template mistral-v7'\n");
9798
exit(1);
9899
}
99100

examples/llava/tests.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ add_test "llama-mtmd-cli" "ggml-org/Qwen2.5-VL-3B-Instruct-GGUF:Q4_K_M"
5959

6060
# to test the big models, run: ./tests.sh big
6161
add_test_big "llama-mtmd-cli" "ggml-org/pixtral-12b-GGUF:Q4_K_M"
62+
add_test_big "llama-mtmd-cli" "ggml-org/Mistral-Small-3.1-24B-Instruct-2503-GGUF" "mistral-v7"
6263

6364
# these models always give the wrong answer, not sure why
6465
# add_test "llama-mtmd-cli" "ggml-org/SmolVLM-Instruct-GGUF:Q4_K_M"

gguf-py/gguf/constants.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ class ClipVision:
231231
BLOCK_COUNT = "clip.vision.block_count"
232232
IMAGE_MEAN = "clip.vision.image_mean"
233233
IMAGE_STD = "clip.vision.image_std"
234+
SPATIAL_MERGE_SIZE = "clip.vision.spatial_merge_size"
234235
USE_GELU = "clip.use_gelu"
235236
USE_SILU = "clip.use_silu"
236237

@@ -491,6 +492,7 @@ class MODEL_TENSOR(IntEnum):
491492
V_ENC_FFN_DOWN = auto()
492493
V_PRE_NORM = auto()
493494
V_POST_NORM = auto()
495+
V_MM_INP_NORM = auto()
494496
V_MM_INP_PROJ = auto() # gemma3
495497
V_MM_SOFT_EMB_NORM = auto() # gemma3
496498
V_RESMPL_POS_EMBD_K = auto() # minicpmv
@@ -505,6 +507,7 @@ class MODEL_TENSOR(IntEnum):
505507
V_RESMPL_PROJ = auto() # minicpmv
506508
V_RESMPL_QUERY = auto() # minicpmv
507509
V_TOK_EMBD_IMG_BREAK = auto() # pixtral
510+
V_MM_PATCH_MERGER = auto() # mistral small 3.1
508511

509512

510513
MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
@@ -747,6 +750,7 @@ class MODEL_TENSOR(IntEnum):
747750
MODEL_TENSOR.V_PRE_NORM: "v.pre_ln",
748751
MODEL_TENSOR.V_POST_NORM: "v.post_ln",
749752
MODEL_TENSOR.V_MM_INP_PROJ: "mm.input_projection",
753+
MODEL_TENSOR.V_MM_INP_NORM: "mm.input_norm",
750754
MODEL_TENSOR.V_MM_SOFT_EMB_NORM: "mm.soft_emb_norm",
751755
MODEL_TENSOR.V_RESMPL_POS_EMBD_K: "resampler.pos_embd_k",
752756
MODEL_TENSOR.V_RESMPL_ATTN_Q: "resampler.attn.q",
@@ -760,6 +764,7 @@ class MODEL_TENSOR(IntEnum):
760764
MODEL_TENSOR.V_RESMPL_PROJ: "resampler.proj",
761765
MODEL_TENSOR.V_RESMPL_QUERY: "resampler.query",
762766
MODEL_TENSOR.V_TOK_EMBD_IMG_BREAK: "v.token_embd.img_break", # pixtral
767+
MODEL_TENSOR.V_MM_PATCH_MERGER: "mm.patch_merger", # mistral small 3.1
763768
}
764769

765770
MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
@@ -783,6 +788,7 @@ class MODEL_TENSOR(IntEnum):
783788
MODEL_TENSOR.V_PRE_NORM,
784789
MODEL_TENSOR.V_POST_NORM,
785790
MODEL_TENSOR.V_MM_INP_PROJ,
791+
MODEL_TENSOR.V_MM_INP_NORM,
786792
MODEL_TENSOR.V_MM_SOFT_EMB_NORM,
787793
MODEL_TENSOR.V_RESMPL_POS_EMBD_K,
788794
MODEL_TENSOR.V_RESMPL_ATTN_Q,
@@ -796,6 +802,7 @@ class MODEL_TENSOR(IntEnum):
796802
MODEL_TENSOR.V_RESMPL_PROJ,
797803
MODEL_TENSOR.V_RESMPL_QUERY,
798804
MODEL_TENSOR.V_TOK_EMBD_IMG_BREAK,
805+
MODEL_TENSOR.V_MM_PATCH_MERGER,
799806
],
800807
MODEL_ARCH.LLAMA: [
801808
MODEL_TENSOR.TOKEN_EMBD,

gguf-py/gguf/gguf_writer.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -972,6 +972,9 @@ def add_vision_image_mean(self, values: Sequence[float]) -> None:
972972
def add_vision_image_std(self, values: Sequence[float]) -> None:
973973
self.add_array(Keys.ClipVision.IMAGE_STD, values)
974974

975+
def add_vision_spatial_merge_size(self, value: int) -> None:
976+
self.add_uint32(Keys.ClipVision.SPATIAL_MERGE_SIZE, value)
977+
975978
def add_vision_use_gelu(self, value: bool) -> None:
976979
self.add_bool(Keys.ClipVision.USE_GELU, value)
977980

gguf-py/gguf/tensor_mapping.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,6 +1001,10 @@ class TensorNameMap:
10011001
"multi_modal_projector.mm_input_projection",
10021002
),
10031003

1004+
MODEL_TENSOR.V_MM_INP_NORM: (
1005+
"multi_modal_projector.norm",
1006+
),
1007+
10041008
MODEL_TENSOR.V_MM_SOFT_EMB_NORM: (
10051009
"multi_modal_projector.mm_soft_emb_norm",
10061010
),
@@ -1052,6 +1056,10 @@ class TensorNameMap:
10521056
MODEL_TENSOR.V_TOK_EMBD_IMG_BREAK: (
10531057
"v.token_embd.img_break", # for pixtral, this is a generated vector
10541058
),
1059+
1060+
MODEL_TENSOR.V_MM_PATCH_MERGER: (
1061+
"multi_modal_projector.patch_merger.merging_layer", # mistral small 3.1
1062+
),
10551063
}
10561064

10571065
# architecture-specific block mappings

0 commit comments

Comments
 (0)