diff --git a/.github/workflows/build-cross.yml b/.github/workflows/build-cross.yml index 97c7368387e8..4486d1220256 100644 --- a/.github/workflows/build-cross.yml +++ b/.github/workflows/build-cross.yml @@ -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' diff --git a/CMakeLists.txt b/CMakeLists.txt index 244f4cb49825..36761bf98358 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 diff --git a/common/arg.cpp b/common/arg.cpp index 15d5ad77af12..0a551349f361 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -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", diff --git a/common/common.h b/common/common.h index 764574e23a09..552ae68266ea 100644 --- a/common/common.h +++ b/common/common.h @@ -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 image; // path to image file(s) int image_min_tokens = -1; int image_max_tokens = -1; diff --git a/convert_hf_to_gguf.py b/convert_hf_to_gguf.py index 5cff86848565..8835491af0f0 100755 --- a/convert_hf_to_gguf.py +++ b/convert_hf_to_gguf.py @@ -1250,19 +1250,77 @@ def does_token_look_special(self, token: str | bytes) -> bool: 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] added_tokens_decoder = tokenizer.added_tokens_decoder # ty: ignore[unresolved-attribute] @@ -3882,7 +3940,7 @@ class Qwen2Model(TextModel): def set_vocab(self): try: self._set_vocab_sentencepiece() - except FileNotFoundError: + except (FileNotFoundError, ModuleNotFoundError, ImportError): self._set_vocab_gpt2() def set_gguf_parameters(self): @@ -4839,6 +4897,54 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter 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 @@ -5342,29 +5448,6 @@ def set_gguf_parameters(self): 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 @@ -14104,6 +14187,8 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st # 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: @@ -14121,6 +14206,8 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st # 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: diff --git a/ggml/include/ggml-profile.h b/ggml/include/ggml-profile.h new file mode 100644 index 000000000000..8b0a7be4373a --- /dev/null +++ b/ggml/include/ggml-profile.h @@ -0,0 +1,41 @@ +#pragma once + +#include "ggml.h" + +#include + +//#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 diff --git a/ggml/src/ggml-profile.c b/ggml/src/ggml-profile.c new file mode 100644 index 000000000000..d8410292ec07 --- /dev/null +++ b/ggml/src/ggml-profile.c @@ -0,0 +1,289 @@ +#include "ggml-profile.h" + +#include +#include +#include + +#ifdef GGML_BUILD_PROFILE +# if defined(_WIN32) +int g_current_token_idx = -1; + +void ggml_set_current_token_idx(int idx) { + g_current_token_idx = idx; +} + +void ggml_profile_init_trace_file(void) { +} + +void ggml_trace_log_begin(const char * name, const char * cat, const char * args) { + GGML_UNUSED(name); + GGML_UNUSED(cat); + GGML_UNUSED(args); +} + +void ggml_trace_log_end(const char * name, const char * cat, const char * args) { + GGML_UNUSED(name); + GGML_UNUSED(cat); + GGML_UNUSED(args); +} + +void ggml_profile_log_op_begin(struct ggml_tensor * t) { + GGML_UNUSED(t); +} + +void ggml_profile_log_op_end(struct ggml_tensor * t) { + GGML_UNUSED(t); +} + +void ggml_profile_flush_tls(void) { +} + +void ggml_profile_flush_trace(void) { +} +# else +# include +# include +# if defined(__linux__) +# include +# include +# endif + +static int g_trace_enabled = 0; +static pthread_once_t g_trace_once = PTHREAD_ONCE_INIT; + +static void ggml_trace_parse_env(void) { + const char * env = getenv("GGML_TRACE"); + if (env && (env[0] == '1' || env[0] == 'y' || env[0] == 'Y')) { + g_trace_enabled = 1; + } else { + g_trace_enabled = 0; + } +} + +# define TRACE_ENABLED() (pthread_once(&g_trace_once, ggml_trace_parse_env), g_trace_enabled) + +static inline int64_t ggml_trace_now_us(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t) ts.tv_sec * 1000000LL + ts.tv_nsec / 1000; +} + +static inline unsigned long ggml_trace_tid(void) { +# if defined(__linux__) + return (unsigned long) syscall(SYS_gettid); +# else + return (unsigned long) (uintptr_t) pthread_self(); +# endif +} + +static pthread_mutex_t g_trace_mutex = PTHREAD_MUTEX_INITIALIZER; +static FILE * g_trace_file = NULL; + +# define TRACE_BUFFER_SIZE (64 * 1024) + +__thread char g_trace_tls_buffer[TRACE_BUFFER_SIZE]; +__thread size_t g_trace_tls_offset = 0; + +int g_current_token_idx = -1; + +void ggml_set_current_token_idx(int idx) { + g_current_token_idx = idx; +} + +static void ggml_profile_init_trace_file_locked(void) { + if (!g_trace_file) { + g_trace_file = fopen("ggml_trace.json", "w"); + if (g_trace_file) { + fputs("[\n", g_trace_file); + } + } +} + +void ggml_profile_init_trace_file(void) { + if (!TRACE_ENABLED()) { + return; + } + + pthread_mutex_lock(&g_trace_mutex); + ggml_profile_init_trace_file_locked(); + pthread_mutex_unlock(&g_trace_mutex); +} + +static void ggml_json_escape(const char * src, char * dst, size_t dst_size) { + size_t i = 0; + for (; *src && i + 2 < dst_size; src++) { + if (*src == '"' || *src == '\\') { + dst[i++] = '\\'; + } + dst[i++] = *src; + } + dst[i] = '\0'; +} + +static inline const char * ggml_tensor_name_safe(struct ggml_tensor * t) { + return (t && t->name[0] != '\0') ? t->name : "N/A"; +} + +static void ggml_format_tensor_info(struct ggml_tensor * t, const char * prefix, char * buf, size_t buf_size) { + if (!t) { + snprintf(buf, buf_size, "\"%s_exists\":false", prefix); + return; + } + + char escaped_name[64]; + ggml_json_escape(ggml_tensor_name_safe(t), escaped_name, sizeof(escaped_name)); + + snprintf(buf, buf_size, + "\"%s_shape\":\"[%ld,%ld,%ld,%ld]\"," + "\"%s_strides\":\"[%ld,%ld,%ld,%ld]\"," + "\"%s_type\":\"%s\"," + "\"%s_name\":\"%s\"", + prefix, t->ne[0], t->ne[1], t->ne[2], t->ne[3], + prefix, t->nb[0], t->nb[1], t->nb[2], t->nb[3], + prefix, ggml_type_name(t->type), prefix, escaped_name); +} + +static void ggml_format_op_args(struct ggml_tensor * t, const char * exec_path, char * buf, size_t buf_size) { + char out_info[256]; + char src0_info[256]; + char src1_info[256]; + + ggml_format_tensor_info(t, "out", out_info, sizeof(out_info)); + ggml_format_tensor_info(t->src[0], "src0", src0_info, sizeof(src0_info)); + ggml_format_tensor_info(t->src[1], "src1", src1_info, sizeof(src1_info)); + + char op_name[64]; + ggml_json_escape(ggml_op_name(t->op), op_name, sizeof(op_name)); + + if (exec_path) { + char escaped_path[256]; + ggml_json_escape(exec_path, escaped_path, sizeof(escaped_path)); + + snprintf(buf, buf_size, "\"op_name\":\"%s\",\"exec_path\":\"%s\",%s,%s,%s", op_name, escaped_path, out_info, + src0_info, src1_info); + } else { + snprintf(buf, buf_size, "\"op_name\":\"%s\",%s,%s,%s", op_name, out_info, src0_info, src1_info); + } +} + +static inline void ggml_trace_tls_flush_locked(void) { + if (g_trace_tls_offset == 0 || !g_trace_file) { + return; + } + + fwrite(g_trace_tls_buffer, 1, g_trace_tls_offset, g_trace_file); + g_trace_tls_offset = 0; +} + +static inline void ggml_trace_write(const char * json) { + if (!TRACE_ENABLED()) { + return; + } + + size_t len = strlen(json); + + if (g_trace_tls_offset + len >= TRACE_BUFFER_SIZE) { + pthread_mutex_lock(&g_trace_mutex); + ggml_profile_init_trace_file_locked(); + ggml_trace_tls_flush_locked(); + pthread_mutex_unlock(&g_trace_mutex); + } + + memcpy(g_trace_tls_buffer + g_trace_tls_offset, json, len); + g_trace_tls_offset += len; +} + +void ggml_trace_log_begin(const char * name, const char * cat, const char * args) { + if (!TRACE_ENABLED()) { + return; + } + + char buf[1024]; + + snprintf(buf, sizeof(buf), + "{\"name\":\"%s\",\"cat\":\"%s\",\"ph\":\"B\"," + "\"ts\":%ld,\"pid\":1,\"tid\":%lu,\"args\":{%s}},\n", + name, cat, ggml_trace_now_us(), ggml_trace_tid(), args ? args : ""); + + ggml_trace_write(buf); +} + +void ggml_trace_log_end(const char * name, const char * cat, const char * args) { + if (!TRACE_ENABLED()) { + return; + } + + char buf[1024]; + + snprintf(buf, sizeof(buf), + "{\"name\":\"%s\",\"cat\":\"%s\",\"ph\":\"E\"," + "\"ts\":%ld,\"pid\":1,\"tid\":%lu,\"args\":{%s}},\n", + name, cat, ggml_trace_now_us(), ggml_trace_tid(), args ? args : ""); + + ggml_trace_write(buf); +} + +void ggml_profile_log_op_begin(struct ggml_tensor * t) { + if (!TRACE_ENABLED()) { + return; + } + + char args[1024]; + ggml_format_op_args(t, NULL, args, sizeof(args)); + + char name[128], tname[64]; + ggml_json_escape(ggml_tensor_name_safe(t), tname, sizeof(tname)); + + snprintf(name, sizeof(name), "%s (%s)", ggml_op_name(t->op), tname); + + ggml_trace_log_begin(name, "Operator", args); +} + +void ggml_profile_log_op_end(struct ggml_tensor * t) { + if (!TRACE_ENABLED()) { + return; + } + + char name[128], tname[64]; + ggml_json_escape(ggml_tensor_name_safe(t), tname, sizeof(tname)); + + snprintf(name, sizeof(name), "%s (%s)", ggml_op_name(t->op), tname); + + ggml_trace_log_end(name, "Operator", NULL); +} + +void ggml_profile_flush_tls(void) { + if (!TRACE_ENABLED()) { + return; + } + + pthread_mutex_lock(&g_trace_mutex); + ggml_profile_init_trace_file_locked(); + ggml_trace_tls_flush_locked(); + pthread_mutex_unlock(&g_trace_mutex); +} + +void ggml_profile_flush_trace(void) { + if (!TRACE_ENABLED()) { + return; + } + + pthread_mutex_lock(&g_trace_mutex); + + if (g_trace_file) { + ggml_trace_tls_flush_locked(); + + long pos = ftell(g_trace_file); + if (pos >= 2) { + fseek(g_trace_file, pos - 2, SEEK_SET); // remove ",\n" + } + + fputs("\n]\n", g_trace_file); + fclose(g_trace_file); + g_trace_file = NULL; + } + + pthread_mutex_unlock(&g_trace_mutex); +} +# endif +#endif diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 3d9714ab1661..bf745baa8333 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -10,6 +10,7 @@ #include "llama-model.h" #include "llama-ext.h" #include "llama.h" +#include "ggml-profile.h" #include #include @@ -3761,11 +3762,25 @@ int32_t llama_encode( int32_t llama_decode( llama_context * ctx, llama_batch batch) { +#ifdef GGML_BUILD_PROFILE + // Distinguish between prefill and decode phases + const char * phase_name = (batch.n_tokens > 1) ? "llama_decode_prefill" : "llama_decode_generate"; + + char args[128]; + snprintf(args, sizeof(args), "\"n_tokens\":%d", batch.n_tokens); + + ggml_trace_log_begin(phase_name, "Decode", args); +#endif + const int ret = ctx->decode(batch); if (ret != 0 && ret != 1) { LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret); } +#ifdef GGML_BUILD_PROFILE + ggml_trace_log_end(phase_name, "Decode", NULL); +#endif + return ret; } diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index f43cf546ca08..4b5439b3ab62 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -1,10 +1,10 @@ #include "llama-vocab.h" +#include "ggml-profile.h" #include "ggml.h" #include "gguf.h" #include "llama-impl.h" #include "llama-model-loader.h" - #include "unicode.h" #include @@ -26,15 +26,15 @@ // struct naive_trie { - naive_trie() : has_value(false), value(0) { - } + naive_trie() : has_value(false), value(0) {} + void insert(const char * key, size_t len, int32_t value = 0) { if (len == 0) { this->has_value = true; - this->value = value; + this->value = value; return; } - char c = key[0]; + char c = key[0]; auto res = children.find(c); if (res != children.end()) { res->second.insert(key + 1, len - 1, value); @@ -43,11 +43,12 @@ struct naive_trie { res.first->second.insert(key + 1, len - 1, value); } } + std::pair get_longest_prefix(const char * key, size_t len, size_t offset = 0) const { if (len == 0 || offset == len) { return std::make_pair(key, offset); } - char c = key[offset]; + char c = key[offset]; auto res = children.find(c); if (res != children.end()) { return res->second.get_longest_prefix(key, len, offset + 1); @@ -55,6 +56,7 @@ struct naive_trie { return std::make_pair(key, offset); } + const struct naive_trie * traverse(const char c) const { auto res = children.find(c); if (res != children.end()) { @@ -64,8 +66,8 @@ struct naive_trie { return NULL; } std::map children; - bool has_value; - llama_token value; + bool has_value; + llama_token value; }; // @@ -74,15 +76,16 @@ struct naive_trie { struct llm_tokenizer { llm_tokenizer() {} + virtual ~llm_tokenizer() = default; }; struct llm_symbol { using index = int; - index prev; - index next; + index prev; + index next; const char * text; - size_t n; + size_t n; }; static_assert(std::is_trivially_copyable::value, "llm_symbol is not trivially copyable"); @@ -99,12 +102,13 @@ struct llm_bigram_spm { return (l.score < r.score) || (l.score == r.score && l.left > r.left); } }; + using queue_storage = std::vector; - using queue = std::priority_queue; + using queue = std::priority_queue; llm_symbol::index left; llm_symbol::index right; - float score; - size_t size; + float score; + size_t size; }; struct llm_tokenizer_spm : llm_tokenizer { @@ -116,13 +120,13 @@ struct llm_tokenizer_spm_session { void tokenize(const std::string & text, std::vector & output) { // split string into utf8 chars - int index = 0; - size_t offs = 0; + int index = 0; + size_t offs = 0; while (offs < text.size()) { llm_symbol sym; - size_t len = unicode_len_utf8(text[offs]); - sym.text = text.c_str() + offs; - sym.n = std::min(len, text.size() - offs); + size_t len = unicode_len_utf8(text[offs]); + sym.text = text.c_str() + offs; + sym.n = std::min(len, text.size() - offs); offs += sym.n; sym.prev = index - 1; sym.next = offs == text.size() ? -1 : index + 1; @@ -140,12 +144,11 @@ struct llm_tokenizer_spm_session { auto bigram = work_queue.top(); work_queue.pop(); - auto & left_sym = symbols[bigram.left]; + auto & left_sym = symbols[bigram.left]; auto & right_sym = symbols[bigram.right]; // if one of the symbols already got merged, skip it. - if (left_sym.n == 0 || right_sym.n == 0 || - left_sym.n + right_sym.n != bigram.size) { + if (left_sym.n == 0 || right_sym.n == 0 || left_sym.n + right_sym.n != bigram.size) { continue; } @@ -172,9 +175,9 @@ struct llm_tokenizer_spm_session { } } -private: + private: void resegment(llm_symbol & symbol, std::vector & output) { - auto text = std::string(symbol.text, symbol.n); + auto text = std::string(symbol.text, symbol.n); auto token = vocab.text_to_token(text); // Do we need to support is_unused? @@ -188,7 +191,7 @@ struct llm_tokenizer_spm_session { if (p == rev_merge.end()) { // output any symbols that did not form tokens as bytes. output.reserve(output.size() + symbol.n); - for (int j = 0; j < (int)symbol.n; ++j) { + for (int j = 0; j < (int) symbol.n; ++j) { llama_token id = vocab.byte_to_token(symbol.text[j]); output.push_back(id); } @@ -203,8 +206,8 @@ struct llm_tokenizer_spm_session { if (left == -1 || right == -1) { return; } - const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n); - auto token = vocab.text_to_token(text); + const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n); + auto token = vocab.text_to_token(text); if (token == LLAMA_TOKEN_NULL) { return; @@ -232,8 +235,8 @@ struct llm_tokenizer_spm_session { // currently unused // const llm_tokenizer_spm * spm_tokenizer; - std::vector symbols; - llm_bigram_spm::queue work_queue; + std::vector symbols; + llm_bigram_spm::queue work_queue; std::map> rev_merge; }; @@ -245,9 +248,9 @@ struct llm_tokenizer_spm_session { // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused -template, typename Compare = std::less> +template , typename Compare = std::less> class llama_priority_queue : public std::priority_queue { -public: + public: using std::priority_queue::priority_queue; T pop_move() { @@ -257,7 +260,7 @@ class llama_priority_queue : public std::priority_queue { return item; } - void pop() = delete; + void pop() = delete; }; struct llm_bigram_bpe { @@ -268,12 +271,12 @@ struct llm_bigram_bpe { }; using queue_storage = std::vector; - using queue = llama_priority_queue; + using queue = llama_priority_queue; llm_symbol::index left; llm_symbol::index right; - std::string text; - int rank; - size_t size; + std::string text; + int rank; + size_t size; }; struct llm_tokenizer_bpe : llm_tokenizer { @@ -286,7 +289,8 @@ struct llm_tokenizer_bpe : llm_tokenizer { //"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", // adapted: https://github.com/ggml-org/llama.cpp/pull/6920#issuecomment-2080233989 - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1," + "3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_JAIS2: @@ -295,20 +299,26 @@ struct llm_tokenizer_bpe : llm_tokenizer { //"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s{512}(?!\\S)|\\s{256}(?!\\S)|\\s{128}(?!\\S)|\\s{64}(?!\\S)|\\s{32}(?!\\S)|\\s{16}(?!\\S)|\\s{8}(?!\\S)|\\s{4}(?!\\S)|\\s{1,2}(?!\\S)|\\s{1}", // adapted: same as llama3 but with cascading whitespace pattern - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s{512}(?!\\S)|\\s{256}(?!\\S)|\\s{128}(?!\\S)|\\s{64}(?!\\S)|\\s{32}(?!\\S)|\\s{16}(?!\\S)|\\s{8}(?!\\S)|\\s{4}(?!\\S)|\\s{1,2}(?!\\S)|\\s{1}", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1," + "3}| " + "?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s{512}(?!\\S)|\\s{256}(?!\\S)|\\s{128}(?!\\S)|\\s{" + "64}(?!\\S)|\\s{32}(?!\\S)|\\s{16}(?!\\S)|\\s{8}(?!\\S)|\\s{4}(?!\\S)|\\s{1,2}(?!\\S)|\\s{1}", }; break; case LLAMA_VOCAB_PRE_TYPE_DBRX: case LLAMA_VOCAB_PRE_TYPE_SMAUG: regex_exprs = { // same as llama3 - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1," + "3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM: regex_exprs = { "[\r\n]", - "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+", + "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-" + "ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-" + "ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+", "\\s?[!-/:-~!-/:-~‘-‟ -。]+", "\\s+$", "[一-龥ࠀ-一가-퟿]+", @@ -321,22 +331,24 @@ struct llm_tokenizer_bpe : llm_tokenizer { regex_exprs = { "\\p{N}{1,3}", "[一-龥぀-ゟ゠-ヿ]+", - "[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\r\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| ?[\\p{P}\\p{S}]+[\r\n]*|\\s*[\r\n]+|\\s+(?!\\S)|\\s+", + "[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\r\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| " + "?[\\p{P}\\p{S}]+[\r\n]*|\\s*[\r\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_YOUTU: regex_exprs = { - "[가-힣ㄱ-ㆎ]+|[!…“”‘’—:;,、-〿︰-﹏]+|[ㄅ-ㄯ]+|[一-龥぀-ゟ゠-ヿ]+", - "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "[가-힣ㄱ-ㆎ]+|[!…“”‘’—:;,、-〿︰-﹏]+|[ㄅ-ㄯ]+|[一-龥぀-ゟ゠-" + "ヿ]" + "+", + "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|" + "'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{" + "Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" + "?|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER: regex_exprs = { - "[\r\n]", - "\\s?\\p{L}+", - "\\s?\\p{P}+", - "[一-龥ࠀ-一가-퟿]+", - "\\p{N}", + "[\r\n]", "\\s?\\p{L}+", "\\s?\\p{P}+", "[一-龥ࠀ-一가-퟿]+", "\\p{N}", }; break; case LLAMA_VOCAB_PRE_TYPE_FALCON: @@ -375,14 +387,16 @@ struct llm_tokenizer_bpe : llm_tokenizer { regex_exprs = { // original regex from tokenizer.json // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| " + "?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_QWEN35: regex_exprs = { // original regex from tokenizer.json // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|" + "\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_PORO: @@ -394,7 +408,8 @@ struct llm_tokenizer_bpe : llm_tokenizer { break; case LLAMA_VOCAB_PRE_TYPE_CHATGLM4: regex_exprs = { - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1," + "3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_VIKING: @@ -407,7 +422,9 @@ struct llm_tokenizer_bpe : llm_tokenizer { // original regex from tokenizer.json // "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" regex_exprs = { - "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[" + "\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| " + "?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_CHAMELEON: @@ -416,11 +433,11 @@ struct llm_tokenizer_bpe : llm_tokenizer { // However, since the upstream pre-tokenizer uses them, they are also // included here (see https://huggingface.co/facebook/chameleon-7b). regex_exprs = { - "", // Sentinel tokens + "", // Sentinel tokens "(IMGIMG)((A|B|C|D|E|F|G|H|I){1,4})Z", // Image tokens - "([\\t\\n]| | )", // directly from tokenizer.json - "\\p{N}", // Individual digits - "[\\p{P}!-/:-@\\[-`{-~]", // Punctuation, Isolated + "([\\t\\n]| | )", // directly from tokenizer.json + "\\p{N}", // Individual digits + "[\\p{P}!-/:-@\\[-`{-~]", // Punctuation, Isolated "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)", }; break; @@ -429,7 +446,10 @@ struct llm_tokenizer_bpe : llm_tokenizer { regex_exprs = { // original regex from tokenizer.json // "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", - "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV]" + "[eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(" + "?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| " + "?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_TINY_AYA: @@ -437,7 +457,10 @@ struct llm_tokenizer_bpe : llm_tokenizer { // original regex from tokenizer.json: "\\d{1,3}(?=(?:\\d{3})*\\b)" "\\d{1,3}(?=(?:\\d{3})*\\b)", // original regex from tokenizer.json: "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" - "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|" + "'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{" + "Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" + "?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_KIMI_K2: @@ -458,21 +481,24 @@ struct llm_tokenizer_bpe : llm_tokenizer { // original regex from tokenizer.json // "'(?i:[sdmt]|ll|ve|re)|[^\\r\\n\\p{L}\\p{N}]?+\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]++[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+" // FIXME? Changed possessive quantifiers (?+ and ++) to greedy to avoid errors and imatrix hanging (tried atomic grouping but it's not supported?) - "'(?:[sSdDmMtT]|[lL][lL]|[vV][eE]|[rR][eE])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+", + "'(?:[sSdDmMtT]|[lL][lL]|[vV][eE]|[rR][eE])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| " + "?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_SEED_CODER: regex_exprs = { // original regex from tokenizer.json // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\r\n]+|\\s*[\r\n]+|\\s+(?!\\S)|\\s+" - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\\r\\n]+|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}|" + " ?[^\\s\\p{L}\\p{N}\\r\\n]+|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_GROK_2: regex_exprs = { // original regex from tokenizer.json // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| " + "?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_AFMOE: @@ -481,16 +507,21 @@ struct llm_tokenizer_bpe : llm_tokenizer { // Groups digits with leading 1-2 based on total length modulo 3 "\\p{AFMoE_digits}", // CJK and Asian scripts (using direct Unicode literals) - "[一-鿿㐀-䶿豈-﫿぀-ゟ゠-ヿ・-゚⼀-⿟เ-๿຀-໿ក-៿က-႟ꩠ-ꩿꧠ-꧿가-힯ᄀ-ᇿ]+", + "[一-鿿㐀-䶿豈-﫿぀-ゟ゠-ヿ・-゚⼀-⿟เ-๿຀-໿ក-៿က-႟ꩠ-ꩿꧠ-꧿가-힯ᄀ-" + "ᇿ]" + "+", // Main BPE pattern - "[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\\r\\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| ?[\\p{P}\\p{S}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "[!\"#$%&'()*+,\\-./" + ":;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\\r\\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| " + "?[\\p{P}\\p{S}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE: regex_exprs = { // original regex from tokenizer.json // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?(?:\\p{L}\\p{M}*(?: \\p{L}\\p{M}*)*)+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]?|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+" - "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?(?:\\p{L}\\p{M}*(?: \\p{L}\\p{M}*)*)+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]?|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?(?:\\p{L}\\p{M}*(?" + ": \\p{L}\\p{M}*)*)+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]?|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+", }; break; case LLAMA_VOCAB_PRE_TYPE_GEMMA4: @@ -501,7 +532,7 @@ struct llm_tokenizer_bpe : llm_tokenizer { regex_exprs = { "[^\\n]+|[\\n]+", }; - byte_encode = false; // uses raw UTF-8, not GPT-2 byte encoding + byte_encode = false; // uses raw UTF-8, not GPT-2 byte encoding break; case LLAMA_VOCAB_PRE_TYPE_SARVAM_MOE: // Sarvam uses SPM-style BPE (same shape as Gemma4): spaces replaced with U+2581 @@ -524,15 +555,15 @@ struct llm_tokenizer_bpe : llm_tokenizer { } std::vector regex_exprs; - bool byte_encode = true; // GPT-2 byte encoding; false for SPM-style BPE (raw UTF-8) + bool byte_encode = true; // GPT-2 byte encoding; false for SPM-style BPE (raw UTF-8) }; struct llm_tokenizer_bpe_session { - llm_tokenizer_bpe_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : vocab(vocab), tokenizer(tokenizer) {} + llm_tokenizer_bpe_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : + vocab(vocab), + tokenizer(tokenizer) {} - static void append(const llama_token token_id, std::vector & output) { - output.push_back(token_id); - } + static void append(const llama_token token_id, std::vector & output) { output.push_back(token_id); } bool append_bos(std::vector & output) const { if (vocab.get_add_bos()) { @@ -557,19 +588,21 @@ struct llm_tokenizer_bpe_session { LLAMA_LOG_WARN( "%s: Added a BOS token to the prompt as specified by the model but the prompt " "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. " - "Are you sure this is what you want?\n", __FUNCTION__); + "Are you sure this is what you want?\n", + __FUNCTION__); } - if (vocab.get_add_eos() && output.size() >= 2 && *(output.end()-2) == vocab.token_eos()) { + if (vocab.get_add_eos() && output.size() >= 2 && *(output.end() - 2) == vocab.token_eos()) { LLAMA_LOG_WARN( "%s: Added a EOS token to the prompt as specified by the model but the prompt " "also ends with a EOS token. So now the final prompt ends with 2 EOS tokens. " - "Are you sure this is what you want?\n", __FUNCTION__); + "Are you sure this is what you want?\n", + __FUNCTION__); } } void tokenize(const std::string & text, std::vector & output) { - int final_prev_index = -1; - const auto word_collection = unicode_regex_split(text, tokenizer.regex_exprs, tokenizer.byte_encode); + int final_prev_index = -1; + const auto word_collection = unicode_regex_split(text, tokenizer.regex_exprs, tokenizer.byte_encode); symbols_final.clear(); auto tok_pre = vocab.get_pre_type(); @@ -578,27 +611,27 @@ struct llm_tokenizer_bpe_session { work_queue = llm_bigram_bpe::queue(); symbols.clear(); - int index = 0; + int index = 0; size_t offset = 0; //if (vocab.tokenizer_ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) { if (vocab.get_ignore_merges() && vocab.text_to_token(word) != LLAMA_TOKEN_NULL) { - symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()}); + symbols.emplace_back(llm_symbol{ -1, -1, word.c_str(), word.size() }); offset = word.size(); } else if (tok_pre == LLAMA_VOCAB_PRE_TYPE_GEMMA4 && word.find_first_not_of('\n') == std::string::npos) { // fix for gemma 4, ref: https://github.com/ggml-org/llama.cpp/pull/21343 auto tok = vocab.text_to_token(word); if (tok != LLAMA_TOKEN_NULL) { - symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()}); + symbols.emplace_back(llm_symbol{ -1, -1, word.c_str(), word.size() }); offset = word.size(); } } while (offset < word.size()) { llm_symbol sym; - size_t char_len = std::min(word.size() - offset, (size_t) unicode_len_utf8(word[offset])); - sym.text = word.c_str() + offset; - sym.n = char_len; + size_t char_len = std::min(word.size() - offset, (size_t) unicode_len_utf8(word[offset])); + sym.text = word.c_str() + offset; + sym.n = char_len; offset += sym.n; sym.prev = index - 1; sym.next = offset == word.size() ? -1 : index + 1; @@ -613,13 +646,13 @@ struct llm_tokenizer_bpe_session { while (!work_queue.empty()) { auto bigram = work_queue.pop_move(); - auto & left_symbol = symbols[bigram.left]; + auto & left_symbol = symbols[bigram.left]; auto & right_symbol = symbols[bigram.right]; if (left_symbol.n == 0 || right_symbol.n == 0) { continue; } - std::string left_token = std::string(left_symbol.text, left_symbol.n); + std::string left_token = std::string(left_symbol.text, left_symbol.n); std::string right_token = std::string(right_symbol.text, right_symbol.n); if (left_token + right_token != bigram.text) { continue; // Skip this bigram if it's outdated @@ -662,8 +695,8 @@ struct llm_tokenizer_bpe_session { continue; } - const std::string str = std::string(symbol.text, symbol.n); - const auto token = vocab.text_to_token(str); + const std::string str = std::string(symbol.text, symbol.n); + const auto token = vocab.text_to_token(str); if (token == LLAMA_TOKEN_NULL) { for (auto j = str.begin(); j != str.end(); ++j) { @@ -673,10 +706,10 @@ struct llm_tokenizer_bpe_session { token_multibyte = vocab.text_to_token(byte_str); } else { // For non-byte-encoded BPE (e.g. gemma-4), byte tokens use <0xXX> format - static const char * hex = "0123456789ABCDEF"; - const uint8_t ch = (uint8_t)*j; - const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 }; - token_multibyte = vocab.text_to_token(buf); + static const char * hex = "0123456789ABCDEF"; + const uint8_t ch = (uint8_t) *j; + const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 }; + token_multibyte = vocab.text_to_token(buf); } if (token_multibyte != LLAMA_TOKEN_NULL) { output.push_back(token_multibyte); @@ -689,12 +722,12 @@ struct llm_tokenizer_bpe_session { } } -private: + private: void add_new_bigram(int left, int right) { if (left == -1 || right == -1) { return; } - std::string left_token = std::string(symbols[left].text, symbols[left].n); + std::string left_token = std::string(symbols[left].text, symbols[left].n); std::string right_token = std::string(symbols[right].text, symbols[right].n); int rank_found = -1; @@ -716,12 +749,12 @@ struct llm_tokenizer_bpe_session { work_queue.push(bigram); } - const llama_vocab & vocab; + const llama_vocab & vocab; const llm_tokenizer_bpe & tokenizer; std::vector symbols; std::vector symbols_final; - llm_bigram_bpe::queue work_queue; + llm_bigram_bpe::queue work_queue; }; // @@ -749,7 +782,7 @@ struct llm_tokenizer_wpm_session { // prepend phantom space const std::string word1 = "\xe2\x96\x81" + word; - const int n = word1.size(); + const int n = word1.size(); const size_t current_tokens = output.size(); @@ -763,14 +796,14 @@ struct llm_tokenizer_wpm_session { if (id != LLAMA_TOKEN_NULL) { output.push_back(id); match = true; - i = j - 1; + i = j - 1; break; } } - if (!match) { // discard all + if (!match) { // discard all output.resize(current_tokens); - break; // and discard next tokens + break; // and discard next tokens } } @@ -782,9 +815,9 @@ struct llm_tokenizer_wpm_session { } // TODO: reduce string copies by using cpts_offs array - static std::vector preprocess(const std::string & text) { + static std::vector preprocess(const std::string & text) { const std::vector cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text)); - std::vector words(1, ""); + std::vector words(1, ""); for (const uint32_t cpt : cpts_nfd) { const auto flags = unicode_cpt_flags_from_cpt(cpt); @@ -796,20 +829,20 @@ struct llm_tokenizer_wpm_session { continue; } - assert (!flags.is_separator); + assert(!flags.is_separator); if (cpt == 0 || cpt == 0xFFFD || flags.is_control) { continue; } const std::string s = unicode_cpt_to_utf8(unicode_tolower(cpt)); - if (flags.is_punctuation || ( cpt < 0x7F && flags.is_symbol ) || is_chinese_char(cpt)) { + if (flags.is_punctuation || (cpt < 0x7F && flags.is_symbol) || is_chinese_char(cpt)) { if (words.back().size()) { // finish previous word if any words.emplace_back(); } - words.back() = s; // single char word - words.emplace_back(); // start a new word + words.back() = s; // single char word + words.emplace_back(); // start a new word } else { - words.back() += s; // append char to word + words.back() += s; // append char to word } } @@ -821,20 +854,16 @@ struct llm_tokenizer_wpm_session { } static bool is_chinese_char(uint32_t cpt) { - return - (cpt >= 0x04E00 && cpt <= 0x09FFF) || - (cpt >= 0x03400 && cpt <= 0x04DBF) || - (cpt >= 0x20000 && cpt <= 0x2A6DF) || - (cpt >= 0x2A700 && cpt <= 0x2B73F) || - (cpt >= 0x2B740 && cpt <= 0x2B81F) || - (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920 - (cpt >= 0x0F900 && cpt <= 0x0FAFF) || - (cpt >= 0x2F800 && cpt <= 0x2FA1F); - //(cpt >= 0x3000 && cpt <= 0x303F) || - //(cpt >= 0xFF00 && cpt <= 0xFFEF); + return (cpt >= 0x04E00 && cpt <= 0x09FFF) || (cpt >= 0x03400 && cpt <= 0x04DBF) || + (cpt >= 0x20000 && cpt <= 0x2A6DF) || (cpt >= 0x2A700 && cpt <= 0x2B73F) || + (cpt >= 0x2B740 && cpt <= 0x2B81F) || + (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920 + (cpt >= 0x0F900 && cpt <= 0x0FAFF) || (cpt >= 0x2F800 && cpt <= 0x2FA1F); + //(cpt >= 0x3000 && cpt <= 0x303F) || + //(cpt >= 0xFF00 && cpt <= 0xFFEF); } -private: + private: const llama_vocab & vocab; // currently unused // const llm_tokenizer_wpm * wpm_tokenizer; @@ -859,13 +888,13 @@ struct llm_tokenizer_ugm : llm_tokenizer { // Next xcda_blob_size bytes contain entries of XOR-compressed compact // double array (XCDA). Each entry is bit-packed into a 32-bit integer. - xcda_array = (const uint32_t *) &precompiled_charsmap[charsmap_offset]; + xcda_array = (const uint32_t *) &precompiled_charsmap[charsmap_offset]; xcda_array_size = xcda_blob_size / sizeof(uint32_t); charsmap_offset += xcda_blob_size; // Remaining bytes of precompiled charsmap contain null-terminated // replacement strings for prefixes matched by the XCDA. - prefix_replacements = &precompiled_charsmap[charsmap_offset]; + prefix_replacements = &precompiled_charsmap[charsmap_offset]; prefix_replacements_size = precompiled_charsmap.size() - charsmap_offset; } @@ -877,9 +906,7 @@ struct llm_tokenizer_ugm : llm_tokenizer { max_score = std::max(max_score, token_data.score); } - if (vocab.is_normal(id) || - vocab.is_user_defined(id) || - vocab.is_unused(id)) { + if (vocab.is_normal(id) || vocab.is_user_defined(id) || vocab.is_unused(id)) { token_matcher.insert(token_data.text.data(), token_data.text.size(), id); } @@ -894,11 +921,11 @@ struct llm_tokenizer_ugm : llm_tokenizer { // escaped space symbol - U+2581 (Lower One Eighth Block) const std::string escaped_space = "\xE2\x96\x81"; - const char * prefix_replacements = NULL; - size_t prefix_replacements_size = 0; + const char * prefix_replacements = NULL; + size_t prefix_replacements_size = 0; - const uint32_t * xcda_array = NULL; - size_t xcda_array_size = 0; + const uint32_t * xcda_array = NULL; + size_t xcda_array_size = 0; struct naive_trie user_defined_token_matcher; @@ -912,7 +939,9 @@ struct llm_tokenizer_ugm : llm_tokenizer { }; struct llm_tokenizer_ugm_session { - llm_tokenizer_ugm_session(const llama_vocab & vocab, const llm_tokenizer_ugm & tokenizer) : vocab(vocab), tokenizer(tokenizer) {} + llm_tokenizer_ugm_session(const llama_vocab & vocab, const llm_tokenizer_ugm & tokenizer) : + vocab(vocab), + tokenizer(tokenizer) {} /* This implementation is based on SentencePiece optimized Viterbi algorithm for * unigram language models. The general idea is to: @@ -940,19 +969,20 @@ struct llm_tokenizer_ugm_session { } // initialize score_sum to -FLT_MAX so it will be always lower than sums of token scores - std::vector tokenization_results(input_len + 1, {vocab.token_unk(), 0, -DBL_MAX}); + std::vector tokenization_results(input_len + 1, { vocab.token_unk(), 0, -DBL_MAX }); // at the beginning tokenization score is zero tokenization_results[0] = { vocab.token_unk(), 0, 0 }; for (size_t input_offset = 0; input_offset < input_len;) { size_t prefix_offset = input_offset; // calculate how many code units are in the currently processed UTF code point - size_t n_utf8_code_units = std::min(unicode_len_utf8(normalized[input_offset]), input_len - input_offset); + size_t n_utf8_code_units = + std::min(unicode_len_utf8(normalized[input_offset]), input_len - input_offset); // traverse the token matcher trie to find a matching token - bool single_codepoint_token_found = false; - const struct best_tokenization & current_best = tokenization_results[input_offset]; - const struct naive_trie * node = tokenizer.token_matcher.traverse(normalized[prefix_offset++]); + bool single_codepoint_token_found = false; + const struct best_tokenization & current_best = tokenization_results[input_offset]; + const struct naive_trie * node = tokenizer.token_matcher.traverse(normalized[prefix_offset++]); while (prefix_offset <= input_len && node != NULL) { // check if we found valid token in prefix @@ -961,19 +991,19 @@ struct llm_tokenizer_ugm_session { if (prefix_offset - input_offset == n_utf8_code_units) { single_codepoint_token_found = true; } - llama_token token_id = node->value; + llama_token token_id = node->value; const auto & token_data = vocab.get_token_data(token_id); // we set the user-defined token scores to 0 to make them more likely to be selected // (normal token scores are log probabilities, so they are negative) // score type is double here to make tokenization results exactly // the same as in the HF tokenizer using SentencePiece - const double token_score = vocab.is_user_defined(token_id) ? 0.0 : token_data.score; - const double challenger_score = current_best.score_sum + token_score; - struct best_tokenization & current_champ = tokenization_results[prefix_offset]; + const double token_score = vocab.is_user_defined(token_id) ? 0.0 : token_data.score; + const double challenger_score = current_best.score_sum + token_score; + struct best_tokenization & current_champ = tokenization_results[prefix_offset]; if (challenger_score > current_champ.score_sum) { struct best_tokenization challenger = { token_id, input_offset, challenger_score }; - current_champ = challenger; + current_champ = challenger; } } node = node->traverse(normalized[prefix_offset++]); @@ -982,12 +1012,12 @@ struct llm_tokenizer_ugm_session { // if we didn't find a valid token corresponding to the whole UTF code point // then use unknown token as the tokenization of this UTF code point if (!single_codepoint_token_found) { - const double challenger_score = current_best.score_sum + tokenizer.unknown_token_score; - prefix_offset = input_offset + n_utf8_code_units; + const double challenger_score = current_best.score_sum + tokenizer.unknown_token_score; + prefix_offset = input_offset + n_utf8_code_units; struct best_tokenization & current_champ = tokenization_results[prefix_offset]; if (challenger_score > current_champ.score_sum) { struct best_tokenization challenger = { vocab.token_unk(), input_offset, challenger_score }; - current_champ = challenger; + current_champ = challenger; } } @@ -998,7 +1028,8 @@ struct llm_tokenizer_ugm_session { // now backtrack from the end to gather token ids of the best tokenization // merge sequences of consecutive unknown tokens into single unknown tokens bool is_prev_unknown = false; - for (struct best_tokenization & tokenization = tokenization_results[input_len]; ; tokenization = tokenization_results[tokenization.input_offset]) { + for (struct best_tokenization & tokenization = tokenization_results[input_len];; + tokenization = tokenization_results[tokenization.input_offset]) { bool is_unknown = tokenization.token_id == vocab.token_unk(); if (!(is_prev_unknown && is_unknown)) { output.push_back(tokenization.token_id); @@ -1013,31 +1044,30 @@ struct llm_tokenizer_ugm_session { std::reverse(output.begin() + output_size, output.end()); } -private: - + private: // helper structure for returning normalization results struct normalization_result { const char * normalized; - size_t normalized_len; - size_t consumed_input; + size_t normalized_len; + size_t consumed_input; }; - void normalize(const std::string& input, std::string * normalized) { + void normalize(const std::string & input, std::string * normalized) { normalized->clear(); normalized->reserve(input.size() * 3); const std::string space = vocab.get_escape_whitespaces() ? tokenizer.escaped_space : " "; const bool shall_prepend_space = !vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix(); - const bool shall_append_space = vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix(); - const bool shall_merge_spaces = vocab.get_remove_extra_whitespaces(); + const bool shall_append_space = vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix(); + const bool shall_merge_spaces = vocab.get_remove_extra_whitespaces(); bool is_space_prepended = false; - bool processing_non_ws = false; + bool processing_non_ws = false; size_t input_len = input.size(); - for (size_t input_offset = 0; input_offset < input_len; ) { + for (size_t input_offset = 0; input_offset < input_len;) { auto norm_res = normalize_prefix(input, input_offset); for (size_t i = 0; i < norm_res.normalized_len; i++) { char c = norm_res.normalized[i]; @@ -1078,41 +1108,47 @@ struct llm_tokenizer_ugm_session { * Entries containing indexes of replacement sequences have set bit 31 */ struct xcda_array_view { - public: - xcda_array_view(const uint32_t * xcda_array, size_t xcda_array_size) : xcda_array(xcda_array), xcda_array_size(xcda_array_size) { - } + public: + xcda_array_view(const uint32_t * xcda_array, size_t xcda_array_size) : + xcda_array(xcda_array), + xcda_array_size(xcda_array_size) {} + uint32_t get_base(size_t index) { uint32_t packed_node = get_node(index); return (packed_node >> 10) << ((packed_node & (1U << 9)) >> 6); } + uint32_t get_lcheck(size_t index) { uint32_t packed_node = get_node(index); return packed_node & ((1U << 31) | 0xff); } + bool get_leaf(size_t index) { uint32_t packed_node = get_node(index); return (packed_node >> 8) & 1; } + uint32_t get_value(size_t index) { uint32_t packed_node = get_node(index); return packed_node & ((1U << 31) - 1); } - private: + private: uint32_t get_node(size_t index) { if (index >= xcda_array_size) { throw std::runtime_error("Index out of array bounds in XCDA array!"); } return xcda_array[index]; } + const uint32_t * xcda_array; - size_t xcda_array_size; + size_t xcda_array_size; }; // this structure stores the best tokenization so far at input_offset struct best_tokenization { llama_token token_id; - size_t input_offset; - double score_sum; + size_t input_offset; + double score_sum; }; struct normalization_result normalize_prefix(const std::string & input, size_t input_offset) { @@ -1122,7 +1158,7 @@ struct llm_tokenizer_ugm_session { // if input prefix matches some user-defined token return this token as normalization result auto user_defined_token_match = - tokenizer.user_defined_token_matcher.get_longest_prefix(&input[input_offset], input.size() - input_offset); + tokenizer.user_defined_token_matcher.get_longest_prefix(&input[input_offset], input.size() - input_offset); if (user_defined_token_match.second > 0) { return { &input[input_offset], user_defined_token_match.second, user_defined_token_match.second }; } @@ -1139,7 +1175,7 @@ struct llm_tokenizer_ugm_session { // the index of the previous node and c is a numerical character value uint32_t node_index = 0; // get BASE of the root node - node_index = xcda_view.get_base(node_index); + node_index = xcda_view.get_base(node_index); for (size_t prefix_offset = input_offset; prefix_offset < input.size(); prefix_offset++) { unsigned char c = input[prefix_offset]; if (c == 0) { @@ -1156,8 +1192,7 @@ struct llm_tokenizer_ugm_session { node_index ^= xcda_view.get_base(node_index); // if LEAF of the current node is true, it means that its BASE points to the node // containing index of replacement sequence for currently matched input prefix - if (is_leaf) - { + if (is_leaf) { longest_prefix_length = prefix_offset - input_offset + 1; // get index of replacement sequence for currently matched input prefix longest_prefix_offset = xcda_view.get_value(node_index); @@ -1186,7 +1221,7 @@ struct llm_tokenizer_ugm_session { } } - const llama_vocab & vocab; + const llama_vocab & vocab; const llm_tokenizer_ugm & tokenizer; }; @@ -1199,16 +1234,16 @@ static std::vector llama_unescape_rwkv_token(const std::string & escape output.reserve(escaped.size()); // Parser state - bool escaping = false; + bool escaping = false; uint8_t hex_remaining = 0; - uint8_t hex_acc = 0; + uint8_t hex_acc = 0; // Step through characters, performing parsing for (const char & c : escaped) { // If we're parsing a hex code, interpret the next character if (hex_remaining != 0) { uint8_t value = (c >= 'a') ? (c - 'a' + 10) : (c - '0'); - hex_acc = (hex_acc << 4) + value; + hex_acc = (hex_acc << 4) + value; hex_remaining -= 1; if (hex_remaining == 0) { @@ -1256,7 +1291,7 @@ struct llm_tokenizer_rwkv : llm_tokenizer { // build trie for (uint32_t id = 0; id < vocab.n_tokens(); ++id) { const auto & data = vocab.get_token_data(id); - const auto text = llama_unescape_rwkv_token(data.text); + const auto text = llama_unescape_rwkv_token(data.text); token_matcher.insert((const char *) text.data(), text.size(), id); } } @@ -1265,7 +1300,9 @@ struct llm_tokenizer_rwkv : llm_tokenizer { }; struct llm_tokenizer_rwkv_session { - llm_tokenizer_rwkv_session(const llama_vocab & vocab, const llm_tokenizer_rwkv & tokenizer) : vocab(vocab), tokenizer(tokenizer) {} + llm_tokenizer_rwkv_session(const llama_vocab & vocab, const llm_tokenizer_rwkv & tokenizer) : + vocab(vocab), + tokenizer(tokenizer) {} void tokenize(const std::string & text, std::vector & output) { uint32_t position = 0; @@ -1279,11 +1316,11 @@ struct llm_tokenizer_rwkv_session { } // traverse the trie to find the longest matching token - uint32_t token_id = 0; + uint32_t token_id = 0; uint32_t token_length = 0; while (node != NULL) { if (node->has_value) { - token_id = node->value; + token_id = node->value; token_length = position + 1; } node = node->traverse(text[++position]); @@ -1295,15 +1332,13 @@ struct llm_tokenizer_rwkv_session { } } -private: - const llama_vocab & vocab; + private: + const llama_vocab & vocab; const llm_tokenizer_rwkv & tokenizer; }; struct llm_tokenizer_plamo2 : llm_tokenizer { - llm_tokenizer_plamo2(const llama_vocab & vocab) { - build(vocab); - } + llm_tokenizer_plamo2(const llama_vocab & vocab) { build(vocab); } void build(const llama_vocab & vocab) { // Reset internal structures @@ -1313,7 +1348,7 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { table_.clear(); // Build token list and byte mapping - std::unordered_map suffix_to_score; + std::unordered_map suffix_to_score; std::unordered_map token_to_id; for (size_t token_id = 0; token_id < vocab.n_tokens(); ++token_id) { @@ -1324,9 +1359,9 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { // Handle byte tokens if (vocab.is_byte(token_id)) { if (entry.text.length() == 6 && entry.text.substr(0, 3) == "<0x" && entry.text.back() == '>') { - std::string hex_str = entry.text.substr(3, 2); - int byte_val = std::stoi(hex_str, nullptr, 16); - bytes_[byte_val] = static_cast(token_id); + std::string hex_str = entry.text.substr(3, 2); + int byte_val = std::stoi(hex_str, nullptr, 16); + bytes_[byte_val] = static_cast(token_id); } continue; } @@ -1370,7 +1405,7 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { // Build suffix_to_id and to_suffix_id_ std::unordered_map suffix_to_id; - int32_t num_pieces = 0; + int32_t num_pieces = 0; for (const auto & suffix : suffixes) { suffix_to_id[suffix] = num_pieces; @@ -1382,11 +1417,11 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { remaining += unicode_cpt_to_utf8(cpts[i]); } - int64_t piece_code = (static_cast(cpts[0]) << 32) | suffix_to_id[remaining]; + int64_t piece_code = (static_cast(cpts[0]) << 32) | suffix_to_id[remaining]; to_suffix_id_[piece_code] = num_pieces; // Count number of pieces for this suffix - int32_t pieces_for_suffix = 1; // sentinel row + int32_t pieces_for_suffix = 1; // sentinel row for (int32_t piece_length = static_cast(cpts.size()); piece_length > 0; --piece_length) { std::string piece; for (int32_t i = 0; i < piece_length; ++i) { @@ -1421,12 +1456,12 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { } table_[table_idx][TABLE_PIECE_LENGTH] = piece_length; - auto token_it = token_to_id.find(piece); - table_[table_idx][TABLE_TOKEN_ID] = (token_it != token_to_id.end()) ? token_it->second : -1; + auto token_it = token_to_id.find(piece); + table_[table_idx][TABLE_TOKEN_ID] = (token_it != token_to_id.end()) ? token_it->second : -1; float score = score_it->second; - table_[table_idx][TABLE_SCORE] = std::isfinite(score) ? - static_cast(std::round(score * 1e4)) : INVALID_SCORE; + table_[table_idx][TABLE_SCORE] = + std::isfinite(score) ? static_cast(std::round(score * 1e4)) : INVALID_SCORE; table_[table_idx][TABLE_PIECE_ID] = suffix_to_id[piece]; table_idx++; @@ -1434,8 +1469,8 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { // Add sentinel row table_[table_idx][TABLE_PIECE_LENGTH] = 1; - table_[table_idx][TABLE_TOKEN_ID] = -1; - table_[table_idx][TABLE_SCORE] = UNKNOWN_SCORE; + table_[table_idx][TABLE_TOKEN_ID] = -1; + table_[table_idx][TABLE_SCORE] = UNKNOWN_SCORE; table_idx++; } } @@ -1469,8 +1504,8 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { // Find next suffix ID for (size_t p = suffix_id; p < table_.size(); ++p) { int64_t piece_code = (static_cast(c) << 32) | table_[p][TABLE_PIECE_ID]; - auto it = to_suffix_id_.find(piece_code); - suffix_id = (it != to_suffix_id_.end()) ? it->second : 0; + auto it = to_suffix_id_.find(piece_code); + suffix_id = (it != to_suffix_id_.end()) ? it->second : 0; if (suffix_id > 0 || table_[p][TABLE_SCORE] == UNKNOWN_SCORE) { break; @@ -1482,13 +1517,13 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { int32_t score = table_[p][TABLE_SCORE]; if (score > INVALID_SCORE) { int32_t piece_length = table_[p][TABLE_PIECE_LENGTH]; - int64_t s = scores[i + piece_length] - score; + int64_t s = scores[i + piece_length] - score; if (s < scores[i]) { - scores[i] = s; + scores[i] = s; path[i][PATH_TOKEN_LENGTH] = piece_length; - path[i][PATH_TOKEN_ID] = table_[p][TABLE_TOKEN_ID]; - path[i][PATH_NUM_TOKENS] = path[i + piece_length][PATH_NUM_TOKENS] + 1; + path[i][PATH_TOKEN_ID] = table_[p][TABLE_TOKEN_ID]; + path[i][PATH_NUM_TOKENS] = path[i + piece_length][PATH_NUM_TOKENS] + 1; if (score == UNKNOWN_SCORE) { // Add UTF-8 byte count @@ -1514,7 +1549,7 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { } else { // Fall back to byte tokens uint32_t c = unicode_data[pos]; - int s = 1 + (c >= 0x80) + (c >= 0x800) + (c >= 0x10000); + int s = 1 + (c >= 0x80) + (c >= 0x800) + (c >= 0x10000); for (int i = 0; i < s; ++i) { uint8_t b; @@ -1537,7 +1572,7 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { return token_ids; } -private: + private: // Constants for table structure static constexpr int32_t TABLE_PIECE_LENGTH = 0; static constexpr int32_t TABLE_TOKEN_ID = 1; @@ -1545,9 +1580,9 @@ struct llm_tokenizer_plamo2 : llm_tokenizer { static constexpr int32_t TABLE_PIECE_ID = 3; // Constants for path array - static constexpr int32_t PATH_TOKEN_LENGTH = 0; - static constexpr int32_t PATH_TOKEN_ID = 1; - static constexpr int32_t PATH_NUM_TOKENS = 2; + static constexpr int32_t PATH_TOKEN_LENGTH = 0; + static constexpr int32_t PATH_TOKEN_ID = 1; + static constexpr int32_t PATH_NUM_TOKENS = 2; // Score constants static constexpr int32_t INVALID_SCORE = -20000000; @@ -1575,7 +1610,7 @@ struct llm_tokenizer_plamo2_session { output.insert(output.end(), tokens.begin(), tokens.end()); } -private: + private: const llm_tokenizer_plamo2 & tokenizer; }; @@ -1589,36 +1624,34 @@ typedef enum FRAGMENT_BUFFER_VARIANT_TYPE { } FRAGMENT_BUFFER_VARIANT_TYPE; struct fragment_buffer_variant { - fragment_buffer_variant(llama_token _token) - : + fragment_buffer_variant(llama_token _token) : type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN), token(_token), raw_text(_dummy), offset(0), length(0) {} - fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length) - : + fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length) : type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT), - token((llama_token) - 1), + token((llama_token) -1), raw_text(_raw_text), offset(_offset), - length(_length){ - GGML_ASSERT(_offset >= 0); - GGML_ASSERT(_length >= 1); - GGML_ASSERT(offset + length <= raw_text.length()); - } + length(_length) { + GGML_ASSERT(_offset >= 0); + GGML_ASSERT(_length >= 1); + GGML_ASSERT(offset + length <= raw_text.length()); + } const FRAGMENT_BUFFER_VARIANT_TYPE type; - const llama_token token; - const std::string _dummy; - const std::string & raw_text; - const uint64_t offset; - const uint64_t length; + const llama_token token; + const std::string _dummy; + const std::string & raw_text; + const uint64_t offset; + const uint64_t length; }; struct llama_vocab::impl { - uint32_t n_token_types = 0; // for BERT-style token types + uint32_t n_token_types = 0; // for BERT-style token types std::string tokenizer_model; std::string tokenizer_pre; @@ -1626,7 +1659,7 @@ struct llama_vocab::impl { enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM; enum llama_vocab_pre_type pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; - int max_token_len = 0; // used for optimizing longest token search + int max_token_len = 0; // used for optimizing longest token search // default LLaMA special tokens // TODO: should we set all of these to LLAMA_TOKEN_NULL? @@ -1646,8 +1679,8 @@ struct llama_vocab::impl { llama_token special_fim_suf_id = LLAMA_TOKEN_NULL; llama_token special_fim_mid_id = LLAMA_TOKEN_NULL; llama_token special_fim_pad_id = LLAMA_TOKEN_NULL; - llama_token special_fim_rep_id = LLAMA_TOKEN_NULL; // repo - llama_token special_fim_sep_id = LLAMA_TOKEN_NULL; // file separator + llama_token special_fim_rep_id = LLAMA_TOKEN_NULL; // repo + llama_token special_fim_sep_id = LLAMA_TOKEN_NULL; // file separator // tokenizer flags bool add_space_prefix = false; @@ -1664,13 +1697,15 @@ struct llama_vocab::impl { std::vector id_to_token; std::vector cache_special_tokens; - std::vector cache_token_to_piece; // llama_token_to_piece(special = true); + std::vector cache_token_to_piece; // llama_token_to_piece(special = true); + struct pair_hash { size_t operator()(const std::pair & p) const { return std::hash{}(p.first) ^ //create some hash for pair (std::hash{}(p.second) << 1); } }; + std::unordered_map, int, pair_hash> bpe_ranks; // set of all tokens that cause "end of generation" @@ -1680,8 +1715,7 @@ struct llama_vocab::impl { std::vector precompiled_charsmap; - impl(const llama_vocab & vocab) : vocab(vocab) { - } + impl(const llama_vocab & vocab) : vocab(vocab) {} ~impl() = default; @@ -1691,13 +1725,13 @@ struct llama_vocab::impl { std::string type_name() const; - bool is_normal (llama_token id) const; - bool is_unknown (llama_token id) const; - bool is_control (llama_token id) const; - bool is_byte (llama_token id) const; + bool is_normal(llama_token id) const; + bool is_unknown(llama_token id) const; + bool is_control(llama_token id) const; + bool is_byte(llama_token id) const; bool is_user_defined(llama_token id) const; - bool is_unused (llama_token id) const; - bool is_eog (llama_token id) const; + bool is_unused(llama_token id) const; + bool is_eog(llama_token id) const; uint8_t token_to_byte(llama_token id) const; @@ -1707,50 +1741,35 @@ struct llama_vocab::impl { void tokenizer_st_partition(std::forward_list & buffer, bool parse_special) const; - std::string token_to_piece_for_cache( - llama_token token, - bool special) const; - + std::string token_to_piece_for_cache(llama_token token, bool special) const; - std::vector tokenize( - const std::string & raw_text, - bool add_special, - bool parse_special = false) const; + std::vector tokenize(const std::string & raw_text, bool add_special, bool parse_special = false) const; - int32_t tokenize( - const char * text, - int32_t text_len, - llama_token * tokens, - int32_t n_tokens_max, - bool add_special, - bool parse_special) const; + int32_t tokenize(const char * text, + int32_t text_len, + llama_token * tokens, + int32_t n_tokens_max, + bool add_special, + bool parse_special) const; // does not write null-terminator to buf - int32_t token_to_piece( - llama_token token, - char * buf, - int32_t length, - int32_t lstrip, - bool special) const; + int32_t token_to_piece(llama_token token, char * buf, int32_t length, int32_t lstrip, bool special) const; // use cached data const std::string & token_to_piece(llama_token token) const; - int32_t detokenize( - const llama_token * tokens, - int32_t n_tokens, - char * text, - int32_t text_len_max, - bool remove_special, - bool unparse_special) const; + int32_t detokenize(const llama_token * tokens, + int32_t n_tokens, + char * text, + int32_t text_len_max, + bool remove_special, + bool unparse_special) const; - std::string detokenize( - const std::vector & tokens, - bool special) const; + std::string detokenize(const std::vector & tokens, bool special) const; void print_info() const; -private: + private: const llama_vocab & vocab; }; @@ -1760,7 +1779,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { // determine vocab type { ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model); - ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false); + ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false); ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, n_token_types, false); @@ -1812,9 +1831,9 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { type = LLAMA_VOCAB_TYPE_BPE; // read bpe merges and populate bpe ranks - const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str()); + const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str()); // Kimi-K2 uses custom tokenization without traditional BPE merges - const bool is_kimi_k2 = (tokenizer_pre == "kimi-k2"); + const bool is_kimi_k2 = (tokenizer_pre == "kimi-k2"); if (merges_keyidx == -1) { if (!is_kimi_k2) { @@ -1860,7 +1879,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { special_pad_id = 0; special_mask_id = LLAMA_TOKEN_NULL; - const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str()); + const int precompiled_charsmap_keyidx = + gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str()); if (precompiled_charsmap_keyidx != -1) { const gguf_type pc_type = gguf_get_arr_type(ctx, precompiled_charsmap_keyidx); GGML_ASSERT(pc_type == GGUF_TYPE_INT8 || pc_type == GGUF_TYPE_UINT8); @@ -1871,10 +1891,10 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { #if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ // correct endianness of data in precompiled_charsmap binary blob uint32_t * xcda_blob_size = (uint32_t *) &precompiled_charsmap[0]; - *xcda_blob_size = __builtin_bswap32(*xcda_blob_size); + *xcda_blob_size = __builtin_bswap32(*xcda_blob_size); assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap); - size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t); - uint32_t * xcda_array = (uint32_t *) &precompiled_charsmap[sizeof(uint32_t)]; + size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t); + uint32_t * xcda_array = (uint32_t *) &precompiled_charsmap[sizeof(uint32_t)]; for (size_t i = 0; i < xcda_array_size; ++i) { xcda_array[i] = __builtin_bswap32(xcda_array[i]); } @@ -1893,11 +1913,11 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { type = LLAMA_VOCAB_TYPE_PLAMO2; // PLaMo-2 default special tokens (these will be overridden by model config) - special_bos_id = 1; // <|plamo:bos|> - special_eos_id = 2; // <|plamo:eos|> - special_unk_id = 0; // <|plamo:unk|> - special_sep_id = LLAMA_TOKEN_NULL; - special_pad_id = 3; // <|plamo:pad|> + special_bos_id = 1; // <|plamo:bos|> + special_eos_id = 2; // <|plamo:eos|> + special_unk_id = 0; // <|plamo:unk|> + special_sep_id = LLAMA_TOKEN_NULL; + special_pad_id = 3; // <|plamo:pad|> special_mask_id = LLAMA_TOKEN_NULL; } else if (tokenizer_model == "gemma4") { type = LLAMA_VOCAB_TYPE_BPE; @@ -1941,9 +1961,9 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { // for now, only BPE models have pre-tokenizers if (type == LLAMA_VOCAB_TYPE_BPE) { - add_space_prefix = false; + add_space_prefix = false; escape_whitespaces = false; - clean_spaces = true; + clean_spaces = true; if (tokenizer_pre.empty()) { LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__); LLAMA_LOG_WARN("%s: \n", __func__); @@ -1955,63 +1975,40 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; } else if (tokenizer_pre == "default") { pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; - } else if ( - tokenizer_pre == "llama3" || - tokenizer_pre == "llama-v3" || - tokenizer_pre == "llama-bpe"|| - tokenizer_pre == "falcon3" || - tokenizer_pre == "falcon-h1" || - tokenizer_pre == "pixtral" || - tokenizer_pre == "midm-2.0" || - tokenizer_pre == "lfm2" || - tokenizer_pre == "jina-v5-nano") { - pre_type = LLAMA_VOCAB_PRE_TYPE_LLAMA3; + } else if (tokenizer_pre == "llama3" || tokenizer_pre == "llama-v3" || tokenizer_pre == "llama-bpe" || + tokenizer_pre == "falcon3" || tokenizer_pre == "falcon-h1" || tokenizer_pre == "pixtral" || + tokenizer_pre == "midm-2.0" || tokenizer_pre == "lfm2" || tokenizer_pre == "jina-v5-nano") { + pre_type = LLAMA_VOCAB_PRE_TYPE_LLAMA3; ignore_merges = true; - add_bos = true; - } else if ( - tokenizer_pre == "deepseek-llm") { - pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM; - clean_spaces = false; - } else if ( - tokenizer_pre == "deepseek-coder") { - pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER; + add_bos = true; + } else if (tokenizer_pre == "deepseek-llm") { + pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM; clean_spaces = false; - } else if ( - tokenizer_pre == "deepseek-v3") { - pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM; + } else if (tokenizer_pre == "deepseek-coder") { + pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER; clean_spaces = false; - } else if ( - tokenizer_pre == "youtu") { - pre_type = LLAMA_VOCAB_PRE_TYPE_YOUTU; + } else if (tokenizer_pre == "deepseek-v3") { + pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM; clean_spaces = false; + } else if (tokenizer_pre == "youtu") { + pre_type = LLAMA_VOCAB_PRE_TYPE_YOUTU; + clean_spaces = false; ignore_merges = true; - } else if ( - tokenizer_pre == "falcon") { + } else if (tokenizer_pre == "falcon") { pre_type = LLAMA_VOCAB_PRE_TYPE_FALCON; - } else if ( - tokenizer_pre == "mpt") { + } else if (tokenizer_pre == "mpt") { pre_type = LLAMA_VOCAB_PRE_TYPE_MPT; - } else if ( - tokenizer_pre == "starcoder") { + } else if (tokenizer_pre == "starcoder") { pre_type = LLAMA_VOCAB_PRE_TYPE_STARCODER; - } else if ( - tokenizer_pre == "gpt-2" || - tokenizer_pre == "phi-2" || - tokenizer_pre == "jina-es" || - tokenizer_pre == "jina-de" || - tokenizer_pre == "gigachat" || - tokenizer_pre == "jina-v2-es" || - tokenizer_pre == "jina-v2-de" || - tokenizer_pre == "a.x-4.0" || - tokenizer_pre == "mellum" || - tokenizer_pre == "modern-bert") { + } else if (tokenizer_pre == "gpt-2" || tokenizer_pre == "phi-2" || tokenizer_pre == "jina-es" || + tokenizer_pre == "jina-de" || tokenizer_pre == "gigachat" || tokenizer_pre == "jina-v2-es" || + tokenizer_pre == "jina-v2-de" || tokenizer_pre == "a.x-4.0" || tokenizer_pre == "mellum" || + tokenizer_pre == "modern-bert") { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2; - } else if ( - tokenizer_pre == "jais-2") { + } else if (tokenizer_pre == "jais-2") { pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS2; - } else if ( - tokenizer_pre == "gemma4") { - pre_type = LLAMA_VOCAB_PRE_TYPE_GEMMA4; + } else if (tokenizer_pre == "gemma4") { + pre_type = LLAMA_VOCAB_PRE_TYPE_GEMMA4; escape_whitespaces = true; } else if ( tokenizer_pre == "sarvam-moe") { @@ -2023,187 +2020,143 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "jina-v2-code" || tokenizer_pre == "roberta-bpe") { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2; - add_sep = true; - } else if ( - tokenizer_pre == "refact") { + add_sep = true; + } else if (tokenizer_pre == "refact") { pre_type = LLAMA_VOCAB_PRE_TYPE_REFACT; - } else if ( - tokenizer_pre == "command-r") { - pre_type = LLAMA_VOCAB_PRE_TYPE_COMMAND_R; + } else if (tokenizer_pre == "command-r") { + pre_type = LLAMA_VOCAB_PRE_TYPE_COMMAND_R; clean_spaces = false; - } else if ( - tokenizer_pre == "qwen2" || - tokenizer_pre == "deepseek-r1-qwen" || - tokenizer_pre == "kormo" || - tokenizer_pre == "f2llmv2") { - pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; + } else if (tokenizer_pre == "qwen2" || tokenizer_pre == "deepseek-r1-qwen" || tokenizer_pre == "kormo" || + tokenizer_pre == "f2llmv2") { + pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; clean_spaces = false; - } else if ( - tokenizer_pre == "qwen35") { - pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35; + } else if (tokenizer_pre == "qwen35") { + pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35; clean_spaces = false; - } else if ( - tokenizer_pre == "stablelm2") { + } else if (tokenizer_pre == "stablelm2") { pre_type = LLAMA_VOCAB_PRE_TYPE_STABLELM2; - } else if ( - tokenizer_pre == "olmo") { + } else if (tokenizer_pre == "olmo") { pre_type = LLAMA_VOCAB_PRE_TYPE_OLMO; - } else if ( - tokenizer_pre == "dbrx") { + } else if (tokenizer_pre == "dbrx") { pre_type = LLAMA_VOCAB_PRE_TYPE_DBRX; - } else if ( - tokenizer_pre == "smaug-bpe") { + } else if (tokenizer_pre == "smaug-bpe") { pre_type = LLAMA_VOCAB_PRE_TYPE_SMAUG; - } else if ( - tokenizer_pre == "poro-chat") { - pre_type = LLAMA_VOCAB_PRE_TYPE_PORO; + } else if (tokenizer_pre == "poro-chat") { + pre_type = LLAMA_VOCAB_PRE_TYPE_PORO; clean_spaces = false; - } else if ( - tokenizer_pre == "glm4" || - tokenizer_pre == "chatglm-bpe") { - pre_type = LLAMA_VOCAB_PRE_TYPE_CHATGLM4; + } else if (tokenizer_pre == "glm4" || tokenizer_pre == "chatglm-bpe") { + pre_type = LLAMA_VOCAB_PRE_TYPE_CHATGLM4; special_bos_id = LLAMA_TOKEN_NULL; - } else if ( - tokenizer_pre == "viking") { - pre_type = LLAMA_VOCAB_PRE_TYPE_VIKING; + } else if (tokenizer_pre == "viking") { + pre_type = LLAMA_VOCAB_PRE_TYPE_VIKING; clean_spaces = false; - } else if ( - tokenizer_pre == "jais") { + } else if (tokenizer_pre == "jais") { pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS; - } else if ( - tokenizer_pre == "tekken") { - pre_type = LLAMA_VOCAB_PRE_TYPE_TEKKEN; - clean_spaces = false; + } else if (tokenizer_pre == "tekken") { + pre_type = LLAMA_VOCAB_PRE_TYPE_TEKKEN; + clean_spaces = false; ignore_merges = true; - add_bos = true; - } else if ( - tokenizer_pre == "smollm") { - pre_type = LLAMA_VOCAB_PRE_TYPE_SMOLLM; + add_bos = true; + } else if (tokenizer_pre == "smollm") { + pre_type = LLAMA_VOCAB_PRE_TYPE_SMOLLM; clean_spaces = false; - } else if ( - tokenizer_pre == "codeshell") { + } else if (tokenizer_pre == "codeshell") { pre_type = LLAMA_VOCAB_PRE_TYPE_CODESHELL; - } else if ( - tokenizer_pre == "bloom") { + } else if (tokenizer_pre == "bloom") { pre_type = LLAMA_VOCAB_PRE_TYPE_BLOOM; - } else if ( - tokenizer_pre == "gpt3-finnish") { + } else if (tokenizer_pre == "gpt3-finnish") { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH; - } else if ( - tokenizer_pre == "exaone") { + } else if (tokenizer_pre == "exaone") { pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE; - } else if ( - tokenizer_pre == "exaone4") { + } else if (tokenizer_pre == "exaone4") { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2; - } else if ( - tokenizer_pre == "exaone-moe") { + } else if (tokenizer_pre == "exaone-moe") { pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE; - } else if ( - tokenizer_pre == "chameleon") { - pre_type = LLAMA_VOCAB_PRE_TYPE_CHAMELEON; - add_bos = true; + } else if (tokenizer_pre == "chameleon") { + pre_type = LLAMA_VOCAB_PRE_TYPE_CHAMELEON; + add_bos = true; clean_spaces = false; - } else if ( - tokenizer_pre == "minerva-7b") { + } else if (tokenizer_pre == "minerva-7b") { pre_type = LLAMA_VOCAB_PRE_TYPE_MINERVA; - } else if ( - tokenizer_pre == "megrez") { + } else if (tokenizer_pre == "megrez") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; - } else if ( - tokenizer_pre == "gpt-4o" || - tokenizer_pre == "llama4" || - tokenizer_pre == "kanana2") { - pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O; + } else if (tokenizer_pre == "gpt-4o" || tokenizer_pre == "llama4" || tokenizer_pre == "kanana2") { + pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O; clean_spaces = false; - } else if ( - tokenizer_pre == "tiny_aya") { - pre_type = LLAMA_VOCAB_PRE_TYPE_TINY_AYA; + } else if (tokenizer_pre == "tiny_aya") { + pre_type = LLAMA_VOCAB_PRE_TYPE_TINY_AYA; clean_spaces = false; - } else if ( - tokenizer_pre == "superbpe") { - pre_type = LLAMA_VOCAB_PRE_TYPE_SUPERBPE; + } else if (tokenizer_pre == "superbpe") { + pre_type = LLAMA_VOCAB_PRE_TYPE_SUPERBPE; clean_spaces = false; - } else if ( - tokenizer_pre == "trillion") { - pre_type = LLAMA_VOCAB_PRE_TYPE_TRILLION; + } else if (tokenizer_pre == "trillion") { + pre_type = LLAMA_VOCAB_PRE_TYPE_TRILLION; clean_spaces = false; - } else if ( - tokenizer_pre == "granite-docling") { - pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_DOCLING; + } else if (tokenizer_pre == "granite-docling") { + pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_DOCLING; clean_spaces = false; - } else if ( - tokenizer_pre == "bailingmoe" || - tokenizer_pre == "bailingmoe2" || - tokenizer_pre == "llada-moe") { - pre_type = LLAMA_VOCAB_PRE_TYPE_BAILINGMOE; + } else if (tokenizer_pre == "bailingmoe" || tokenizer_pre == "bailingmoe2" || + tokenizer_pre == "llada-moe") { + pre_type = LLAMA_VOCAB_PRE_TYPE_BAILINGMOE; clean_spaces = false; - } else if ( - tokenizer_pre == "seed-coder") { - pre_type = LLAMA_VOCAB_PRE_TYPE_SEED_CODER; + } else if (tokenizer_pre == "seed-coder") { + pre_type = LLAMA_VOCAB_PRE_TYPE_SEED_CODER; clean_spaces = false; - } else if ( - tokenizer_pre == "hunyuan") { - pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN; + } else if (tokenizer_pre == "hunyuan") { + pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN; clean_spaces = false; - } else if ( - tokenizer_pre == "hunyuan-dense") { - pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN_DENSE; + } else if (tokenizer_pre == "hunyuan-dense") { + pre_type = LLAMA_VOCAB_PRE_TYPE_HUNYUAN_DENSE; clean_spaces = false; - } else if ( - tokenizer_pre == "joyai-llm") { - pre_type = LLAMA_VOCAB_PRE_TYPE_JOYAI_LLM; + } else if (tokenizer_pre == "joyai-llm") { + pre_type = LLAMA_VOCAB_PRE_TYPE_JOYAI_LLM; clean_spaces = false; - } else if ( - tokenizer_pre == "kimi-k2") { - pre_type = LLAMA_VOCAB_PRE_TYPE_KIMI_K2; + } else if (tokenizer_pre == "kimi-k2") { + pre_type = LLAMA_VOCAB_PRE_TYPE_KIMI_K2; clean_spaces = false; - } else if ( - tokenizer_pre == "grok-2") { - pre_type = LLAMA_VOCAB_PRE_TYPE_GROK_2; + } else if (tokenizer_pre == "grok-2") { + pre_type = LLAMA_VOCAB_PRE_TYPE_GROK_2; clean_spaces = false; - } else if ( - tokenizer_pre == "afmoe") { - pre_type = LLAMA_VOCAB_PRE_TYPE_AFMOE; + } else if (tokenizer_pre == "afmoe") { + pre_type = LLAMA_VOCAB_PRE_TYPE_AFMOE; clean_spaces = false; - } else if ( - tokenizer_pre == "minimax-m2") { - pre_type = LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2; + } else if (tokenizer_pre == "minimax-m2") { + pre_type = LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2; clean_spaces = false; - } else if ( - tokenizer_pre == "solar-open") { - pre_type = LLAMA_VOCAB_PRE_TYPE_SOLAR_OPEN; + } else if (tokenizer_pre == "solar-open") { + pre_type = LLAMA_VOCAB_PRE_TYPE_SOLAR_OPEN; clean_spaces = false; } else { throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str())); } } else if (type == LLAMA_VOCAB_TYPE_SPM) { - pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; + pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; add_space_prefix = true; - clean_spaces = false; - add_bos = true; - add_eos = false; + clean_spaces = false; + add_bos = true; + add_eos = false; } else if (type == LLAMA_VOCAB_TYPE_WPM) { - pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; + pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; add_space_prefix = false; - clean_spaces = true; - add_bos = true; - add_eos = false; - add_sep = true; + clean_spaces = true; + add_bos = true; + add_eos = false; + add_sep = true; } else if (type == LLAMA_VOCAB_TYPE_UGM) { pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; - add_bos = false; - add_eos = true; + add_bos = false; + add_eos = true; } else if (type == LLAMA_VOCAB_TYPE_RWKV) { - pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; + pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; add_space_prefix = false; - clean_spaces = false; - add_bos = false; - add_eos = false; + clean_spaces = false; + add_bos = false; + add_eos = false; } else { pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT; } - ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, add_space_prefix, false); + ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, add_space_prefix, false); ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, remove_extra_whitespaces, false); } @@ -2214,24 +2167,26 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { const uint32_t n_tokens = gguf_get_arr_n(ctx, token_idx); - const float * scores = nullptr; - const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str()); + const float * scores = nullptr; + const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str()); if (score_idx != -1) { const uint32_t n_scores = gguf_get_arr_n(ctx, score_idx); if (n_scores < n_tokens) { - throw std::runtime_error("Index out of array bounds for scores (" + std::to_string(n_scores) + " < " + std::to_string(n_tokens) + ")\n"); + throw std::runtime_error("Index out of array bounds for scores (" + std::to_string(n_scores) + " < " + + std::to_string(n_tokens) + ")\n"); } - scores = (const float * ) gguf_get_arr_data(ctx, score_idx); + scores = (const float *) gguf_get_arr_data(ctx, score_idx); } - const int * toktypes = nullptr; - const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str()); + const int * toktypes = nullptr; + const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str()); if (toktype_idx != -1) { const uint32_t n_toktypes = gguf_get_arr_n(ctx, toktype_idx); if (n_toktypes < n_tokens) { - throw std::runtime_error("Index out of array bounds for toktypes (" + std::to_string(n_toktypes) + " < " + std::to_string(n_tokens) + ")\n"); + throw std::runtime_error("Index out of array bounds for toktypes (" + std::to_string(n_toktypes) + " < " + + std::to_string(n_tokens) + ")\n"); } - toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx); + toktypes = (const int *) gguf_get_arr_data(ctx, toktype_idx); } id_to_token.resize(n_tokens); @@ -2244,23 +2199,39 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { } token_to_id[word] = i; - max_token_len = std::max(max_token_len, (int) word.size()); + max_token_len = std::max(max_token_len, (int) word.size()); auto & token_data = id_to_token[i]; - token_data.text = std::move(word); - token_data.score = scores ? scores[i] : 0.0f; - token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; + token_data.text = std::move(word); + token_data.score = scores ? scores[i] : 0.0f; + token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file - switch(toktypes[i]) { - case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break; - case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break; - case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break; - case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break; - case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break; - case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break; - case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break; - default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break; + switch (toktypes[i]) { + case LLAMA_TOKEN_TYPE_UNKNOWN: + token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; + break; + case LLAMA_TOKEN_TYPE_UNUSED: + token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; + break; + case LLAMA_TOKEN_TYPE_NORMAL: + token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; + break; + case LLAMA_TOKEN_TYPE_CONTROL: + token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; + break; + case LLAMA_TOKEN_TYPE_USER_DEFINED: + token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; + break; + case LLAMA_TOKEN_TYPE_BYTE: + token_data.attr = LLAMA_TOKEN_ATTR_BYTE; + break; + case LLAMA_TOKEN_TYPE_UNDEFINED: + token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; + break; + default: + token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; + break; } } } @@ -2273,7 +2244,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { try { linefeed_id = vocab.byte_to_token('\n'); } catch (const std::exception & e) { - LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what()); + LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", + __func__, e.what()); linefeed_id = special_pad_id; } } else if (type == LLAMA_VOCAB_TYPE_WPM) { @@ -2297,38 +2269,38 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { // special tokens { const std::vector> special_token_types = { - { LLM_KV_TOKENIZER_BOS_ID, special_bos_id }, - { LLM_KV_TOKENIZER_EOS_ID, special_eos_id }, - { LLM_KV_TOKENIZER_EOT_ID, special_eot_id }, - { LLM_KV_TOKENIZER_EOM_ID, special_eom_id }, - { LLM_KV_TOKENIZER_UNK_ID, special_unk_id }, - { LLM_KV_TOKENIZER_SEP_ID, special_sep_id }, - { LLM_KV_TOKENIZER_PAD_ID, special_pad_id }, - { LLM_KV_TOKENIZER_MASK_ID, special_mask_id }, - { LLM_KV_TOKENIZER_FIM_PRE_ID, special_fim_pre_id }, - { LLM_KV_TOKENIZER_FIM_SUF_ID, special_fim_suf_id }, - { LLM_KV_TOKENIZER_FIM_MID_ID, special_fim_mid_id }, - { LLM_KV_TOKENIZER_FIM_PAD_ID, special_fim_pad_id }, - { LLM_KV_TOKENIZER_FIM_REP_ID, special_fim_rep_id }, - { LLM_KV_TOKENIZER_FIM_SEP_ID, special_fim_sep_id }, - - // deprecated - { LLM_KV_TOKENIZER_PREFIX_ID, special_fim_pre_id }, - { LLM_KV_TOKENIZER_SUFFIX_ID, special_fim_suf_id }, - { LLM_KV_TOKENIZER_MIDDLE_ID, special_fim_mid_id }, + {LLM_KV_TOKENIZER_BOS_ID, special_bos_id }, + { LLM_KV_TOKENIZER_EOS_ID, special_eos_id }, + { LLM_KV_TOKENIZER_EOT_ID, special_eot_id }, + { LLM_KV_TOKENIZER_EOM_ID, special_eom_id }, + { LLM_KV_TOKENIZER_UNK_ID, special_unk_id }, + { LLM_KV_TOKENIZER_SEP_ID, special_sep_id }, + { LLM_KV_TOKENIZER_PAD_ID, special_pad_id }, + { LLM_KV_TOKENIZER_MASK_ID, special_mask_id }, + { LLM_KV_TOKENIZER_FIM_PRE_ID, special_fim_pre_id}, + { LLM_KV_TOKENIZER_FIM_SUF_ID, special_fim_suf_id}, + { LLM_KV_TOKENIZER_FIM_MID_ID, special_fim_mid_id}, + { LLM_KV_TOKENIZER_FIM_PAD_ID, special_fim_pad_id}, + { LLM_KV_TOKENIZER_FIM_REP_ID, special_fim_rep_id}, + { LLM_KV_TOKENIZER_FIM_SEP_ID, special_fim_sep_id}, + + // deprecated + { LLM_KV_TOKENIZER_PREFIX_ID, special_fim_pre_id}, + { LLM_KV_TOKENIZER_SUFFIX_ID, special_fim_suf_id}, + { LLM_KV_TOKENIZER_MIDDLE_ID, special_fim_mid_id}, }; for (const auto & it : special_token_types) { const std::string & key = kv(std::get<0>(it)); - int32_t & id = std::get<1>(it); + int32_t & id = std::get<1>(it); uint32_t new_id; if (!ml.get_key(std::get<0>(it), new_id, false)) { continue; } if (new_id >= id_to_token.size()) { - LLAMA_LOG_WARN("%s: bad special token: '%s' = %u, using default id %d\n", - __func__, key.c_str(), new_id, id); + LLAMA_LOG_WARN("%s: bad special token: '%s' = %u, using default id %d\n", __func__, key.c_str(), new_id, + id); } else { id = new_id; } @@ -2353,7 +2325,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { if (pre_type == LLAMA_VOCAB_PRE_TYPE_GEMMA4 && !add_bos) { add_bos = true; - LLAMA_LOG_WARN("%s: override '%s' to 'true' for Gemma4\n", __func__, kv(LLM_KV_TOKENIZER_ADD_BOS).c_str()); + LLAMA_LOG_WARN("%s: override '%s' to 'true' for Gemma4\n", __func__, + kv(LLM_KV_TOKENIZER_ADD_BOS).c_str()); } } @@ -2366,23 +2339,18 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { // find EOT token: "<|eot_id|>", "<|im_end|>", "", etc. if (special_eot_id == LLAMA_TOKEN_NULL) { - if (false - || t.first == "<|eot_id|>" - || t.first == "<|im_end|>" - || t.first == "<|end|>" - || t.first == "" - || t.first == "<|endoftext|>" - || t.first == "<|end_of_text|>" // granite - || t.first == "" - || t.first == "_" - || t.first == "[EOT]" // Kimi-K2 - || t.first == "<|end▁of▁sentence|>" // DeepSeek - || t.first == "" // smoldocling - ) { + if (false || t.first == "<|eot_id|>" || t.first == "<|im_end|>" || t.first == "<|end|>" || + t.first == "" || t.first == "<|endoftext|>" || t.first == "<|end_of_text|>" // granite + || t.first == "" || t.first == "_" || t.first == "[EOT]" // Kimi-K2 + || t.first == "<|end▁of▁sentence|>" // DeepSeek + || t.first == "" // smoldocling + ) { special_eot_id = t.second; if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) { - LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n", - __func__, t.second, t.first.c_str()); + LLAMA_LOG_WARN( + "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the " + "model. its type will be overridden\n", + __func__, t.second, t.first.c_str()); attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL); } } @@ -2390,13 +2358,13 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { // find EOM token: "<|eom_id|>" if (special_eom_id == LLAMA_TOKEN_NULL) { - if (false - || t.first == "<|eom_id|>" - ) { + if (false || t.first == "<|eom_id|>") { special_eom_id = t.second; if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) { - LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n", - __func__, t.second, t.first.c_str()); + LLAMA_LOG_WARN( + "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the " + "model. its type will be overridden\n", + __func__, t.second, t.first.c_str()); attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL); } } @@ -2404,20 +2372,19 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { // find FIM_PRE token: "<|fim_prefix|>", "", "
", etc.
             if (special_fim_pre_id == LLAMA_TOKEN_NULL) {
-                if (false
-                        || t.first == "<|fim_prefix|>"  // Qwen
-                        || t.first == ""
-                        || t.first == ""    // Granite
-                        || t.first == "<|fim▁begin|>" // DeepSeek
-                        || t.first == "
"
-                        || t.first == "▁
"          // CodeLlama
-                        || t.first == "<|code_prefix|>" // GLM-4.5
-                        || t.first == "<|prefix|>"      // Falcon-H1-Tiny-Coder
-                        ) {
+                if (false || t.first == "<|fim_prefix|>"                       // Qwen
+                    || t.first == "" || t.first == ""  // Granite
+                    || t.first == "<|fim▁begin|>"                            // DeepSeek
+                    || t.first == "
" || t.first == "▁
"               // CodeLlama
+                    || t.first == "<|code_prefix|>"                            // GLM-4.5
+                    || t.first == "<|prefix|>"                                 // Falcon-H1-Tiny-Coder
+                ) {
                     special_fim_pre_id = t.second;
                     if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_WARN(
+                            "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                            "model. its type will be overridden\n",
+                            __func__, t.second, t.first.c_str());
                         attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                     }
                 }
@@ -2425,20 +2392,19 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
 
             // find FIM_SUF token: "<|fim_suffix|>", "", "", etc.
             if (special_fim_suf_id == LLAMA_TOKEN_NULL) {
-                if (false
-                        || t.first == "<|fim_suffix|>" // Qwen
-                        || t.first == ""
-                        || t.first == ""   // Granite
-                        || t.first == "<|fim▁hole|>" // DeepSeek
-                        || t.first == ""
-                        || t.first == "▁"         // CodeLlama
-                        || t.first == "<|code_suffix|>" // GLM-4.5
-                        || t.first == "<|suffix|>"      // Falcon-H1-Tiny-Coder
-                        ) {
+                if (false || t.first == "<|fim_suffix|>"                       // Qwen
+                    || t.first == "" || t.first == ""  // Granite
+                    || t.first == "<|fim▁hole|>"                             // DeepSeek
+                    || t.first == "" || t.first == "▁"               // CodeLlama
+                    || t.first == "<|code_suffix|>"                            // GLM-4.5
+                    || t.first == "<|suffix|>"                                 // Falcon-H1-Tiny-Coder
+                ) {
                     special_fim_suf_id = t.second;
                     if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_WARN(
+                            "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                            "model. its type will be overridden\n",
+                            __func__, t.second, t.first.c_str());
                         attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                     }
                 }
@@ -2446,20 +2412,19 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
 
             // find FIM_MID token: "<|fim_middle|>", "", "", etc.
             if (special_fim_mid_id == LLAMA_TOKEN_NULL) {
-                if (false
-                        || t.first == "<|fim_middle|>" // Qwen
-                        || t.first == ""
-                        || t.first == ""   // Granite
-                        || t.first == "<|fim▁end|>"  // DeepSeek
-                        || t.first == ""
-                        || t.first == "▁"         // CodeLlama
-                        || t.first == "<|code_middle|>" // GLM-4.5
-                        || t.first == "<|middle|>"      // Falcon-H1-Tiny-Coder
-                        ) {
+                if (false || t.first == "<|fim_middle|>"                       // Qwen
+                    || t.first == "" || t.first == ""  // Granite
+                    || t.first == "<|fim▁end|>"                              // DeepSeek
+                    || t.first == "" || t.first == "▁"               // CodeLlama
+                    || t.first == "<|code_middle|>"                            // GLM-4.5
+                    || t.first == "<|middle|>"                                 // Falcon-H1-Tiny-Coder
+                ) {
                     special_fim_mid_id = t.second;
                     if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_WARN(
+                            "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                            "model. its type will be overridden\n",
+                            __func__, t.second, t.first.c_str());
                         attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                     }
                 }
@@ -2467,17 +2432,16 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
 
             // find FIM_PAD token: "<|fim_pad|>", "", "", etc.
             if (special_fim_pad_id == LLAMA_TOKEN_NULL) {
-                if (false
-                        || t.first == "<|fim_pad|>" // Qwen
-                        || t.first == ""
-                        || t.first == ""   // Granite
-                        || t.first == ""
-                        || t.first == "[PAD]" // Kimi-K2
-                        ) {
+                if (false || t.first == "<|fim_pad|>"                    // Qwen
+                    || t.first == "" || t.first == ""  // Granite
+                    || t.first == "" || t.first == "[PAD]"          // Kimi-K2
+                ) {
                     special_fim_pad_id = t.second;
                     if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_WARN(
+                            "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                            "model. its type will be overridden\n",
+                            __func__, t.second, t.first.c_str());
                         attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                     }
                 }
@@ -2485,17 +2449,16 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
 
             // find FIM_REP token: "<|fim_repo|>", "", "", etc.
             if (special_fim_rep_id == LLAMA_TOKEN_NULL) {
-                if (false
-                        || t.first == "<|fim_repo|>"  // Qwen
-                        || t.first == "<|repo_name|>"
-                        || t.first == ""
-                        || t.first == ""
-                        || t.first == ""    // Granite
-                        ) {
+                if (false || t.first == "<|fim_repo|>"  // Qwen
+                    || t.first == "<|repo_name|>" || t.first == "" || t.first == "" ||
+                    t.first == ""             // Granite
+                ) {
                     special_fim_rep_id = t.second;
                     if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_WARN(
+                            "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                            "model. its type will be overridden\n",
+                            __func__, t.second, t.first.c_str());
                         attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                     }
                 }
@@ -2503,13 +2466,14 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
 
             // find FIM_SEP token: "<|file_sep|>"
             if (special_fim_sep_id == LLAMA_TOKEN_NULL) {
-                if (false
-                        || t.first == "<|file_sep|>" // Qwen
-                        ) {
+                if (false || t.first == "<|file_sep|>"  // Qwen
+                ) {
                     special_fim_sep_id = t.second;
                     if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                        LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_WARN(
+                            "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                            "model. its type will be overridden\n",
+                            __func__, t.second, t.first.c_str());
                         attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                     }
                 }
@@ -2562,41 +2526,36 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
         for (const auto & t : token_to_id) {
             auto & attr = id_to_token[t.second].attr;
 
-            if (false
-                    || t.first == "<|eot_id|>"
-                    || t.first == "<|im_end|>"
-                    || t.first == "<|end|>"
-                    || t.first == "<|return|>" // o200k_harmony
-                    || t.first == "<|call|>"   // o200k_harmony
-                    || t.first == "<|flush|>"  // solar-open
-                    || t.first == "<|calls|>"  // solar-open
-                    || t.first == ""
-                    || t.first == "<|endoftext|>"
-                    || t.first == ""      // paddleocr
-                    || t.first == "<|eom_id|>"
-                    || t.first == ""
-                    || t.first == "_"
-                    || t.first == "[EOT]" // Kimi-K2
-                    || t.first == "[EOS]" // Kimi-K2
-                    || t.first == "<|end_of_text|>"
-                    || t.first == "" // smoldocling
-                    || t.first == ""            // gemma4
-                    || t.first == ""          // gemma4
-                    || t.first == "<|tool_response>" // gemma4
-                    || t.first == "<|end▁of▁sentence|>" // deepseek-ocr
-               ) {
+            if (false || t.first == "<|eot_id|>" || t.first == "<|im_end|>" || t.first == "<|end|>" ||
+                t.first == "<|return|>"                                                           // o200k_harmony
+                || t.first == "<|call|>"                                                          // o200k_harmony
+                || t.first == "<|flush|>"                                                         // solar-open
+                || t.first == "<|calls|>"                                                         // solar-open
+                || t.first == "" || t.first == "<|endoftext|>" || t.first == ""  // paddleocr
+                || t.first == "<|eom_id|>" || t.first == "" || t.first == "_" ||
+                t.first == "[EOT]"                                                                // Kimi-K2
+                || t.first == "[EOS]"                                                             // Kimi-K2
+                || t.first == "<|end_of_text|>" || t.first == ""                // smoldocling
+                || t.first == ""                                                             // gemma4
+                || t.first == ""                                                           // gemma4
+                || t.first == "<|tool_response>"                                                  // gemma4
+                || t.first == "<|end_of_sentence|>"                                               // paddleocr
+                || t.first == "<|end▁of▁sentence|>"                                             // deepseek-ocr
+            ) {
                 special_eog_ids.insert(t.second);
                 if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
-                    LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
-                            __func__, t.second, t.first.c_str());
+                    LLAMA_LOG_WARN(
+                        "%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the "
+                        "model. its type will be overridden\n",
+                        __func__, t.second, t.first.c_str());
                     attr = (llama_token_attr) (attr | LLAMA_TOKEN_ATTR_CONTROL);
                 }
             } else {
                 if (attr & LLAMA_TOKEN_ATTR_CONTROL && !(attr & LLAMA_TOKEN_ATTR_UNUSED)) {
                     // token is control, but not marked as EOG -> print a debug log
                     if (special_eog_ids.count(t.second) == 0) {
-                        LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n",
-                                __func__, t.second, t.first.c_str());
+                        LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n", __func__, t.second,
+                                        t.first.c_str());
                     }
                 }
             }
@@ -2606,9 +2565,10 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
         for (const auto & t : token_to_id) {
             auto & attr = id_to_token[t.second].attr;
 
-            if (t.first == "<|channel|>" || t.first == "<|message|>" || t.first == "<|start|>" || t.first == "<|constrain|>") {
+            if (t.first == "<|channel|>" || t.first == "<|message|>" || t.first == "<|start|>" ||
+                t.first == "<|constrain|>") {
                 LLAMA_LOG_WARN("%s: setting token '%s' (%d) attribute to USER_DEFINED (%u), old attributes: %u\n",
-                        __func__, t.first.c_str(), t.second, LLAMA_TOKEN_ATTR_USER_DEFINED, attr);
+                               __func__, t.first.c_str(), t.second, LLAMA_TOKEN_ATTR_USER_DEFINED, attr);
 
                 attr = LLAMA_TOKEN_ATTR_USER_DEFINED;
             }
@@ -2617,17 +2577,20 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
         // sanity checks
         if (special_eos_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eos_id) == 0) {
             special_eog_ids.insert(special_eos_id);
-            LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
+            LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n",
+                           __func__);
         }
 
         if (special_eot_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eot_id) == 0) {
             special_eog_ids.insert(special_eot_id);
-            LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
+            LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n",
+                           __func__);
         }
 
         if (special_eom_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eom_id) == 0) {
             special_eog_ids.insert(special_eom_id);
-            LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
+            LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n",
+                           __func__);
         }
 
         // TODO: workaround for o200k_harmony and solar-open tokenizer: the "<|end|>" token should not be EOG
@@ -2655,7 +2618,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
                     has_flush = true;
                 } else if (text == "<|end|>") {
                     has_end = true;
-                    end_id = tid;
+                    end_id  = tid;
                 }
             }
 
