Commit 5a09582d8 for llama.cpp
commit 5a09582d80600fb5b0a8966e870061bddc8a3732
Author: Seohyun Choi <blackking26@naver.com>
Date: Thu Nov 26 03:38:12 2026 +0900
model : add RAON-1-mini-preview support (#32176)
* vocab : add RAON pre-tokenizer and NFC normalization
* model : add RAON hybrid attention and mHC graph
* convert : add MXFP8 weight dequantization
* convert : add RAON HF to GGUF conversion and schema
* chat : add the RAON chat template
* tests : add RAON vocab regression files for test-tokenizer-0
* llama-quant : add RAON quantization rules for attention projections
* vocab : move RAON to the standard tokenizer list and remove its dedicated tokenizer test
* convert : move MTP layer check to filter_tensors and correct comment on _KEEP_UNQUANTIZED
* convert : add orphan-scale gurad for MXFP8 scales
* model : remove redundant graph expansion, use require() for RDA head size validation, and add comment for MLA latent normalization
* llama : share KDA conv1d between Raon and Kimi K3
* convert : remove redundant MXFP8 dequantization
* model : align RAON MoE call formatting with other models
* tests : remove RAON quantization test
* model : match RAON MoE weight normalization to the HF reference
* set expert_weights_norm_eps to 1e-20, which introduced in commit 5c008e0
* tests : add Metal fusion test for Raon
Assisted-by: Codex
Assisted-by: Claude Opus 5.5
---------
Co-authored-by: Dong Won Kim <63934649+ddwkim@users.noreply.github.com>
Co-authored-by: Hyeonghwan Kim (κΉνν) <kim2h7903@krafton.com>
Co-authored-by: Seohyun Choi <seohyun.choi@krafton.com>
Co-authored-by: Piotr Wilkin <piotr.wilkin@syndatis.com>
diff --git a/conversion/__init__.py b/conversion/__init__.py
index 59ea85094..679682010 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -308,6 +308,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"RWForCausalLM": "falcon",
"RWKV6Qwen2ForCausalLM": "rwkv",
"RWKV7ForCausalLM": "rwkv",
+ "Raon1MiniForCausalLM": "raon1_mini",
"RobertaForSequenceClassification": "bert",
"RobertaModel": "bert",
"RuGPT3XLForCausalLM": "gpt2",
diff --git a/conversion/base.py b/conversion/base.py
index 540a66ba5..f55d85600 100644
--- a/conversion/base.py
+++ b/conversion/base.py
@@ -2473,6 +2473,9 @@ class TextModel(ModelBase):
if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3":
# ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF
res = "domyn-edge"
+ if chkhsh == "ffdae2f611dc6903980be2fbb108467cb97376d7d03cd332bb7e2602f87fa1f1":
+ # ref: https://huggingface.co/KRAFTON/Raon-1-mini-preview
+ res = "raon"
if res is None:
logger.warning("\n")
diff --git a/conversion/raon1_mini.py b/conversion/raon1_mini.py
new file mode 100644
index 000000000..6a195766b
--- /dev/null
+++ b/conversion/raon1_mini.py
@@ -0,0 +1,206 @@
+from __future__ import annotations
+
+from typing import Any, Callable, Iterable
+
+import torch
+from torch import Tensor
+
+from .base import ModelBase, TextModel, gguf
+
+
+_REQUIRED = object()
+
+
+def _renamed_key(config: dict[str, Any], new: str, old: str, default: Any = _REQUIRED) -> Any:
+ # the HF config accepts the older spellings (kda_layers, mhc_*): null counts as absent, a conflicting pair is an error
+ values = [config[key] for key in (new, old) if config.get(key) is not None]
+ if len(values) == 2 and values[0] != values[1]:
+ raise ValueError(f"Raon-1 mini config has conflicting {new}={values[0]!r} and {old}={values[1]!r}")
+ if values:
+ return values[0]
+ if default is _REQUIRED:
+ raise KeyError(f"Raon-1 mini config needs {new} (or the older spelling {old})")
+ return default
+
+
+def _rda_config(hp: dict[str, Any]) -> dict[str, Any]:
+ # rda_config is the current spelling; older exports use linear_attn_config with short_conv_kernel_size / use_full_rank_gate / full_attn_layers / kda_layers
+ if hp.get("rda_config") is not None and hp.get("linear_attn_config") is not None:
+ raise ValueError("Raon-1 mini config has both rda_config and the older linear_attn_config")
+ config = hp["rda_config"] if hp.get("rda_config") is not None else hp["linear_attn_config"]
+ result = {
+ "num_heads": config["num_heads"],
+ "head_dim": config["head_dim"],
+ "conv_kernel_size": _renamed_key(config, "conv_kernel_size", "short_conv_kernel_size"),
+ "full_rank_gate": _renamed_key(config, "full_rank_gate", "use_full_rank_gate"),
+ "mla_layers": _renamed_key(config, "mla_layers", "full_attn_layers"),
+ "rda_layers": _renamed_key(config, "rda_layers", "kda_layers"),
+ }
+ # absent and null differ here (see set_gguf_parameters), so the key is copied only when present
+ if "gate_lower_bound" in config:
+ result["gate_lower_bound"] = config["gate_lower_bound"]
+ return result
+
+
+@ModelBase.register("Raon1MiniForCausalLM")
+@ModelBase.example("KRAFTON/Raon-1-mini-preview")
+class Raon1MiniModel(TextModel):
+ model_arch = gguf.MODEL_ARCH.RAON1_MINI
+
+ # mHC sites: HF module name -> tensor prefix; each site has 10 parameters, packed into fn / base / scale
+ _MHC_SITES = (("self_attn_raon_mhc", "HC_ATTN"), ("mlp_raon_mhc", "HC_FFN"))
+ _MHC_PARTS = ("phi_pre", "phi_post", "res.phi_z", "b_pre", "b_post", "res.b_z",
+ "alpha_pre", "alpha_post", "res.alpha_z", "res.eta")
+ # Keep these tensors at F16 for direct conversion to Q8_0, TQ1_0 or TQ2_0.
+ _KEEP_UNQUANTIZED = ("hc_attn_fn", "hc_ffn_fn", "ssm_f_a", "ssm_f_b", "ssm_beta", "ssm_rda")
+ _KEEP_UNQUANTIZED_Q8_0 = ("attn_kv_a_mqa", "attn_k_b", "attn_v_b")
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._experts: dict[tuple[int, str], dict[int, Tensor]] = {}
+ self._mhc: dict[tuple[int, str], dict[str, Tensor]] = {}
+ self._rda_layers = set(_rda_config(self.hparams)["rda_layers"])
+
+ def filter_tensors(self, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
+ filtered = super().filter_tensors(item)
+ if filtered is None:
+ return None
+
+ name, _ = filtered
+ if name.startswith("model.layers."):
+ layer = name.split(".", 3)[2]
+ # MTP layers follow the main model layers.
+ if layer.isdecimal() and int(layer) >= self.hparams["num_hidden_layers"]:
+ return None
+
+ return filtered
+
+ def set_gguf_parameters(self):
+ hp = self.hparams
+ rda_config = _rda_config(hp)
+ n_layer = hp["num_hidden_layers"]
+ # 1-based layer ids, as in the HF config (is_rda_layer: layer_idx + 1 in rda_layers)
+ rda = self._rda_layers
+ mla = set(rda_config["mla_layers"])
+ if rda & mla or rda | mla != set(range(1, n_layer + 1)):
+ raise ValueError("Raon-1 mini attention layer lists must partition all layers")
+ # the hybrid memory needs both layer kinds
+ if not rda or not mla:
+ raise ValueError("Raon-1 mini needs at least one RDA (rda_layers) and one MLA (mla_layers) layer")
+ if hp.get("tie_word_embeddings"):
+ raise ValueError("Raon-1 mini with tie_word_embeddings is not supported (the released model has a separate lm_head)")
+ if (not hp["mla_use_nope"] or not hp["mla_use_output_gate"]
+ or not rda_config["full_rank_gate"] or hp["hidden_act"] != "situ"
+ or hp["moe_router_activation_func"] != "sigmoid"
+ or hp.get("use_grouped_topk") or hp.get("routed_expert_hidden_size")
+ or hp.get("attn_res_block_size") or hp["moe_layer_freq"] != 1):
+ raise ValueError("Unsupported Raon-1 mini architecture variant")
+ if rda_config["num_heads"] != hp["num_attention_heads"]:
+ raise ValueError("Raon-1 mini RDA and MLA head counts must match")
+
+ super().set_gguf_parameters()
+ self.gguf_writer.add_vocab_size(hp["vocab_size"])
+ self.gguf_writer.add_head_count_kv([0 if i + 1 in rda else 1 for i in range(n_layer)])
+ self.gguf_writer.add_ssm_conv_kernel(rda_config["conv_kernel_size"])
+ # the .get() defaults below are the HF config defaults
+ self.gguf_writer.add_ssm_time_step_rank(_renamed_key(hp, "rda_decay_rank", "kda_decay_rank", 128))
+ self.gguf_writer.add_kda_head_dim(rda_config["head_dim"])
+ # HF uses -5.0 when the key is absent; an explicit null selects the unbounded gate
+ if (bound := rda_config.get("gate_lower_bound", -5.0)) is not None:
+ self.gguf_writer.add_kda_gate_lower_bound(bound)
+ self.gguf_writer.add_q_lora_rank(hp["q_lora_rank"])
+ self.gguf_writer.add_kv_lora_rank(hp["kv_lora_rank"])
+ self.gguf_writer.add_rope_dimension_count(hp["qk_rope_head_dim"])
+ self.gguf_writer.add_key_length(hp["kv_lora_rank"] + hp["qk_rope_head_dim"])
+ self.gguf_writer.add_value_length(hp["kv_lora_rank"])
+ self.gguf_writer.add_key_length_mla(hp["qk_nope_head_dim"] + hp["qk_rope_head_dim"])
+ self.gguf_writer.add_value_length_mla(hp["v_head_dim"])
+ self.gguf_writer.add_latent_norm_rms_eps(hp.get("mla_latent_norm_eps", 1e-6))
+ self.gguf_writer.add_expert_feed_forward_length(hp["moe_intermediate_size"])
+ self.gguf_writer.add_expert_shared_count(hp["num_shared_experts"])
+ self.gguf_writer.add_leading_dense_block_count(hp["first_k_dense_replace"])
+ self.gguf_writer.add_expert_weights_scale(hp["routed_scaling_factor"])
+ self.gguf_writer.add_expert_weights_norm(hp["moe_renormalize"])
+ self.gguf_writer.add_activation_situ_beta(hp["activation_situ_beta"])
+ self.gguf_writer.add_activation_situ_linear_beta(hp["activation_situ_linear_beta"])
+ self.gguf_writer.add_hyper_connection_count(_renamed_key(hp, "raon_mhc_streams", "mhc_streams", 4))
+ self.gguf_writer.add_hyper_connection_epsilon(_renamed_key(hp, "raon_mhc_selector_eps", "mhc_selector_eps", 1e-5))
+ self.gguf_writer.add_hyper_connection_magnitude(_renamed_key(hp, "raon_mhc_post_factor", "mhc_post_factor", 2.0))
+
+ def prepare_tensors(self):
+ super().prepare_tensors()
+ if self._experts or self._mhc:
+ raise ValueError(f"Incomplete Raon-1 mini tensor groups: experts={list(self._experts)}, mHC={list(self._mhc)}")
+
+ def tensor_force_quant(self, name, new_name, bid, n_dims):
+ if ".hc_" in new_name and not new_name.endswith("_fn.weight"):
+ return gguf.GGMLQuantizationType.F32
+ quantized = (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.LlamaFileType.MOSTLY_TQ1_0, gguf.LlamaFileType.MOSTLY_TQ2_0)
+ if self.ftype in quantized and new_name.startswith("blk."):
+ keep = self._KEEP_UNQUANTIZED
+ if self.ftype == gguf.LlamaFileType.MOSTLY_Q8_0:
+ keep += self._KEEP_UNQUANTIZED_Q8_0
+ if new_name.split(".")[2] in keep:
+ return gguf.GGMLQuantizationType.F16
+ return super().tensor_force_quant(name, new_name, bid, n_dims)
+
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
+ for site, prefix in self._MHC_SITES:
+ marker = f".{site}."
+ if marker not in name:
+ continue
+ assert bid is not None
+ parts = self._mhc.setdefault((bid, site), {})
+ suffix = name.split(marker, 1)[1]
+ if suffix in parts:
+ raise ValueError(f"Duplicate tensor {name}")
+ parts[suffix] = data_torch
+ if len(parts) < len(self._MHC_PARTS):
+ return
+ fn = torch.cat([parts[k] for k in ("phi_pre", "phi_post", "res.phi_z")])
+ base = torch.cat([parts[k].float() for k in ("b_pre", "b_post", "res.b_z")])
+ scale = torch.stack([parts[k].float().reshape(()) for k in ("alpha_pre", "alpha_post", "res.alpha_z", "res.eta")])
+ for kind, tensor in (("FN", fn), ("BASE", base), ("SCALE", scale)):
+ yield from super().modify_tensors(tensor, self.format_tensor_name(getattr(gguf.MODEL_TENSOR, f"{prefix}_{kind}"), bid), bid)
+ del self._mhc[(bid, site)]
+ return
+
+ # moe.experts.{e}.{gate,down,up}_proj; older exports: block_sparse_moe.experts.{e}.{w1,w2,w3}
+ if ".moe.experts." in name or ".block_sparse_moe.experts." in name:
+ assert bid is not None
+ tail = name.split(".experts.", 1)[1].split(".")
+ eid, wid = int(tail[0]), tail[1]
+ group = self._experts.setdefault((bid, wid), {})
+ if eid in group or not 0 <= eid < self.hparams["num_experts"]:
+ raise ValueError(f"Invalid expert tensor {name}")
+ group[eid] = data_torch
+ if len(group) == self.hparams["num_experts"]:
+ tid = {"gate_proj": gguf.MODEL_TENSOR.FFN_GATE_EXP, "down_proj": gguf.MODEL_TENSOR.FFN_DOWN_EXP,
+ "up_proj": gguf.MODEL_TENSOR.FFN_UP_EXP, "w1": gguf.MODEL_TENSOR.FFN_GATE_EXP,
+ "w2": gguf.MODEL_TENSOR.FFN_DOWN_EXP, "w3": gguf.MODEL_TENSOR.FFN_UP_EXP}[wid]
+ yield from super().modify_tensors(torch.stack([group[i] for i in range(len(group))]), self.format_tensor_name(tid, bid), bid)
+ del self._experts[(bid, wid)]
+ return
+
+ if name.endswith("kv_b_proj.weight"):
+ n_head = self.hparams["num_attention_heads"]
+ qk_nope_head_dim, v_head_dim = self.hparams["qk_nope_head_dim"], self.hparams["v_head_dim"]
+ kv_b = data_torch.reshape(n_head, qk_nope_head_dim + v_head_dim, self.hparams["kv_lora_rank"])
+ k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
+ yield from super().modify_tensors(k_b.transpose(1, 2).contiguous(), name.replace("kv_b_proj", "k_b_proj"), bid)
+ yield from super().modify_tensors(v_b.contiguous(), name.replace("kv_b_proj", "v_b_proj"), bid)
+ return
+ if name.endswith(".self_attn.g_proj.weight"):
+ assert bid is not None
+ rda = bid + 1 in self._rda_layers
+ tid = gguf.MODEL_TENSOR.SSM_G if rda else gguf.MODEL_TENSOR.ATTN_GATE
+ yield self.format_tensor_name(tid, bid), data_torch
+ return
+ if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")):
+ data_torch = data_torch.reshape(1, -1, 1, data_torch.shape[-1])
+ if name.endswith(".A_log"):
+ data_torch = -torch.exp(data_torch.float())
+ # dt_bias -> the name SSM_DT's mapping expects, as for qwen3next
+ if name.endswith(".dt_bias"):
+ name = name.removesuffix(".dt_bias") + ".dt_proj.bias"
+ yield from super().modify_tensors(data_torch, name, bid)
diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py
index 91fb418a5..0b623a7b0 100755
--- a/convert_hf_to_gguf_update.py
+++ b/convert_hf_to_gguf_update.py
@@ -169,6 +169,7 @@ models = [
{"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", },
{"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", },
{"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", },
+ {"name": "raon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KRAFTON/Raon-1-mini-preview", },
]
# some models are known to be broken upstream, so we will skip them as exceptions
diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py
index bebc87067..15163565d 100644
--- a/gguf-py/gguf/constants.py
+++ b/gguf-py/gguf/constants.py
@@ -199,6 +199,7 @@ class Keys:
VALUE_LENGTH = "{arch}.attention.value_length"
LAYERNORM_EPS = "{arch}.attention.layer_norm_epsilon"
LAYERNORM_RMS_EPS = "{arch}.attention.layer_norm_rms_epsilon"
+ LATENT_NORM_RMS_EPS = "{arch}.attention.latent_norm_rms_epsilon"
GROUPNORM_EPS = "{arch}.attention.group_norm_epsilon"
GROUPNORM_GROUPS = "{arch}.attention.group_norm_groups"
CAUSAL = "{arch}.attention.causal"
@@ -775,6 +776,7 @@ class MODEL_ARCH(IntEnum):
KIMI_LINEAR = auto()
KIMI_K3 = auto()
KIMI_K31 = auto()
+ RAON1_MINI = auto()
TALKIE = auto()
MELLUM = auto()
NANBEIGE = auto()
@@ -978,6 +980,7 @@ class MODEL_TENSOR(IntEnum):
SSM_F_A = auto() # Kimi Linear
SSM_F_B = auto() # Kimi Linear
SSM_BETA = auto() # Kimi Linear qwen3.5
+ SSM_RDA = auto() # Raon-1 mini
SSM_G_A = auto() # Kimi Linear
SSM_G_B = auto() # Kimi Linear
SSM_G = auto() # Kimi K3 (full-rank KDA gate, replaces SSM_G_A/SSM_G_B)
@@ -1804,6 +1807,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.KIMI_LINEAR: "kimi-linear",
MODEL_ARCH.KIMI_K3: "kimi-k3",
MODEL_ARCH.KIMI_K31: "kimi-k31",
+ MODEL_ARCH.RAON1_MINI: "raon1",
MODEL_ARCH.TALKIE: "talkie",
MODEL_ARCH.MELLUM: "mellum",
MODEL_ARCH.NANBEIGE: "nanbeige",
@@ -2005,6 +2009,7 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
MODEL_TENSOR.SSM_F_A: "blk.{bid}.ssm_f_a", # Kimi Linear
MODEL_TENSOR.SSM_F_B: "blk.{bid}.ssm_f_b", # Kimi Linear
MODEL_TENSOR.SSM_BETA: "blk.{bid}.ssm_beta", # Kimi Linear qwen3.5
+ MODEL_TENSOR.SSM_RDA: "blk.{bid}.ssm_rda", # Raon-1 mini
MODEL_TENSOR.SSM_G_A: "blk.{bid}.ssm_g_a", # Kimi Linear
MODEL_TENSOR.SSM_G_B: "blk.{bid}.ssm_g_b", # Kimi Linear
MODEL_TENSOR.SSM_G: "blk.{bid}.ssm_g", # Kimi K3
@@ -6976,6 +6981,56 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.FFN_ROUTED_UP,
MODEL_TENSOR.FFN_ROUTED_NORM,
],
+ MODEL_ARCH.RAON1_MINI: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ # MLA (full-attention layers)
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_GATE,
+ MODEL_TENSOR.ATTN_Q_A,
+ MODEL_TENSOR.ATTN_Q_B,
+ MODEL_TENSOR.ATTN_KV_A_MQA,
+ MODEL_TENSOR.ATTN_K_B,
+ MODEL_TENSOR.ATTN_V_B,
+ MODEL_TENSOR.ATTN_Q_A_NORM,
+ MODEL_TENSOR.ATTN_KV_A_NORM,
+ # RDA (linear-attention layers)
+ MODEL_TENSOR.SSM_CONV1D_Q,
+ MODEL_TENSOR.SSM_CONV1D_K,
+ MODEL_TENSOR.SSM_CONV1D_V,
+ MODEL_TENSOR.SSM_F_A,
+ MODEL_TENSOR.SSM_F_B,
+ MODEL_TENSOR.SSM_BETA,
+ MODEL_TENSOR.SSM_RDA,
+ MODEL_TENSOR.SSM_A,
+ MODEL_TENSOR.SSM_G,
+ MODEL_TENSOR.SSM_DT,
+ MODEL_TENSOR.SSM_NORM,
+ MODEL_TENSOR.HC_ATTN_FN,
+ MODEL_TENSOR.HC_ATTN_BASE,
+ MODEL_TENSOR.HC_ATTN_SCALE,
+ MODEL_TENSOR.HC_FFN_FN,
+ MODEL_TENSOR.HC_FFN_BASE,
+ MODEL_TENSOR.HC_FFN_SCALE,
+ # FFN
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_EXP_PROBS_B,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ ],
MODEL_ARCH.TALKIE: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT,
diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py
index 900aef614..28b481e65 100644
--- a/gguf-py/gguf/gguf_writer.py
+++ b/gguf-py/gguf/gguf_writer.py
@@ -1053,6 +1053,9 @@ class GGUFWriter:
def add_layer_norm_rms_eps(self, value: float) -> None:
self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
+ def add_latent_norm_rms_eps(self, value: float) -> None:
+ self.add_float32(Keys.Attention.LATENT_NORM_RMS_EPS.format(arch=self.arch), value)
+
def add_group_norm_eps(self, value: float) -> None:
self.add_float32(Keys.Attention.GROUPNORM_EPS.format(arch=self.arch), value)
diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py
index c6946d53c..a8e7367c3 100644
--- a/gguf-py/gguf/tensor_mapping.py
+++ b/gguf-py/gguf/tensor_mapping.py
@@ -719,6 +719,7 @@ class TensorNameMap:
"backbone.layers.{bid}.mixer.gate.e_score_correction", # nemotron-h-moe
"model.layers.{bid}.mlp.e_score_correction", # exaone-moe
"model.layers.{bid}.block_sparse_moe.gate.e_score_correction", # kimi
+ "model.layers.{bid}.moe.gate.e_score_correction", # raon1_mini
"model.layers.{bid}.moe.router_bias", # step3.5 expert selection bias
"model.layers.{bid}.mlp.experts.e_score_correction", # laguna
),
@@ -792,6 +793,7 @@ class TensorNameMap:
"layers.{bid}.shared_experts.w3", # mistral-large
"backbone.layers.{bid}.mixer.shared_experts.up_proj", # nemotron-h-moe
"model.layers.{bid}.block_sparse_moe.shared_experts.up_proj", # kimi
+ "model.layers.{bid}.moe.shared_experts.up_proj", # raon1_mini
"model.layers.{bid}.share_expert.up_proj", # step3.5
),
@@ -845,6 +847,7 @@ class TensorNameMap:
"model.layers.{bid}.mlp.shared_mlp.gate_proj", # hunyuan
"layers.{bid}.shared_experts.w1", # mistral-large
"model.layers.{bid}.block_sparse_moe.shared_experts.gate_proj", # kimi
+ "model.layers.{bid}.moe.shared_experts.gate_proj", # raon1_mini
"model.layers.{bid}.share_expert.gate_proj", # step3.5
),
@@ -1027,6 +1030,7 @@ class TensorNameMap:
"layers.{bid}.shared_experts.w2", # mistral-large
"backbone.layers.{bid}.mixer.shared_experts.down_proj", # nemotron-h-moe
"model.layers.{bid}.block_sparse_moe.shared_experts.down_proj", # kimi
+ "model.layers.{bid}.moe.shared_experts.down_proj", # raon1_mini
"model.layers.{bid}.share_expert.down_proj", # step3.5
"layers.{bid}.moe.shared_expert.down", # metis16
),
@@ -1289,6 +1293,10 @@ class TensorNameMap:
"model.layers.{bid}.self_attn.b_proj", # Kimi Linear
"model.layers.{bid}.attention.b_proj", # bailingmoe3
),
+ # Raon-1 mini RDA: per-head write-gate offset
+ MODEL_TENSOR.SSM_RDA: (
+ "model.layers.{bid}.self_attn.rda_w_proj",
+ ),
# Kimi K3 latent MoE: routed experts operate in a down-projected space
MODEL_TENSOR.FFN_ROUTED_DOWN: (
"model.layers.{bid}.block_sparse_moe.routed_expert_down_proj",
diff --git a/models/templates/KRAFTON-Raon-1-mini-preview.jinja b/models/templates/KRAFTON-Raon-1-mini-preview.jinja
new file mode 100644
index 000000000..eff7831af
--- /dev/null
+++ b/models/templates/KRAFTON-Raon-1-mini-preview.jinja
@@ -0,0 +1,134 @@
+{#- Text-only ChatML SFT protocol for raon-1-mini. -#}
+{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else false %}
+{%- macro render_content(content, is_system_content=false) %}
+ {%- if content is string %}
+ {{- content }}
+ {%- elif content is iterable and content is not mapping %}
+ {%- for item in content %}
+ {%- if 'text' in item %}
+ {{- item.text }}
+ {%- else %}
+ {{- raise_exception('raon-1-mini supports text content only.') }}
+ {%- endif %}
+ {%- endfor %}
+ {%- elif content is none or content is undefined %}
+ {{- '' }}
+ {%- else %}
+ {{- raise_exception('Unexpected content type.') }}
+ {%- endif %}
+{%- endmacro %}
+{%- macro render_assistant_body(message, content, reasoning_content, preserve_reasoning) %}
+ {%- if preserve_reasoning and reasoning_content|trim %}
+ {{- '<think>\n' + reasoning_content|trim + '\n</think>\n\n' }}
+ {%- else %}
+ {{- '<think></think>\n\n' }}
+ {%- endif %}
+ {{- content }}
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
+ {%- for tool_call in message.tool_calls %}
+ {%- if tool_call.function is defined %}
+ {%- set tool_call = tool_call.function %}
+ {%- endif %}
+ {%- if loop.first %}
+ {%- if content|trim %}
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
+ {%- else %}
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
+ {%- endif %}
+ {%- if tool_call.arguments is defined %}
+ {%- for args_name, args_value in tool_call.arguments|items %}
+ {{- '<parameter=' + args_name + '>\n' }}
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
+ {{- args_value }}
+ {{- '\n</parameter>\n' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '</function>\n</tool_call>' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '<|im_end|>' }}
+{%- endmacro %}
+{%- if not messages %}
+ {{- raise_exception('No messages provided.') }}
+{%- endif %}
+{%- if tools and tools is iterable and tools is not mapping %}
+ {{- '<|im_start|>system\n' }}
+ {{- '# Tools\n\nYou have access to the following functions:\n\n<tools>' }}
+ {%- for tool in tools %}
+ {{- '\n' }}
+ {{- tool | tojson }}
+ {%- endfor %}
+ {{- '\n</tools>' }}
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
+ {%- if messages[0].role == 'system' %}
+ {%- set content = render_content(messages[0].content, true)|trim %}
+ {%- if content %}
+ {{- '\n\n' + content }}
+ {%- endif %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+{%- elif messages[0].role == 'system' %}
+ {%- set content = render_content(messages[0].content, true)|trim %}
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
+{%- endif %}
+{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
+{%- for message in messages[::-1] %}
+ {%- set index = (messages|length - 1) - loop.index0 %}
+ {%- if ns.multi_step_tool and message.role == 'user' %}
+ {%- set content = render_content(message.content)|trim %}
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
+ {%- set ns.multi_step_tool = false %}
+ {%- set ns.last_query_index = index %}
+ {%- endif %}
+ {%- endif %}
+{%- endfor %}
+{%- for message in messages %}
+ {%- set content = render_content(message.content)|trim %}
+ {%- if message.role == 'system' %}
+ {%- if not loop.first %}
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
+ {%- endif %}
+ {%- elif message.role == 'user' %}
+ {{- '<|im_start|>user\n' + content + '<|im_end|>\n' }}
+ {%- elif message.role == 'assistant' %}
+ {%- set reasoning_content = '' %}
+ {%- if message.reasoning_content is string %}
+ {%- set reasoning_content = message.reasoning_content %}
+ {%- elif content.startswith('<think>') and '</think>' in content %}
+ {%- set thinking_parts = content.split('</think>', 1) %}
+ {%- set reasoning_content = thinking_parts[0][7:].strip('\n') %}
+ {%- set content = thinking_parts[1].lstrip('\n') %}
+ {%- endif %}
+ {{- '<|im_start|>assistant\n' }}
+ {%- set preserve_reasoning = (not truncate_history_thinking) or (loop.index0 > ns.last_query_index) %}
+ {%- if message.loss is defined and message.loss is false %}
+ {{- render_assistant_body(message, content, reasoning_content, preserve_reasoning) }}
+ {%- else %}
+ {%- generation %}
+ {{- render_assistant_body(message, content, reasoning_content, preserve_reasoning) }}
+ {%- endgeneration %}
+ {%- endif %}
+ {{- '\n' }}
+ {%- elif message.role == 'tool' %}
+ {%- if loop.previtem and loop.previtem.role != 'tool' %}
+ {{- '<|im_start|>user' }}
+ {%- endif %}
+ {{- '\n<tool_response>\n' + content + '\n</tool_response>' }}
+ {%- if loop.last or loop.nextitem.role != 'tool' %}
+ {{- '<|im_end|>\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- raise_exception('Unexpected message role.') }}
+ {%- endif %}
+{%- endfor %}
+{%- if add_generation_prompt %}
+ {{- '<|im_start|>assistant\n' }}
+ {%- if enable_thinking is defined and enable_thinking is false %}
+ {{- '<think></think>\n\n' }}
+ {%- else %}
+ {{- '<think>\n' }}
+ {%- endif %}
+{%- endif %}
diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp
index e14f91557..53889e037 100644
--- a/src/llama-arch.cpp
+++ b/src/llama-arch.cpp
@@ -171,6 +171,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_KIMI_LINEAR, "kimi-linear" },
{ LLM_ARCH_KIMI_K3, "kimi-k3" },
{ LLM_ARCH_KIMI_K31, "kimi-k31" },
+ { LLM_ARCH_RAON1_MINI, "raon1" },
{ LLM_ARCH_GLM5_NEXT, "glm5-next" },
{ LLM_ARCH_TALKIE, "talkie" },
{ LLM_ARCH_MELLUM, "mellum" },
@@ -309,6 +310,7 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
{ LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
{ LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
{ LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
+ { LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, "%s.attention.latent_norm_rms_epsilon" },
{ LLM_KV_ATTENTION_GROUPNORM_EPS, "%s.attention.group_norm_epsilon" },
{ LLM_KV_ATTENTION_GROUPNORM_GROUPS, "%s.attention.group_norm_groups" },
{ LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
@@ -703,6 +705,7 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
{ LLM_TENSOR_SSM_F_A, "blk.%d.ssm_f_a" },
{ LLM_TENSOR_SSM_F_B, "blk.%d.ssm_f_b" },
{ LLM_TENSOR_SSM_BETA, "blk.%d.ssm_beta" },
+ { LLM_TENSOR_SSM_RDA, "blk.%d.ssm_rda" },
{ LLM_TENSOR_SSM_G_A, "blk.%d.ssm_g_a" },
{ LLM_TENSOR_SSM_G, "blk.%d.ssm_g" },
{ LLM_TENSOR_ATTN_RES_SCORE, "blk.%d.attn_res_score" },
@@ -1146,6 +1149,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{LLM_TENSOR_SSM_F_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_F_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_BETA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
+ {LLM_TENSOR_SSM_RDA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_G_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_G, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_RES_SCORE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
@@ -1497,6 +1501,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) {
case LLM_ARCH_BAILINGMOE3:
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
+ case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_GLM5_NEXT:
case LLM_ARCH_QWEN35:
case LLM_ARCH_QWEN35MOE:
@@ -1530,6 +1535,7 @@ bool llm_arch_supports_rs_rollback(const llm_arch & arch) {
switch (arch) {
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
+ case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_QWEN35:
case LLM_ARCH_QWEN35MOE:
case LLM_ARCH_CLOVER_MOE:
@@ -1611,6 +1617,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
case LLM_ARCH_BAILINGMOE3:
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
+ case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_QWEN3TTS:
case LLM_ARCH_LIMITE:
return false;
diff --git a/src/llama-arch.h b/src/llama-arch.h
index 9d0ced590..fedc879bf 100644
--- a/src/llama-arch.h
+++ b/src/llama-arch.h
@@ -169,6 +169,7 @@ enum llm_arch {
LLM_ARCH_KIMI_LINEAR,
LLM_ARCH_KIMI_K3,
LLM_ARCH_KIMI_K31,
+ LLM_ARCH_RAON1_MINI,
LLM_ARCH_GLM5_NEXT,
LLM_ARCH_TALKIE,
LLM_ARCH_MELLUM,
@@ -315,6 +316,7 @@ enum llm_kv {
LLM_KV_ATTENTION_VALUE_LENGTH,
LLM_KV_ATTENTION_LAYERNORM_EPS,
LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
+ LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS,
LLM_KV_ATTENTION_GROUPNORM_EPS,
LLM_KV_ATTENTION_GROUPNORM_GROUPS,
LLM_KV_ATTENTION_CAUSAL,
@@ -710,6 +712,7 @@ enum llm_tensor {
LLM_TENSOR_SSM_F_A, // kimi: forget gate projection A
LLM_TENSOR_SSM_F_B, // kimi: forget gate projection B
LLM_TENSOR_SSM_BETA, // kimi: beta mixing coefficient and qwen3.5
+ LLM_TENSOR_SSM_RDA, // raon1_mini: write gate offset
LLM_TENSOR_SSM_G_A, // kimi: output gate projection A
LLM_TENSOR_SSM_G_B, // kimi: output gate projection B
LLM_TENSOR_SSM_G, // kimi-k3: full-rank KDA gate
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 38a37ae75..aa0b93045 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -196,7 +196,7 @@ llama_context::llama_context(
model.arch == LLM_ARCH_CLOVER_MOE ||
// KDA
model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT ||
- model.arch == LLM_ARCH_BAILINGMOE3);
+ model.arch == LLM_ARCH_BAILINGMOE3 || model.arch == LLM_ARCH_RAON1_MINI);
cparams.n_threads = params.n_threads;
cparams.n_threads_batch = params.n_threads_batch;
diff --git a/src/llama-hparams.h b/src/llama-hparams.h
index b6a373bfe..e87667a7d 100644
--- a/src/llama-hparams.h
+++ b/src/llama-hparams.h
@@ -146,6 +146,7 @@ struct llama_hparams {
float f_norm_eps;
float f_norm_rms_eps;
float f_norm_group_eps;
+ float f_norm_rms_eps_latent = 0.0f; // RMS norm of the MLA q/kv latents (Raon-1 mini)
// post norms use their own epsilon
float f_post_norm_eps = 0.0f;
diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp
index 51315fb5c..00b169ef6 100644
--- a/src/llama-model-saver.cpp
+++ b/src/llama-model-saver.cpp
@@ -268,6 +268,7 @@ void llama_model_saver::add_kv_from_model() {
add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
add_kv(LLM_KV_POST_NORM_EPS, hparams.f_post_norm_eps);
+ add_kv(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, hparams.f_norm_rms_eps_latent);
add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, hparams.f_norm_group_eps);
add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, hparams.n_norm_groups);
add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_COUNT, hparams.n_value_expert);
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index e451b244e..72ad1b0e3 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -391,6 +391,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
return new llama_model_kimi_k3(params);
case LLM_ARCH_KIMI_K31:
return new llama_model_kimi_k31(params);
+ case LLM_ARCH_RAON1_MINI:
+ return new llama_model_raon1_mini(params);
case LLM_ARCH_GLM5_NEXT:
return new llama_model_glm5_next(params);
case LLM_ARCH_STEP35:
@@ -1195,6 +1197,7 @@ const char * llm_type_name(llm_type type) {
case LLM_TYPE_21B_A3B: return "21B.A3B";
case LLM_TYPE_24B_A2B: return "24B.A2B";
case LLM_TYPE_26B_A4B: return "26B.A4B";
+ case LLM_TYPE_29B_A4B: return "29B.A4B";
case LLM_TYPE_30B_A3B: return "30B.A3B";
case LLM_TYPE_31B_A3_5B: return "31B.A3.5B";
case LLM_TYPE_32B_A9B: return "32B.A9B";
@@ -3892,6 +3895,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
case LLM_ARCH_KIMI_LINEAR:
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
+ case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_GLM5_NEXT:
case LLM_ARCH_STARCODER:
case LLM_ARCH_INKLING2:
diff --git a/src/llama-model.h b/src/llama-model.h
index 72e5fd6cb..62fbda68a 100644
--- a/src/llama-model.h
+++ b/src/llama-model.h
@@ -130,6 +130,7 @@ enum llm_type {
LLM_TYPE_21B_A3B, // Ernie MoE small
LLM_TYPE_24B_A2B, // lfm2moe
LLM_TYPE_26B_A4B, // Gemma4
+ LLM_TYPE_29B_A4B, // Raon-1 mini
LLM_TYPE_30B_A3B,
LLM_TYPE_31B_A3_5B,
LLM_TYPE_32B_A9B, // Granite4 Hybrid
@@ -612,6 +613,7 @@ struct llama_layer {
struct ggml_tensor * ssm_f_a = nullptr;
struct ggml_tensor * ssm_f_b = nullptr;
struct ggml_tensor * ssm_beta = nullptr;
+ struct ggml_tensor * ssm_rda = nullptr;
struct ggml_tensor * ssm_g_a = nullptr;
struct ggml_tensor * ssm_g_b = nullptr;
struct ggml_tensor * ssm_o_norm = nullptr;
diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp
index 5381f672a..c1fab892f 100644
--- a/src/llama-quant.cpp
+++ b/src/llama-quant.cpp
@@ -407,6 +407,15 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param
quantize &= name.find("hc_") == std::string::npos;
}
+ // raon1_mini: mHC selectors and small RDA gate projections
+ if (arch == LLM_ARCH_RAON1_MINI) {
+ quantize &= name.find("hc_") == std::string::npos;
+ quantize &= name.find("ssm_f_a.weight") == std::string::npos;
+ quantize &= name.find("ssm_f_b.weight") == std::string::npos;
+ quantize &= name.find("ssm_beta.weight") == std::string::npos;
+ quantize &= name.find("ssm_rda.weight") == std::string::npos;
+ }
+
// the decision head of vllm-decision2 is small and computed in F32
if (arch == LLM_ARCH_VLLM_DECISION2) {
quantize &= name.compare(0, 9, "decision.") != 0;
@@ -500,6 +509,10 @@ static ggml_type tensor_type_fallback(quantize_state_impl & qs, const ggml_tenso
return fallback_type;
}
+static double bits_per_weight(ggml_type t) {
+ return 8.0 * ggml_type_size(t) / ggml_blck_size(t);
+}
+
// select the target tensor type based on tensor category, ftype, and model arch
static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype, tensor_category category) {
const std::string name = ggml_get_name(tensor);
@@ -538,11 +551,19 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
}
}
+ // raon1_mini: at Q6_K and Q8_0, where the floors below do not apply, keep the MLA latent projections at source precision:
+ // quantizing them costs +5.8% mean KL in Q8_0 for 44 MB. --pure and --tensor-type bypass this, as for the floors
+ if (arch == LLM_ARCH_RAON1_MINI && (ftype == LLAMA_FTYPE_MOSTLY_Q6_K || ftype == LLAMA_FTYPE_MOSTLY_Q8_0) && (
+ name.find("attn_kv_a_mqa.weight") != std::string::npos ||
+ name.find("attn_k_b.weight") != std::string::npos ||
+ name.find("attn_v_b.weight") != std::string::npos)) {
+ return tensor->type;
+ }
+
// bumping to q8_0 is preferred since these tensors are not really big
// TODO: nemotron 3 super shares ffn_latent and afmoe, bailingmoe3, dots3note, hy-v4, kimi-k3 and laguna share attn_gate.
// Widening the guard is likely a win there too, but it changes their files, so it wants a perplexity comparison per architecture first.
if (arch == LLM_ARCH_MUSE_SPARK && (category == TENSOR_CATEGORY_FFN_LATENT || category == TENSOR_CATEGORY_ATTENTION_GATE)) {
- auto bits_per_weight = [](ggml_type t) { return 8.0 * ggml_type_size(t) / ggml_blck_size(t); };
if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { new_type = GGML_TYPE_Q8_0; }
}
@@ -724,6 +745,34 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
++qs.i_ffn_up;
}
+ // raon1_mini: the dense attention projections and the shared expert carry most of the low-bit loss, attn_output and attn_gate most of all
+ // only raise to a floor, after the counters above are updated, so the rest of the mixture does not change
+ if (arch == LLM_ARCH_RAON1_MINI && ggml_is_quantized(new_type)) {
+ const bool k_4_5 = ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M ||
+ ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M;
+ // IQ4_XS/NL and the 1-3 bit K and IQ mixtures (not Q2_0, TQ1_0, TQ2_0 or Q1_0)
+ const bool low = ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
+ ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ||
+ ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
+ ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S ||
+ ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S ||
+ ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M;
+ ggml_type floor_type = GGML_TYPE_COUNT;
+ if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT || category == TENSOR_CATEGORY_ATTENTION_GATE) {
+ floor_type = k_4_5 ? GGML_TYPE_Q8_0 : low ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT;
+ } else if (name.find("attn_q_a.weight") != std::string::npos || name.find("attn_q_b.weight") != std::string::npos ||
+ name.find("attn_k_b.weight") != std::string::npos || name.find("attn_kv_a_mqa.weight") != std::string::npos ||
+ name.find("attn_v_b.weight") != std::string::npos || name.find("_shexp.weight") != std::string::npos) {
+ floor_type = k_4_5 || low ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT;
+ } else if (category == TENSOR_CATEGORY_ATTENTION_Q || category == TENSOR_CATEGORY_ATTENTION_K ||
+ category == TENSOR_CATEGORY_ATTENTION_V || name.find("ssm_g.weight") != std::string::npos) {
+ floor_type = k_4_5 ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT;
+ }
+ if (floor_type != GGML_TYPE_COUNT && bits_per_weight(new_type) < bits_per_weight(floor_type)) {
+ new_type = floor_type;
+ }
+ }
+
return new_type;
}
diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp
index 9e83a983e..674daaa23 100644
--- a/src/llama-vocab.cpp
+++ b/src/llama-vocab.cpp
@@ -401,6 +401,12 @@ struct llm_tokenizer_bpe : llm_tokenizer {
"(?:'[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_RAON:
+ regex_exprs = {
+ // regex from tokenizer.json (the CJK ranges are literal characters there), matched byte for byte in unicode_regex_split_custom()
+ " ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\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
@@ -685,6 +691,14 @@ struct llm_tokenizer_bpe_session {
}
}
word_collection = unicode_regex_split(normalized_text, tokenizer.regex_exprs, tokenizer.byte_encode);
+ } else if (tok_pre == LLAMA_VOCAB_PRE_TYPE_RAON) {
+ // Raon-1 mini's HF tokenizer applies an NFC normalizer before pre-tokenization.
+ // TODO: the converter also writes tokenizer.ggml.normalizer.nfc (read for UGM only); gate BPE on that flag once #30708 lands
+ std::string normalized_text;
+ for (const uint32_t cpt : unicode_cpts_normalize_nfc(unicode_cpts_from_utf8(text))) {
+ normalized_text += unicode_cpt_to_utf8(cpt);
+ }
+ word_collection = unicode_regex_split(normalized_text, tokenizer.regex_exprs, tokenizer.byte_encode);
} else {
word_collection = unicode_regex_split(text, tokenizer.regex_exprs, tokenizer.byte_encode);
}
@@ -2561,6 +2575,9 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
tokenizer_pre == "domyn-edge") {
pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2;
clean_spaces = false;
+ } else if (tokenizer_pre == "raon") {
+ pre_type = LLAMA_VOCAB_PRE_TYPE_RAON;
+ clean_spaces = false;
} else if (
tokenizer_pre == "qwen35") {
pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35;
diff --git a/src/llama-vocab.h b/src/llama-vocab.h
index 425a3236c..b3e8cd7e1 100644
--- a/src/llama-vocab.h
+++ b/src/llama-vocab.h
@@ -77,6 +77,7 @@ enum llama_vocab_pre_type {
LLAMA_VOCAB_PRE_TYPE_SOPRANO = 65,
LLAMA_VOCAB_PRE_TYPE_TEKKEN_NUM3 = 66,
LLAMA_VOCAB_PRE_TYPE_ZONOS3 = 67,
+ LLAMA_VOCAB_PRE_TYPE_RAON = 68,
};
// HF Metaspace pre-tokenizer prepend_scheme
diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp
index f05bd8c0a..f71e7fddd 100644
--- a/src/models/delta-net-base.cpp
+++ b/src/models/delta-net-base.cpp
@@ -80,6 +80,50 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
return conv_input;
}
+// qkv selects one third of the shared convolution state row: Q, K or V.
+ggml_tensor * llm_build_delta_net_base::build_kda_conv1d(
+ llm_graph_input_rs * inp,
+ ggml_tensor * conv_states_all,
+ ggml_tensor * conv_states_seq,
+ int64_t qkv,
+ ggml_tensor * x_proj,
+ ggml_tensor * conv_w,
+ int64_t d_conv,
+ int64_t head_dim,
+ int64_t n_heads,
+ int64_t n_seq_tokens,
+ int64_t n_seqs,
+ int il) {
+ const int64_t d_inner = head_dim * n_heads;
+ const int64_t conv_state_size = (d_conv - 1) * d_inner;
+ const int64_t n_embd_r_total = 3 * conv_state_size;
+
+ ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
+
+ ggml_tensor * conv_x = nullptr;
+ if (cparams.rs_replay) {
+ // the row holds the q, k and v conv histories one after the other
+ conv_x = build_conv_state_replay(inp, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_states_seq, qkv);
+ } else {
+ ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_states_seq, d_conv - 1, d_inner, n_seqs,
+ (d_conv - 1) * ggml_element_size(conv_states_seq),
+ n_embd_r_total * ggml_element_size(conv_states_seq),
+ qkv * conv_state_size * ggml_element_size(conv_states_seq));
+
+ conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_3d), 0);
+
+ build_conv_state_store(inp, conv_states_all, conv_x, d_conv - 1,
+ ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ }
+
+ ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
+ ggml_tensor * conv_out = ggml_ssm_conv(ctx0, conv_x, conv_weight);
+ conv_out = ggml_reshape_2d(ctx0, conv_out, d_inner, n_tokens);
+ conv_out = ggml_silu(ctx0, conv_out);
+
+ return ggml_reshape_4d(ctx0, conv_out, head_dim, n_heads, n_seq_tokens, n_seqs);
+}
+
// [TAG_RECURRENT_REPLAY]
// rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled
// back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits
diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp
index e0ef7b6cd..846a48866 100644
--- a/src/models/kimi-k3.cpp
+++ b/src/models/kimi-k3.cpp
@@ -351,42 +351,6 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) :
// KDA layer
//
-// causal conv1d over one of Q/K/V. `qkv` selects which third of the conv state to use
-ggml_tensor * llama_model_kimi_k3::graph::build_kda_conv1d(
- llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
- int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
- const int64_t d_inner = head_dim * n_head_kda;
- const int64_t conv_state_size = (d_conv - 1) * d_inner;
- const int64_t n_embd_r_total = 3 * conv_state_size;
-
- ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
- ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
-
- ggml_tensor * conv_x = nullptr;
- if (cparams.rs_replay) {
- // the row holds the q, k and v conv histories one after the other
- conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
- } else {
- ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
- (d_conv - 1) * ggml_element_size(conv_state_all),
- n_embd_r_total * ggml_element_size(conv_state_all),
- qkv * conv_state_size * ggml_element_size(conv_state_all));
-
- conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
-
- build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
- ggml_row_size(conv_states_all->type, qkv * conv_state_size));
- }
-
- ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
- ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
- Xcur = ggml_reshape_2d(ctx0, Xcur, d_inner, n_tokens);
- Xcur = ggml_silu(ctx0, Xcur);
-
- return ggml_reshape_4d(ctx0, Xcur, head_dim, n_head_kda, n_seq_tokens, n_seqs);
-}
-
ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer(
ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda,
@@ -397,9 +361,12 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer(
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
- ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
- ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
- ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, ggml_mul_mat(ctx0, layer.wq, cur),
+ layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, ggml_mul_mat(ctx0, layer.wk, cur),
+ layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, ggml_mul_mat(ctx0, layer.wv, cur),
+ layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
diff --git a/src/models/models.h b/src/models/models.h
index dbf5f977a..85b97dda0 100644
--- a/src/models/models.h
+++ b/src/models/models.h
@@ -55,6 +55,20 @@ struct llm_build_delta_net_base : public llm_graph_context {
int64_t conv_channels,
int il);
+ ggml_tensor * build_kda_conv1d(
+ llm_graph_input_rs * inp,
+ ggml_tensor * conv_states_all,
+ ggml_tensor * conv_states_seq,
+ int64_t qkv,
+ ggml_tensor * x_proj,
+ ggml_tensor * conv_w,
+ int64_t d_conv,
+ int64_t head_dim,
+ int64_t n_heads,
+ int64_t n_seq_tokens,
+ int64_t n_seqs,
+ int il);
+
// run delta-net attention and write the new recurrent state(s) back to ssm_states_all
// s: (head_v_dim, head_v_dim, num_v_heads, n_seqs); returns output: (head_v_dim, num_v_heads, n_seq_tokens, n_seqs)
ggml_tensor * build_recurrent_attn(
@@ -3296,11 +3310,6 @@ struct llama_model_kimi_k3 : public llama_model_base {
int64_t d_conv, int64_t head_dim, int64_t n_head_kda,
int64_t d_inner, int64_t n_seq_tokens, int64_t n_seqs, int il);
- // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
- ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
- int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il);
-
ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer,
llm_graph_input_attn_k * inp_attn_k,
llm_graph_input_attn_kv * inp_attn_kv,
@@ -3363,6 +3372,39 @@ struct llama_model_kimi_k31 : public llama_model_base {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
+struct llama_model_raon1_mini : public llama_model_base {
+ llama_model_raon1_mini(const struct llama_model_params & params) : llama_model_base(params) {}
+ void load_arch_hparams(llama_model_loader & ml) override;
+ void load_arch_tensors(llama_model_loader & ml) override;
+ uint32_t graph_nodes_per_tensor() const override { return 64; }
+ std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
+
+ struct graph : public llm_build_delta_net_base {
+ graph(const llm_graph_params & params);
+
+ ggml_tensor * helmert = nullptr;
+ ggml_tensor * identity = nullptr;
+ ggml_tensor * chart_base = nullptr;
+
+ ggml_tensor * build_hc_pre(ggml_tensor * x, ggml_tensor * fn, ggml_tensor * scale,
+ ggml_tensor * base, ggml_tensor ** post, ggml_tensor ** comb, int il);
+
+ ggml_tensor * build_hc_post(ggml_tensor * x, ggml_tensor * branch,
+ ggml_tensor * post, ggml_tensor * comb, int il);
+
+ ggml_tensor * build_rda_gate(ggml_tensor * x, ggml_tensor * ssm_a);
+
+ ggml_tensor * build_rda_layer(ggml_tensor * cur, const llama_layer & layer,
+ llm_graph_input_rs * inp_rs, int il);
+
+ ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer,
+ llm_graph_input_attn_k * inp_attn_k, int il);
+
+ ggml_tensor * build_situ_ffn(ggml_tensor * cur, ggml_tensor * up, ggml_tensor * gate,
+ ggml_tensor * down, int il);
+ };
+};
+
struct llama_model_glm5_next : public llama_model_base {
llama_model_glm5_next(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
diff --git a/src/models/raon1-mini.cpp b/src/models/raon1-mini.cpp
new file mode 100644
index 000000000..e5b1671ec
--- /dev/null
+++ b/src/models/raon1-mini.cpp
@@ -0,0 +1,484 @@
+#include "models.h"
+
+#include "llama-impl.h"
+
+#include "llama-memory-recurrent.h"
+
+void llama_model_raon1_mini::load_arch_hparams(llama_model_loader & ml) {
+ ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
+ ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl);
+ ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl);
+ ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
+ ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
+ ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
+ ml.get_key(LLM_KV_KDA_HEAD_DIM, hparams.n_embd_head_kda);
+ ml.get_key(LLM_KV_KDA_GATE_LOWER_BOUND, hparams.kda_gate_lower_bound, false);
+
+ uint32_t n_rda = 0;
+ for (uint32_t i = 0; i < hparams.n_layer(); ++i) {
+ hparams.is_recr_impl[i] = hparams.n_head_kv(i) == 0;
+ n_rda += hparams.is_recr_impl[i];
+ if (!hparams.is_recr_impl[i] && hparams.n_head_kv(i) != 1) {
+ throw std::runtime_error(format("Raon-1 mini MLA layers must have one KV head, layer %u has %u", i, hparams.n_head_kv(i)));
+ }
+ }
+ // the hybrid memory needs both kinds: RDA layers (head_count_kv 0) and MLA layers (head_count_kv 1)
+ if (n_rda == 0 || n_rda == hparams.n_layer()) {
+ throw std::runtime_error(format("Raon-1 mini needs both RDA and MLA layers, got %u RDA of %u layers", n_rda, hparams.n_layer()));
+ }
+
+ ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all);
+ ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
+ ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
+ ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
+ ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm);
+ ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func);
+
+ ml.get_key(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, hparams.f_norm_rms_eps_latent);
+ ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
+ ml.get_key(LLM_KV_HYPER_CONNECTION_COUNT, hparams.dsv4_hc_mult);
+ ml.get_key(LLM_KV_HYPER_CONNECTION_EPSILON, hparams.dsv4_hc_eps);
+ ml.get_key(LLM_KV_HYPER_CONNECTION_MAGNITUDE, hparams.hc_magnitude);
+ ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta);
+ ml.get_key(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, hparams.situ_linear_beta);
+
+ // The Raon router normalizes selected scores by sum(scores) + 1e-20.
+ hparams.expert_weights_norm_eps = 1e-20f;
+
+ auto require = [](bool ok, const std::string & what) {
+ if (!ok) {
+ throw std::runtime_error("invalid Raon-1 mini hyperparameters: " + what);
+ }
+ };
+ // accepted ranges; only 2-4 mHC streams and a conv width of 4 have been run (the released model uses 4 streams)
+ require(hparams.dsv4_hc_mult >= 2 && hparams.dsv4_hc_mult <= 8, format("hyper_connection.count %u is not in [2, 8]", hparams.dsv4_hc_mult));
+ require(hparams.ssm_d_conv == 4, format("ssm.conv_kernel %u is not 4", hparams.ssm_d_conv));
+ require(hparams.ssm_dt_rank > 0, "ssm.time_step_rank is 0");
+ require(hparams.n_lora_q > 0 && hparams.n_lora_kv > 0, "q_lora_rank or kv_lora_rank is 0");
+ // the absorbed MLA attends over the latent: V is the kv_lora_rank-wide latent
+ require(hparams.n_embd_head_v_full == hparams.n_lora_kv, format("the MLA value length %u is not kv_lora_rank %u", hparams.n_embd_head_v_full, hparams.n_lora_kv));
+ require(hparams.n_embd_head_k_mla() > hparams.n_rot(), format("the MLA key length %u is not larger than the RoPE dimension %u", hparams.n_embd_head_k_mla(), hparams.n_rot()));
+ require(hparams.f_norm_rms_eps_latent > 0 && hparams.dsv4_hc_eps > 0, "a normalization epsilon is not positive");
+ require(hparams.hc_magnitude > 0, "hyper_connection.magnitude is not positive");
+ require(hparams.situ_beta > 0 && hparams.situ_linear_beta > 0, "a SiTU beta is not positive");
+ require(hparams.n_layer_dense_lead <= hparams.n_layer(), format("leading_dense_block_count %u is larger than block_count %u", hparams.n_layer_dense_lead, hparams.n_layer()));
+ const auto head_dim = hparams.n_embd_head_kda;
+ require(head_dim == 16 || head_dim == 32 || head_dim == 64 || head_dim == 128,
+ format("RDA head dimension %u is not 16, 32, 64 or 128", head_dim));
+
+ switch (hparams.n_layer()) {
+ case 25: type = LLM_TYPE_29B_A4B; break;
+ default: type = LLM_TYPE_UNKNOWN;
+ }
+}
+
+void llama_model_raon1_mini::load_arch_tensors(llama_model_loader &) {
+ LLAMA_LOAD_LOCALS;
+
+ const int64_t hc = hparams.dsv4_hc_mult;
+ // selector width per mHC site: pre (hc) + post (hc) + combination ((hc-1)^2, Helmert coordinates)
+ const int64_t hc_mix_dim = 2*hc + (hc - 1)*(hc - 1);
+
+ tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
+
+ output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
+ output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0);
+
+ for (int i = 0; i < n_layer; ++i) {
+ auto & layer = layers[i];
+
+ layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
+ layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
+
+ layer.hc_attn_fn = create_tensor(tn(LLM_TENSOR_HC_ATTN_FN, "weight", i), {hc*n_embd, hc_mix_dim}, 0);
+ layer.hc_attn_base = create_tensor(tn(LLM_TENSOR_HC_ATTN_BASE, "weight", i), {hc_mix_dim}, 0);
+ // scale: alpha_pre, alpha_post, alpha_z, eta
+ layer.hc_attn_scale = create_tensor(tn(LLM_TENSOR_HC_ATTN_SCALE, "weight", i), {4}, 0);
+ layer.hc_ffn_fn = create_tensor(tn(LLM_TENSOR_HC_FFN_FN, "weight", i), {hc*n_embd, hc_mix_dim}, 0);
+ layer.hc_ffn_base = create_tensor(tn(LLM_TENSOR_HC_FFN_BASE, "weight", i), {hc_mix_dim}, 0);
+ layer.hc_ffn_scale = create_tensor(tn(LLM_TENSOR_HC_FFN_SCALE, "weight", i), {4}, 0);
+
+ const int64_t head_dim = hparams.n_embd_head_kda;
+ const int64_t d_conv = hparams.ssm_d_conv;
+ const int64_t d_inner = head_dim * n_head;
+
+ if (hparams.is_recr(i)) {
+ layer.ssm_q_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_Q, "weight", i), {d_conv, 1, d_inner, 1}, 0);
+ layer.ssm_k_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_K, "weight", i), {d_conv, 1, d_inner, 1}, 0);
+ layer.ssm_v_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_V, "weight", i), {d_conv, 1, d_inner, 1}, 0);
+
+ create_tensor_qkv(layer, i, n_embd, d_inner, d_inner, d_inner, 0);
+
+ layer.ssm_f_a = create_tensor(tn(LLM_TENSOR_SSM_F_A, "weight", i), {n_embd, hparams.ssm_dt_rank}, 0);
+ layer.ssm_f_b = create_tensor(tn(LLM_TENSOR_SSM_F_B, "weight", i), {hparams.ssm_dt_rank, d_inner}, 0);
+ layer.ssm_beta = create_tensor(tn(LLM_TENSOR_SSM_BETA, "weight", i), {n_embd, n_head}, 0);
+ layer.ssm_rda = create_tensor(tn(LLM_TENSOR_SSM_RDA, "weight", i), {n_embd, n_head}, 0);
+
+ layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A_NOSCAN, i), {n_head}, 0);
+ layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner}, 0);
+
+ layer.ssm_g = create_tensor(tn(LLM_TENSOR_SSM_G, "weight", i), {n_embd, d_inner}, 0);
+ layer.ssm_o_norm = create_tensor(tn(LLM_TENSOR_SSM_NORM, "weight", i), {head_dim}, 0);
+ layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {d_inner, n_embd}, 0);
+ } else {
+ const int64_t q_lora_rank = hparams.n_lora_q;
+ const int64_t kv_lora_rank = hparams.n_lora_kv;
+ const int64_t n_embd_head_k = hparams.n_embd_head_k_mla();
+ const int64_t n_embd_head_v = hparams.n_embd_head_v_mla();
+ const int64_t qk_rope_head_dim = hparams.n_rot();
+ const int64_t qk_nope_head_dim = n_embd_head_k - qk_rope_head_dim;
+
+ layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0);
+ layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0);
+ layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0);
+ layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head*n_embd_head_k}, 0);
+ layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + qk_rope_head_dim}, 0);
+ layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {qk_nope_head_dim, kv_lora_rank, n_head}, 0);
+ layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v, n_head}, 0);
+ layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head*n_embd_head_v}, 0);
+
+ layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head * n_embd_head_v, n_embd}, 0);
+ }
+
+ if (i < (int) hparams.n_layer_dense_lead) {
+ layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
+ layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
+ layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
+ } else {
+ const int64_t n_ff_exp = hparams.n_ff_exp();
+
+ layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
+ layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0);
+
+ layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0);
+ layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
+ layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0);
+
+ if (hparams.n_expert_shared > 0) {
+ const int64_t n_ff_shexp = n_ff_exp * hparams.n_expert_shared;
+ layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0);
+ layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0);
+ layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0);
+ }
+ }
+ }
+}
+
+std::unique_ptr<llm_graph_context> llama_model_raon1_mini::build_arch_graph(const llm_graph_params & params) const {
+ return std::make_unique<graph>(params);
+}
+
+// decay gate from x = f_b(f_a(cur)) + dt_bias; ssm_a holds -exp(A_log)
+// with gate_lower_bound: g = lower_bound * sigmoid(exp(A_log) * x), else g = -softplus(exp(A_log) * x)
+ggml_tensor * llama_model_raon1_mini::graph::build_rda_gate(ggml_tensor * x, ggml_tensor * ssm_a) {
+ const int64_t head_dim = hparams.n_embd_head_kda;
+
+ ggml_tensor * A = ggml_reshape_3d(ctx0, ssm_a, 1, n_head, 1);
+
+ x = ggml_reshape_3d(ctx0, x, head_dim, n_head, n_tokens);
+ x = ggml_mul(ctx0, x, A);
+
+ // gate_lower_bound is not a clamp - when set, it swaps the decay gate activation
+ if (hparams.kda_gate_lower_bound > -INFINITY) {
+ x = ggml_sigmoid(ctx0, ggml_scale(ctx0, x, -1.0f));
+ return ggml_scale(ctx0, x, hparams.kda_gate_lower_bound);
+ }
+
+ return ggml_neg(ctx0, ggml_softplus(ctx0, ggml_neg(ctx0, x)));
+}
+
+// Raon delta attention: a gated delta-rule layer whose write gate differs from its erase gate
+ggml_tensor * llama_model_raon1_mini::graph::build_rda_layer(
+ ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, int il) {
+ const int64_t head_dim = hparams.n_embd_head_kda;
+ const int64_t d_conv = hparams.ssm_d_conv;
+ const int64_t d_inner = head_dim * n_head;
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
+ const int64_t n_seqs = ubatch.n_seqs;
+
+ ggml_tensor * conv_states_all = inp_rs->mctx->get_r_l(il);
+ ggml_tensor * conv_states_seq = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
+
+ ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 0, build_lora_mm(layer.wq, cur),
+ layer.ssm_q_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 1, build_lora_mm(layer.wk, cur),
+ layer.ssm_k_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 2, build_lora_mm(layer.wv, cur),
+ layer.ssm_v_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
+ cb(Qcur, "rda_q_conv", il);
+ cb(Kcur, "rda_k_conv", il);
+ cb(Vcur, "rda_v_conv", il);
+
+ ggml_tensor * f_a = build_lora_mm(layer.ssm_f_a, cur);
+ ggml_tensor * g1 = build_lora_mm(layer.ssm_f_b, f_a);
+ g1 = ggml_add(ctx0, g1, layer.ssm_dt_b);
+ g1 = build_rda_gate(g1, layer.ssm_a);
+ cb(g1, "rda_g1", il);
+
+ g1 = ggml_reshape_4d(ctx0, g1, head_dim, n_head, n_seq_tokens, n_seqs);
+
+ // erase gate sigmoid(beta), write gate sigmoid(beta + delta); the write/erase ratio is folded into V
+ ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur);
+ beta = ggml_reshape_4d(ctx0, beta, 1, n_head, n_seq_tokens, n_seqs);
+ ggml_tensor * delta = build_lora_mm(layer.ssm_rda, cur);
+ delta = ggml_reshape_4d(ctx0, delta, 1, n_head, n_seq_tokens, n_seqs);
+ ggml_tensor * erase = ggml_softplus(ctx0, ggml_neg(ctx0, beta));
+ ggml_tensor * write = ggml_softplus(ctx0, ggml_neg(ctx0, ggml_add(ctx0, beta, delta)));
+ Vcur = ggml_mul(ctx0, Vcur, ggml_exp(ctx0, ggml_sub(ctx0, erase, write)));
+ cb(Vcur, "rda_v_scaled", il);
+ beta = ggml_sigmoid(ctx0, beta);
+ cb(beta, "rda_beta", il);
+
+ // same as HF F.normalize(eps=1e-6): x / max(||x||, eps)
+ const float eps_norm = 1e-6f;
+ Qcur = ggml_l2_norm(ctx0, Qcur, eps_norm);
+ Kcur = ggml_l2_norm(ctx0, Kcur, eps_norm);
+
+ ggml_tensor * g2 = build_lora_mm(layer.ssm_g, cur);
+
+ // scan and state update
+ ggml_tensor * ssm_states_all = inp_rs->mctx->get_s_l(il);
+ ggml_tensor * state = build_rs(inp_rs, ssm_states_all, hparams.n_embd_s(), n_seqs);
+ state = ggml_reshape_4d(ctx0, state, head_dim, head_dim, n_head, n_seqs);
+
+ ggml_tensor * output = build_recurrent_attn(inp_rs, ssm_states_all, Qcur, Kcur, Vcur, g1, beta, state, il);
+ output = ggml_cont(ctx0, output);
+ cb(output, "rda_scan_out", il);
+
+ // output gate, then RMSNorm(o) * sigmoid(g2)
+ g2 = ggml_reshape_3d(ctx0, g2, head_dim, n_head, n_tokens);
+
+ ggml_tensor * o = ggml_reshape_3d(ctx0, output, head_dim, n_head, n_tokens);
+ ggml_tensor * normed = build_norm(o, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il);
+ cb(g2, "rda_g2", il);
+ cb(normed, "rda_normed", il);
+ ggml_tensor * gated = ggml_mul(ctx0, normed, ggml_sigmoid(ctx0, g2));
+
+ gated = ggml_cont_2d(ctx0, gated, d_inner, n_tokens);
+ cur = build_lora_mm(layer.wo, gated);
+ cb(cur, "rda_out", il);
+
+ return cur;
+}
+
+ggml_tensor * llama_model_raon1_mini::graph::build_hc_pre(
+ ggml_tensor * x, ggml_tensor * fn, ggml_tensor * scale, ggml_tensor * base,
+ ggml_tensor ** post, ggml_tensor ** comb, int il) {
+ const int64_t hc = hparams.dsv4_hc_mult;
+ const int64_t nm = hc - 1;
+ const int64_t nt = x->ne[2];
+ ggml_tensor * flat = ggml_reshape_2d(ctx0, x, n_embd*hc, nt);
+ ggml_tensor * rms = ggml_sqrt(ctx0, ggml_scale_bias(ctx0, ggml_mean(ctx0, ggml_sqr(ctx0, flat)), 1.0f, hparams.dsv4_hc_eps));
+ ggml_tensor * mixes = ggml_div(ctx0, build_lora_mm(fn, flat), rms);
+ cb(mixes, "hc_mixes", il);
+
+ auto affine = [&](int64_t offset, int64_t width, int64_t si) {
+ ggml_tensor * z = ggml_view_2d(ctx0, mixes, width, nt, mixes->nb[1], offset*mixes->nb[0]);
+ ggml_tensor * a = ggml_view_1d(ctx0, scale, 1, si*scale->nb[0]);
+ ggml_tensor * b = ggml_view_1d(ctx0, base, width, offset*base->nb[0]);
+ return ggml_add(ctx0, ggml_mul(ctx0, z, a), b);
+ };
+ ggml_tensor * pre = ggml_sigmoid(ctx0, affine(0, hc, 0));
+ *post = ggml_scale(ctx0, ggml_sigmoid(ctx0, affine(hc, hc, 1)), hparams.hc_magnitude);
+ // combination: z ((hc-1)^2 Helmert coordinates) -> e = H z H^T, rho = 1 + max(0, max(-e / chart_base)),
+ // phi = chart_base + e / rho (doubly stochastic), comb = I + sigmoid(eta) * (phi - I)
+ ggml_tensor * z = ggml_cont_3d(ctx0, affine(2*hc, nm*nm, 2), nm, nm, nt);
+ ggml_tensor * e = ggml_mul_mat(ctx0, helmert, z);
+ e = ggml_mul_mat(ctx0, helmert, ggml_cont(ctx0, ggml_transpose(ctx0, e)));
+ ggml_tensor * ratio = ggml_neg(ctx0, ggml_div(ctx0, e, chart_base));
+ ratio = ggml_reshape_2d(ctx0, ratio, hc*hc, nt);
+ ggml_tensor * rho = ggml_pool_1d(ctx0, ratio, GGML_OP_POOL_MAX, hc*hc, hc*hc, 0);
+ rho = ggml_scale_bias(ctx0, ggml_clamp(ctx0, rho, 0.0f, INFINITY), 1.0f, 1.0f);
+ rho = ggml_reshape_3d(ctx0, rho, 1, 1, nt);
+ ggml_tensor * phi = ggml_add(ctx0, ggml_div(ctx0, e, rho), chart_base);
+ ggml_tensor * gamma = ggml_sigmoid(ctx0, ggml_view_1d(ctx0, scale, 1, 3*scale->nb[0]));
+ *comb = ggml_add(ctx0, ggml_mul(ctx0, ggml_sub(ctx0, phi, identity), gamma), identity);
+ cb(*comb, "hc_comb", il);
+ cb(pre, "hc_pre", il);
+ cb(*post, "hc_post", il);
+
+ if (cparams.fused_dsv4_hc_pre) {
+ ggml_tensor * result = ggml_dsv4_hc_pre(ctx0, x, pre);
+ res->add_fused_node({LLM_FUSED_OP_DSV4_HC_PRE, result, il});
+ return result;
+ }
+
+ ggml_tensor * result = nullptr;
+ for (int64_t i = 0; i < hc; ++i) {
+ ggml_tensor * xi = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], i*x->nb[1]);
+ ggml_tensor * wi = ggml_view_2d(ctx0, pre, 1, nt, pre->nb[1], i*pre->nb[0]);
+ ggml_tensor * term = ggml_mul(ctx0, xi, wi);
+ result = result ? ggml_add(ctx0, result, term) : term;
+ }
+ return result;
+}
+
+ggml_tensor * llama_model_raon1_mini::graph::build_hc_post(
+ ggml_tensor * x, ggml_tensor * branch, ggml_tensor * post, ggml_tensor * comb, int il) {
+ if (cparams.fused_dsv4_hc_post) {
+ ggml_tensor * result = ggml_dsv4_hc_post(ctx0, branch, x, post, comb);
+ res->add_fused_node({LLM_FUSED_OP_DSV4_HC_POST, result, il});
+ return result;
+ }
+
+ const int64_t hc = hparams.dsv4_hc_mult;
+ const int64_t nt = x->ne[2];
+ ggml_tensor * result = nullptr;
+ for (int64_t dst = 0; dst < hc; ++dst) {
+ ggml_tensor * sum = nullptr;
+ for (int64_t src = 0; src < hc; ++src) {
+ ggml_tensor * xi = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], src*x->nb[1]);
+ ggml_tensor * wi = ggml_view_2d(ctx0, comb, 1, nt, comb->nb[2], dst*comb->nb[0] + src*comb->nb[1]);
+ ggml_tensor * term = ggml_mul(ctx0, xi, wi);
+ sum = sum ? ggml_add(ctx0, sum, term) : term;
+ }
+ ggml_tensor * wi = ggml_view_2d(ctx0, post, 1, nt, post->nb[1], dst*post->nb[0]);
+ sum = ggml_add(ctx0, sum, ggml_mul(ctx0, branch, wi));
+ sum = ggml_reshape_3d(ctx0, sum, n_embd, 1, nt);
+ result = result ? ggml_concat(ctx0, result, sum, 1) : sum;
+ }
+ return result;
+}
+
+ggml_tensor * llama_model_raon1_mini::graph::build_mla_layer(
+ ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, int il) {
+ const int64_t nr = hparams.n_rot();
+ const int64_t nk = hparams.n_embd_head_k_mla();
+ const int64_t nn = nk - nr;
+ const int64_t rank = hparams.n_lora_kv;
+ // Raon defines a separate RMSNorm epsilon for its Q and KV latent projections.
+ const float eps = hparams.f_norm_rms_eps_latent;
+ ggml_tensor * q = build_lora_mm(layer.wq_a, cur);
+ q = ggml_mul(ctx0, ggml_rms_norm(ctx0, q, eps), layer.attn_q_a_norm);
+ cb(q, "mla_q_norm", il);
+ q = build_lora_mm(layer.wq_b, q);
+ ggml_tensor * kv = build_lora_mm(layer.wkv_a_mqa, cur);
+ ggml_tensor * latent = ggml_view_2d(ctx0, kv, rank, n_tokens, kv->nb[1], 0);
+ latent = ggml_mul(ctx0, ggml_rms_norm(ctx0, latent, eps), layer.attn_kv_a_norm);
+ cb(latent, "mla_kv_norm", il);
+ // NoPE: the "rope" dims of q and k are concatenated as they are, without rotation
+ ggml_tensor * extra = ggml_view_3d(ctx0, kv, nr, 1, n_tokens, kv->nb[1], kv->nb[1], rank*kv->nb[0]);
+ ggml_tensor * q_nope = ggml_view_3d(ctx0, q, nn, n_head, n_tokens, nk*q->nb[0], q->nb[1], 0);
+ ggml_tensor * q_extra = ggml_view_3d(ctx0, q, nr, n_head, n_tokens, nk*q->nb[0], q->nb[1], nn*q->nb[0]);
+ q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
+ q_nope = build_lora_mm(layer.wk_b, q_nope);
+ q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
+ q = ggml_concat(ctx0, q_nope, q_extra, 0);
+ latent = ggml_reshape_3d(ctx0, latent, rank, 1, n_tokens);
+ ggml_tensor * k = ggml_concat(ctx0, latent, extra, 0);
+ ggml_tensor * out = build_attn(inp_attn_k, nullptr, nullptr, nullptr, q, k, latent,
+ nullptr, nullptr, layer.wv_b, 1.0f/sqrtf(nk), il);
+ out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, cur)));
+ cb(out, "mla_gated", il);
+ return build_lora_mm(layer.wo, out);
+}
+
+// dense SiTU-GLU feed-forward for the lead layers and the shared expert:
+// situ(gate, up) = beta*tanh(gate/beta)*sigmoid(gate) * lb*tanh(up/lb)
+// build_ffn has no SiTU case; the routed experts go through build_moe_ffn, which has one
+ggml_tensor * llama_model_raon1_mini::graph::build_situ_ffn(
+ ggml_tensor * cur, ggml_tensor * up, ggml_tensor * gate, ggml_tensor * down, int il) {
+ const float beta = hparams.situ_beta;
+ const float lb = hparams.situ_linear_beta;
+
+ ggml_tensor * u = build_lora_mm(up, cur);
+ cb(u, "ffn_up", il);
+ ggml_tensor * g = build_lora_mm(gate, cur);
+ cb(g, "ffn_gate", il);
+
+ ggml_tensor * act = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, g, 1.0f/beta)), beta);
+ act = ggml_mul(ctx0, act, ggml_sigmoid(ctx0, g));
+ u = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, u, 1.0f/lb)), lb);
+ cur = ggml_mul(ctx0, act, u);
+ cb(cur, "ffn_situ", il);
+
+ cur = build_lora_mm(down, cur);
+ cb(cur, "ffn_out", il);
+ return cur;
+}
+
+llama_model_raon1_mini::graph::graph(const llm_graph_params & params) : llm_build_delta_net_base(params) {
+ const int64_t hc = hparams.dsv4_hc_mult;
+ const int64_t nm = hc - 1;
+ helmert = nullptr;
+ for (int64_t i = 0; i < hc; ++i) {
+ ggml_tensor * row = nullptr;
+ for (int64_t j = 0; j < nm; ++j) {
+ const float v = (i <= j ? 1.0f : i == j + 1 ? -(float) (j + 1) : 0.0f)/sqrtf((j + 1)*(j + 2));
+ ggml_tensor * c = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1), v);
+ row = row ? ggml_concat(ctx0, row, c, 0) : c;
+ }
+ row = ggml_reshape_2d(ctx0, row, nm, 1);
+ helmert = helmert ? ggml_concat(ctx0, helmert, row, 1) : row;
+ }
+ identity = ggml_diag(ctx0, ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, hc), 1.0f));
+ chart_base = ggml_scale_bias(ctx0, identity, 0.5f, 0.5f/hc);
+
+ ggml_tensor * inp = build_inp_embd(model.tok_embd);
+ inp = ggml_reshape_3d(ctx0, inp, n_embd, 1, n_tokens);
+ inp = ggml_repeat_4d(ctx0, inp, n_embd, hc, n_tokens, 1);
+ auto * inputs = build_inp_mem_hybrid_k();
+ auto * inp_rs = inputs->get_recr();
+ auto * inp_attn = inputs->get_attn();
+ auto * out_ids = build_inp_out_ids();
+ GGML_ASSERT(ubatch.n_seqs != 0 && ubatch.equal_seqs());
+ GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens*ubatch.n_seqs);
+
+ for (int il = 0; il < n_layer; ++il) {
+ const auto & layer = model.layers[il];
+ ggml_tensor * post;
+ ggml_tensor * comb;
+ ggml_tensor * cur = build_hc_pre(inp, layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base, &post, &comb, il);
+ cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);
+ cb(cur, "attn_norm", il);
+ if (hparams.is_recr(il)) {
+ cur = build_rda_layer(cur, layer, inp_rs, il);
+ } else {
+ cur = build_mla_layer(cur, layer, inp_attn, il);
+ }
+ inp = build_hc_post(inp, cur, post, comb, il);
+ cb(inp, "hc_attn_out", il);
+ cur = build_hc_pre(inp, layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base, &post, &comb, il);
+ cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);
+ cb(cur, "ffn_norm", il);
+ if (il < (int) hparams.n_layer_dense_lead) {
+ cur = build_situ_ffn(cur, layer.ffn_up, layer.ffn_gate, layer.ffn_down, il);
+ } else {
+ ggml_tensor * moe = build_moe_ffn(cur,
+ layer.ffn_gate_inp,
+ layer.ffn_up_exps,
+ layer.ffn_gate_exps,
+ layer.ffn_down_exps,
+ layer.ffn_exp_probs_b,
+ hparams.n_expert, hparams.n_expert_used(),
+ LLM_FFN_SITU, hparams.expert_weights_norm,
+ hparams.expert_weights_scale,
+ (llama_expert_gating_func_type) hparams.expert_gating_func,
+ il);
+ if (layer.ffn_gate_shexp) {
+ ggml_tensor * shared = build_situ_ffn(cur, layer.ffn_up_shexp, layer.ffn_gate_shexp,
+ layer.ffn_down_shexp, il);
+ moe = ggml_add(ctx0, moe, shared);
+ }
+ cur = moe;
+ }
+ inp = build_hc_post(inp, cur, post, comb, il);
+ inp = build_cvec(inp, il);
+ cb(inp, "l_out", il);
+ }
+ ggml_tensor * cur = nullptr;
+ for (int64_t i = 0; i < hc; ++i) {
+ ggml_tensor * x = ggml_view_2d(ctx0, inp, n_embd, n_tokens, inp->nb[2], i*inp->nb[1]);
+ cur = cur ? ggml_add(ctx0, cur, x) : x;
+ }
+ cur = ggml_scale(ctx0, cur, 1.0f/hc);
+ if (out_ids) {
+ cur = ggml_get_rows(ctx0, cur, out_ids);
+ }
+ cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1);
+ cb(cur, "result_norm", -1);
+ res->t_embd = cur;
+ cur = build_lora_mm(model.output, cur);
+ cb(cur, "result_output", -1);
+ res->t_logits = cur;
+}
diff --git a/src/unicode.cpp b/src/unicode.cpp
index 9226c73db..ea5957514 100644
--- a/src/unicode.cpp
+++ b/src/unicode.cpp
@@ -1221,6 +1221,178 @@ static std::vector<size_t> unicode_regex_split_custom_newlines(const std::string
return bpe_offsets;
}
+// regex: ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\p{L})\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\p{L})\p{M}*)+)*|\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N}))| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+
+// Raon-1 mini: CJK runs are split from other letters, letter runs keep marks and can span one space, digits are grouped by 3 from the right
+static std::vector<size_t> unicode_regex_split_custom_raon(const std::string & text, const std::vector<size_t> & offsets) {
+ std::vector<size_t> bpe_offsets;
+ bpe_offsets.reserve(offsets.size());
+
+ const auto cpts = unicode_cpts_from_utf8(text);
+
+ size_t start = 0;
+ for (auto offset : offsets) {
+ const size_t offset_ini = start;
+ const size_t offset_end = start + offset;
+ assert(offset_end <= cpts.size());
+ start = offset_end;
+
+ static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
+ auto _get_cpt = [&] (const size_t pos) -> uint32_t {
+ return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
+ };
+
+ auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
+ return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
+ };
+
+ // [\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]
+ auto _is_cjk = [&] (const size_t pos) -> bool {
+ const uint32_t cpt = _get_cpt(pos);
+ return (0x4e00 <= cpt && cpt <= 0x9fa5) || (0x3040 <= cpt && cpt <= 0x30ff);
+ };
+
+ // (?![CJK])\p{L}
+ auto _is_letter = [&] (const size_t pos) -> bool {
+ return _get_flags(pos).is_letter && !_is_cjk(pos);
+ };
+
+ // [^\s\p{L}\p{N}]
+ auto _is_punct = [&] (const size_t pos) -> bool {
+ if (pos < offset_ini || offset_end <= pos) {
+ return false;
+ }
+ const auto flags = _get_flags(pos);
+ return !flags.is_whitespace && !flags.is_letter && !flags.is_number;
+ };
+
+ size_t _prev_end = offset_ini;
+ auto _add_token = [&] (const size_t end) -> size_t {
+ assert(_prev_end <= end && end <= offset_end);
+ size_t len = end - _prev_end;
+ if (len > 0) {
+ bpe_offsets.push_back(len);
+ }
+ _prev_end = end;
+ return len;
+ };
+
+ for (size_t pos = offset_ini; pos < offset_end; ) {
+ const uint32_t cpt = _get_cpt(pos);
+ const auto flags = _get_flags(pos);
+
+ // the CJK, letter and punctuation alternatives accept one optional leading space
+ size_t pos2 = pos + (cpt == ' ');
+
+ // regex: ' ?[CJK]+'
+ if (_is_cjk(pos2)) {
+ do {
+ pos2++;
+ } while (_is_cjk(pos2));
+ pos += _add_token(pos2);
+ continue;
+ }
+
+ // regex: ' ?(?:(?:(?![CJK])\p{L})\p{M}*)+(?: (?:(?:(?![CJK])\p{L})\p{M}*)+)*'
+ if (_is_letter(pos2)) {
+ while (true) {
+ pos2++;
+ while (_get_flags(pos2).is_accent_mark) {
+ pos2++;
+ }
+ if (_is_letter(pos2)) {
+ continue;
+ }
+ // a single space joins two letter runs
+ if (_get_cpt(pos2) == ' ' && _is_letter(pos2 + 1)) {
+ pos2++;
+ continue;
+ }
+ break;
+ }
+ pos += _add_token(pos2);
+ continue;
+ }
+
+ // regex: '\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N}))' - groups of three from the right
+ if (flags.is_number) {
+ size_t digit_start = pos;
+ size_t digit_count = 0;
+
+ // Count consecutive digits
+ while (_get_flags(pos).is_number && pos < offset_end) {
+ digit_count++;
+ pos++;
+ }
+
+ // Split based on total length modulo 3
+ size_t remainder = digit_count % 3;
+ size_t current = digit_start;
+
+ // Emit leading 1-2 digits if needed
+ if (remainder > 0) {
+ _add_token(current + remainder);
+ current += remainder;
+ }
+
+ // Emit groups of 3
+ while (current < digit_start + digit_count) {
+ _add_token(current + 3);
+ current += 3;
+ }
+ continue;
+ }
+
+ // regex: ' ?[^\s\p{L}\p{N}]+[\r\n/]*'
+ if (_is_punct(pos2)) {
+ do {
+ pos2++;
+ } while (_is_punct(pos2));
+ uint32_t cpt2 = _get_cpt(pos2);
+ while (cpt2 == '\r' || cpt2 == '\n' || cpt2 == '/') {
+ cpt2 = _get_cpt(++pos2);
+ }
+ pos += _add_token(pos2);
+ continue;
+ }
+
+ // regex: '\s*[\r\n]+'
+ size_t num_whitespaces = 0;
+ size_t last_end_r_or_n = 0;
+ while (_get_flags(pos + num_whitespaces).is_whitespace) {
+ const uint32_t cpt2 = _get_cpt(pos + num_whitespaces);
+ if (cpt2 == '\r' || cpt2 == '\n') {
+ last_end_r_or_n = pos + num_whitespaces + 1;
+ }
+ num_whitespaces++;
+ }
+ if (last_end_r_or_n > 0) {
+ pos = last_end_r_or_n;
+ _add_token(pos);
+ continue;
+ }
+
+ // regex: '\s+(?!\S)'
+ if (num_whitespaces > 1 && _get_cpt(pos + num_whitespaces) != OUT_OF_RANGE) {
+ pos += num_whitespaces - 1;
+ _add_token(pos);
+ continue;
+ }
+
+ // regex: '\s+'
+ if (num_whitespaces > 0) {
+ pos += num_whitespaces;
+ _add_token(pos);
+ continue;
+ }
+
+ // no matches
+ _add_token(++pos);
+ }
+ }
+
+ return bpe_offsets;
+}
+
static std::vector<size_t> unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
std::vector<size_t> bpe_offsets;
@@ -1255,6 +1427,9 @@ static std::vector<size_t> unicode_regex_split_custom(const std::string & text,
// Splits digits into groups of 3 from the right (e.g., 1234567 -> 1, 234, 567)
// TODO: Revisit this regex, in case there are any subtle tokenization differences with the original regex.
bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets);
+ } else if (regex_expr == " ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\p{N}))| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+") {
+ // Raon-1 mini: must match the LLAMA_VOCAB_PRE_TYPE_RAON regex in llama-vocab.cpp byte for byte
+ bpe_offsets = unicode_regex_split_custom_raon(text, offsets);
}
return bpe_offsets;
diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv
index 5b7ea1868..ccb222e93 100644
--- a/tests/fusion/MTL.csv
+++ b/tests/fusion/MTL.csv
@@ -334,6 +334,11 @@ qwen4exp ,0 ,any ,RMS_NORM+MUL , 13
qwen4exp ,0 ,any ,RMS_NORM+SCALE , 2
qwen4exp ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen4exp ,0 ,any ,SSM_CONV+UNARY , 1
+raon1 ,0 ,any ,ADD+ADD+ADD , 1
+raon1 ,0 ,any ,GATED_DELTA_NET+CPY , 1
+raon1 ,0 ,any ,MUL+ADD , 2
+raon1 ,0 ,any ,RMS_NORM+MUL , 8
+raon1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1
refact ,0 ,any ,RMS_NORM+MUL , 5
refact ,0 ,any ,RMS_NORM+MUL , 5
ricursive ,0 ,any ,RMS_NORM+MUL , 9
diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp
index 20a3cc6a0..83c11cc2d 100644
--- a/tests/test-chat.cpp
+++ b/tests/test-chat.cpp
@@ -4255,6 +4255,215 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
.expect_content("Hello, world!\nWhat's up?")
.run();
}
+ {
+ // Raon-1 mini: ChatML turns, an explicit <think> envelope on every assistant turn and Qwen3-Coder style XML tool calls
+ auto tst = peg_tester("models/templates/KRAFTON-Raon-1-mini-preview.jinja", detailed_debug);
+
+ // reasoning on: the generation prompt opens "<think>\n"
+ tst.test("I'm\nthinking\n</think>\n\nHello, world!\nWhat's up?")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(true)
+ .expect(message_assist_thoughts)
+ .run();
+
+ tst.test("I'm\nthinking\n</think>\n\nHello, world!\nWhat's up?")
+ .reasoning_format(COMMON_REASONING_FORMAT_NONE)
+ .enable_thinking(true)
+ .expect_content("<think>\nI'm\nthinking\n</think>\n\nHello, world!\nWhat's up?")
+ .run();
+
+ // reasoning off: the generation prompt already closes the envelope
+ tst.test("Hello, world!\nWhat's up?")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .expect(message_assist)
+ .run();
+
+ // typed arguments: integer
+ tst.test(
+ "<tool_call>\n"
+ "<function=special_function>\n"
+ "<parameter=arg1>\n1\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ special_function_tool })
+ .expect(message_assist_call)
+ .expect_rules({ "tool-0", "tool-0-arg-0" })
+ .run();
+
+ tst.test(
+ "I'm\nthinking\n</think>\n\n"
+ "<tool_call>\n"
+ "<function=special_function>\n"
+ "<parameter=arg1>\n1\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(true)
+ .tools({ special_function_tool })
+ .expect(message_assist_call_thoughts)
+ .run();
+
+ // typed arguments: string and integer, optional arguments out of order
+ tst.test(
+ "<tool_call>\n"
+ "<function=tool_2req_4opt>\n"
+ "<parameter=req1>\nhello\n</parameter>\n"
+ "<parameter=req2>\n42\n</parameter>\n"
+ "<parameter=opt4>\n100\n</parameter>\n"
+ "<parameter=opt1>\nworld\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ tool_2req_4opt })
+ .expect_tool_calls({
+ { "tool_2req_4opt", R"({"req1": "hello", "req2": 42, "opt4": 100, "opt1": "world"})", {} },
+ })
+ .run();
+
+ // typed arguments: boolean, object and array values stay JSON
+ tst.test(
+ "<tool_call>\n"
+ "<function=toggle>\n"
+ "<parameter=enabled>\ntrue\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>\n"
+ "<tool_call>\n"
+ "<function=set_config>\n"
+ "<parameter=config>\n{\"mode\": \"fast\", \"level\": 2}\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>\n"
+ "<tool_call>\n"
+ "<function=todo_list>\n"
+ "<parameter=todos>\n[{\"item\": \"Check stuff\", \"selected\": false}]\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .parallel_tool_calls(true)
+ .tools({ toggle_tool, config_tool, todo_list })
+ .expect_tool_calls({
+ { "toggle", R"({"enabled": true})", {} },
+ { "set_config", R"({"config": {"mode": "fast", "level": 2}})", {} },
+ { "todo_list", R"({"todos": [{"item": "Check stuff", "selected": false}]})", {} },
+ })
+ .run();
+
+ // a string argument that looks like a number stays a string
+ tst.test(
+ "<tool_call>\n"
+ "<function=edit>\n"
+ "<parameter=filename>\n2024.c\n</parameter>\n"
+ "<parameter=oldString>\n1\n</parameter>\n"
+ "<parameter=newString>\n2\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ edit_tool })
+ .expect_tool_calls({
+ { "edit", R"({"filename": "2024.c", "oldString": "1", "newString": "2"})", {} },
+ })
+ .run();
+
+ // nullable arguments
+ tst.test(
+ "<tool_call>\n"
+ "<function=set_nullable_str>\n"
+ "<parameter=name>\nnull\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ nullable_string_tool })
+ .expect_tool_calls({
+ { "set_nullable_str", R"({"name": null})", {} },
+ })
+ .run();
+
+ tst.test(
+ "<tool_call>\n"
+ "<function=set_nullable_str>\n"
+ "<parameter=name>\nhello world\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ nullable_string_tool })
+ .expect_tool_calls({
+ { "set_nullable_str", R"({"name": "hello world"})", {} },
+ })
+ .run();
+
+ tst.test(
+ "<tool_call>\n"
+ "<function=set_nullable_int>\n"
+ "<parameter=count>\nnull\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ nullable_int_tool })
+ .expect_tool_calls({
+ { "set_nullable_int", R"({"count": null})", {} },
+ })
+ .run();
+
+ tst.test(
+ "<tool_call>\n"
+ "<function=set_nullable_int>\n"
+ "<parameter=count>\n42\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .tools({ nullable_int_tool })
+ .expect_tool_calls({
+ { "set_nullable_int", R"({"count": 42})", {} },
+ })
+ .run();
+
+ // content before the call, then reasoning + parallel calls
+ tst.test(
+ "I'm\nthinking\n</think>\n\n"
+ "Hello, world!\nWhat's up?\n\n"
+ "<tool_call>\n"
+ "<function=special_function>\n"
+ "<parameter=arg1>\n1\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(true)
+ .tools({ special_function_tool })
+ .expect(message_assist_call_thoughts_content)
+ .run();
+
+ tst.test(
+ "<tool_call>\n"
+ "<function=special_function>\n"
+ "<parameter=arg1>\n1\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>\n"
+ "<tool_call>\n"
+ "<function=special_function_with_opt>\n"
+ "<parameter=arg1>\n1\n</parameter>\n"
+ "<parameter=arg2>\n2\n</parameter>\n"
+ "</function>\n"
+ "</tool_call>")
+ .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
+ .enable_thinking(false)
+ .parallel_tool_calls(true)
+ .tools({ special_function_tool, special_function_tool_with_optional_param })
+ .expect_tool_calls({
+ { "special_function", R"({"arg1": 1})", {} },
+ { "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} },
+ })
+ .run();
+ }
+
{
auto tst = peg_tester("models/templates/deepseek-ai-DeepSeek-V3.1.jinja", detailed_debug);
tst.test(
@@ -8188,6 +8397,13 @@ static void test_template_generation_prompt() {
check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n<think>\nI'm");
}
+ {
+ auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja");
+ check(tmpls, basic(), "<|im_start|>assistant\n<think>\n");
+ check(tmpls, continuation_content(), "<|im_start|>assistant\n<think>\nI'm thinking\n</think>\n\nHello, ");
+ check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n<think>\nI'm");
+ }
+
{
auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja");
check(tmpls, basic(), "<|start|>assistant");
@@ -8698,6 +8914,179 @@ static void test_deepseek_v4_1_message_fields() {
}
}
+// Raon-1 mini template (models/templates/KRAFTON-Raon-1-mini-preview.jinja) prompt rendering
+static void test_raon_prompt() {
+ LOG_DBG("%s\n", __func__);
+
+ auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja");
+
+ common_chat_msg developer_msg;
+ developer_msg.role = "developer";
+ developer_msg.content = "You are RAON.";
+
+ common_chat_msg system_msg = developer_msg;
+ system_msg.role = "system";
+
+ auto render = [&](const std::vector<common_chat_msg> & messages, bool with_tools, bool enable_thinking = true) {
+ common_chat_templates_inputs inputs;
+ inputs.messages = messages;
+ inputs.enable_thinking = enable_thinking;
+ if (with_tools) {
+ inputs.tools = { special_function_tool };
+ }
+ return common_chat_templates_apply(tmpls.get(), inputs);
+ };
+
+ // a leading developer message is rendered as the system turn (the template itself rejects "developer")
+ {
+ const auto prompt = render({ developer_msg, message_user }, false).prompt.str();
+ assert_equals(std::string(
+ "<|im_start|>system\nYou are RAON.<|im_end|>\n"
+ "<|im_start|>user\nHey there!<|im_end|>\n"
+ "<|im_start|>assistant\n<think>\n"), prompt);
+ assert_equals(render({ system_msg, message_user }, false).prompt.str(), prompt);
+ }
+
+ // with tools the system text follows the tool block in the same system turn
+ {
+ const auto prompt = render({ developer_msg, message_user }, true).prompt.str();
+ assert_equals(true, string_starts_with(prompt, "<|im_start|>system\n# Tools\n\n"));
+ assert_contains(prompt, "\"name\": \"special_function\"");
+ assert_contains(prompt, "</IMPORTANT>\n\nYou are RAON.<|im_end|>\n<|im_start|>user\nHey there!<|im_end|>\n");
+ assert_not_contains(prompt, "developer");
+ assert_equals(render({ system_msg, message_user }, true).prompt.str(), prompt);
+ }
+
+ // reasoning off closes the think envelope in the generation prompt
+ {
+ const auto params = render({ message_user }, false, /* enable_thinking = */ false);
+ assert_equals(std::string("<|im_start|>assistant\n<think></think>\n\n"), params.generation_prompt);
+ assert_ends_with(params.prompt.str(), params.generation_prompt);
+ }
+
+ // assistant history as HF apply_chat_template renders it: kept reasoning and tool calls after the last query, an earlier turn's reasoning kept by default and dropped with truncate_history_thinking=true
+ {
+ common_chat_msg calls;
+ calls.role = "assistant";
+ calls.reasoning_content = "Two calls.";
+ calls.tool_calls.push_back({ "special_function", "{\"arg1\": 1}", "call_1" });
+ calls.tool_calls.push_back({ "special_function", "{\"arg1\": 2}", "call_2" });
+ common_chat_msg r1; r1.role = "tool"; r1.tool_call_id = "call_1"; r1.content = "one";
+ common_chat_msg r2; r2.role = "tool"; r2.tool_call_id = "call_2"; r2.content = "two";
+ common_chat_msg user_q; user_q.role = "user"; user_q.content = "Call it twice.";
+ assert_ends_with(render({ user_q, calls, r1, r2 }, true).prompt.str(), std::string(
+ "<|im_start|>user\n"
+ "Call it twice.<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ "<think>\n"
+ "Two calls.\n"
+ "</think>\n"
+ "\n"
+ "<tool_call>\n"
+ "<function=special_function>\n"
+ "<parameter=arg1>\n"
+ "1\n"
+ "</parameter>\n"
+ "</function>\n"
+ "</tool_call>\n"
+ "<tool_call>\n"
+ "<function=special_function>\n"
+ "<parameter=arg1>\n"
+ "2\n"
+ "</parameter>\n"
+ "</function>\n"
+ "</tool_call><|im_end|>\n"
+ "<|im_start|>user\n"
+ "<tool_response>\n"
+ "one\n"
+ "</tool_response>\n"
+ "<tool_response>\n"
+ "two\n"
+ "</tool_response><|im_end|>\n"
+ "<|im_start|>assistant\n"
+ "<think>\n"));
+
+ common_chat_msg old; old.role = "assistant"; old.content = "<think>Old thought.\n</think>\n\nAnswer.";
+ common_chat_msg again; again.role = "user"; again.content = "Again.";
+ // with truncate_history_thinking = true the earlier turn's reasoning is dropped
+ {
+ common_chat_templates_inputs inputs;
+ inputs.messages = { user_q, old, again };
+ inputs.chat_template_kwargs["truncate_history_thinking"] = "true";
+ assert_equals(std::string(
+ "<|im_start|>user\n"
+ "Call it twice.<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ "<think></think>\n"
+ "\n"
+ "Answer.<|im_end|>\n"
+ "<|im_start|>user\n"
+ "Again.<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ "<think>\n"), common_chat_templates_apply(tmpls.get(), inputs).prompt.str());
+ }
+
+ // by default (the template defaults truncate_history_thinking to false) the earlier turn keeps the reasoning split out of its content
+ {
+ assert_equals(std::string(
+ "<|im_start|>user\n"
+ "Call it twice.<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ "<think>\n"
+ "Old thought.\n"
+ "</think>\n"
+ "\n"
+ "Answer.<|im_end|>\n"
+ "<|im_start|>user\n"
+ "Again.<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ "<think>\n"), render({ user_q, old, again }, false).prompt.str());
+ }
+ }
+
+ // continuing an assistant message without reasoning: the shared Qwen3-Coder handler writes "<think>\n\n</think>\n\n", the template "<think></think>\n\n"; this pins the handler's behaviour
+ {
+ common_chat_templates_inputs inputs;
+ inputs.messages = { message_user, simple_assist_msg("Hello, ") };
+ inputs.add_generation_prompt = false;
+ inputs.continue_final_message = COMMON_CHAT_CONTINUATION_CONTENT;
+ assert_ends_with(common_chat_templates_apply(tmpls.get(), inputs).prompt.str(),
+ std::string("<|im_start|>assistant\n<think>\n\n</think>\n\nHello, "));
+ }
+
+ // Keep system instructions in order, including instructions sent as developer messages.
+ {
+ common_chat_msg second_system = system_msg;
+ second_system.content = "Keep it short.";
+
+ const std::string system_turn = "<|im_start|>system\nYou are RAON.<|im_end|>\n";
+ const std::string second_system_turn = "<|im_start|>system\nKeep it short.<|im_end|>\n";
+ const std::string user_turn = "<|im_start|>user\nHey there!<|im_end|>\n";
+ const std::string generation_prompt = "<|im_start|>assistant\n<think>\n";
+
+ assert_equals(system_turn + second_system_turn + user_turn + generation_prompt,
+ render({ system_msg, second_system, message_user }, false).prompt.str());
+ assert_equals(system_turn + user_turn + second_system_turn + generation_prompt,
+ render({ system_msg, message_user, second_system }, false).prompt.str());
+ assert_equals(user_turn + system_turn + generation_prompt,
+ render({ message_user, developer_msg }, false).prompt.str());
+
+ // A system instruction can start a conversation without a user message.
+ assert_equals(system_turn + generation_prompt, render({ system_msg }, false).prompt.str());
+ }
+
+ // A closing tag in the answer is literal, even after an initial reasoning block.
+ {
+ const auto literal = simple_assist_msg("The answer quotes </think>.");
+ assert_contains(render({ message_user, literal, message_user }, false).prompt.str(),
+ "<|im_start|>assistant\n<think></think>\n\nThe answer quotes </think>.<|im_end|>\n");
+
+ const auto with_reasoning = simple_assist_msg("<think>Reasoning.</think>\n\nThe answer quotes </think>.");
+ assert_contains(render({ message_user, with_reasoning, message_user }, false).prompt.str(),
+ "<|im_start|>assistant\n<think>\nReasoning.\n</think>\n\nThe answer quotes </think>.<|im_end|>\n");
+ }
+}
+
static void test_prompt_parts() {
LOG_DBG("%s\n", __func__);
const std::string tmpl_src =
@@ -9132,6 +9521,7 @@ int main(int argc, char ** argv) {
test_deepseek_v4_tool_result_ordering();
test_deepseek_v4_1_message_fields();
test_inkling2_media_blocks();
+ test_raon_prompt();
test_template_generation_prompt();
test_reasoning_effort_caps();
test_prompt_parts();
diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp
index a7deed9f7..e9e7a6cbf 100644
--- a/tests/test-llama-archs.cpp
+++ b/tests/test-llama-archs.cpp
@@ -300,6 +300,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
|| arch == LLM_ARCH_BAILINGMOE3
|| arch == LLM_ARCH_KIMI_K3
|| arch == LLM_ARCH_KIMI_K31
+ || arch == LLM_ARCH_RAON1_MINI
|| arch == LLM_ARCH_MISTRAL4
|| arch == LLM_ARCH_MISTRAL_LARGE4
|| arch == LLM_ARCH_HY_V4
@@ -386,7 +387,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
if (arch == LLM_ARCH_PLAMO2 || arch == LLM_ARCH_JAMBA || arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE ||
arch == LLM_ARCH_GRANITE_HYBRID || arch == LLM_ARCH_LFM2 || arch == LLM_ARCH_LFM2MOE || arch == LLM_ARCH_LFM3 ||
arch == LLM_ARCH_KIMI_LINEAR || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 ||
- arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4_FLASH
+ arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_RAON1_MINI
) {
GGML_ASSERT(n_layer >= 2);
std::vector<uint32_t> n_head_per_layer;
@@ -398,7 +399,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
: (il == 1 ? 0 : n_head));
}
// GLM5 next KDA heads come from the uniform head count, only head_count_kv is per layer.
- if (arch == LLM_ARCH_GLM5_NEXT) {
+ if (arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_RAON1_MINI) {
ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head);
// the MLA cache holds one latent head
for (uint32_t & n : n_head_per_layer) {
@@ -440,6 +441,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
|| arch == LLM_ARCH_BAILINGMOE3
|| arch == LLM_ARCH_KIMI_K3
|| arch == LLM_ARCH_KIMI_K31
+ || arch == LLM_ARCH_RAON1_MINI
|| arch == LLM_ARCH_GLM5_NEXT
|| arch == LLM_ARCH_HY_V4
|| arch == LLM_ARCH_HY_V4_FLASH
@@ -485,6 +487,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
ms.add_kv(LLM_KV_ATTENTION_CLAMP_KQV, 1.0f);
ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, 1e-5f);
ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f);
+ ms.add_kv(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, 1e-6f);
ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, 1e-5f);
ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, uint32_t(8));
ms.add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(64) : uint32_t(512));
@@ -546,6 +549,14 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, false);
}
+ if (arch == LLM_ARCH_RAON1_MINI) {
+ ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f);
+ ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true);
+ ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4));
+ ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1e-5f);
+ ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f);
+ }
+
// MSA requires one indexer head per GQA (KV) head, unlike the DSA archs where the
// indexer head count is independent of the main attention head count.
if (arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_GLM5_NEXT) {
@@ -1209,6 +1220,7 @@ static bool moe_mandatory(const llm_arch arch) {
case LLM_ARCH_KIMI_LINEAR:
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
+ case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_GLM5_NEXT:
case LLM_ARCH_STEP35:
case LLM_ARCH_MISTRAL4: