Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
f3b9369
feat(mtmd): add EP vision variant of llama-mtmd-cli
co-seven Feb 28, 2026
fca6bd2
feat(ggml-profile): add more stage for profile
Mar 2, 2026
3ce2522
mtmd-ep: align image boundary policy and simplify debug paths
co-seven Mar 3, 2026
b6a4608
server: add EP vision backend with runtime selection
co-seven Mar 5, 2026
ea645ce
mtmd: update EP cli flow and add qwen3vl preprocess docs
co-seven Mar 5, 2026
d8c0e65
ep vision: add direct jpg preprocessing for server and mtmd cli
co-seven Mar 6, 2026
b2d780f
docs: add EP multimodal usage and qwen3vl tuning note
co-seven Mar 6, 2026
b3a0b25
update doc
co-seven Mar 10, 2026
46e213e
updating build doc for EP accelerator
co-seven Mar 10, 2026
9a3f28d
smt: simplify spacemit vision integration
co-seven Mar 11, 2026
1e66622
smt: remove verbose runtime logging
co-seven Mar 11, 2026
515b1ee
smt: rename vision integration and tighten gating
co-seven Mar 12, 2026
4b444fa
feat: add audio support(Qwen3ASR) for smt.
co-seven Mar 24, 2026
fd1bc5c
fix: adjust backend loader
co-seven Mar 24, 2026
84d4a0d
fix: EP thread num set to 4
co-seven Mar 24, 2026
fb734cb
feat: add profile for audio&vision encoder
Mar 30, 2026
59fadd0
Add vision/audio encode to summary timing print
Apr 1, 2026
0c611b4
support qwen3.5 model arch
co-seven Apr 1, 2026
eefdebe
bugfix for qwen3.5 model arch
co-seven Apr 1, 2026
38700d6
support different inputsize for encoder
co-seven Apr 1, 2026
0d50190
fix:add tokenizer.json fallback for TokenizersBackend models
co-seven Apr 2, 2026
4a5adea
feat: add warmup for smt llama-server
co-seven Apr 9, 2026
52fab41
feat: add SMT-only vision_history control for multimodal chat
co-seven Apr 10, 2026
ff32442
fix: support config thread num
co-seven Apr 24, 2026
ff0c974
bugfix: fix qwen3vl image embedding hidden size mistake and add audio…
co-seven Apr 28, 2026
73117cd
mtmd: support ep_config threading options
co-seven May 8, 2026
0acf203
mtmd: support legacy config and ep_config Spacemit EP options
co-seven May 9, 2026
bac31df
fix: resolve merge conflicts in server-common.cpp and server-context.cpp
co-seven May 9, 2026
0386720
feat(mtmd): add PaddleOCR-VL support to llama-server SMT vision pipeline
co-seven May 14, 2026
f51fc67
fix(server): restore SMT context compile fixes
co-seven May 15, 2026
1c47eb6
docs: restore build-riscv64-spacemit.md to upstream version
co-seven May 15, 2026
0e07454
fix: address review updates for profiling and server context
co-seven May 15, 2026
38a9ca6
fix: update SMT mtmd CLI and guard POSIX-only backend usage
co-seven May 15, 2026
a3675de
fix: merge duplicate Qwen3ASR converter definitions
co-seven May 15, 2026
3c135a3
fix: add build cross for PR process
co-seven May 15, 2026
7e81288
fix: yml format
co-seven May 15, 2026
3b7a695
fix(server): restore prompt cache reload for cleared idle slots
co-seven May 18, 2026
9bba967
Potential fix for pull request finding
co-seven May 18, 2026
44a7170
fix: address review feedback for prompt cache, profiling, and SMT paths
co-seven May 18, 2026
ba8c191
fix: use get_vocab() for fast tokenizers
co-seven May 18, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/build-cross.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ on:
'ggml/src/spacemit/*',
'ggml/src/arch/loongarch/*'
]
pull_request:
branches:
- master
- spacemit-mtmd
# run once every week
schedule:
- cron: '0 0 * * 0'
Expand Down
5 changes: 5 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ option(LLAMA_TESTS_INSTALL "llama: install tests"
# 3rd party libs
option(LLAMA_OPENSSL "llama: use openssl to support HTTPS" ON)
option(LLAMA_LLGUIDANCE "llama-common: include LLGuidance library for structured output in common utils" OFF)
option(LLAMA_SERVER_SMT_VISION "llama: enable SpacemiT multimodal SMT extensions" OFF)

if (LLAMA_SERVER_SMT_VISION)
add_compile_definitions(LLAMA_SERVER_SMT_VISION=1)
endif()


# Required for relocatable CMake package
Expand Down
19 changes: 19 additions & 0 deletions common/arg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2197,6 +2197,25 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.mmproj_use_gpu = value;
}
).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ_OFFLOAD"));
#if defined(LLAMA_SERVER_SMT_VISION)
add_opt(common_arg(
{"--media-backend", "--vision-backend"}, "{auto|mtmd|smt}",
string_format("multimodal backend selection (default: %s)", params.media_backend.c_str()),
[](common_params & params, const std::string & value) {
if (value != "auto" && value != "mtmd" && value != "smt") {
throw std::invalid_argument("media-backend must be one of: auto, mtmd, smt");
}
params.media_backend = value;
}
).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MTMD}).set_env("LLAMA_ARG_MEDIA_BACKEND"));
add_opt(common_arg(
{"--smt-config-dir"}, "DIR",
"path to SMT config directory (config.json + ONNX model files)",
[](common_params & params, const std::string & value) {
params.smt_config_dir = value;
}
).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MTMD}).set_env("LLAMA_ARG_SMT_CONFIG_DIR"));
#endif
add_opt(common_arg(
{"--image", "--audio"}, "FILE",
"path to an image or audio file. use with multimodal models, use comma-separated values for multiple files\n",
Expand Down
4 changes: 4 additions & 0 deletions common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,10 @@ struct common_params {
struct common_params_model mmproj;
bool mmproj_use_gpu = true; // use GPU for multimodal model
bool no_mmproj = false; // explicitly disable multimodal model
#if defined(LLAMA_SERVER_SMT_VISION)
std::string media_backend = "auto"; // multimodal backend: auto|mtmd|smt
std::string smt_config_dir; // SMT config dir (config.json + ONNX)
#endif
std::vector<std::string> image; // path to image file(s)
int image_min_tokens = -1;
int image_max_tokens = -1;
Expand Down
145 changes: 116 additions & 29 deletions convert_hf_to_gguf.py
Original file line number Diff line number Diff line change
Expand Up @@ -1250,22 +1250,80 @@

return seems_special

def load_hf_tokenizer(self, *, trust_remote_code: bool = False):
from transformers import AutoTokenizer, PreTrainedTokenizerFast

try:
return AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=trust_remote_code)
except ValueError as exc:
tokenizer_config_path = self.dir_model / "tokenizer_config.json"
tokenizer_class = None

if tokenizer_config_path.is_file():
with open(tokenizer_config_path, encoding="utf-8") as f:
tokenizer_class = json.load(f).get("tokenizer_class")

if tokenizer_class != "TokenizersBackend":
raise

tokenizer_json_path = self.dir_model / "tokenizer.json"
tokenizer_config = {}
if tokenizer_config_path.is_file():
with open(tokenizer_config_path, encoding="utf-8") as f:
tokenizer_config = json.load(f)

if tokenizer_json_path.is_file():
logger.warning(
"AutoTokenizer failed for %s with tokenizer_class=%s; "
"falling back to tokenizer.json",
self.dir_model,
tokenizer_class,
)
return PreTrainedTokenizerFast(
tokenizer_file=str(tokenizer_json_path),
bos_token=tokenizer_config.get("bos_token"),
eos_token=tokenizer_config.get("eos_token"),
unk_token=tokenizer_config.get("unk_token"),
pad_token=tokenizer_config.get("pad_token"),
clean_up_tokenization_spaces=tokenizer_config.get("clean_up_tokenization_spaces", False),
split_special_tokens=tokenizer_config.get("split_special_tokens", False),
)

logger.warning(
"AutoTokenizer failed for %s with tokenizer_class=%s; "
"falling back to AutoProcessor.tokenizer",
self.dir_model,
tokenizer_class,
)

from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained(
self.dir_model,
trust_remote_code=trust_remote_code,
)
tokenizer = getattr(processor, "tokenizer", None)
if tokenizer is None:
raise ValueError("AutoProcessor fallback did not provide a tokenizer") from exc

return tokenizer

# used for GPT-2 BPE and WordPiece vocabs
def get_vocab_base(self) -> tuple[list[str], list[int], str]:
tokens: list[str] = []
toktypes: list[int] = []

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(self.dir_model)
vocab_size = self.hparams.get("vocab_size", len(tokenizer.vocab)) # ty: ignore[unresolved-attribute]
assert max(tokenizer.vocab.values()) < vocab_size # ty: ignore[unresolved-attribute]
tokenizer = self.load_hf_tokenizer()
vocab = tokenizer.get_vocab()
vocab_size = self.hparams.get("vocab_size", len(vocab))
assert max(vocab.values()) < vocab_size

tokpre = self.get_vocab_base_pre(tokenizer)

reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in tokenizer.vocab.items()} # ty: ignore[unresolved-attribute]
reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in vocab.items()}
added_vocab = tokenizer.get_added_vocab() # ty: ignore[unresolved-attribute]