@@ -2663,16 +2626,19 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
                 special_eog_ids.erase(end_id);
 
                 auto & attr = id_to_token[end_id].attr;
-                attr = LLAMA_TOKEN_ATTR_USER_DEFINED;
+                attr        = LLAMA_TOKEN_ATTR_USER_DEFINED;
 
-                LLAMA_LOG_WARN("%s: special_eog_ids contains both '<|return|>' and '<|call|>', or '<|calls|>' and '<|flush|>' tokens, removing '<|end|>' token from EOG list\n", __func__);
+                LLAMA_LOG_WARN(
+                    "%s: special_eog_ids contains both '<|return|>' and '<|call|>', or '<|calls|>' and '<|flush|>' "
+                    "tokens, removing '<|end|>' token from EOG list\n",
+                    __func__);
             }
         }
 
         // workaround for gemma4 and paddleocr: do not include  as an eog token
         {
             bool has_tool_response = false;
-            bool has_s = false;
+            bool has_s             = false;
 
             llama_token s_id = LLAMA_TOKEN_NULL;
 
@@ -2682,7 +2648,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
                     has_tool_response = true;
                 } else if (text == "") {
                     has_s = true;
-                    s_id = tid;
+                    s_id  = tid;
                 }
             }
 
@@ -2690,9 +2656,10 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
                 special_eog_ids.erase(s_id);
 
                 auto & attr = id_to_token[s_id].attr;