Check warning on line 1324 in convert_hf_to_gguf.py

View workflow job for this annotation

GitHub Actions / python type-check

ty (unused-ignore-comment)

convert_hf_to_gguf.py:1324:52: unused-ignore-comment: Unused `ty: ignore` directive help: Remove the unused suppression comment

added_tokens_decoder = tokenizer.added_tokens_decoder # ty: ignore[unresolved-attribute]

Check warning on line 1326 in convert_hf_to_gguf.py

View workflow job for this annotation

GitHub Actions / python type-check

ty (unused-ignore-comment)

convert_hf_to_gguf.py:1326:64: unused-ignore-comment: Unused `ty: ignore` directive help: Remove the unused suppression comment

for i in range(vocab_size):
if i not in reverse_vocab:
Expand All @@ -1278,7 +1336,7 @@
# To avoid unexpected issues - we make sure to normalize non-normalized tokens
if not added_tokens_decoder[i].normalized:
previous_token = token
token = tokenizer.decode(tokenizer.encode(token, add_special_tokens=False)) # ty: ignore[unresolved-attribute, invalid-assignment]

Check warning on line 1339 in convert_hf_to_gguf.py

View workflow job for this annotation

GitHub Actions / python type-check

ty (unused-ignore-comment)

convert_hf_to_gguf.py:1339:102: unused-ignore-comment: Unused `ty: ignore` directive help: Remove the unused suppression comment
if previous_token != token:
logger.info(f"{repr(previous_token)} is encoded and decoded back to {repr(token)} using AutoTokenizer")