-                attr = LLAMA_TOKEN_ATTR_NORMAL;
+                attr        = LLAMA_TOKEN_ATTR_NORMAL;
 
-                LLAMA_LOG_WARN("%s: special_eog_ids contains '<|tool_response>', removing '' token from EOG list\n", __func__);
+                LLAMA_LOG_WARN("%s: special_eog_ids contains '<|tool_response>', removing '' token from EOG list\n",
+                               __func__);
             }
         }
     }
@@ -2700,16 +2667,16 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
     // build special tokens cache
     {
         for (llama_token id = 0; id < (llama_token) n_tokens; ++id) {
-            if (id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
+            if (id_to_token[id].attr &
+                (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
                 cache_special_tokens.push_back(id);
             }
         }
 
         std::sort(cache_special_tokens.begin(), cache_special_tokens.end(),
-            [&] (const llama_token a, const llama_token b) {
-                return id_to_token[a].text.size() > id_to_token[b].text.size();
-            }
-        );
+                  [&](const llama_token a, const llama_token b) {
+                      return id_to_token[a].text.size() > id_to_token[b].text.size();
+                  });
 
         LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t) cache_special_tokens.size());
     }
@@ -2736,7 +2703,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
     //NOTE: Per token attributes are missing from the GGUF file.
     //TODO: Extract attributes from GGUF file.
     {
-        auto _contains_any = [] (const std::string & str, const std::vector & substrs) -> bool {
+        auto _contains_any = [](const std::string & str, const std::vector & substrs) -> bool {
             for (const auto & substr : substrs) {
                 if (str.find(substr) != std::string::npos) {
                     return true;
@@ -2745,13 +2712,13 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
             return false;
         };
 
-        auto _set_tokenid_attr = [&] (const llama_token id, llama_token_attr attr, bool value) {
-            uint32_t current = id_to_token.at(id).attr;
-            current = value ? (current | attr) : (current & ~attr);
+        auto _set_tokenid_attr = [&](const llama_token id, llama_token_attr attr, bool value) {
+            uint32_t current     = id_to_token.at(id).attr;
+            current              = value ? (current | attr) : (current & ~attr);
             id_to_token[id].attr = (llama_token_attr) current;
         };
 
-        auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
+        auto _set_token_attr = [&](const std::string & token, llama_token_attr attr, bool value) {
             _set_tokenid_attr(token_to_id.at(token), attr, value);
         };
 
@@ -2759,42 +2726,36 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
         std::string tokenizer_pre;
         std::string general_arch;
 
-        ml.get_key(LLM_KV_GENERAL_NAME,  model_name,    false);
+        ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
         ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
         ml.get_key(LLM_KV_GENERAL_ARCHITECTURE, general_arch, false);
 
         // model name to lowercase
         std::transform(model_name.begin(), model_name.end(), model_name.begin(),
-            [] (const std::string::value_type x) {
-                return std::tolower(x);
-            }
-        );
+                       [](const std::string::value_type x) { return std::tolower(x); });
 
         // set attributes by model/tokenizer/architecture name
-        if (false
-                || _contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})
-                || _contains_any(general_arch, {"nomic-bert-moe", "jina-bert-v3"})
-           ) {
+        if (false || _contains_any(tokenizer_pre, { "jina-v2-de", "jina-v2-es", "jina-v2-code" }) ||
+            _contains_any(general_arch, { "nomic-bert-moe", "jina-bert-v3" })) {
             if (token_to_id.count("") == 0) {
                 LLAMA_LOG_WARN("%s: Mask token is missing in vocab, please reconvert model!\n", __func__);
             } else {
                 _set_token_attr("", LLAMA_TOKEN_ATTR_LSTRIP, true);
             }
-        } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
+        } else if (_contains_any(model_name, { "phi-3", "phi3" })) {
             for (auto id : cache_special_tokens) {
                 _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
             }
-            for (const auto * token : {""}) {
+            for (const auto * token : { "" }) {
                 _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
             }
-            for (const auto * token : {"", "", "<|endoftext|>"}) {
+            for (const auto * token : { "", "", "<|endoftext|>" }) {
                 _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
             }
-        } else if (_contains_any(model_name, {"modern-bert"})) {
-            if (token_to_id.count("[MASK]") == 0 ) {
+        } else if (_contains_any(model_name, { "modern-bert" })) {
+            if (token_to_id.count("[MASK]") == 0) {
                 LLAMA_LOG_WARN("%s: Mask token missing in vocab!\n", __func__);
-            }
-            else {
+            } else {
                 _set_token_attr("[MASK]", LLAMA_TOKEN_ATTR_LSTRIP, true);
             }
         }
@@ -2805,16 +2766,24 @@ enum llama_vocab_type llama_vocab::impl::get_type() const {
     return type;
 }
 
-std::string llama_vocab::impl::type_name() const{
+std::string llama_vocab::impl::type_name() const {
     switch (type) {
-        case LLAMA_VOCAB_TYPE_NONE:   return "no vocab";
-        case LLAMA_VOCAB_TYPE_SPM:    return "SPM";
-        case LLAMA_VOCAB_TYPE_BPE:    return "BPE";
-        case LLAMA_VOCAB_TYPE_WPM:    return "WPM";
-        case LLAMA_VOCAB_TYPE_UGM:    return "UGM";
-        case LLAMA_VOCAB_TYPE_RWKV:   return "RWKV";
-        case LLAMA_VOCAB_TYPE_PLAMO2: return "PLaMo2";
-        default:                      return "unknown";
+        case LLAMA_VOCAB_TYPE_NONE:
+            return "no vocab";
+        case LLAMA_VOCAB_TYPE_SPM:
+            return "SPM";
+        case LLAMA_VOCAB_TYPE_BPE:
+            return "BPE";
+        case LLAMA_VOCAB_TYPE_WPM:
+            return "WPM";
+        case LLAMA_VOCAB_TYPE_UGM:
+            return "UGM";
+        case LLAMA_VOCAB_TYPE_RWKV:
+            return "RWKV";
+        case LLAMA_VOCAB_TYPE_PLAMO2:
+            return "PLaMo2";
+        default:
+            return "unknown";
     }
 }
 
@@ -2858,18 +2827,21 @@ uint8_t llama_vocab::impl::token_to_byte(llama_token id) const {
     const auto & token_data = id_to_token.at(id);
     switch (get_type()) {
         case LLAMA_VOCAB_TYPE_SPM:
-        case LLAMA_VOCAB_TYPE_UGM: {
-            auto buf = token_data.text.substr(3, 2);
-            return strtol(buf.c_str(), NULL, 16);
-        }
-        case LLAMA_VOCAB_TYPE_BPE: {
-            // Gemma4 uses BPE with SPM-style byte fallback tokens (<0xXX>)
-            auto buf = token_data.text.substr(3, 2);
-            return strtol(buf.c_str(), NULL, 16);
-        }
-        case LLAMA_VOCAB_TYPE_WPM: {
-            GGML_ABORT("fatal error");
-        }
+        case LLAMA_VOCAB_TYPE_UGM:
+            {
+                auto buf = token_data.text.substr(3, 2);
+                return strtol(buf.c_str(), NULL, 16);
+            }
+        case LLAMA_VOCAB_TYPE_BPE:
+            {
+                // Gemma4 uses BPE with SPM-style byte fallback tokens (<0xXX>)
+                auto buf = token_data.text.substr(3, 2);
+                return strtol(buf.c_str(), NULL, 16);
+            }
+        case LLAMA_VOCAB_TYPE_WPM:
+            {
+                GGML_ABORT("fatal error");
+            }
         default:
             GGML_ABORT("fatal error");
     }
@@ -2913,7 +2885,8 @@ void llama_vocab::impl::init_tokenizer(enum llama_vocab_type type) {
 
 // #define PRETOKENIZERDEBUG
 
-void llama_vocab::impl::tokenizer_st_partition(std::forward_list & buffer, bool parse_special) const {
+void llama_vocab::impl::tokenizer_st_partition(std::forward_list & buffer,
+                                               bool                                         parse_special) const {
     // for each special token
     for (const llama_token special_id : cache_special_tokens) {
         const auto & data = vocab.get_token_data(special_id);
@@ -2945,13 +2918,18 @@ void llama_vocab::impl::tokenizer_st_partition(std::forward_listlength(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
+                    LLAMA_LOG_WARN("FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset,
+                                   raw_text_base_length,
+                                   raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
 #endif
                     auto source = std::distance(buffer.begin(), it);
 
@@ -2960,10 +2938,11 @@ void llama_vocab::impl::tokenizer_st_partition(std::forward_list raw_text_base_offset) {
                         // left
                         const int64_t left_reminder_offset = raw_text_base_offset + 0;
-                        int64_t left_reminder_length = match - raw_text_base_offset;
+                        int64_t       left_reminder_length = match - raw_text_base_offset;
 
                         if (data.attr & LLAMA_TOKEN_ATTR_LSTRIP) {
-                            while (left_reminder_length > 0 && isspace(raw_text[left_reminder_offset + left_reminder_length - 1])) {
+                            while (left_reminder_length > 0 &&
+                                   isspace(raw_text[left_reminder_offset + left_reminder_length - 1])) {
                                 left_reminder_length--;
                             }
                         }
@@ -2974,7 +2953,8 @@ void llama_vocab::impl::tokenizer_st_partition(std::forward_listsubstr(left_reminder_offset, left_reminder_length).c_str());
+                        LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length,
+                                       raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
 #endif
                     }
 
@@ -2985,7 +2965,8 @@ void llama_vocab::impl::tokenizer_st_partition(std::forward_list 0 && isspace(raw_text[right_reminder_offset])) {
@@ -3000,7 +2981,8 @@ void llama_vocab::impl::tokenizer_st_partition(std::forward_listsubstr(right_reminder_offset, right_reminder_length).c_str());
+                        LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length,
+                                       raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
 #endif
 
                         if (source == 0) {
@@ -3014,7 +2996,8 @@ void llama_vocab::impl::tokenizer_st_partition(std::forward_listsubstr(raw_text_base_offset, raw_text_base_length).c_str());
+                        LLAMA_LOG_WARN("RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length,
+                                       raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
 #endif
                     } else {
                         if (source == 0) {
@@ -3040,8 +3023,7 @@ std::string llama_vocab::impl::token_to_piece_for_cache(llama_token token, bool
         piece.resize(-n_chars);
         int check = vocab.token_to_piece(token, &piece[0], piece.size(), 0, special);
         GGML_ASSERT(check == -n_chars);
-    }
-    else {
+    } else {
         piece.resize(n_chars);
     }
 
@@ -3076,13 +3058,12 @@ static std::string llama_decode_text(const std::string & text) {
     return decoded_text;
 }
 
-std::vector llama_vocab::impl::tokenize(
-        const std::string & raw_text,
-        bool add_special,
-        bool parse_special) const {
+std::vector llama_vocab::impl::tokenize(const std::string & raw_text,
+                                                     bool                add_special,
+                                                     bool                parse_special) const {
     GGML_ASSERT(tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first.");
 
-    std::vector output;
+    std::vector                   output;
     std::forward_list fragment_buffer;
 
     if (!raw_text.empty()) {
@@ -3118,13 +3099,14 @@ std::vector llama_vocab::impl::tokenize(
                         text += fragment.raw_text.substr(fragment.offset, fragment.length);
 
 #ifdef PRETOKENIZERDEBUG
-                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
+                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length,
+                                       text.c_str());
 #endif
                         llama_escape_whitespace(text);
                         llm_tokenizer_spm_session session(vocab);
                         session.tokenize(text, output);
                         is_prev_special = false;
-                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
+                    } else {  // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         output.push_back(fragment.token);
                         is_prev_special = true;
                     }
@@ -3134,14 +3116,16 @@ std::vector llama_vocab::impl::tokenize(
                     LLAMA_LOG_WARN(
                         "%s: Added a BOS token to the prompt as specified by the model but the prompt "
                         "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
-                        "Are you sure this is what you want?\n", __FUNCTION__);
+                        "Are you sure this is what you want?\n",
+                        __FUNCTION__);
                 }
 
                 if (add_special && add_eos) {
                     GGML_ASSERT(special_eos_id != LLAMA_TOKEN_NULL);
                     output.push_back(special_eos_id);
                 }
-            } break;
+            }
+            break;
         case LLAMA_VOCAB_TYPE_BPE:
             {
                 llm_tokenizer_bpe_session session(vocab, *static_cast(tokenizer.get()));
@@ -3159,10 +3143,11 @@ std::vector llama_vocab::impl::tokenize(
                         }
 
 #ifdef PRETOKENIZERDEBUG
-                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
+                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length,
+                                       text.c_str());
 #endif
                         session.tokenize(text, output);
-                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
+                    } else {  // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         session.append(fragment.token, output);
                     }
                 }
@@ -3171,7 +3156,8 @@ std::vector llama_vocab::impl::tokenize(
                     session.append_eos(output);
                     session.check_double_bos_eos(output);
                 }
-            } break;
+            }
+            break;
         case LLAMA_VOCAB_TYPE_WPM:
             {
                 if (add_special) {
@@ -3186,10 +3172,11 @@ std::vector llama_vocab::impl::tokenize(
                         std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
 
 #ifdef PRETOKENIZERDEBUG
-                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
+                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length,
+                                       text.c_str());
 #endif
                         session.tokenize(text, output);
-                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
+                    } else {  // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         output.push_back(fragment.token);
                     }
                 }
@@ -3198,7 +3185,8 @@ std::vector llama_vocab::impl::tokenize(
                     GGML_ASSERT(special_sep_id != LLAMA_TOKEN_NULL);
                     output.push_back(special_sep_id);
                 }
-            } break;
+            }
+            break;
         case LLAMA_VOCAB_TYPE_UGM:
             {
                 if (add_special && add_bos) {
@@ -3211,10 +3199,11 @@ std::vector llama_vocab::impl::tokenize(
                     if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
                         std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
 #ifdef PRETOKENIZERDEBUG
-                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
+                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length,
+                                       text.c_str());
 #endif
                         session.tokenize(text, output);
-                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
+                    } else {  // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         output.push_back(fragment.token);
                     }
                 }
@@ -3223,14 +3212,16 @@ std::vector llama_vocab::impl::tokenize(
                     LLAMA_LOG_WARN(
                         "%s: Added a BOS token to the prompt as specified by the model but the prompt "
                         "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
-                        "Are you sure this is what you want?\n", __FUNCTION__);
+                        "Are you sure this is what you want?\n",
+                        __FUNCTION__);
                 }
 
                 if (add_special && add_eos) {
                     GGML_ASSERT(special_eos_id != LLAMA_TOKEN_NULL);
                     output.push_back(special_eos_id);
                 }
-            } break;
+            }
+            break;
         case LLAMA_VOCAB_TYPE_RWKV:
             {
                 llm_tokenizer_rwkv_session session(vocab, *static_cast(tokenizer.get()));
@@ -3239,15 +3230,17 @@ std::vector llama_vocab::impl::tokenize(
                         std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
 
 #ifdef PRETOKENIZERDEBUG
-                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
+                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length,
+                                       text.c_str());
 #endif
 
                         session.tokenize(text, output);
-                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
+                    } else {  // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         output.push_back(fragment.token);
                     }
                 }
-            } break;
+            }
+            break;
         case LLAMA_VOCAB_TYPE_PLAMO2:
             {
                 llm_tokenizer_plamo2_session session(*static_cast(tokenizer.get()));
@@ -3256,15 +3249,17 @@ std::vector llama_vocab::impl::tokenize(
                         std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
 
 #ifdef PRETOKENIZERDEBUG
-                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
+                        LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length,
+                                       text.c_str());
 #endif
 
                         session.tokenize(text, output);
-                    } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
+                    } else {  // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         output.push_back(fragment.token);
                     }
                 }
-            } break;
+            }
+            break;
         case LLAMA_VOCAB_TYPE_NONE:
             GGML_ABORT("fatal error");
     }
@@ -3272,17 +3267,21 @@ std::vector llama_vocab::impl::tokenize(
     return output;
 }
 
-int32_t llama_vocab::impl::token_to_piece(llama_token token, char * buf, int32_t length, int32_t lstrip, bool special) const {
+int32_t llama_vocab::impl::token_to_piece(llama_token token,
+                                          char *      buf,
+                                          int32_t     length,
+                                          int32_t     lstrip,
+                                          bool        special) const {
     // ref: https://github.com/ggml-org/llama.cpp/pull/7587#discussion_r1620983843
-    static const int attr_special = LLAMA_TOKEN_ATTR_UNKNOWN | LLAMA_TOKEN_ATTR_CONTROL;
-    const llama_token_attr attr = token_get_attr(token);
+    static const int       attr_special = LLAMA_TOKEN_ATTR_UNKNOWN | LLAMA_TOKEN_ATTR_CONTROL;
+    const llama_token_attr attr         = token_get_attr(token);
     if (!special && (attr & attr_special)) {
         return 0;
     }
 
     // copy piece chars to output text buffer
     // skip up to 'lstrip' leading spaces before copying
-    auto _try_copy = [=] (const char * token, size_t size) -> int32_t {
+    auto _try_copy = [=](const char * token, size_t size) -> int32_t {
         if (size >= static_cast(std::numeric_limits::max())) {
             GGML_ABORT("invalid token size: %zu exceeds int32_t limit", size);
         }
@@ -3291,7 +3290,7 @@ int32_t llama_vocab::impl::token_to_piece(llama_token token, char * buf, int32_t
             token++;
             size--;
         }
-        if (length < (int32_t)size) {
+        if (length < (int32_t) size) {
             return -(int32_t) size;
         }
         memcpy(buf, token, size);
@@ -3313,74 +3312,78 @@ int32_t llama_vocab::impl::token_to_piece(llama_token token, char * buf, int32_t
         switch (get_type()) {
             case LLAMA_VOCAB_TYPE_WPM:
             case LLAMA_VOCAB_TYPE_SPM:
-            case LLAMA_VOCAB_TYPE_UGM: {
-                // NOTE: we accept all unsupported token types,
-                // suppressing them like CONTROL tokens.
-                if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
-                    return _try_copy(token_text.data(), token_text.size());
-                }
-                if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
-                    std::string result = token_text;
-                    llama_unescape_whitespace(result);
-                    return _try_copy(result.data(), result.size());
-                }
-                if (attr & LLAMA_TOKEN_ATTR_BYTE) {
-                    char byte = (char) token_to_byte(token);
-                    return _try_copy((char*) &byte, 1);
-                }
-                break;
-            }
-            case LLAMA_VOCAB_TYPE_BPE: {
-                // NOTE: we accept all unsupported token types,
-                // suppressing them like CONTROL tokens.
-                if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
-                    return _try_copy(token_text.data(), token_text.size());
-                }
-                if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
-                    if (escape_whitespaces) {
-                        // SPM-style BPE: tokens contain ▁ for spaces
+            case LLAMA_VOCAB_TYPE_UGM:
+                {
+                    // NOTE: we accept all unsupported token types,
+                    // suppressing them like CONTROL tokens.
+                    if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
+                        return _try_copy(token_text.data(), token_text.size());
+                    }
+                    if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
                         std::string result = token_text;
                         llama_unescape_whitespace(result);
                         return _try_copy(result.data(), result.size());
                     }
-                    std::string result = llama_decode_text(token_text);
-                    return _try_copy(result.data(), result.size());
+                    if (attr & LLAMA_TOKEN_ATTR_BYTE) {
+                        char byte = (char) token_to_byte(token);
+                        return _try_copy((char *) &byte, 1);
+                    }
+                    break;
                 }
-                if (attr & LLAMA_TOKEN_ATTR_BYTE) {
-                    char byte = (char) token_to_byte(token);
-                    return _try_copy((char*) &byte, 1);
+            case LLAMA_VOCAB_TYPE_BPE:
+                {
+                    // NOTE: we accept all unsupported token types,
+                    // suppressing them like CONTROL tokens.
+                    if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
+                        return _try_copy(token_text.data(), token_text.size());
+                    }
+                    if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
+                        if (escape_whitespaces) {
+                            // SPM-style BPE: tokens contain ▁ for spaces
+                            std::string result = token_text;
+                            llama_unescape_whitespace(result);
+                            return _try_copy(result.data(), result.size());
+                        }
+                        std::string result = llama_decode_text(token_text);
+                        return _try_copy(result.data(), result.size());
+                    }
+                    if (attr & LLAMA_TOKEN_ATTR_BYTE) {
+                        char byte = (char) token_to_byte(token);
+                        return _try_copy((char *) &byte, 1);
+                    }
+                    break;
                 }
-                break;
-            }
-            case LLAMA_VOCAB_TYPE_RWKV: {
-                std::vector result = llama_unescape_rwkv_token(token_text);
+            case LLAMA_VOCAB_TYPE_RWKV:
+                {
+                    std::vector result = llama_unescape_rwkv_token(token_text);
 
-                // If we don't have enough space, return an error
-                if (result.size() > (size_t)length) {
-                    return -(int)result.size();
-                }
+                    // If we don't have enough space, return an error
+                    if (result.size() > (size_t) length) {
+                        return -(int) result.size();
+                    }
 
-                memcpy(buf, result.data(), result.size());
-                return (int)result.size();
-            }
-            case LLAMA_VOCAB_TYPE_PLAMO2: {
-                // PLaMo-2 uses similar token handling as BPE/SPM
-                if (vocab.is_byte(token)) {
-                    // Handle byte tokens like <0xXX>
-                    if (token_text.length() == 6 && token_text.substr(0, 3) == "<0x" && token_text.back() == '>') {
-                        int hex_val = std::stoi(token_text.substr(3, 2), nullptr, 16);
-                        if (length < 1) {
-                            return -1;
+                    memcpy(buf, result.data(), result.size());
+                    return (int) result.size();
+                }
+            case LLAMA_VOCAB_TYPE_PLAMO2:
+                {
+                    // PLaMo-2 uses similar token handling as BPE/SPM
+                    if (vocab.is_byte(token)) {
+                        // Handle byte tokens like <0xXX>
+                        if (token_text.length() == 6 && token_text.substr(0, 3) == "<0x" && token_text.back() == '>') {
+                            int hex_val = std::stoi(token_text.substr(3, 2), nullptr, 16);
+                            if (length < 1) {
+                                return -1;
+                            }
+                            buf[0] = static_cast(hex_val);
+                            return 1;
                         }
-                        buf[0] = static_cast(hex_val);
-                        return 1;
                     }
-                }
 
-                // Normal token - just copy the text
-                std::string result = token_text;
-                return _try_copy(result.data(), result.size());
-            }
+                    // Normal token - just copy the text
+                    std::string result = token_text;
+                    return _try_copy(result.data(), result.size());
+                }
             default:
                 GGML_ABORT("fatal error");
         }
@@ -3393,13 +3396,12 @@ const std::string & llama_vocab::impl::token_to_piece(llama_token token) const {
     return cache_token_to_piece.at(token);
 }
 
-int32_t llama_vocab::impl::detokenize(
-               const llama_token * tokens,
-                         int32_t   n_tokens,
-                            char * text,
-                         int32_t   text_len_max,
-                            bool   remove_special,
-                            bool   unparse_special) const {
+int32_t llama_vocab::impl::detokenize(const llama_token * tokens,
+                                      int32_t             n_tokens,
+                                      char *              text,
+                                      int32_t             text_len_max,
+                                      bool                remove_special,
+                                      bool                unparse_special) const {
     if (type == LLAMA_VOCAB_TYPE_NONE) {
         return 0;
     }
@@ -3429,13 +3431,13 @@ int32_t llama_vocab::impl::detokenize(
     for (int32_t i = 0; i < n_tokens; ++i) {
         GGML_ASSERT(avail >= 0);
         int32_t n_chars = token_to_piece(tokens[i], text, avail, remove_space, unparse_special);
-        remove_space = false;
+        remove_space    = false;
         if (n_chars < 0) {
             avail = 0;
             total -= n_chars;
         } else if (n_chars > 0) {
             avail -= n_chars;
-            text  += n_chars;
+            text += n_chars;
             total += n_chars;
         }
     }
@@ -3449,12 +3451,12 @@ int32_t llama_vocab::impl::detokenize(
 
         // first pass: characters ?!.,  //TODO: where do these characters come from?
         const int32_t total1 = total;
-        total = total ? 1 : 0;
+        total                = total ? 1 : 0;
         for (int32_t i = 1; i < total1; ++i) {
             const char x = text[i];
             if (text[i - 1] == ' ') {
                 if (x == '?' || x == '!' || x == '.' || x == ',') {  // " ?", " !", " .", " ,"
-                    total--;  // remove space
+                    total--;                                         // remove space
                 }
             }
             text[total++] = x;
@@ -3462,19 +3464,19 @@ int32_t llama_vocab::impl::detokenize(
 
         // second pass: strip single apostrophe between spaces
         const int32_t total2 = total;
-        total = total ? 1 : 0;
+        total                = total ? 1 : 0;
         for (int32_t i = 1; i < total2; ++i) {
             const char x = text[i];
             if (x == '\'' && i + 1 < total2 && text[i - 1] == ' ' && text[i + 1] == ' ') {  // " ' "
-                total--;           // remove prev space
-                text[++i] = '\0';  // remove next space
+                total--;                                                                    // remove prev space
+                text[++i] = '\0';                                                           // remove next space
             }
             text[total++] = x;
         }
 
         // third pass: apostrophe contractions  //NOTE: this makes sense?
         const int32_t total3 = total;
-        total = total ? 1 : 0;
+        total                = total ? 1 : 0;
         for (int32_t i = 1; i < total3; ++i) {
             const char x = text[i];
             if (text[i - 1] == ' ') {
@@ -3483,13 +3485,13 @@ int32_t llama_vocab::impl::detokenize(
                     if (x1 == 't' || x1 == 'd') {  // " 't", " 'd"
                         //total--;  // remove space
                     } else if (x1 == 's' || x1 == 'm') {  // " 's", " 'm"
-                        total--;  // remove space
+                        total--;                          // remove space
                     } else if (i + 2 < total3) {
                         const char x2 = text[i + 2];
                         if ((x1 == 'l' && x2 == 'l')) {  // " 'll"
                             //total--;  // remove space
                         } else if ((x1 == 'r' && x2 == 'e') || (x1 == 'v' && x2 == 'e')) {  // " 're", " 've"
-                            total--;  // remove space
+                            total--;                                                        // remove space
                         } else {
                             //total--;  // remove space
                         }
@@ -3506,38 +3508,82 @@ int32_t llama_vocab::impl::detokenize(
 }
 
 void llama_vocab::impl::print_info() const {
-    LLAMA_LOG_INFO("%s: vocab type            = %s\n",     __func__, type_name().c_str());
-    LLAMA_LOG_INFO("%s: n_vocab               = %u\n",     __func__, vocab.n_tokens());
-    LLAMA_LOG_INFO("%s: n_merges              = %u\n",     __func__, (uint32_t) bpe_ranks.size());
+    LLAMA_LOG_INFO("%s: vocab type            = %s\n", __func__, type_name().c_str());
+    LLAMA_LOG_INFO("%s: n_vocab               = %u\n", __func__, vocab.n_tokens());
+    LLAMA_LOG_INFO("%s: n_merges              = %u\n", __func__, (uint32_t) bpe_ranks.size());
 
     // special tokens
-    if (special_bos_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: BOS token             = %d '%s'\n", __func__, special_bos_id,     id_to_token.at(special_bos_id).text.c_str() );  }
-    if (special_eos_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: EOS token             = %d '%s'\n", __func__, special_eos_id,     id_to_token.at(special_eos_id).text.c_str() );  }
-    if (special_eot_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: EOT token             = %d '%s'\n", __func__, special_eot_id,     id_to_token.at(special_eot_id).text.c_str() );  }
-    if (special_eom_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: EOM token             = %d '%s'\n", __func__, special_eom_id,     id_to_token.at(special_eom_id).text.c_str() );  }
-    if (special_unk_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: UNK token             = %d '%s'\n", __func__, special_unk_id,     id_to_token.at(special_unk_id).text.c_str() );  }
-    if (special_sep_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: SEP token             = %d '%s'\n", __func__, special_sep_id,     id_to_token.at(special_sep_id).text.c_str() );  }
-    if (special_pad_id  != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: PAD token             = %d '%s'\n", __func__, special_pad_id,     id_to_token.at(special_pad_id).text.c_str() );  }
-    if (special_mask_id != LLAMA_TOKEN_NULL)    { LLAMA_LOG_INFO( "%s: MASK token            = %d '%s'\n", __func__, special_mask_id,    id_to_token.at(special_mask_id).text.c_str() ); }
-
-    if (linefeed_id != LLAMA_TOKEN_NULL)        { LLAMA_LOG_INFO( "%s: LF token              = %d '%s'\n", __func__, linefeed_id,        id_to_token.at(linefeed_id).text.c_str() ); }
-
-    if (special_fim_pre_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM PRE token         = %d '%s'\n", __func__, special_fim_pre_id, id_to_token.at(special_fim_pre_id).text.c_str() ); }
-    if (special_fim_suf_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM SUF token         = %d '%s'\n", __func__, special_fim_suf_id, id_to_token.at(special_fim_suf_id).text.c_str() ); }
-    if (special_fim_mid_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM MID token         = %d '%s'\n", __func__, special_fim_mid_id, id_to_token.at(special_fim_mid_id).text.c_str() ); }
-    if (special_fim_pad_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM PAD token         = %d '%s'\n", __func__, special_fim_pad_id, id_to_token.at(special_fim_pad_id).text.c_str() ); }
-    if (special_fim_rep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM REP token         = %d '%s'\n", __func__, special_fim_rep_id, id_to_token.at(special_fim_rep_id).text.c_str() ); }
-    if (special_fim_sep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM SEP token         = %d '%s'\n", __func__, special_fim_sep_id, id_to_token.at(special_fim_sep_id).text.c_str() ); }
+    if (special_bos_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: BOS token             = %d '%s'\n", __func__, special_bos_id,
+                       id_to_token.at(special_bos_id).text.c_str());
+    }
+    if (special_eos_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: EOS token             = %d '%s'\n", __func__, special_eos_id,
+                       id_to_token.at(special_eos_id).text.c_str());
+    }
+    if (special_eot_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: EOT token             = %d '%s'\n", __func__, special_eot_id,
+                       id_to_token.at(special_eot_id).text.c_str());
+    }
+    if (special_eom_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: EOM token             = %d '%s'\n", __func__, special_eom_id,
+                       id_to_token.at(special_eom_id).text.c_str());
+    }
+    if (special_unk_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: UNK token             = %d '%s'\n", __func__, special_unk_id,
+                       id_to_token.at(special_unk_id).text.c_str());
+    }
+    if (special_sep_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: SEP token             = %d '%s'\n", __func__, special_sep_id,
+                       id_to_token.at(special_sep_id).text.c_str());
+    }
+    if (special_pad_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: PAD token             = %d '%s'\n", __func__, special_pad_id,
+                       id_to_token.at(special_pad_id).text.c_str());
+    }
+    if (special_mask_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: MASK token            = %d '%s'\n", __func__, special_mask_id,
+                       id_to_token.at(special_mask_id).text.c_str());
+    }
+
+    if (linefeed_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: LF token              = %d '%s'\n", __func__, linefeed_id,
+                       id_to_token.at(linefeed_id).text.c_str());
+    }
+
+    if (special_fim_pre_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: FIM PRE token         = %d '%s'\n", __func__, special_fim_pre_id,
+                       id_to_token.at(special_fim_pre_id).text.c_str());
+    }
+    if (special_fim_suf_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: FIM SUF token         = %d '%s'\n", __func__, special_fim_suf_id,
+                       id_to_token.at(special_fim_suf_id).text.c_str());
+    }
+    if (special_fim_mid_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: FIM MID token         = %d '%s'\n", __func__, special_fim_mid_id,
+                       id_to_token.at(special_fim_mid_id).text.c_str());
+    }
+    if (special_fim_pad_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: FIM PAD token         = %d '%s'\n", __func__, special_fim_pad_id,
+                       id_to_token.at(special_fim_pad_id).text.c_str());
+    }
+    if (special_fim_rep_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: FIM REP token         = %d '%s'\n", __func__, special_fim_rep_id,
+                       id_to_token.at(special_fim_rep_id).text.c_str());
+    }
+    if (special_fim_sep_id != LLAMA_TOKEN_NULL) {
+        LLAMA_LOG_INFO("%s: FIM SEP token         = %d '%s'\n", __func__, special_fim_sep_id,
+                       id_to_token.at(special_fim_sep_id).text.c_str());
+    }
 
     for (const auto & id : special_eog_ids) {
-        LLAMA_LOG_INFO( "%s: EOG token             = %d '%s'\n", __func__, id, id_to_token.at(id).text.c_str() );
+        LLAMA_LOG_INFO("%s: EOG token             = %d '%s'\n", __func__, id, id_to_token.at(id).text.c_str());
     }
 
     LLAMA_LOG_INFO("%s: max token length      = %d\n", __func__, max_token_len);
 }
 
-llama_vocab::llama_vocab() : pimpl(new impl(*this)) {
-}
+llama_vocab::llama_vocab() : pimpl(new impl(*this)) {}
 
 llama_vocab::~llama_vocab() = default;
 
@@ -3569,7 +3615,7 @@ uint32_t llama_vocab::n_token_types() const {
     return (uint32_t) pimpl->n_token_types;
 }
 
-std::string llama_vocab::type_name() const{
+std::string llama_vocab::type_name() const {
     return pimpl->type_name();
 }
 
@@ -3610,26 +3656,29 @@ llama_token llama_vocab::byte_to_token(uint8_t ch) const {
     static const char * hex = "0123456789ABCDEF";
     switch (get_type()) {
         case LLAMA_VOCAB_TYPE_SPM:
-        case LLAMA_VOCAB_TYPE_UGM: {
-            const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
-            auto token = pimpl->token_to_id.find(buf);
-            if (token != pimpl->token_to_id.end()) {
-                return (*token).second;
+        case LLAMA_VOCAB_TYPE_UGM:
+            {
+                const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
+                auto       token  = pimpl->token_to_id.find(buf);
+                if (token != pimpl->token_to_id.end()) {
+                    return (*token).second;
+                }
+                // Try to fall back to just the byte as a string
+                const char buf2[2] = { (char) ch, 0 };
+                return pimpl->token_to_id.at(buf2);
             }
-            // Try to fall back to just the byte as a string
-            const char buf2[2] = { (char)ch, 0 };
-            return pimpl->token_to_id.at(buf2);
-        }
         case LLAMA_VOCAB_TYPE_WPM:
-        case LLAMA_VOCAB_TYPE_BPE: {
-            return pimpl->token_to_id.at(unicode_byte_to_utf8(ch));
-        }
-        case LLAMA_VOCAB_TYPE_PLAMO2: {
-            // PLaMo-2 uses byte tokens in format <0xXX>
-            char hex_str[8];
-            snprintf(hex_str, sizeof(hex_str), "<0x%02X>", ch);
-            return pimpl->token_to_id.at(hex_str);
-        }
+        case LLAMA_VOCAB_TYPE_BPE:
+            {
+                return pimpl->token_to_id.at(unicode_byte_to_utf8(ch));
+            }
+        case LLAMA_VOCAB_TYPE_PLAMO2:
+            {
+                // PLaMo-2 uses byte tokens in format <0xXX>
+                char hex_str[8];
+                snprintf(hex_str, sizeof(hex_str), "<0x%02X>", ch);
+                return pimpl->token_to_id.at(hex_str);
+            }
         default:
             GGML_ABORT("fatal error");
     }
@@ -3776,8 +3825,8 @@ int llama_vocab::max_token_len() const {
 }
 
 int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
-    GGML_ASSERT(token_left.find(' ')   == std::string::npos);
-    GGML_ASSERT(token_right.find(' ')  == std::string::npos);
+    GGML_ASSERT(token_left.find(' ') == std::string::npos);
+    GGML_ASSERT(token_right.find(' ') == std::string::npos);
 
     auto it = pimpl->bpe_ranks.find(std::make_pair(token_left, token_right));
     if (it == pimpl->bpe_ranks.end()) {
@@ -3801,13 +3850,12 @@ std::vector llama_vocab::get_precompiled_charsmap() const {
     return pimpl->precompiled_charsmap;
 }
 
-int32_t llama_vocab::tokenize(
-                  const char * text,
-                     int32_t   text_len,
-                 llama_token * tokens,
-                     int32_t   n_tokens_max,
-                        bool   add_special,
-                        bool   parse_special) const {
+int32_t llama_vocab::tokenize(const char *  text,
+                              int32_t       text_len,
+                              llama_token * tokens,
+                              int32_t       n_tokens_max,
+                              bool          add_special,
+                              bool          parse_special) const {
     auto res = tokenize(std::string(text, text_len), add_special, parse_special);
     if (res.size() >= static_cast(std::numeric_limits::max())) {
         LLAMA_LOG_ERROR("%s: tokenization result size %zu exceeds int32_t limit\n", __func__, res.size());
@@ -3826,10 +3874,9 @@ int32_t llama_vocab::tokenize(
     return res.size();
 }
 
-std::vector llama_vocab::tokenize(
-        const std::string & raw_text,
-        bool add_special,
-        bool parse_special) const {
+std::vector llama_vocab::tokenize(const std::string & raw_text,
+                                               bool                add_special,
+                                               bool                parse_special) const {
     return pimpl->tokenize(raw_text, add_special, parse_special);
 }
 
@@ -3841,24 +3888,25 @@ int32_t llama_vocab::token_to_piece(llama_token token, char * buf, int32_t lengt
     return pimpl->token_to_piece(token, buf, length, lstrip, special);
 }
 
-int32_t llama_vocab::detokenize(
-               const llama_token * tokens,
-                         int32_t   n_tokens,
-                            char * text,
-                         int32_t   text_len_max,
-                            bool   remove_special,
-                            bool   unparse_special) const {
+int32_t llama_vocab::detokenize(const llama_token * tokens,
+                                int32_t             n_tokens,
+                                char *              text,
+                                int32_t             text_len_max,
+                                bool                remove_special,
+                                bool                unparse_special) const {
     return pimpl->detokenize(tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
 }
 
 std::string llama_vocab::detokenize(const std::vector & tokens, bool special) const {
     std::string text;
     text.resize(std::max(text.capacity(), tokens.size()));
-    int32_t n_chars = detokenize(tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
+    int32_t n_chars =
+        detokenize(tokens.data(), (int32_t) tokens.size(), &text[0], (int32_t) text.size(), false, special);
     if (n_chars < 0) {
         text.resize(-n_chars);
-        n_chars = detokenize(tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
-        GGML_ASSERT(n_chars <= (int32_t)text.size());  // whitespace trimming is performed after per-token detokenization
+        n_chars = detokenize(tokens.data(), (int32_t) tokens.size(), &text[0], (int32_t) text.size(), false, special);
+        GGML_ASSERT(n_chars <=
+                    (int32_t) text.size());  // whitespace trimming is performed after per-token detokenization
     }
 
     text.resize(n_chars);
@@ -3929,7 +3977,7 @@ llama_token llama_vocab_sep(const struct llama_vocab * vocab) {
     return vocab->token_sep();
 }
 
-llama_token llama_vocab_nl (const struct llama_vocab * vocab) {
+llama_token llama_vocab_nl(const struct llama_vocab * vocab) {
     return vocab->token_nl();
 }
 
@@ -3973,7 +4021,7 @@ llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab) {
     return vocab->token_fim_sep();
 }
 
-llama_token llama_vocab_mask(const struct llama_vocab* vocab) {
+llama_token llama_vocab_mask(const struct llama_vocab * vocab) {
     return vocab->token_mask();
 }
 
@@ -4020,7 +4068,7 @@ llama_token llama_token_eot(const struct llama_vocab * vocab) {
 // deprecated
 llama_token llama_token_cls(const struct llama_vocab * vocab) {
     //return llama_vocab_cls(vocab);
-    return llama_vocab_bos(vocab); // avoid deprecation warning
+    return llama_vocab_bos(vocab);  // avoid deprecation warning
 }
 
 // deprecated
@@ -4029,7 +4077,7 @@ llama_token llama_token_sep(const struct llama_vocab * vocab) {
 }
 
 // deprecated
-llama_token llama_token_nl (const struct llama_vocab * vocab) {
+llama_token llama_token_nl(const struct llama_vocab * vocab) {
     return llama_vocab_nl(vocab);
 }
 
@@ -4082,34 +4130,34 @@ llama_token llama_token_fim_sep(const struct llama_vocab * vocab) {
 // tokenization
 //
 
-int32_t llama_tokenize(
-    const struct llama_vocab * vocab,
-                  const char * text,
-                     int32_t   text_len,
-                 llama_token * tokens,
-                     int32_t   n_tokens_max,
-                        bool   add_special,
-                        bool   parse_special) {
-    return vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special);
-}
-
-int32_t llama_token_to_piece(
-    const struct llama_vocab * vocab,
-                 llama_token   token,
-                        char * buf,
-                     int32_t   length,
-                     int32_t   lstrip,
-                        bool   special) {
+int32_t llama_tokenize(const struct llama_vocab * vocab,
+                       const char *               text,
+                       int32_t                    text_len,
+                       llama_token *              tokens,
+                       int32_t                    n_tokens_max,
+                       bool                       add_special,
+                       bool                       parse_special) {
+    ggml_trace_log_begin("llama_tokenize", "Tokenizer", NULL);
+    int32_t result = vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special);
+    ggml_trace_log_end("llama_tokenize", "Tokenizer", NULL);
+    return result;
+}
+
+int32_t llama_token_to_piece(const struct llama_vocab * vocab,
+                             llama_token                token,
+                             char *                     buf,
+                             int32_t                    length,
+                             int32_t                    lstrip,
+                             bool                       special) {
     return vocab->token_to_piece(token, buf, length, lstrip, special);
 }
 
-int32_t llama_detokenize(
-    const struct llama_vocab * vocab,
-           const llama_token * tokens,
-                     int32_t   n_tokens,
-                        char * text,
-                     int32_t   text_len_max,
-                        bool   remove_special,
-                        bool   unparse_special) {
+int32_t llama_detokenize(const struct llama_vocab * vocab,
+                         const llama_token *        tokens,
+                         int32_t                    n_tokens,
+                         char *                     text,
+                         int32_t                    text_len_max,
+                         bool                       remove_special,
+                         bool                       unparse_special) {
     return vocab->detokenize(tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
 }
diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt
index a76adc9b80bd..62bd7988efb1 100644
--- a/tools/mtmd/CMakeLists.txt
+++ b/tools/mtmd/CMakeLists.txt
@@ -122,3 +122,58 @@ add_executable(llama-mtmd-debug debug/mtmd-debug.cpp)
 set_target_properties(llama-mtmd-debug PROPERTIES OUTPUT_NAME llama-mtmd-debug)
 target_link_libraries(llama-mtmd-debug PRIVATE llama-common mtmd Threads::Threads)
 target_compile_features(llama-mtmd-debug PRIVATE cxx_std_17)
+
+if(LLAMA_SERVER_SMT_VISION)
+    if(WIN32)
+        message(FATAL_ERROR "LLAMA_SERVER_SMT_VISION is not supported on Windows because the SMT audio backend depends on POSIX dlopen APIs")
+    endif()
+
+    if(NOT DEFINED SPACEMIT_ORT_DIR)
+        message(FATAL_ERROR "SPACEMIT_ORT_DIR must be set when LLAMA_SERVER_SMT_VISION=ON")
+    endif()
+
+    set(SPACEMIT_ORT_INC_DIR "${SPACEMIT_ORT_DIR}/include")
+    set(SPACEMIT_ORT_LIB_DIR "${SPACEMIT_ORT_DIR}/lib")
+    set(SPACEMIT_ORT_SAMPLE_DIR "${SPACEMIT_ORT_DIR}/samples")
+
+    if(NOT EXISTS "${SPACEMIT_ORT_SAMPLE_DIR}/spine_vision_engine.cc")
+        message(FATAL_ERROR "Could not find spine_vision_engine.cc in SPACEMIT_ORT_DIR='${SPACEMIT_ORT_DIR}'")
+    endif()
+    if(NOT EXISTS "${SPACEMIT_ORT_SAMPLE_DIR}/spine_llm_argparser.cc")
+        message(FATAL_ERROR "Could not find spine_llm_argparser.cc in SPACEMIT_ORT_DIR='${SPACEMIT_ORT_DIR}'")
+    endif()
+
+    if(EXISTS "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.so")
+        set(ONNXRUNTIME_LIB "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.so")
+    elseif(EXISTS "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.a")
+        set(ONNXRUNTIME_LIB "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.a")
+    else()
+        message(FATAL_ERROR "Could not find libonnxruntime.{so,a} in SPACEMIT_ORT_DIR='${SPACEMIT_ORT_DIR}'")
+    endif()
+
+    target_sources(${TARGET} PRIVATE
+        mtmd-cli-smt.cpp
+        smt-audio-wrapper.cpp
+        smt-vision-preprocess.cpp
+        smt-vision-wrapper.cpp
+        ${SPACEMIT_ORT_SAMPLE_DIR}/spine_vision_engine.cc
+        ${SPACEMIT_ORT_SAMPLE_DIR}/spine_llm_argparser.cc
+    )
+
+    target_include_directories(${TARGET} PRIVATE
+        .
+        ../..
+        ../../vendor
+        ${SPACEMIT_ORT_SAMPLE_DIR}
+        ${SPACEMIT_ORT_INC_DIR}
+    )
+
+    target_link_libraries(${TARGET} PRIVATE
+        ${ONNXRUNTIME_LIB}
+    )
+    if(CMAKE_DL_LIBS)
+        target_link_libraries(${TARGET} PRIVATE ${CMAKE_DL_LIBS})
+    endif()
+
+    target_compile_definitions(${TARGET} PRIVATE LLAMA_SERVER_SMT_VISION=1)
+endif()
diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp
index 8f0a9875b104..46fa9b58cf98 100644
--- a/tools/mtmd/mtmd-audio.cpp
+++ b/tools/mtmd/mtmd-audio.cpp
@@ -525,6 +525,49 @@ static bool log_mel_spectrogram(
     return true;
 }
 
+bool mtmd_audio_compute_log_mel_spectrogram(const float * samples,
+                                            size_t        n_samples,
+                                            int           n_threads,
+                                            int           n_mel,
+                                            int           n_fft,
+                                            int           window_len,
+                                            int           hop_len,
+                                            int           sample_rate,
+                                            bool          center_padding,
+                                            float         preemph,
+                                            bool          use_natural_log,
+                                            bool          norm_per_feature,
+                                            mtmd_audio_mel & out) {
+    if (samples == nullptr || n_samples == 0 || n_mel <= 0 || n_fft <= 0 || window_len <= 0 || hop_len <= 0 ||
+        sample_rate <= 0) {
+        return false;
+    }
+
+    mtmd_audio_cache cache;
+    cache.fill_sin_cos_table(n_fft);
+    cache.fill_hann_window(window_len, true);
+    cache.fill_mel_filterbank_matrix(n_mel, n_fft, sample_rate);
+
+    filter_params params;
+    params.n_mel            = n_mel;
+    params.n_fft_bins       = 1 + (n_fft / 2);
+    params.hann_window_size = window_len;
+    params.hop_length       = hop_len;
+    params.sample_rate      = sample_rate;
+    params.center_padding   = center_padding;
+    params.preemph          = preemph;
+    params.use_natural_log  = use_natural_log;
+    params.norm_per_feature = norm_per_feature;
+
+    return log_mel_spectrogram(
+            samples,
+            (int) n_samples,
+            std::max(1, n_threads),
+            params,
+            cache,
+            out);
+}
+
 //
 // mtmd_audio_preprocessor_whisper
 //
diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h
index c1a705de522f..e6b363b1f905 100644
--- a/tools/mtmd/mtmd-audio.h
+++ b/tools/mtmd/mtmd-audio.h
@@ -96,6 +96,22 @@ struct mtmd_audio_preprocessor_gemma4a : mtmd_audio_preprocessor {
     mtmd_audio_cache cache;
 };
 
+// Generic helper to compute a log-mel spectrogram with the same implementation used by mtmd.
+// The output layout is [n_mel, n_len] flattened in row-major order per mel bin.
+bool mtmd_audio_compute_log_mel_spectrogram(const float * samples,
+                                            size_t        n_samples,
+                                            int           n_threads,
+                                            int           n_mel,
+                                            int           n_fft,
+                                            int           window_len,
+                                            int           hop_len,
+                                            int           sample_rate,
+                                            bool          center_padding,
+                                            float         preemph,
+                                            bool          use_natural_log,
+                                            bool          norm_per_feature,
+                                            mtmd_audio_mel & out);
+
 //
 // streaming ISTFT - converts spectrogram frames back to audio one frame at a time
 //
diff --git a/tools/mtmd/mtmd-cli-smt.cpp b/tools/mtmd/mtmd-cli-smt.cpp
new file mode 100644
index 000000000000..783ba7ed750d
--- /dev/null
+++ b/tools/mtmd/mtmd-cli-smt.cpp
@@ -0,0 +1,1414 @@
+// Multimodal CLI SMT backend using the SpacemiT SMT ONNX vision engine.
+// Integrated into llama-mtmd-cli and selected via --vision-backend smt
+// LLM inference logic (loading, sampling, generation) is reused from the original mtmd-cli
+
+#include "arg.h"
+#include "log.h"
+#include "common.h"
+#include "sampling.h"
+#include "llama.h"
+#include "ggml.h"
+#include "console.h"
+#include "chat.h"
+#include "smt-audio-wrapper.h"
+#include "smt-vision-wrapper.h"
+#include "smt-vision-preprocess.h"
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
+#include 
+#include 
+#elif defined (_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include 
+#include 
+#endif
+
+static volatile bool g_is_generating = false;
+static volatile bool g_is_interrupted = false;
+
+static void show_additional_info(int /*argc*/, char ** argv) {
+    LOG(
+        "Usage: %s [options] -m  --media-backend smt --smt-config-dir  [--image  | --audio ] -p \n\n"
+        "  -m and --smt-config-dir are required\n"
+        "  --image/--audio and -p are optional, if NOT provided, the CLI will run in chat mode\n",
+        argv[0]
+    );
+}
+
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
+static void sigint_handler(int signo) {
+    if (signo == SIGINT) {
+        if (g_is_generating) {
+            g_is_generating = false;
+        } else {
+            console::cleanup();
+            if (g_is_interrupted) {
+                _exit(1);
+            }
+            g_is_interrupted = true;
+        }
+    }
+}
+#endif
+
+// ============================================================
+// Prompt chunking utilities
+// text/image are evaluated in order, aligned with mtmd chunk strategy
+// ============================================================
+
+static const std::string k_media_marker = "<__media__>";
+static const std::string k_legacy_image_marker = "<__image__>";
+
+static void replace_all(std::string & s, const std::string & from, const std::string & to);
+static std::vector split_keep_marker(const std::string & input, const std::string & marker);
+
+enum class smt_chunk_type {
+    text,
+    image,
+    audio,
+};
+
+enum class smt_init_mode {
+    auto_probe,
+    image_only,
+    audio_only,
+    mixed,
+};
+
+struct smt_prompt_chunk {
+    smt_chunk_type type = smt_chunk_type::text;
+    std::vector tokens_text;
+    std::string media_path;
+};
+
+struct smt_pending_media {
+    smt_chunk_type type = smt_chunk_type::image;
+    std::string path;
+};
+
+enum class smt_image_boundary_mode {
+    native,      // follow native mtmd model-family rules
+    auto_detect, // probe vocab for known token pairs
+    none,        // do not inject image boundary tokens
+};
+
+enum class smt_media_anchor_mode {
+    auto_mode, // apply on known architectures for multi-image prompts
+    on,        // always apply for multi-image prompts
+    off,       // disable prompt canonicalization
+};
+
+static std::string to_lower_ascii(std::string s) {
+    std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
+        return (char)std::tolower(c);
+    });
+    return s;
+}
+
+static smt_image_boundary_mode smt_image_boundary_mode_from_env() {
+    const char * env = std::getenv("MTMD_SMT_IMAGE_BOUNDARY");
+    if (env == nullptr || env[0] == '\0') {
+        return smt_image_boundary_mode::native;
+    }
+
+    const std::string value = to_lower_ascii(env);
+    if (value == "native") {
+        return smt_image_boundary_mode::native;
+    }
+    if (value == "auto" || value == "detect") {
+        return smt_image_boundary_mode::auto_detect;
+    }
+    if (value == "none" || value == "off" || value == "0") {
+        return smt_image_boundary_mode::none;
+    }
+
+    LOG_WRN("[SMT] unknown MTMD_SMT_IMAGE_BOUNDARY='%s', fallback to 'native'\n", env);
+    return smt_image_boundary_mode::native;
+}
+
+static const char * smt_image_boundary_mode_name(smt_image_boundary_mode mode) {
+    switch (mode) {
+        case smt_image_boundary_mode::native:      return "native";
+        case smt_image_boundary_mode::auto_detect: return "auto";
+        case smt_image_boundary_mode::none:        return "none";
+    }
+    return "native";
+}
+
+static bool contains_icase(const std::string & text, const std::string & pattern) {
+    return to_lower_ascii(text).find(to_lower_ascii(pattern)) != std::string::npos;
+}
+
+static bool arch_requires_mrope(const std::string & arch_name) {
+    return contains_icase(arch_name, "qwen2vl") ||
+           contains_icase(arch_name, "qwen2_5_vl") ||
+           contains_icase(arch_name, "qwen3vl") ||
+           contains_icase(arch_name, "glm4v") ||
+           contains_icase(arch_name, "paddleocr");
+}
+
+static bool arch_is_qwen3asr(const std::string & arch_name) {
+    return contains_icase(arch_name, "qwen3asr");
+}
+
+static std::pair infer_image_grid_xy(int n_tokens) {
+    if (n_tokens <= 0) {
+        return {0, 0};
+    }
+
+    // Choose the factor pair closest to square to approximate (nx, ny).
+    int best_y = 1;
+    int best_x = n_tokens;
+    int root = (int) std::sqrt((double) n_tokens);
+    for (int y = root; y >= 1; --y) {
+        if (n_tokens % y == 0) {
+            best_y = y;
+            best_x = n_tokens / y;
+            break;
+        }
+    }
+    return {best_x, best_y};
+}
+
+static smt_media_anchor_mode smt_media_anchor_mode_from_env() {
+    const char * env = std::getenv("MTMD_SMT_MEDIA_ANCHOR");
+    if (env == nullptr || env[0] == '\0') {
+        return smt_media_anchor_mode::off;
+    }
+    const std::string value = to_lower_ascii(env);
+    if (value == "auto") {
+        return smt_media_anchor_mode::auto_mode;
+    }
+    if (value == "on" || value == "1" || value == "true") {
+        return smt_media_anchor_mode::on;
+    }
+    if (value == "off" || value == "0" || value == "false") {
+        return smt_media_anchor_mode::off;
+    }
+    LOG_WRN("[SMT] unknown MTMD_SMT_MEDIA_ANCHOR='%s', fallback to 'off'\n", env);
+    return smt_media_anchor_mode::off;
+}
+
+static const char * smt_media_anchor_mode_name(smt_media_anchor_mode mode) {
+    switch (mode) {
+        case smt_media_anchor_mode::auto_mode: return "auto";
+        case smt_media_anchor_mode::on:        return "on";
+        case smt_media_anchor_mode::off:       return "off";
+    }
+    return "auto";
+}
+
+static std::vector tokenize_exact_special(llama_context * lctx, const std::string & token_text) {
+    auto toks = common_tokenize(lctx, token_text, /*add_special*/ false, /*parse_special*/ true);
+    if (toks.size() != 1) {
+        return {};
+    }
+    // Ensure this is a true special-token hit, not byte-level fallback.
+    if (common_token_to_piece(lctx, toks[0]) != token_text) {
+        return {};
+    }
+    return toks;
+}
+
+static std::pair, std::vector> detect_image_boundary_tokens(llama_context * lctx) {
+    // Keep order aligned with mtmd.cpp init_vision() common projector families.
+    static const std::vector> candidates = {
+        {"<|vision_start|>", "<|vision_end|>"},
+        {"<|image_start|>",  "<|image_end|>"},
+        {"", ""},
+        {"",            ""},
+        {"<|begin_of_image|>", "<|end_of_image|>"},
+        {"<|IMAGE_START|>",  "<|IMAGE_END|>"},
+        {"<|im_start|>",     "<|im_end|>"},
+        {"",          ""},
+    };
+
+    for (const auto & [beg_s, end_s] : candidates) {
+        auto beg = tokenize_exact_special(lctx, beg_s);
+        auto end = tokenize_exact_special(lctx, end_s);
+        if (!beg.empty() && !end.empty()) {
+            return {std::move(beg), std::move(end)};
+        }
+    }
+    return {};
+}
+
+static bool should_apply_media_anchor(const std::string & arch_name, size_t n_images, smt_media_anchor_mode mode) {
+    if (n_images < 2) {
+        return false;
+    }
+    switch (mode) {
+        case smt_media_anchor_mode::off:
+            return false;
+        case smt_media_anchor_mode::on:
+            return true;
+        case smt_media_anchor_mode::auto_mode:
+            return contains_icase(arch_name, "llavaqwen2forcausallm") || contains_icase(arch_name, "llavaqwen2");
+    }
+    return false;
+}
+
+static std::string canonicalize_multimage_prompt(
+        const std::string & prompt,
+        size_t n_images,
+        const std::string & arch_name,
+        smt_media_anchor_mode mode,
+        bool & changed) {
+    changed = false;
+    if (!should_apply_media_anchor(arch_name, n_images, mode)) {
+        return prompt;
+    }
+
+    std::string normalized = prompt;
+    replace_all(normalized, k_legacy_image_marker, k_media_marker);
+
+    const auto parts = split_keep_marker(normalized, k_media_marker);
+    size_t marker_count = 0;
+    for (const auto & p : parts) {
+        if (p == k_media_marker) {
+            marker_count++;
+        }
+    }
+
+    if (marker_count != n_images || marker_count < 2) {
+        return normalized;
+    }
+
+    std::string output;
+    output.reserve(normalized.size() + marker_count * 48 + 64);
+    output += "Please align images by order index. ";
+    output += "Image #1 maps to the first media slot, Image #2 to the second, and so on.\n";
+
+    size_t image_idx = 0;
+    for (const auto & part : parts) {
+        if (part == k_media_marker) {
+            image_idx++;
+            output += "[Image ";
+            output += std::to_string(image_idx);
+            output += " Begin]\n";
+            output += k_media_marker;
+            output += "\n[Image ";
+            output += std::to_string(image_idx);
+            output += " End]\n";
+        } else {
+            output += part;
+        }
+    }
+
+    changed = (output != normalized);
+    return output;
+}
+
+static std::pair, std::vector>
+detect_image_boundary_tokens_native(llama_context * lctx, const std::string & arch_name) {
+    // Match native mtmd behavior in mtmd.cpp::init_vision().
+    if (contains_icase(arch_name, "qwen2vl") || contains_icase(arch_name, "qwen2_5_vl") ||
+        contains_icase(arch_name, "qwen3vl") || contains_icase(arch_name, "youtuvl")) {
+        return {
+            tokenize_exact_special(lctx, "<|vision_start|>"),
+            tokenize_exact_special(lctx, "<|vision_end|>")
+        };
+    }
+    if (contains_icase(arch_name, "llama4")) {
+        return {
+            tokenize_exact_special(lctx, "<|image_start|>"),
+            tokenize_exact_special(lctx, "<|image_end|>")
+        };
+    }
+    if (contains_icase(arch_name, "gemma3")) {
+        return {
+            tokenize_exact_special(lctx, ""),
+            tokenize_exact_special(lctx, "")
+        };
+    }
+    if (contains_icase(arch_name, "internvl")) {
+        return {
+            tokenize_exact_special(lctx, ""),
+            tokenize_exact_special(lctx, "")
+        };
+    }
+    if (contains_icase(arch_name, "glm4v")) {
+        return {
+            tokenize_exact_special(lctx, "<|begin_of_image|>"),
+            tokenize_exact_special(lctx, "<|end_of_image|>")
+        };
+    }
+    if (contains_icase(arch_name, "paddleocr")) {
+        return {
+            tokenize_exact_special(lctx, "<|IMAGE_START|>"),
+            tokenize_exact_special(lctx, "<|IMAGE_END|>")
+        };
+    }
+    if (contains_icase(arch_name, "lightonocr")) {
+        return {
+            tokenize_exact_special(lctx, "<|im_start|>"),
+            tokenize_exact_special(lctx, "<|im_end|>")
+        };
+    }
+    return {};
+}
+
+static std::pair, std::vector>
+resolve_image_boundary_tokens(llama_context * lctx,
+                              const std::string & arch_name,
+                              smt_image_boundary_mode mode) {
+    if (mode == smt_image_boundary_mode::none) {
+        return {};
+    }
+    if (mode == smt_image_boundary_mode::auto_detect) {
+        return detect_image_boundary_tokens(lctx);
+    }
+    return detect_image_boundary_tokens_native(lctx, arch_name);
+}
+
+static std::pair, std::vector>
+resolve_audio_boundary_tokens(llama_context * lctx, const std::string & arch_name) {
+    if (!arch_is_qwen3asr(arch_name)) {
+        return {};
+    }
+    return {
+        tokenize_exact_special(lctx, "<|audio_start|>"),
+        tokenize_exact_special(lctx, "<|audio_end|>")
+    };
+}
+
+static void replace_all(std::string & s, const std::string & from, const std::string & to) {
+    if (from.empty()) {
+        return;
+    }
+    size_t pos = 0;
+    while ((pos = s.find(from, pos)) != std::string::npos) {
+        s.replace(pos, from.size(), to);
+        pos += to.size();
+    }
+}
+
+static std::vector split_keep_marker(const std::string & input, const std::string & marker) {
+    std::vector out;
+    if (input.empty()) {
+        return out;
+    }
+
+    size_t start = 0;
+    while (true) {
+        size_t pos = input.find(marker, start);
+        if (pos == std::string::npos) {
+            out.push_back(input.substr(start));
+            break;
+        }
+        if (pos > start) {
+            out.push_back(input.substr(start, pos - start));
+        }
+        out.push_back(marker);
+        start = pos + marker.size();
+    }
+    return out;
+}
+
+static std::vector read_binary_file(const std::string & path) {
+    std::ifstream file(path, std::ios::binary);
+    if (!file) {
+        throw std::runtime_error("Unable to open image file: " + path);
+    }
+
+    return std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator());
+}
+
+static bool looks_like_audio_file(const std::vector & bytes) {
+    if (bytes.size() < 12) {
+        return false;
+    }
+
+    const char * buf = reinterpret_cast(bytes.data());
+    const bool is_wav = std::memcmp(buf, "RIFF", 4) == 0 && std::memcmp(buf + 8, "WAVE", 4) == 0;
+    const bool is_mp3 = bytes.size() >= 3 && (
+        std::memcmp(buf, "ID3", 3) == 0 ||
+        (static_cast(buf[0]) == 0xFF && (static_cast(buf[1]) & 0xE0) == 0xE0)
+    );
+    const bool is_flac = std::memcmp(buf, "fLaC", 4) == 0;
+    return is_wav || is_mp3 || is_flac;
+}
+
+static smt_chunk_type detect_media_type_from_file(const std::string & path) {
+    const auto bytes = read_binary_file(path);
+    return looks_like_audio_file(bytes) ? smt_chunk_type::audio : smt_chunk_type::image;
+}
+
+static smt_init_mode infer_init_mode_from_params(const common_params & params) {
+    bool need_image = false;
+    bool need_audio = false;
+
+    for (const auto & media : params.image) {
+        const auto type = detect_media_type_from_file(media);
+        need_image = need_image || type == smt_chunk_type::image;
+        need_audio = need_audio || type == smt_chunk_type::audio;
+    }
+
+    if (need_image && need_audio) {
+        return smt_init_mode::mixed;
+    }
+    if (need_image) {
+        return smt_init_mode::image_only;
+    }
+    if (need_audio) {
+        return smt_init_mode::audio_only;
+    }
+
+    return smt_init_mode::auto_probe;
+}
+
+static std::string write_temp_bin_file(const std::vector & data) {
+#if defined(_WIN32)
+    char temp_path[MAX_PATH] = {0};
+    char temp_file[MAX_PATH] = {0};
+
+    if (GetTempPathA(MAX_PATH, temp_path) == 0) {
+        throw std::runtime_error("failed to get temp path");
+    }
+    if (GetTempFileNameA(temp_path, "mep", 0, temp_file) == 0) {
+        throw std::runtime_error("failed to create temp file");
+    }
+
+    FILE * fp = std::fopen(temp_file, "wb");
+    if (!fp) {
+        throw std::runtime_error("failed to open temp file");
+    }
+    const size_t n = std::fwrite(data.data(), 1, data.size(), fp);
+    std::fclose(fp);
+    if (n != data.size()) {
+        std::remove(temp_file);
+        throw std::runtime_error("failed to write temp file");
+    }
+    return std::string(temp_file);
+#else
+    char tmpl[] = "/tmp/llama-mtmd-smt-XXXXXX";
+    const int fd = mkstemp(tmpl);
+    if (fd < 0) {
+        throw std::runtime_error("failed to create temp file");
+    }
+
+    size_t written = 0;
+    while (written < data.size()) {
+        const ssize_t n = write(fd, data.data() + written, data.size() - written);
+        if (n <= 0) {
+            close(fd);
+            std::remove(tmpl);
+            throw std::runtime_error("failed to write temp file");
+        }
+        written += (size_t) n;
+    }
+    close(fd);
+    return std::string(tmpl);
+#endif
+}
+
+static void append_text_chunk(std::vector & chunks, std::vector && tokens) {
+    if (tokens.empty()) {
+        return;
+    }
+    if (!chunks.empty() && chunks.back().type == smt_chunk_type::text) {
+        auto & dst = chunks.back().tokens_text;
+        dst.insert(dst.end(), tokens.begin(), tokens.end());
+        return;
+    }
+
+    smt_prompt_chunk chunk;
+    chunk.type = smt_chunk_type::text;
+    chunk.tokens_text = std::move(tokens);
+    chunks.emplace_back(std::move(chunk));
+}
+
+static bool tokenize_to_smt_chunks(
+        const llama_vocab * vocab,
+        const std::string & formatted_chat,
+        bool add_special,
+        bool parse_special,
+        const std::vector & media_inputs,
+        std::vector & out_chunks) {
+    out_chunks.clear();
+
+    std::string input = formatted_chat;
+    replace_all(input, k_legacy_image_marker, k_media_marker);
+
+    size_t n_images_used = 0;
+    const auto parts = split_keep_marker(input, k_media_marker);
+    for (const auto & part : parts) {
+        if (part == k_media_marker) {
+            if (n_images_used >= media_inputs.size()) {
+                LOG_ERR("Number of media inputs (%zu) does not match number of media markers in prompt\n", media_inputs.size());
+                return false;
+            }
+            smt_prompt_chunk chunk;
+            chunk.type = media_inputs[n_images_used].type;
+            chunk.media_path = media_inputs[n_images_used].path;
+            n_images_used++;
+            out_chunks.emplace_back(std::move(chunk));
+        } else {
+            append_text_chunk(out_chunks, common_tokenize(vocab, part, /*add_special*/ false, parse_special));
+        }
+    }
+
+    if (n_images_used != media_inputs.size()) {
+        LOG_ERR("Number of media inputs (%zu) does not match number of media markers in prompt (%zu)\n",
+                media_inputs.size(), n_images_used);
+        return false;
+    }
+
+    if (add_special && llama_vocab_get_add_bos(vocab)) {
+        const llama_token bos = llama_vocab_bos(vocab);
+        if (bos != LLAMA_TOKEN_NULL) {
+            if (!out_chunks.empty() && out_chunks.front().type == smt_chunk_type::text) {
+                out_chunks.front().tokens_text.insert(out_chunks.front().tokens_text.begin(), bos);
+            } else {
+                smt_prompt_chunk bos_chunk;
+                bos_chunk.type = smt_chunk_type::text;
+                bos_chunk.tokens_text = { bos };
+                out_chunks.insert(out_chunks.begin(), std::move(bos_chunk));
+            }
+        }
+    }
+
+    if (add_special && llama_vocab_get_add_eos(vocab)) {
+        const llama_token eos = llama_vocab_eos(vocab);
+        if (eos != LLAMA_TOKEN_NULL) {
+            if (!out_chunks.empty() && out_chunks.back().type == smt_chunk_type::text) {
+                out_chunks.back().tokens_text.push_back(eos);
+            } else {
+                smt_prompt_chunk eos_chunk;
+                eos_chunk.type = smt_chunk_type::text;
+                eos_chunk.tokens_text = { eos };
+                out_chunks.emplace_back(std::move(eos_chunk));
+            }
+        }
+    }
+
+    return true;
+}
+
+// ============================================================
+// Decode embedding batch into LLM
+// (Adapted from mtmd-helper.cpp decode_embd_batch + mtmd_helper_decode_image_chunk)
+// Supports both normal positional encoding and M-RoPE positional layout.
+// ============================================================
+
+static int decode_embd(llama_context * lctx,
+                       float * embd,
+                       int n_tokens,
+                       int n_embd,
+                       llama_pos & n_past,
+                       int n_batch,
+                       bool logits_last,
+                       bool use_mrope_pos,
+                       int nx,
+                       int ny) {
+    const int n_pos_per_embd = use_mrope_pos ? 4 : 1;
+
+    // Allocate auxiliary arrays (managed manually, not via llama_batch_init).
+    std::vector      pos((size_t) n_tokens * n_pos_per_embd);
+    std::vector        n_seq_id(n_tokens);
+    std::vector   seq_id_0(n_tokens);
+    std::vector seq_ids(n_tokens);
+    std::vector         logits(n_tokens, 0);
+
+    for (int i = 0; i < n_tokens; ++i) {
+        seq_id_0[i] = 0;
+        seq_ids[i]  = &seq_id_0[i];
+    }
+
+    if (use_mrope_pos) {
+        if (nx > 0 && ny > 0 && nx * ny == n_tokens) {
+            for (int y = 0; y < ny; ++y) {
+                for (int x = 0; x < nx; ++x) {
+                    const int i = y * nx + x;
+                    pos[(size_t) i] = n_past;
+                    pos[(size_t) i + n_tokens] = n_past + y;
+                    pos[(size_t) i + 2 * n_tokens] = n_past + x;
+                    pos[(size_t) i + 3 * n_tokens] = 0;
+                }
+            }
+        } else {
+            // Fallback to 1D M-RoPE-style positions if grid inference is inconsistent.
+            for (int i = 0; i < n_tokens; ++i) {
+                pos[(size_t) i] = n_past + i;
+                pos[(size_t) i + n_tokens] = n_past + i;
+                pos[(size_t) i + 2 * n_tokens] = n_past + i;
+                pos[(size_t) i + 3 * n_tokens] = 0;
+            }
+        }
+    } else {
+        for (int i = 0; i < n_tokens; ++i) {
+            pos[(size_t) i] = n_past + i;
+        }
+    }
+
+    int processed = 0;
+    while (processed < n_tokens) {
+        int batch_size = std::min(n_batch, n_tokens - processed);
+        bool is_last_batch = (processed + batch_size >= n_tokens);
+
+        for (int i = 0; i < batch_size; ++i) {
+            if (!use_mrope_pos) {
+                pos[processed + i] = n_past + processed + i;
+            }
+            n_seq_id[processed + i] = 1;
+            logits[processed + i]   = (logits_last && is_last_batch && i == batch_size - 1);
+        }
+
+        llama_pos * pos_ptr = nullptr;
+        std::vector pos_view;
+        if (use_mrope_pos) {
+            pos_view.reserve((size_t) batch_size * n_pos_per_embd);
+            for (int d = 0; d < n_pos_per_embd; ++d) {
+                const size_t src_idx = (size_t) d * n_tokens + processed;
+                pos_view.insert(pos_view.end(), pos.data() + src_idx, pos.data() + src_idx + batch_size);
+            }
+            pos_ptr = pos_view.data();
+        } else {
+            pos_ptr = pos.data() + processed;
+        }
+
+        llama_batch batch = {
+            /*n_tokens  =*/ batch_size,
+            /*token     =*/ nullptr,
+            /*embd      =*/ embd + (size_t)processed * n_embd,
+            /*pos       =*/ pos_ptr,
+            /*n_seq_id  =*/ n_seq_id.data() + processed,
+            /*seq_id    =*/ seq_ids.data()  + processed,
+            /*logits    =*/ logits.data()   + processed,
+        };
+
+        int ret = llama_decode(lctx, batch);
+        if (ret != 0) {
+            LOG_ERR("Failed to decode embedding batch at offset %d\n", processed);
+            return ret;
+        }
+
+        processed += batch_size;
+    }
+
+    if (use_mrope_pos) {
+        n_past += std::max(nx, ny);
+    } else {
+        n_past += n_tokens;
+    }
+
+    return 0;
+}
+
+static int decode_tokens(llama_context * lctx,
+                         const std::vector & tokens,
+                         llama_pos & n_past,
+                         int n_batch,
+                         bool logits_last) {
+    if (tokens.empty()) {
+        return 0;
+    }
+
+    llama_batch batch = llama_batch_init(n_batch, 0, 1);
+    size_t i = 0;
+    while (i < tokens.size()) {
+        batch.n_tokens = 0;
+        for (; i < tokens.size() && batch.n_tokens < n_batch; ++i) {
+            const int32_t j = batch.n_tokens;
+            batch.token[j]     = tokens[i];
+            batch.pos[j]       = n_past + j;
+            batch.n_seq_id[j]  = 1;
+            batch.seq_id[j][0] = 0;
+            batch.logits[j]    = false;
+            batch.n_tokens++;
+        }
+
+        if (logits_last && i == tokens.size()) {
+            batch.logits[batch.n_tokens - 1] = true;
+        }
+
+        if (llama_decode(lctx, batch) != 0) {
+            llama_batch_free(batch);
+            return 1;
+        }
+        n_past += batch.n_tokens;
+    }
+
+    llama_batch_free(batch);
+    return 0;
+}
+
+// ============================================================
+// Context structure
+// ============================================================
+
+struct mtmd_cli_smt_context {
+    std::unique_ptr smt_vision_ctx;
+    std::unique_ptr  smt_audio_ctx;
+    common_init_result_ptr llama_init;
+
+    llama_model       * model;
+    llama_context     * lctx;
+    const llama_vocab * vocab;
+    common_sampler    * smpl;
+    llama_batch         batch;
+    int                 n_batch;
+
+    int64_t hidden_size = 0;
+    bool use_mrope_pos = false;
+    std::vector tok_img_beg;
+    std::vector tok_img_end;
+    std::vector tok_audio_beg;
+    std::vector tok_audio_end;
+    smt_image_boundary_mode img_boundary_mode = smt_image_boundary_mode::native;
+    smt_media_anchor_mode media_anchor_mode = smt_media_anchor_mode::off;
+
+    // Pending media paths
+    std::vector pending_media;
+
+    // Chat template
+    common_chat_templates_ptr tmpls;
+    std::vector chat_history;
+    bool use_jinja = false;
+
+    // Legacy template antiprompt
+    llama_tokens antiprompt_tokens;
+
+    int n_threads    = 1;
+    llama_pos n_past = 0;
+
+    mtmd_cli_smt_context(common_params & params, const std::string & smt_config_dir)
+        : llama_init(common_init_from_params(params))
+    {
+        model = llama_init->model();
+        lctx  = llama_init->context();
+        vocab = llama_model_get_vocab(model);
+        smpl  = common_sampler_init(model, params.sampling);
+        n_threads = params.cpuparams.n_threads;
+        batch = llama_batch_init(1, 0, 1);
+        n_batch = params.n_batch;
+
+        if (!model || !lctx) {
+            LOG_ERR("Failed to initialize LLM model\n");
+            exit(1);
+        }
+
+        // Chat template
+        tmpls = common_chat_templates_init(model, params.chat_template);
+        use_jinja = params.use_jinja;
+        chat_history.clear();
+
+        std::string primary_architecture;
+        const smt_init_mode init_mode = infer_init_mode_from_params(params);
+        std::string vision_error;
+        std::string audio_error;
+
+        const bool try_vision = init_mode == smt_init_mode::auto_probe ||
+                                init_mode == smt_init_mode::image_only ||
+                                init_mode == smt_init_mode::mixed;
+        const bool try_audio = init_mode == smt_init_mode::auto_probe ||
+                               init_mode == smt_init_mode::audio_only ||
+                               init_mode == smt_init_mode::mixed;
+
+        if (try_vision) {
+            try {
+                smt_vision_ctx = smt_vision_context::create(smt_config_dir);
+                hidden_size = smt_vision_ctx->hidden_size();
+                primary_architecture = smt_vision_ctx->architecture();
+            } catch (const std::exception & e) {
+                vision_error = e.what();
+            }
+        }
+
+        if (try_audio) {
+            try {
+                smt_audio_ctx = smt_audio_context::create(smt_config_dir);
+                if (hidden_size == 0) {
+                    hidden_size = smt_audio_ctx->hidden_size();
+                } else if (hidden_size != smt_audio_ctx->hidden_size()) {
+                    LOG_ERR("FATAL: SMT audio hidden_size (%" PRId64 ") != current SMT hidden_size (%" PRId64 ")\n",
+                            smt_audio_ctx->hidden_size(), hidden_size);
+                    exit(1);
+                }
+                if (primary_architecture.empty()) {
+                    primary_architecture = smt_audio_ctx->architecture();
+                }
+            } catch (const std::exception & e) {
+                audio_error = e.what();
+            }
+        }
+
+        if (init_mode == smt_init_mode::image_only && !smt_vision_ctx) {
+            LOG_ERR("FATAL: failed to initialize SMT vision backend from %s: %s\n",
+                    smt_config_dir.c_str(), vision_error.empty() ? "unknown error" : vision_error.c_str());
+            exit(1);
+        }
+
+        if (init_mode == smt_init_mode::audio_only && !smt_audio_ctx) {
+            LOG_ERR("FATAL: failed to initialize SMT audio backend from %s: %s\n",
+                    smt_config_dir.c_str(), audio_error.empty() ? "unknown error" : audio_error.c_str());
+            exit(1);
+        }
+
+        if (init_mode == smt_init_mode::mixed && (!smt_vision_ctx || !smt_audio_ctx)) {
+            LOG_ERR("FATAL: mixed SMT request requires both vision and audio backends\n");
+            if (!smt_vision_ctx) {
+                LOG_ERR("FATAL: vision backend init failed: %s\n",
+                        vision_error.empty() ? "unknown error" : vision_error.c_str());
+            }
+            if (!smt_audio_ctx) {
+                LOG_ERR("FATAL: audio backend init failed: %s\n",
+                        audio_error.empty() ? "unknown error" : audio_error.c_str());
+            }
+            exit(1);
+        }
+
+        if (!smt_vision_ctx && !smt_audio_ctx) {
+            LOG_ERR("FATAL: neither SMT vision nor SMT audio backend is available in %s\n", smt_config_dir.c_str());
+            exit(1);
+        }
+
+        use_mrope_pos = arch_requires_mrope(primary_architecture);
+        img_boundary_mode = smt_image_boundary_mode_from_env();
+        media_anchor_mode = smt_media_anchor_mode_from_env();
+        if (hidden_size <= 0 || hidden_size > INT_MAX) {
+            LOG_ERR("FATAL: invalid SMT hidden_size (%" PRId64 ")\n", hidden_size);
+            exit(1);
+        }
+
+        // Validate n_embd matches
+        int model_n_embd = llama_model_n_embd(model);
+        if (model_n_embd != hidden_size) {
+            LOG_ERR("FATAL: model n_embd (%d) != SMT hidden_size (%" PRId64 ")\n", model_n_embd, hidden_size);
+            exit(1);
+        }
+
+        // Align image boundary tokens with native mtmd behavior by default.
+        if (smt_vision_ctx) {
+            auto boundaries = resolve_image_boundary_tokens(lctx, smt_vision_ctx->architecture(), img_boundary_mode);
+            tok_img_beg = std::move(boundaries.first);
+            tok_img_end = std::move(boundaries.second);
+            if (tok_img_beg.empty() || tok_img_end.empty() ||
+                tok_img_beg.front() == LLAMA_TOKEN_NULL || tok_img_end.front() == LLAMA_TOKEN_NULL) {
+                tok_img_beg.clear();
+                tok_img_end.clear();
+            }
+        }
+
+        if (smt_audio_ctx) {
+            auto audio_boundaries = resolve_audio_boundary_tokens(lctx, smt_audio_ctx->architecture());
+            tok_audio_beg = std::move(audio_boundaries.first);
+            tok_audio_end = std::move(audio_boundaries.second);
+            if (tok_audio_beg.empty() || tok_audio_end.empty() ||
+                tok_audio_beg.front() == LLAMA_TOKEN_NULL || tok_audio_end.front() == LLAMA_TOKEN_NULL) {
+                tok_audio_beg.clear();
+                tok_audio_end.clear();
+            }
+        }
+
+        // Antiprompt for legacy templates
+        if (params.chat_template == "vicuna") {
+            antiprompt_tokens = common_tokenize(lctx, "ASSISTANT:", false, true);
+        } else if (params.chat_template == "deepseek") {
+            antiprompt_tokens = common_tokenize(lctx, "###", false, true);
+        }
+    }
+
+    ~mtmd_cli_smt_context() {
+        llama_batch_free(batch);
+        common_sampler_free(smpl);
+    }
+
+    bool check_antiprompt(const llama_tokens & generated_tokens) {
+        if (antiprompt_tokens.empty() || generated_tokens.size() < antiprompt_tokens.size()) {
+            return false;
+        }
+        return std::equal(
+            generated_tokens.end() - antiprompt_tokens.size(),
+            generated_tokens.end(),
+            antiprompt_tokens.begin()
+        );
+    }
+
+    void add_image(const std::string & binary_path) {
+        pending_media.push_back({ smt_chunk_type::image, binary_path });
+    }
+
+    void add_audio(const std::string & audio_path) {
+        pending_media.push_back({ smt_chunk_type::audio, audio_path });
+    }
+
+    void add_media_auto(const std::string & media_path) {
+        pending_media.push_back({ detect_media_type_from_file(media_path), media_path });
+    }
+
+    size_t pending_image_count() const {
+        size_t count = 0;
+        for (const auto & media : pending_media) {
+            if (media.type == smt_chunk_type::image) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    bool has_pending_audio_only() const {
+        if (pending_media.empty()) {
+            return false;
+        }
+        for (const auto & media : pending_media) {
+            if (media.type != smt_chunk_type::audio) {
+                return false;
+            }
+        }
+        return true;
+    }
+};
+
+// ============================================================
+// Generate response (reused from mtmd-cli.cpp)
+// ============================================================
+
+static int generate_response(mtmd_cli_smt_context & ctx, int n_predict) {
+    llama_tokens generated_tokens;
+    for (int i = 0; i < n_predict; i++) {
+        if (i > n_predict || !g_is_generating || g_is_interrupted) {
+            LOG("\n");
+            break;
+        }
+
+        llama_token token_id = common_sampler_sample(ctx.smpl, ctx.lctx, -1);
+        generated_tokens.push_back(token_id);
+        common_sampler_accept(ctx.smpl, token_id, true);
+
+        if (llama_vocab_is_eog(ctx.vocab, token_id) || ctx.check_antiprompt(generated_tokens)) {
+            LOG("\n");
+            break;
+        }
+
+        LOG("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
+        fflush(stdout);
+
+        if (g_is_interrupted) {
+            LOG("\n");
+            break;
+        }
+
+        // Eval the token
+        common_batch_clear(ctx.batch);
+        common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
+        if (llama_decode(ctx.lctx, ctx.batch)) {
+            LOG_ERR("failed to decode token\n");
+            return 1;
+        }
+    }
+
+    std::string generated_text = common_detokenize(ctx.lctx, generated_tokens);
+    common_chat_msg msg;
+    msg.role    = "assistant";
+    msg.content = generated_text;
+    ctx.chat_history.push_back(std::move(msg));
+
+    return 0;
+}
+
+// ============================================================
+// Chat formatting (reused from mtmd-cli.cpp)
+// ============================================================
+
+static std::string chat_add_and_format(mtmd_cli_smt_context & ctx, common_chat_msg & new_msg) {
+    auto formatted = common_chat_format_single(ctx.tmpls.get(), ctx.chat_history,
+        new_msg, new_msg.role == "user",
+        ctx.use_jinja);
+    ctx.chat_history.push_back(new_msg);
+    return formatted;
+}
+
+static std::string collect_system_text(const mtmd_cli_smt_context & ctx) {
+    std::string system_text;
+    for (const auto & msg : ctx.chat_history) {
+        if (msg.role == "system") {
+            system_text += msg.content;
+        }
+    }
+    return system_text;
+}
+
+static std::string strip_media_markers_from_prompt(const std::string & prompt) {
+    std::string text = prompt;
+    replace_all(text, k_legacy_image_marker, k_media_marker);
+    replace_all(text, k_media_marker, "");
+    return string_strip(text);
+}
+
+static std::string format_qwen3asr_audio_prompt(const mtmd_cli_smt_context & ctx, const common_chat_msg & msg) {
+    std::string prompt;
+    prompt.reserve(msg.content.size() + ctx.pending_media.size() * 16 + 128);
+    prompt += "<|im_start|>system\n";
+    prompt += collect_system_text(ctx);
+    prompt += "<|im_end|>\n";
+    prompt += "<|im_start|>user\n";
+    for (const auto & media : ctx.pending_media) {
+        GGML_ASSERT(media.type == smt_chunk_type::audio);
+        prompt += k_media_marker;
+    }
+    prompt += "<|im_end|>\n";
+    prompt += "<|im_start|>assistant\n";
+    prompt += strip_media_markers_from_prompt(msg.content);
+    return prompt;
+}
+
+// ============================================================
+// Eval message - core multimodal processing
+// ============================================================
+
+static int eval_message_smt(mtmd_cli_smt_context & ctx, common_chat_msg & msg) {
+    struct pending_media_guard {
+        mtmd_cli_smt_context & ctx;
+
+        ~pending_media_guard() {
+            ctx.pending_media.clear();
+        }
+    } guard{ctx};
+
+    bool add_bos = ctx.chat_history.empty();
+
+    if (msg.role == "user" && ctx.pending_image_count() > 0) {
+        bool changed = false;
+        msg.content = canonicalize_multimage_prompt(
+            msg.content,
+            ctx.pending_image_count(),
+            ctx.smt_vision_ctx ? ctx.smt_vision_ctx->architecture() : std::string(),
+            ctx.media_anchor_mode,
+            changed);
+        GGML_UNUSED(changed);
+    }
+
+    std::string formatted_chat;
+    const bool use_qwen3asr_prompt =
+        msg.role == "user" &&
+        ctx.smt_audio_ctx &&
+        arch_is_qwen3asr(ctx.smt_audio_ctx->architecture()) &&
+        ctx.has_pending_audio_only();
+    if (use_qwen3asr_prompt) {
+        formatted_chat = format_qwen3asr_audio_prompt(ctx, msg);
+        ctx.chat_history.push_back(msg);
+        add_bos = false;
+    } else {
+        formatted_chat = chat_add_and_format(ctx, msg);
+    }
+
+    if (g_is_interrupted) return 0;
+
+    std::vector chunks;
+    if (!tokenize_to_smt_chunks(ctx.vocab, formatted_chat, add_bos, true, ctx.pending_media, chunks)) {
+        return 1;
+    }
+
+    for (size_t i = 0; i < chunks.size(); ++i) {
+        const bool logits_last = (i == chunks.size() - 1);
+        const auto & chunk = chunks[i];
+        if (chunk.type == smt_chunk_type::text) {
+            if (decode_tokens(ctx.lctx, chunk.tokens_text, ctx.n_past, ctx.n_batch, logits_last) != 0) {
+                LOG_ERR("Failed to decode text chunk %zu\n", i);
+                return 1;
+            }
+            continue;
+        }
+
+        if (chunk.type == smt_chunk_type::audio) {
+            if (!ctx.smt_audio_ctx) {
+                LOG_ERR("No SMT audio backend is available for '%s'\n", chunk.media_path.c_str());
+                return 1;
+            }
+
+            std::vector audio_embd;
+            try {
+                audio_embd = ctx.smt_audio_ctx->encode_audio(chunk.media_path);
+            } catch (const std::exception & e) {
+                LOG_ERR("Failed to encode audio chunk %zu (%s): %s\n", i, chunk.media_path.c_str(), e.what());
+                return 1;
+            }
+
+            if (audio_embd.empty() || audio_embd.size() % (size_t) ctx.hidden_size != 0) {
+                LOG_ERR("Invalid audio embedding shape from SMT (size=%zu, hidden_size=%" PRId64 ")\n",
+                        audio_embd.size(), ctx.hidden_size);
+                return 1;
+            }
+
+            const int n_audio_tokens = (int) (audio_embd.size() / (size_t) ctx.hidden_size);
+            if (!ctx.tok_audio_beg.empty()) {
+                if (decode_tokens(ctx.lctx, ctx.tok_audio_beg, ctx.n_past, ctx.n_batch, /*logits_last*/ false) != 0) {
+                    LOG_ERR("Failed to decode audio-begin token chunk %zu\n", i);
+                    return 1;
+                }
+            }
+
+            const bool logits_on_embd = logits_last && ctx.tok_audio_end.empty();
+            if (decode_embd(ctx.lctx, audio_embd.data(), n_audio_tokens,
+                            (int) ctx.hidden_size, ctx.n_past, ctx.n_batch, logits_on_embd,
+                            /*use_mrope_pos*/ false, n_audio_tokens, 1) != 0) {
+                LOG_ERR("Failed to decode audio chunk %zu\n", i);
+                return 1;
+            }
+
+            if (!ctx.tok_audio_end.empty()) {
+                if (decode_tokens(ctx.lctx, ctx.tok_audio_end, ctx.n_past, ctx.n_batch, logits_last) != 0) {
+                    LOG_ERR("Failed to decode audio-end token chunk %zu\n", i);
+                    return 1;
+                }
+            }
+            continue;
+        }
+
+        // image chunk
+        if (!ctx.smt_vision_ctx) {
+            LOG_ERR("No SMT vision backend is available for '%s'\n", chunk.media_path.c_str());
+            return 1;
+        }
+
+        std::string smt_input_path = chunk.media_path;
+        std::string temp_input_path;
+        try {
+            const auto image_bytes = read_binary_file(chunk.media_path);
+            auto preproc = smt_vision_preprocess_if_image(
+                image_bytes,
+                ctx.smt_vision_ctx->architecture(),
+                ctx.smt_vision_ctx->input_width(),
+                ctx.smt_vision_ctx->input_height());
+            if (preproc.was_image) {
+                temp_input_path = write_temp_bin_file(preproc.tensor_bytes);
+                smt_input_path = temp_input_path;
+            }
+        } catch (const std::exception & e) {
+            LOG_ERR("Failed to prepare image '%s': %s\n", chunk.media_path.c_str(), e.what());
+            return 1;
+        }
+
+        std::vector image_embd;
+        try {
+            image_embd = ctx.smt_vision_ctx->encode_image(smt_input_path);
+            if (!temp_input_path.empty()) {
+                std::remove(temp_input_path.c_str());
+            }
+        } catch (const std::exception & e) {
+            if (!temp_input_path.empty()) {
+                std::remove(temp_input_path.c_str());
+            }
+            LOG_ERR("Failed to encode image chunk %zu (%s): %s\n", i, chunk.media_path.c_str(), e.what());
+            return 1;
+        }
+
+        if (image_embd.empty() || image_embd.size() % (size_t)ctx.hidden_size != 0) {
+            LOG_ERR("Invalid image embedding shape from SMT (size=%zu, hidden_size=%" PRId64 ")\n",
+                    image_embd.size(), ctx.hidden_size);
+            return 1;
+        }
+
+        const int n_image_tokens = (int)(image_embd.size() / (size_t)ctx.hidden_size);
+        int grid_nx = n_image_tokens;
+        int grid_ny = 1;
+        if (ctx.use_mrope_pos) {
+            auto grid_xy = infer_image_grid_xy(n_image_tokens);
+            grid_nx = grid_xy.first;
+            grid_ny = grid_xy.second;
+        }
+
+        if (!ctx.tok_img_beg.empty()) {
+            if (decode_tokens(ctx.lctx, ctx.tok_img_beg, ctx.n_past, ctx.n_batch, /*logits_last*/ false) != 0) {
+                LOG_ERR("Failed to decode image-begin token chunk %zu\n", i);
+                return 1;
+            }
+        }
+
+        const bool logits_on_embd = logits_last && ctx.tok_img_end.empty();
+        if (decode_embd(ctx.lctx, image_embd.data(), n_image_tokens,
+                        (int)ctx.hidden_size, ctx.n_past, ctx.n_batch, logits_on_embd,
+                        ctx.use_mrope_pos, grid_nx, grid_ny) != 0) {
+            LOG_ERR("Failed to decode image chunk %zu\n", i);
+            return 1;
+        }
+
+        if (!ctx.tok_img_end.empty()) {
+            if (decode_tokens(ctx.lctx, ctx.tok_img_end, ctx.n_past, ctx.n_batch, logits_last) != 0) {
+                LOG_ERR("Failed to decode image-end token chunk %zu\n", i);
+                return 1;
+            }
+        }
+    }
+
+    LOG("\n");
+    return 0;
+}
+
+// ============================================================
+// Main function
+// ============================================================
+
+int mtmd_cli_smt_run(int argc, char ** argv, common_params params) {
+    ggml_time_init();
+    LOG_INF("MTMD_CLI_SMT_BUILD_TAG: spacemit-smt (%s %s)\n", __DATE__, __TIME__);
+
+    common_init();
+
+    if (params.smt_config_dir.empty()) {
+        show_additional_info(argc, argv);
+        LOG_ERR("ERR: Missing --smt-config-dir argument\n");
+        return 1;
+    }
+
+    mtmd_cli_smt_context ctx(params, params.smt_config_dir);
+
+    bool is_single_turn = !params.prompt.empty() && !params.image.empty();
+    int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
+
+    // Ctrl+C handling
+    {
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
+        struct sigaction sigint_action;
+        sigint_action.sa_handler = sigint_handler;
+        sigemptyset (&sigint_action.sa_mask);
+        sigint_action.sa_flags = 0;
+        sigaction(SIGINT, &sigint_action, NULL);
+#elif defined (_WIN32)
+        auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
+            return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
+        };
+        SetConsoleCtrlHandler(reinterpret_cast(console_ctrl_handler), true);
+#endif
+    }
+
+    if (g_is_interrupted) return 130;
+
+    // Evaluate system prompt if present
+    auto eval_system_prompt_if_present = [&] {
+        if (params.system_prompt.empty()) {
+            return 0;
+        }
+        common_chat_msg msg;
+        msg.role = "system";
+        msg.content = params.system_prompt;
+        if (ctx.smt_audio_ctx && arch_is_qwen3asr(ctx.smt_audio_ctx->architecture())) {
+            ctx.chat_history.push_back(msg);
+            return 0;
+        }
+        return eval_message_smt(ctx, msg);
+    };
+
+    if (eval_system_prompt_if_present()) {
+        return 1;
+    }
+
+    if (is_single_turn) {
+        g_is_generating = true;
+
+        // Insert <__media__> marker if not present (same logic as mtmd-cli.cpp)
+        if (params.prompt.find("<__media__>") == std::string::npos) {
+            for (size_t i = 0; i < params.image.size(); i++) {
+                params.prompt = std::string("<__media__>") + params.prompt;
+            }
+        }
+
+        common_chat_msg msg;
+        msg.role = "user";
+        msg.content = params.prompt;
+
+        for (const auto & media : params.image) {
+            ctx.add_media_auto(media);
+        }
+
+        if (eval_message_smt(ctx, msg)) {
+            return 1;
+        }
+        if (!g_is_interrupted && generate_response(ctx, n_predict)) {
+            return 1;
+        }
+    } else {
+        // Chat mode
+        LOG("\n Running in chat mode (SMT media), available commands:");
+        LOG("\n   /image     load an image (.jpg/.png/...) or preprocessed .bin");
+        LOG("\n   /audio     load an audio file (.wav/.mp3/.flac)");
+        LOG("\n   /clear           clear the chat history");
+        LOG("\n   /quit or /exit   exit the program");
+        LOG("\n");
+
+        std::string content;
+
+        while (!g_is_interrupted) {
+            g_is_generating = false;
+            LOG("\n> ");
+            console::set_display(DISPLAY_TYPE_USER_INPUT);
+            std::string line;
+            console::readline(line, false);
+            if (g_is_interrupted) break;
+            console::set_display(DISPLAY_TYPE_RESET);
+            line = string_strip(line);
+            if (line.empty()) {
+                continue;
+            }
+            if (line == "/quit" || line == "/exit") {
+                break;
+            }
+            if (line == "/clear") {
+                ctx.n_past = 0;
+                ctx.chat_history.clear();
+                llama_memory_clear(llama_get_memory(ctx.lctx), true);
+                if (eval_system_prompt_if_present()) {
+                    return 1;
+                }
+                LOG("Chat history cleared\n\n");
+                continue;
+            }
+            g_is_generating = true;
+
+            const bool is_image = line == "/image" || line.find("/image ") == 0;
+            const bool is_audio = line == "/audio" || line.find("/audio ") == 0;
+            if (is_image || is_audio) {
+                if (line.size() < 8) {
+                    LOG_ERR("ERR: Missing media filename\n");
+                    continue;
+                }
+                std::string media_path = line.substr(7);
+                if (is_image) {
+                    ctx.add_image(media_path);
+                    LOG("%s image loaded\n", media_path.c_str());
+                } else {
+                    ctx.add_audio(media_path);
+                    LOG("%s audio loaded\n", media_path.c_str());
+                }
+                content += "<__media__>";
+                continue;
+            } else {
+                content += line;
+            }
+
+            common_chat_msg msg;
+            msg.role = "user";
+            msg.content = content;
+            int ret = eval_message_smt(ctx, msg);
+            if (ret) {
+                return 1;
+            }
+            if (g_is_interrupted) break;
+            if (generate_response(ctx, n_predict)) {
+                return 1;
+            }
+            content.clear();
+        }
+    }
+
+    if (g_is_interrupted) LOG("\nInterrupted by user\n");
+    LOG("\n\n");
+    llama_perf_context_print(ctx.lctx);
+    return g_is_interrupted ? 130 : 0;
+}
diff --git a/tools/mtmd/mtmd-cli.cpp b/tools/mtmd/mtmd-cli.cpp
index d6e551618e88..bc4b7f773abf 100644
--- a/tools/mtmd/mtmd-cli.cpp
+++ b/tools/mtmd/mtmd-cli.cpp
@@ -1,34 +1,35 @@
 #include "arg.h"
-#include "debug.h"
-#include "log.h"
+#include "chat.h"
 #include "common.h"
-#include "sampling.h"
-#include "llama.h"
-#include "ggml.h"
 #include "console.h"
-#include "chat.h"
-#include "mtmd.h"
+#include "debug.h"
+#include "ggml.h"
+#include "llama.h"
+#include "log.h"
 #include "mtmd-helper.h"
+#include "mtmd.h"
+#include "sampling.h"
 
-#include 
 #include 
+
 #include 
 #include 
+#include 
 
-#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
-#include 
-#include 
-#elif defined (_WIN32)
-#define WIN32_LEAN_AND_MEAN
-#ifndef NOMINMAX
-#define NOMINMAX
-#endif
-#include 
-#include 
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+#    include 
+#    include 
+#elif defined(_WIN32)
+#    define WIN32_LEAN_AND_MEAN
+#    ifndef NOMINMAX
+#        define NOMINMAX
+#    endif
+#    include 
+#    include 
 #endif
 
 // volatile, because of signal being an interrupt
-static volatile bool g_is_generating = false;
+static volatile bool g_is_generating  = false;
 static volatile bool g_is_interrupted = false;
 
 /**
@@ -38,18 +39,33 @@ static volatile bool g_is_interrupted = false;
  */
 
 static void show_additional_info(int /*argc*/, char ** argv) {
-    LOG(
-        "Experimental CLI for multimodal\n\n"
+#if defined(LLAMA_SERVER_SMT_VISION)
+    LOG("Experimental CLI for multimodal\n\n"
+        "Usage: %s [options] -m  [--mmproj  | --smt-config-dir ] --image  --audio