Expand Down Expand Up @@ -3882,7 +3940,7 @@
def set_vocab(self):
try:
self._set_vocab_sentencepiece()
except FileNotFoundError:
except (FileNotFoundError, ModuleNotFoundError, ImportError):
self._set_vocab_gpt2()

def set_gguf_parameters(self):
Expand Down Expand Up @@ -4839,6 +4897,54 @@
yield from super().modify_tensors(data_torch, name, bid)


@ModelBase.register("Qwen3ASRForConditionalGeneration")
class Qwen3ASRTextModel(Qwen3Model):
model_arch = gguf.MODEL_ARCH.QWEN3

def __init__(self, dir_model: Path, *args, **kwargs):
hparams = kwargs.pop("hparams", None)
if hparams is None:
hparams = ModelBase.load_hparams(dir_model, self.is_mistral_format)

thinker_config = hparams.get("thinker_config", {})
text_config = dict(thinker_config.get("text_config", {}))
if text_config and text_config.get("architectures") is None and text_config.get("model_type") == "qwen3":
text_config["architectures"] = ["Qwen3ForCausalLM"]
if text_config:
hparams = {**hparams, "text_config": text_config}

super().__init__(dir_model, *args, hparams=hparams, **kwargs)

def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_num_deepstack_layers(0)

def set_vocab(self):
super().set_vocab()
# fix chat template, use correct chatml format
self.gguf_writer.add_chat_template("{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}")
# correct BOS/EOS tokens
with open(self.dir_model / "tokenizer_config.json", "r", encoding="utf-8") as f:
tokenizer_config = json.load(f)
added_tokens = tokenizer_config.get("added_tokens_decoder", {})
for token_id, data in added_tokens.items():
if data.get("content") == "<|im_end|>":
self.gguf_writer.add_bos_token_id(int(token_id))
self.gguf_writer.add_eos_token_id(int(token_id))
break

def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if name.startswith("thinker.audio_tower."):
return

if name.startswith("thinker.model.") or name.startswith("thinker.lm_head."):
name = name.removeprefix("thinker.")
elif name.startswith("thinker."):
return

yield from super().modify_tensors(data_torch, name, bid)


@ModelBase.register("Qwen3MoeForCausalLM")
class Qwen3MoeModel(Qwen2MoeModel):
model_arch = gguf.MODEL_ARCH.QWEN3MOE
Expand Down Expand Up @@ -5342,29 +5448,6 @@
self.gguf_writer.add_num_deepstack_layers(0)


@ModelBase.register("Qwen3ASRForConditionalGeneration")
class Qwen3ASRTextModel(Qwen3VLTextModel):
model_arch = gguf.MODEL_ARCH.QWEN3VL

def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_num_deepstack_layers(0)

def set_vocab(self):
super().set_vocab()
# fix chat template, use correct chatml format
self.gguf_writer.add_chat_template("{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}")
# correct BOS/EOS tokens
with open(self.dir_model / "tokenizer_config.json", "r", encoding="utf-8") as f:
tokenizer_config = json.load(f)
added_tokens = tokenizer_config.get("added_tokens_decoder", {})
for token_id, data in added_tokens.items():
if data.get("content") == "<|im_end|>":
self.gguf_writer.add_bos_token_id(int(token_id))
self.gguf_writer.add_eos_token_id(int(token_id))
break


class _LinearAttentionVReorderBase(Qwen3NextModel):
model_arch = gguf.MODEL_ARCH.QWEN3NEXT # overridden by subclasses
"""reorders V heads from grouped to tiled order for ggml broadcast
Expand Down Expand Up @@ -14104,6 +14187,8 @@
# TODO @ngxson : this won't work correctly if the model has both audio & vision encoders
# maybe we should fallback to text model's arch in that case, since not many models have both
text_config = hparams.get("text_config", {})
if model_type == ModelType.TEXT and hparams.get("thinker_config", {}).get("text_config") is not None:
text_config = hparams["thinker_config"]["text_config"]
vision_config = hparams.get("vision_config", {})
arch = None
if (arches := hparams.get("architectures")) is not None and len(arches) > 0:
Expand All @@ -14121,6 +14206,8 @@
# if "architectures" is found in the sub-config, use that instead
if model_type == ModelType.TEXT and text_config.get("architectures") is not None:
arch = text_config["architectures"][0]
elif model_type == ModelType.TEXT and arch == "Qwen3ASRForConditionalGeneration" and text_config.get("model_type") == "qwen3":
arch = "Qwen3ASRForConditionalGeneration"
elif model_type == ModelType.MMPROJ and vision_config.get("architectures") is not None:
arch = vision_config["architectures"][0]
if arch is None:
Expand Down
41 changes: 41 additions & 0 deletions ggml/include/ggml-profile.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#pragma once

#include "ggml.h"

#include <stdint.h>

//#define GGML_BUILD_PROFILE

#ifdef __cplusplus
extern "C" {
#endif

#ifdef GGML_BUILD_PROFILE
extern int g_current_token_idx;

void ggml_profile_init_trace_file(void);
void ggml_profile_flush_trace(void);
void ggml_set_current_token_idx(int idx);

void ggml_trace_log_begin(const char * name, const char * cat, const char * args);
void ggml_trace_log_end(const char * name, const char * cat, const char * args);

void ggml_profile_log_op_begin(struct ggml_tensor * tensor);
void ggml_profile_log_op_end(struct ggml_tensor * tensor);

void ggml_profile_flush_tls(void);
#else
#define g_current_token_idx 0
#define ggml_profile_init_trace_file() ;
#define ggml_profile_flush_trace() ;
#define ggml_set_current_token_idx(idx) ;
#define ggml_trace_log_begin(name, cat, args) ;
#define ggml_trace_log_end(name, cat, args) ;
#define ggml_profile_log_op_begin(tensor) ;
#define ggml_profile_log_op_end(tensor) ;
#define ggml_profile_flush_tls() ;
#endif

#ifdef __cplusplus
}
#endif
Loading
Loading