Commit 94be107ac for llama.cpp
commit 94be107ac2f2069d8751950487fa7c117242111f
Author: George Burton <8233643+gecBurton@users.noreply.github.com>
Date: Tue Dec 1 20:31:39 2026 +0000
model: add clef-omni (#33354)
* add: model clef-omni
Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com>
* add: has_lm_head to prevent double loading output.weight
* fix: potential key/index error in _load_clef_hparams
* remove: trailing ggml_build_forward_expand(gf, cur), fix: provenance comment
* add: test_decision_media_order to show that the media order matters
* fix: decision_order_media so that media is ordered correctly
* fix: comment in llama_tensor_get_type_impl
* remove: unsused ggml_build_forward_expand(), fix: comment in build_arch_graph
* fix: set min and max vison pixels for ClefOmniMmprojModel
* add: decision type for cloudflare-clef-omni and reject video media
* add: top-level audio in server-decision.cpp
---------
Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com>
diff --git a/common/common.cpp b/common/common.cpp
index b009d460d..da7657d13 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -1170,6 +1170,7 @@ static const std::map<common_decision_type, std::string> COMMON_DECISION_TYPE_NA
{ COMMON_DECISION_TYPE_MINICPM_OCR_JEV, "openbmb-minicpm-ocr-jev" },
{ COMMON_DECISION_TYPE_LFM3_D1, "lfm3-d1" },
{ COMMON_DECISION_TYPE_LFM3_D1_OMNI, "lfm3-d1-omni" },
+ { COMMON_DECISION_TYPE_CLEF_OMNI, "cloudflare-clef-omni" },
// for future models, ALWAYS add org name prefix to avoid name collisions, e.g. "orgname-modelname"
};
@@ -1298,6 +1299,7 @@ common_init_result::common_init_result(common_params & params, bool model_only)
const auto decision_type = common_get_decision_type(model);
// minicpm-ocr-jev reads its class scores from the pooled output, the pooling type is the one of the GGUF
if (decision_type == COMMON_DECISION_TYPE_LAYA || decision_type == COMMON_DECISION_TYPE_KEV || decision_type == COMMON_DECISION_TYPE_CLEF ||
+ decision_type == COMMON_DECISION_TYPE_CLEF_OMNI ||
decision_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || decision_type == COMMON_DECISION_TYPE_VLLM_DECISION2 ||
decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV) {
const auto pooling_type = decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV ? LLAMA_POOLING_TYPE_UNSPECIFIED : LLAMA_POOLING_TYPE_NONE;
diff --git a/common/common.h b/common/common.h
index aa454944c..1d8d57d71 100644
--- a/common/common.h
+++ b/common/common.h
@@ -1002,6 +1002,7 @@ enum common_decision_type {
COMMON_DECISION_TYPE_MINICPM_OCR_JEV, // one score per class, the pooled embeddings output of the last token
COMMON_DECISION_TYPE_LFM3_D1, // same as lfm2-d1, non-causal, label codes A..Z then AA, AB..
COMMON_DECISION_TYPE_LFM3_D1_OMNI, // same as lfm3-d1
+ COMMON_DECISION_TYPE_CLEF_OMNI, // same as clef, with audio input and no video input
COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported
};
diff --git a/conversion/__init__.py b/conversion/__init__.py
index 87624f653..9b72df673 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -50,6 +50,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"ChatGLMModel": "chatglm",
"ChatterboxModel": "chatterbox",
"ClefModel": "clef",
+ "ClefOmniModel": "clef",
"CloverMoeModelLM": "clover",
"CodeShellForCausalLM": "codeshell",
"CogVLMForCausalLM": "cogvlm",
@@ -361,6 +362,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
"AudioFlamingo3ForConditionalGeneration": "ultravox",
"ChatterboxModel": "chatterbox",
"ClefModel": "clef",
+ "ClefOmniModel": "clef",
"CogVLMForCausalLM": "cogvlm",
"Cohere2VisionForConditionalGeneration": "command_r",
"PplxDeciderModel": "pplx_decider",
diff --git a/conversion/clef.py b/conversion/clef.py
index b793d92c8..ff9afa801 100644
--- a/conversion/clef.py
+++ b/conversion/clef.py
@@ -4,7 +4,7 @@ import json
import math
from pathlib import Path
-from typing import Any, Iterable, Iterator, TYPE_CHECKING
+from typing import Any, Callable, Iterable, Iterator, TYPE_CHECKING
import torch
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
from .base import ModelBase, gguf, logger
from .qwen import Qwen3_5TextModel
-from .qwen3vl import Qwen3VLVisionModel
+from .qwen3vl import Qwen3OmniMmprojModel, Qwen3OmniMoeTextModel, Qwen3VLVisionModel
def _is_clef_checkpoint(dir_model: Path) -> bool:
@@ -24,16 +24,16 @@ def _is_clef_checkpoint(dir_model: Path) -> bool:
def _load_clef_hparams(dir_model: Path) -> dict[str, Any]:
logger.info("gguf: detected Clef checkpoint")
hparams = ModelBase.load_hparams(dir_model, False, guess=False)
- hparams["architectures"] = ["ClefModel"]
+ # clef-omni has the same head on the Qwen3-Omni thinker
+ is_omni = "thinker_config" in hparams
+ hparams["architectures"] = ["ClefOmniModel" if is_omni else "ClefModel"]
with open(dir_model / "joint_head_config.json", encoding="utf-8") as f:
hparams["decision"] = json.load(f)
return hparams
-@ModelBase.register("ClefModel")
-class ClefModel(Qwen3_5TextModel):
- model_arch = gguf.MODEL_ARCH.CLEF
- no_mtp = True # the checkpoint has no MTP head
+class _ClefHeadMixin:
+ # the joint schema head, on top of the text model of the class that uses this mixin
# prompt follows joint_schema_model.py of the model repo
_SYSTEM_PROMPT = (
@@ -42,6 +42,17 @@ class ClefModel(Qwen3_5TextModel):
)
# torch.nn.LayerNorm default, used by the head
_HEAD_NORM_EPS = 1e-5
+ # clef-omni puts a newline after each image, clef after all of them
+ _NEWLINE_PER_IMAGE = False
+ _DECISION_TYPE = gguf.DecisionType.CLEF
+
+ model_arch: gguf.MODEL_ARCH
+ hparams: dict[str, Any]
+ block_count: int
+ gguf_writer: gguf.GGUFWriter
+ dir_model: Path
+ format_tensor_name: Callable[..., str]
+ map_tensor_name: Callable[..., str]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -52,7 +63,7 @@ class ClefModel(Qwen3_5TextModel):
self._scales: dict[str, float] = {}
def set_vocab(self):
- super().set_vocab()
+ super().set_vocab() # ty: ignore[missing-attribute]
self.gguf_writer.add_chat_template([{"name": "systemone", "template": self._systemone_template()}])
@classmethod
@@ -75,9 +86,13 @@ class ClefModel(Qwen3_5TextModel):
"{% endif %}"
"{{ ({'option_id': o.key} if d is none else {'description': d, 'option_id': o.key}) | tojson(separators=[',', ':']) }}"
)
+ if cls._NEWLINE_PER_IMAGE:
+ images = "{% for image in images %}{{ image }}" + text("\n") + "{% endfor %}"
+ else:
+ images = "{% for image in images %}{{ image }}{% endfor %}" + text("\n")
return (
text(f"<|im_start|>system\n{cls._SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n")
- + "{% if images %}{{ sep }}{% for image in images %}{{ image }}{% endfor %}" + text("\n") + "{% endif %}"
+ + "{% if images %}{{ sep }}" + images + "{% endif %}"
+ "{{ sep }}" + render("state")
+ "{{ sep }}" + text("\n\nSCHEMA FIELDS:\n")
+ "{% for q in questions %}"
@@ -96,23 +111,23 @@ class ClefModel(Qwen3_5TextModel):
)
def set_gguf_parameters(self):
- super().set_gguf_parameters()
+ super().set_gguf_parameters() # ty: ignore[missing-attribute]
head = self.hparams["decision"]
- self.gguf_writer.add_decision_type(gguf.DecisionType.CLEF)
+ self.gguf_writer.add_decision_type(self._DECISION_TYPE)
self.gguf_writer.add_decision_routing_block_count(head["routing_layers"])
self.gguf_writer.add_decision_block_count(head["layers"])
self.gguf_writer.add_decision_head_count(head["heads"])
self.gguf_writer.add_layer_norm_eps(self._HEAD_NORM_EPS)
def get_tensors(self) -> Iterator[tuple[str, Tensor]]:
- yield from super().get_tensors()
+ yield from super().get_tensors() # ty: ignore[missing-attribute]
from safetensors.torch import load_file
for name, data in load_file(self.dir_model / "joint_head.safetensors").items():
yield "joint_head." + name, data
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if not name.startswith("joint_head."):
- yield from super().modify_tensors(data_torch, name, bid)
+ yield from super().modify_tensors(data_torch, name, bid) # ty: ignore[missing-attribute]
return
parts = name.split(".")
@@ -145,6 +160,31 @@ class ClefModel(Qwen3_5TextModel):
yield self.map_tensor_name(name), data_torch
+@ModelBase.register("ClefModel")
+class ClefModel(_ClefHeadMixin, Qwen3_5TextModel):
+ model_arch = gguf.MODEL_ARCH.CLEF
+ no_mtp = True # the checkpoint has no MTP head
+
+
@ModelBase.register("ClefModel")
class ClefVisionModel(Qwen3VLVisionModel):
pass
+
+
+@ModelBase.register("ClefOmniModel")
+class ClefOmniModel(_ClefHeadMixin, Qwen3OmniMoeTextModel):
+ model_arch = gguf.MODEL_ARCH.CLEF_OMNI
+ _NEWLINE_PER_IMAGE = True
+ _DECISION_TYPE = gguf.DecisionType.CLEF_OMNI
+
+
+@ModelBase.register("ClefOmniModel")
+class ClefOmniMmprojModel(Qwen3OmniMmprojModel):
+ # IMAGE_SIZE of joint_schema_model.py, the image budget is set there and not in the processor config
+ _IMAGE_MIN_PIXELS = 65_536
+ _IMAGE_MAX_PIXELS = 1_048_576
+
+ def set_gguf_parameters(self):
+ super().set_gguf_parameters()
+ self.gguf_writer.add_vision_min_pixels(self._IMAGE_MIN_PIXELS)
+ self.gguf_writer.add_vision_max_pixels(self._IMAGE_MAX_PIXELS)
diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py
index ccae76f82..43dc461ae 100644
--- a/gguf-py/gguf/constants.py
+++ b/gguf-py/gguf/constants.py
@@ -653,6 +653,7 @@ class MODEL_ARCH(IntEnum):
QWEN35MOE = auto()
CLEF = auto()
VLLM_DECISION2 = auto()
+ CLEF_OMNI = auto()
CLOVER_MOE = auto()
QWEN4EXP = auto()
PHI2 = auto()
@@ -1684,6 +1685,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.QWEN35MOE: "qwen35moe",
MODEL_ARCH.CLEF: "clef",
MODEL_ARCH.VLLM_DECISION2: "vllm-decision2",
+ MODEL_ARCH.CLEF_OMNI: "clef-omni",
MODEL_ARCH.CLOVER_MOE: "clover_moe",
MODEL_ARCH.QWEN4EXP: "qwen4exp",
MODEL_ARCH.PHI2: "phi2",
@@ -3775,6 +3777,53 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.DECISION_SCORER,
MODEL_TENSOR.DECISION_SCORER_OUT,
],
+ MODEL_ARCH.CLEF_OMNI: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ # decision head
+ MODEL_TENSOR.TOKEN_TYPES,
+ MODEL_TENSOR.DEC_ATTN_NORM,
+ MODEL_TENSOR.DEC_ATTN_Q,
+ MODEL_TENSOR.DEC_ATTN_K,
+ MODEL_TENSOR.DEC_ATTN_V,
+ MODEL_TENSOR.DEC_ATTN_OUT,
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM,
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM_KV,
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q,
+ MODEL_TENSOR.DEC_CROSS_ATTN_K,
+ MODEL_TENSOR.DEC_CROSS_ATTN_V,
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT,
+ MODEL_TENSOR.DEC_FFN_NORM,
+ MODEL_TENSOR.DEC_FFN_DOWN,
+ MODEL_TENSOR.DEC_FFN_UP,
+ MODEL_TENSOR.DECISION_HIDDEN_NORM,
+ MODEL_TENSOR.DECISION_PROJ_MEMORY,
+ MODEL_TENSOR.DECISION_PROJ_QUESTION,
+ MODEL_TENSOR.DECISION_PROJ_OPTION_QUESTION,
+ MODEL_TENSOR.DECISION_PROJ_GLOBAL,
+ MODEL_TENSOR.DECISION_PROJ_OPTION_CONTEXT,
+ MODEL_TENSOR.DECISION_PROJ_OPTION_LEXICAL,
+ MODEL_TENSOR.DECISION_OPTION_SUMMARY_NORM,
+ MODEL_TENSOR.DECISION_FIELD_NORM,
+ MODEL_TENSOR.DECISION_OPTION_NORM,
+ MODEL_TENSOR.DECISION_SCALES,
+ MODEL_TENSOR.DECISION_SCORER,
+ MODEL_TENSOR.DECISION_SCORER_OUT,
+ ],
MODEL_ARCH.VLLM_DECISION2: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
@@ -7654,6 +7703,7 @@ class DecisionType:
GRANITE_SWITCH = "granite-switch" # same as openjev, run by the decision aLoRA of granite switch
H2O_LIGHTNING = "h2o-lightning" # same as openjev, labels read after an answer prefill
MINICPM_OCR_JEV = "openbmb-minicpm-ocr-jev" # class scores of a value head read at the last token, one fixed task
+ CLEF_OMNI = "cloudflare-clef-omni" # same as clef on the Qwen3-Omni thinker, with audio input and no video input
class VisionProjectorType:
diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp
index e78c3d2a8..f41434f7a 100644
--- a/src/llama-arch.cpp
+++ b/src/llama-arch.cpp
@@ -45,6 +45,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_QWEN35, "qwen35" },
{ LLM_ARCH_QWEN35MOE, "qwen35moe" },
{ LLM_ARCH_CLEF, "clef" },
+ { LLM_ARCH_CLEF_OMNI, "clef-omni" },
{ LLM_ARCH_VLLM_DECISION2, "vllm-decision2" },
{ LLM_ARCH_QWEN4EXP, "qwen4exp" },
{ LLM_ARCH_PHI2, "phi2" },
@@ -1655,6 +1656,7 @@ bool llama_arch_supports_save(llm_arch arch) {
case LLM_ARCH_T5:
case LLM_ARCH_STEP35:
case LLM_ARCH_CLEF: // the head tensors are not saved
+ case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load
case LLM_ARCH_VLLM_DECISION2:
return false;
diff --git a/src/llama-arch.h b/src/llama-arch.h
index 03e8b8c80..7508fd2af 100644
--- a/src/llama-arch.h
+++ b/src/llama-arch.h
@@ -48,6 +48,7 @@ enum llm_arch {
LLM_ARCH_QWEN35,
LLM_ARCH_QWEN35MOE,
LLM_ARCH_CLEF,
+ LLM_ARCH_CLEF_OMNI,
LLM_ARCH_VLLM_DECISION2,
LLM_ARCH_CLOVER_MOE,
LLM_ARCH_QWEN4EXP,
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index 7b6e9ea11..4de143666 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -373,6 +373,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
return new llama_model_qwen35moe(params);
case LLM_ARCH_CLEF:
return new llama_model_clef(params);
+ case LLM_ARCH_CLEF_OMNI:
+ return new llama_model_clef_omni(params);
case LLM_ARCH_VLLM_DECISION2:
return new llama_model_vllm_decision2(params);
case LLM_ARCH_CLOVER_MOE:
@@ -3044,6 +3046,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
case LLM_ARCH_LLADA_MOE:
case LLM_ARCH_RND1:
case LLM_ARCH_CLEF:
+ case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_KOKORO:
case LLM_ARCH_TINY_VOCA:
{
@@ -3977,6 +3980,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
case LLM_ARCH_QWEN35:
case LLM_ARCH_QWEN35MOE:
case LLM_ARCH_CLEF:
+ case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_QWEN4EXP:
case LLM_ARCH_QWEN3TTS:
return LLAMA_ROPE_TYPE_IMROPE;
diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp
index 38eb0d588..2c93e16dc 100644
--- a/src/llama-quant.cpp
+++ b/src/llama-quant.cpp
@@ -528,7 +528,13 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
if (n_expert > 1) {
// Experts may not be consecutive and simply dividing i_ffn_down by n_expert does not work,
// so we need to parse the tensor name
- if (sscanf(tname, "blk.%d.", &i_layer) != 1) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); }
+ if (sscanf(tname, "blk.%d.", &i_layer) != 1) {
+ // the blocks of a decision head use their own numbering, block N is treated like backbone layer N
+ if (sscanf(tname, "dec.blk.%d.", &i_layer) == 1) {
+ return std::make_pair(i_layer, n_layer);
+ }
+ throw std::runtime_error(format("Failed to determine layer for tensor %s", tname));
+ }
if (i_layer < 0 || i_layer >= n_layer) { throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, tname, n_layer)); }
}
diff --git a/src/models/clef-omni.cpp b/src/models/clef-omni.cpp
new file mode 100644
index 000000000..d54332cf0
--- /dev/null
+++ b/src/models/clef-omni.cpp
@@ -0,0 +1,96 @@
+#include "models.h"
+
+void llama_model_clef_omni::load_arch_hparams(llama_model_loader & ml) {
+ llama_model_qwen3vlmoe::load_arch_hparams(ml);
+ head.load_hparams(ml, hparams);
+}
+
+void llama_model_clef_omni::load_arch_tensors(llama_model_loader & ml) {
+ llama_model_qwen3vlmoe::load_arch_tensors(ml);
+ head.load_tensors(ml, *this);
+}
+
+std::unique_ptr<llm_graph_context> llama_model_clef_omni::build_arch_graph(const llm_graph_params & params) const {
+ return std::make_unique<graph>(params);
+}
+
+// the backbone is copied from llama_model_qwen3vlmoe::graph, without the memory module
+// it also drops inp_out_ids (the head reads all tokens) and build_cvec(), as clef does
+llama_model_clef_omni::graph::graph(const llm_graph_params & params) : llm_graph_context(params) {
+ const auto & model = static_cast<const llama_model_clef_omni &>(*params.model);
+
+ const int64_t n_embd_head = hparams.n_embd_head_v();
+
+ GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
+ GGML_ASSERT(n_embd_head == n_rot);
+
+ ggml_tensor * cur;
+ ggml_tensor * inpL;
+
+ inpL = build_inp_embd(model.tok_embd);
+
+ ggml_tensor * inp_pos = build_inp_pos();
+
+ auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this);
+
+ for (int il = 0; il < n_layer; ++il) {
+ ggml_tensor * inpSA = inpL;
+
+ cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il);
+ cb(cur, "attn_norm", il);
+
+ auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il);
+
+ Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il);
+ cb(Qcur, "Qcur_normed", il);
+
+ Qcur = build_rope(Qcur, inp_pos, il);
+
+ Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il);
+ cb(Kcur, "Kcur_normed", il);
+
+ Kcur = build_rope(Kcur, inp_pos, il);
+
+ cur = build_attn(inp_attn,
+ model.layers[il].wo, model.layers[il].wo_b,
+ Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
+
+ ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
+ cb(ffn_inp, "ffn_inp", il);
+
+ cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il);
+ cb(cur, "ffn_norm", il);
+
+ cur = build_moe_ffn(cur,
+ model.layers[il].ffn_gate_inp,
+ model.layers[il].ffn_up_exps,
+ model.layers[il].ffn_gate_exps,
+ model.layers[il].ffn_down_exps,
+ nullptr,
+ n_expert, n_expert_used,
+ LLM_FFN_SILU, true,
+ hparams.expert_weights_scale,
+ LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
+ il);
+ cb(cur, "ffn_moe_out", il);
+
+ cur = ggml_add(ctx0, cur, ffn_inp);
+ cb(cur, "l_out", il);
+
+ if (il < (int) hparams.n_deepstack_layers) {
+ ggml_tensor * ds = ggml_view_2d(ctx0, res->t_inp_embd, n_embd, n_tokens, res->t_inp_embd->nb[1], (il + 1) * n_embd * sizeof(float));
+ cur = ggml_add(ctx0, cur, ds);
+ cb(cur, "deepstack_out", il);
+ }
+
+ inpL = cur;
+ }
+
+ cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1);
+ cb(cur, "result_norm", -1);
+
+ // the head is always evaluated, so that the graph has the same nodes for every batch
+ cur = model.head.build(*this, cur);
+
+ res->t_embd = cur;
+}
diff --git a/src/models/clef.cpp b/src/models/clef.cpp
index d7d94f49b..137561476 100644
--- a/src/models/clef.cpp
+++ b/src/models/clef.cpp
@@ -5,9 +5,7 @@
#include <algorithm>
#include <cmath>
-void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
- llama_model_qwen35::load_arch_hparams(ml);
-
+void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hparams) {
ml.get_key(LLM_KV_DECISION_ROUTING_BLOCK_COUNT, n_layer_routing);
ml.get_key(LLM_KV_DECISION_BLOCK_COUNT, n_layer_joint);
ml.get_key(LLM_KV_DECISION_HEAD_COUNT, n_head_decision);
@@ -23,10 +21,18 @@ void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
hparams.n_embd_out_impl = 1;
}
-void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
- llama_model_qwen35::load_arch_tensors(ml);
+void llama_model_clef::load_arch_hparams(llama_model_loader & ml) {
+ llama_model_qwen35::load_arch_hparams(ml);
+ head.load_hparams(ml, hparams);
+}
- LLAMA_LOAD_LOCALS;
+void llama_clef_head::load_tensors(llama_model_loader & ml, llama_model_base & model) {
+ const auto & tn = model.tn;
+ const int64_t n_embd = model.hparams.n_embd;
+
+ auto create_tensor = [&](const LLM_TN_IMPL & name, const std::initializer_list<int64_t> & ne, int flags) {
+ return model.create_tensor(ml, name, ne, flags);
+ };
const auto * w_memory = ml.get_weight(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight").str().c_str());
const auto * w_ffn = ml.get_weight(tn(LLM_TENSOR_DEC_FFN_UP, "weight", 0).str().c_str());
@@ -82,10 +88,10 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
load_norm(field_norm, LLM_TENSOR_DECISION_FIELD_NORM, n_embd_h);
load_norm(option_norm, LLM_TENSOR_DECISION_OPTION_NORM, n_embd_h);
- output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
+ output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, model.vocab.n_tokens()}, model.TENSOR_NOT_REQUIRED);
if (output_lexical == nullptr) {
- output_lexical = tok_embd;
+ output_lexical = model.tok_embd;
}
proj_memory = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight"), {n_embd, n_embd_h}, 0);
@@ -104,6 +110,11 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
scorer_out_b = create_tensor(tn(LLM_TENSOR_DECISION_SCORER_OUT, "bias"), {1}, 0);
}
+void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
+ llama_model_qwen35::load_arch_tensors(ml);
+ head.load_tensors(ml, *this);
+}
+
std::unique_ptr<llm_graph_context> llama_model_clef::build_arch_graph(const llm_graph_params & params) const {
return std::make_unique<graph>(params);
}
@@ -185,7 +196,7 @@ static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; }
static size_t clef_n_options (int64_t n_tokens) { return std::max<int64_t>(n_tokens - 1, 1); }
// pooling matrices and indices computed from the spans
-class llama_model_clef::input_decision : public llm_graph_input_i {
+class llama_clef_head::input_decision : public llm_graph_input_i {
public:
input_decision(const llama_ubatch & ubatch) :
n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {}
@@ -277,11 +288,7 @@ llama_model_clef::graph::graph(const llm_graph_params & params) :
ggml_tensor * inp_pos = build_inp_pos();
- auto * inp_attn = build_attn_inp_causal();
-
- auto inp_decision_ptr = std::make_unique<input_decision>(ubatch);
- auto * inp_decision = inp_decision_ptr.get();
- res->add_input(std::move(inp_decision_ptr));
+ auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this);
for (int il = 0; il < n_layer; ++il) {
ggml_tensor * inpSA = inpL;
@@ -321,16 +328,9 @@ llama_model_clef::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
// the head is always evaluated, so that the graph has the same nodes for every batch
- cur = build_head(cur, inp_decision);
-
- // row i of the output is the score of option i
- cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0);
- cur = ggml_add(ctx0, cur, inp_decision->status);
- cb(cur, "result_decision", -1);
+ cur = model.head.build(*this, cur);
res->t_embd = cur;
-
- ggml_build_forward_expand(gf, cur);
}
// causal mask by batch order: the tokens of an image share the same position
@@ -361,16 +361,16 @@ public:
};
// same as build_attn_inp_no_cache(), with a causal mask even if the batch is processed by the encoder path
-llm_graph_input_attn_no_cache * llama_model_clef::graph::build_attn_inp_causal() {
- auto inp = std::make_unique<llm_graph_input_attn_clef>(hparams, cparams);
+llm_graph_input_attn_no_cache * llama_clef_head::build_attn_inp_causal(const llm_graph_context & ctx) {
+ auto inp = std::make_unique<llm_graph_input_attn_clef>(ctx.hparams, ctx.cparams);
- const auto type_mask = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32;
+ const auto type_mask = ctx.cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32;
- inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx0, type_mask, GGML_PAD(n_tokens, 256), n_tokens, 1, 1);
+ inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx.ctx0, type_mask, GGML_PAD(ctx.n_tokens, 256), ctx.n_tokens, 1, 1);
ggml_set_input(inp->self_attn_mask.raw);
- cb(inp->self_attn_mask.raw, "self_kq_mask", -1);
+ ctx.cb(inp->self_attn_mask.raw, "self_kq_mask", -1);
- return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp));
+ return (llm_graph_input_attn_no_cache *) ctx.res->add_input(std::move(inp));
}
ggml_tensor * llama_model_clef::graph::build_layer_attn(
@@ -496,21 +496,23 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear(
return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
}
-ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const norm & n) {
- return build_norm(cur, n.w, n.b, LLM_NORM, -1);
+ggml_tensor * llama_clef_head::build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const {
+ return ctx.build_norm(cur, n.w, n.b, LLM_NORM, -1);
}
// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null
-ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) {
+ggml_tensor * llama_clef_head::build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) const {
+ ggml_context * ctx0 = ctx.ctx0;
+
const int64_t n_embd_h = q->ne[0];
- const int64_t n_head_h = model.n_head_decision;
+ const int64_t n_head_h = n_head_decision;
const int64_t d_head = n_embd_h / n_head_h;
const int64_t n_q = q->ne[1];
const int64_t n_kv = kv->ne[1];
- ggml_tensor * Qcur = ggml_add(ctx0, build_lora_mm(a.wq, q), a.bq);
- ggml_tensor * Kcur = ggml_add(ctx0, build_lora_mm(a.wk, kv), a.bk);
- ggml_tensor * Vcur = ggml_add(ctx0, build_lora_mm(a.wv, kv), a.bv);
+ ggml_tensor * Qcur = ggml_add(ctx0, ctx.build_lora_mm(a.wq, q), a.bq);
+ ggml_tensor * Kcur = ggml_add(ctx0, ctx.build_lora_mm(a.wk, kv), a.bk);
+ ggml_tensor * Vcur = ggml_add(ctx0, ctx.build_lora_mm(a.wv, kv), a.bv);
Qcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Qcur, d_head, n_head_h, n_q), 0, 2, 1, 3); // [d_head, n_q, n_head]
Kcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Kcur, d_head, n_head_h, n_kv), 0, 2, 1, 3); // [d_head, n_kv, n_head]
@@ -523,18 +525,29 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten
ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head]
cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q);
- return ggml_add(ctx0, build_lora_mm(a.wo, cur), a.bo);
+ return ggml_add(ctx0, ctx.build_lora_mm(a.wo, cur), a.bo);
}
-ggml_tensor * llama_model_clef::graph::build_head_ffn(ggml_tensor * cur, const head_layer & layer) {
- cur = build_head_norm(cur, layer.ffn_norm);
- cur = ggml_add(ctx0, build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b);
+ggml_tensor * llama_clef_head::build_head_ffn(const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const {
+ ggml_context * ctx0 = ctx.ctx0;
+
+ cur = build_head_norm(ctx, cur, layer.ffn_norm);
+ cur = ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b);
cur = ggml_gelu_erf(ctx0, cur);
- return ggml_add(ctx0, build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b);
+ return ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b);
}
// ref: JointSchemaHead in joint_schema_model.py of the model repo
-ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_decision * inp) {
+ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor * hidden) const {
+ ggml_context * ctx0 = ctx.ctx0;
+
+ const int64_t n_embd = hidden->ne[0];
+ const int64_t n_tokens = hidden->ne[1];
+
+ auto inp_ptr = std::make_unique<input_decision>(ctx.ubatch);
+ auto * inp = inp_ptr.get();
+ ctx.res->add_input(std::move(inp_ptr));
+
const int64_t n_questions = inp->n_questions;
const int64_t n_options = inp->n_options;
@@ -550,9 +563,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_set_input(t);
}
- hidden = build_head_norm(hidden, model.hidden_norm);
+ hidden = build_head_norm(ctx, hidden, hidden_norm);
- ggml_tensor * memory = build_lora_mm(model.proj_memory, hidden); // [n_embd_h, n_tokens]
+ ggml_tensor * memory = ctx.build_lora_mm(proj_memory, hidden); // [n_embd_h, n_tokens]
const int64_t n_embd_h = memory->ne[0];
@@ -565,29 +578,29 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_tensor * opt_ctx = ggml_mul_mat(ctx0, hidden_t, inp->pool_o); // [n_embd, n_options]
// mean of the output embeddings of the tokens of each option
- ggml_tensor * lexical = ggml_get_rows(ctx0, model.output_lexical, inp->tokens);
+ ggml_tensor * lexical = ggml_get_rows(ctx0, output_lexical, inp->tokens);
lexical = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, lexical)), inp->pool_o); // [n_embd, n_options]
// one query per option
- ggml_tensor * options = build_lora_mm(model.proj_option_context, opt_ctx);
- options = ggml_add(ctx0, options, build_lora_mm(model.proj_option_lexical, lexical));
- options = ggml_add(ctx0, options, ggml_get_rows(ctx0, build_lora_mm(model.proj_option_question, question), inp->option_question));
+ ggml_tensor * options = ctx.build_lora_mm(proj_option_context, opt_ctx);
+ options = ggml_add(ctx0, options, ctx.build_lora_mm(proj_option_lexical, lexical));
+ options = ggml_add(ctx0, options, ggml_get_rows(ctx0, ctx.build_lora_mm(proj_option_question, question), inp->option_question));
// the options read the prompt
- for (uint32_t il = 0; il < model.n_layer_routing; ++il) {
- const auto & layer = model.head_layers[il];
+ for (uint32_t il = 0; il < n_layer_routing; ++il) {
+ const auto & layer = head_layers[il];
- ggml_tensor * cur = build_head_attn(
- build_head_norm(options, layer.cross_norm),
- build_head_norm(memory, layer.cross_norm_kv),
+ ggml_tensor * cur = build_head_attn(ctx,
+ build_head_norm(ctx, options, layer.cross_norm),
+ build_head_norm(ctx, memory, layer.cross_norm_kv),
layer.cross_attn);
options = ggml_add(ctx0, options, cur);
- options = ggml_add(ctx0, options, build_head_ffn(options, layer));
+ options = ggml_add(ctx0, options, build_head_ffn(ctx, options, layer));
}
- cb(options, "decision_options", -1);
+ ctx.cb(options, "decision_options", -1);
// one vector per question: its text, a summary of its options, the end of the prompt and its type
- ggml_tensor * fields = build_lora_mm(model.proj_question, question); // [n_embd_h, n_questions]
+ ggml_tensor * fields = ctx.build_lora_mm(proj_question, question); // [n_embd_h, n_questions]
{
// each question weights its own options
ggml_tensor * weights = ggml_mul_mat(ctx0, options, fields); // [n_options, n_questions]
@@ -596,25 +609,25 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_tensor * summary = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, options)), weights);
- fields = ggml_add(ctx0, fields, build_head_norm(summary, model.option_summary_norm));
- fields = ggml_add(ctx0, fields, build_lora_mm(model.proj_global, global));
- fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, model.type_embd, inp->question_type));
+ fields = ggml_add(ctx0, fields, build_head_norm(ctx, summary, option_summary_norm));
+ fields = ggml_add(ctx0, fields, ctx.build_lora_mm(proj_global, global));
+ fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, type_embd, inp->question_type));
}
// the questions read each other and the prompt
- for (uint32_t il = model.n_layer_routing; il < model.head_layers.size(); ++il) {
- const auto & layer = model.head_layers[il];
+ for (uint32_t il = n_layer_routing; il < head_layers.size(); ++il) {
+ const auto & layer = head_layers[il];
- ggml_tensor * cur = build_head_norm(fields, layer.self_norm);
- fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask));
+ ggml_tensor * cur = build_head_norm(ctx, fields, layer.self_norm);
+ fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, cur, layer.self_attn, inp->question_mask));
- cur = build_head_norm(fields, layer.cross_norm);
- fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn));
+ cur = build_head_norm(ctx, fields, layer.cross_norm);
+ fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, memory, layer.cross_attn));
- fields = ggml_add(ctx0, fields, build_head_ffn(fields, layer));
+ fields = ggml_add(ctx0, fields, build_head_ffn(ctx, fields, layer));
}
- fields = build_head_norm(fields, model.field_norm);
- cb(fields, "decision_fields", -1);
+ fields = build_head_norm(ctx, fields, field_norm);
+ ctx.cb(fields, "decision_fields", -1);
const float eps = 1e-12f;
@@ -624,7 +637,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_tensor * prior = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, lexical, eps), anchor)); // [1, n_options]
// joint: each option against the vector of its question
- options = build_head_norm(options, model.option_norm);
+ options = build_head_norm(ctx, options, option_norm);
ggml_tensor * field = ggml_get_rows(ctx0, fields, inp->option_question); // [n_embd_h, n_options]
ggml_tensor * cosine = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, field, eps), ggml_l2_norm(ctx0, options, eps)));
@@ -633,15 +646,22 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
features = ggml_concat(ctx0, features, ggml_mul(ctx0, field, options), 0);
features = ggml_concat(ctx0, features, ggml_abs(ctx0, ggml_sub(ctx0, field, options)), 0);
- ggml_tensor * residual = ggml_add(ctx0, build_lora_mm(model.scorer, features), model.scorer_b);
+ ggml_tensor * residual = ggml_add(ctx0, ctx.build_lora_mm(scorer, features), scorer_b);
residual = ggml_gelu_erf(ctx0, residual);
- residual = ggml_add(ctx0, build_lora_mm(model.scorer_out, residual), model.scorer_out_b); // [1, n_options]
+ residual = ggml_add(ctx0, ctx.build_lora_mm(scorer_out, residual), scorer_out_b); // [1, n_options]
auto scale = [&](int i) {
- return ggml_view_1d(ctx0, model.scales, 1, i * ggml_element_size(model.scales));
+ return ggml_view_1d(ctx0, scales, 1, i * ggml_element_size(scales));
};
ggml_tensor * joint = ggml_add(ctx0, ggml_mul(ctx0, cosine, scale(1)), residual);
- return ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2)));
+ ggml_tensor * cur = ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2)));
+
+ // row i of the output is the score of option i
+ cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0);
+ cur = ggml_add(ctx0, cur, inp->status);
+ ctx.cb(cur, "result_decision", -1);
+
+ return cur;
}
diff --git a/src/models/models.h b/src/models/models.h
index 893e74251..e4bd4eb58 100644
--- a/src/models/models.h
+++ b/src/models/models.h
@@ -701,6 +701,8 @@ struct llama_model_qwen3vlmoe : public llama_model_base {
graph(const llm_graph_params & params);
};
+ // if false, the derived model does not use the LM head and builds its own output
+ virtual bool has_lm_head() const { return true; }
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
@@ -3004,12 +3006,8 @@ struct llama_model_qwen35 : public llama_model_base {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
-// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states
-struct llama_model_clef : public llama_model_qwen35 {
- llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {}
- void load_arch_hparams(llama_model_loader & ml) override;
- void load_arch_tensors(llama_model_loader & ml) override;
-
+// joint decision head of clef, on top of the final hidden states of a backbone evaluated without memory
+struct llama_clef_head {
struct attn {
ggml_tensor * wq = nullptr;
ggml_tensor * bq = nullptr;
@@ -3058,6 +3056,7 @@ struct llama_model_clef : public llama_model_qwen35 {
ggml_tensor * proj_option_context = nullptr;
ggml_tensor * proj_option_lexical = nullptr;
ggml_tensor * scales = nullptr; // prior scale, joint scale, residual gate
+ ggml_tensor * type_embd = nullptr;
ggml_tensor * scorer = nullptr;
ggml_tensor * scorer_b = nullptr;
ggml_tensor * scorer_out = nullptr;
@@ -3066,11 +3065,33 @@ struct llama_model_clef : public llama_model_qwen35 {
class input_decision;
+ void load_hparams(llama_model_loader & ml, llama_hparams & hparams);
+ void load_tensors(llama_model_loader & ml, llama_model_base & model);
+
+ // causal mask by batch order, for the attention layers of the backbone
+ static llm_graph_input_attn_no_cache * build_attn_inp_causal(const llm_graph_context & ctx);
+
+ // hidden: [n_embd, n_tokens]
+ // returns [1, n_tokens], row i is the score of option i
+ ggml_tensor * build(const llm_graph_context & ctx, ggml_tensor * hidden) const;
+
+private:
+ ggml_tensor * build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const;
+ ggml_tensor * build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr) const;
+ ggml_tensor * build_head_ffn (const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const;
+};
+
+// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states
+struct llama_model_clef : public llama_model_qwen35 {
+ llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {}
+ void load_arch_hparams(llama_model_loader & ml) override;
+ void load_arch_tensors(llama_model_loader & ml) override;
+
+ llama_clef_head head;
+
struct graph : public llm_build_delta_net_base {
graph(const llm_graph_params & params);
private:
- llm_graph_input_attn_no_cache * build_attn_inp_causal();
-
ggml_tensor * build_layer_attn(
llm_graph_input_attn_no_cache * inp_attn,
ggml_tensor * cur,
@@ -3081,16 +3102,23 @@ struct llama_model_clef : public llama_model_qwen35 {
ggml_tensor * cur,
int il);
- // hidden: [n_embd, n_tokens], returns one score per option: [1, n_options]
- ggml_tensor * build_head(
- ggml_tensor * hidden,
- input_decision * inp);
+ const llama_model_clef & model;
+ };
- ggml_tensor * build_head_norm(ggml_tensor * cur, const norm & n);
- ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr);
- ggml_tensor * build_head_ffn (ggml_tensor * cur, const head_layer & layer);
+ bool has_lm_head() const override { return false; }
+ std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
+};
- const llama_model_clef & model;
+// Qwen3-Omni thinker (Qwen3 MoE) backbone evaluated without memory, with the clef decision head
+struct llama_model_clef_omni : public llama_model_qwen3vlmoe {
+ llama_model_clef_omni(const struct llama_model_params & params) : llama_model_qwen3vlmoe(params) {}
+ void load_arch_hparams(llama_model_loader & ml) override;
+ void load_arch_tensors(llama_model_loader & ml) override;
+
+ llama_clef_head head;
+
+ struct graph : public llm_graph_context {
+ graph(const llm_graph_params & params);
};
bool has_lm_head() const override { return false; }
diff --git a/src/models/qwen3vlmoe.cpp b/src/models/qwen3vlmoe.cpp
index 0d13a1dc5..acab474ef 100644
--- a/src/models/qwen3vlmoe.cpp
+++ b/src/models/qwen3vlmoe.cpp
@@ -20,10 +20,14 @@ void llama_model_qwen3vlmoe::load_arch_tensors(llama_model_loader &) {
// output
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}, TENSOR_NOT_REQUIRED);
- // if output is NULL, init from the input tok embed
- if (output == NULL) {
- output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
+
+ if (has_lm_head()) {
+ output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
+
+ // if output is NULL, init from the input tok embed
+ if (output == NULL) {
+ output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
+ }
}
for (int i = 0; i < n_layer; ++i) {
diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp
index dc4eeaba4..7b53cd947 100644
--- a/tests/test-llama-archs.cpp
+++ b/tests/test-llama-archs.cpp
@@ -1184,6 +1184,7 @@ static bool moe_mandatory(const llm_arch arch) {
case LLM_ARCH_QWEN3MOE:
case LLM_ARCH_QWEN3NEXT:
case LLM_ARCH_QWEN3VLMOE:
+ case LLM_ARCH_CLEF_OMNI:
case LLM_ARCH_QWEN35MOE:
case LLM_ARCH_CLOVER_MOE:
case LLM_ARCH_QWEN4EXP:
@@ -1297,7 +1298,7 @@ static bool arch_supported(const llm_arch arch) {
if (arch == LLM_ARCH_PLM) {
return false; // TODO tensor shapes
}
- if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_VLLM_DECISION2) {
+ if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_CLEF_OMNI || arch == LLM_ARCH_VLLM_DECISION2) {
return false; // TODO decision head tensors
}
if (arch == LLM_ARCH_DEEPSEEK2OCR) {
diff --git a/tests/test-server-component.cpp b/tests/test-server-component.cpp
index d5933167e..6f0dc64d0 100644
--- a/tests/test-server-component.cpp
+++ b/tests/test-server-component.cpp
@@ -773,6 +773,40 @@ static void test_decision_ocr_jev_validation(testing & t) {
reject_state("two images, three given", files_of(3), "this model needs exactly 2 images");
}
+// server_decision_context::parse_state: "images" and "audio" are aliases of "files"
+//
+
+static void test_decision_media_fields(testing & t) {
+ server_decision_context ctx;
+ ctx.type = COMMON_DECISION_TYPE_CLEF_OMNI;
+
+ // only base64-decoded, the media itself is not parsed here
+ const std::string image = "data:image/png;base64,AAAA";
+ const std::string audio = "data:audio/wav;base64,AQID";
+
+ std::vector<raw_buffer> files;
+ ctx.parse_state({{"state", "x"}, {"audio", json::array({audio})}}, files);
+ t.assert_equal("audio is read", (size_t) 1, files.size());
+ t.assert_true("audio content", files[0] == raw_buffer({1, 2, 3}));
+
+ files.clear();
+ ctx.parse_state({{"state", "x"}, {"files", json::array({image})}, {"images", json::array({image})}, {"audio", json::array({audio})}}, files);
+ t.assert_equal("all fields are read", (size_t) 3, files.size());
+ t.assert_true("audio after files and images", files[2] == raw_buffer({1, 2, 3}));
+
+ files.clear();
+ ctx.parse_state({{"state", "x"}, {"audio", nullptr}}, files);
+ t.assert_true("null audio", files.empty());
+
+ std::string error;
+ try {
+ ctx.parse_state({{"state", "x"}, {"audio", audio}}, files);
+ } catch (const std::invalid_argument & e) {
+ error = e.what();
+ }
+ t.assert_true("audio must be an array: " + error, error.find("\"audio\" must be an array") != std::string::npos);
+}
+
// server_decision_context: the recursive functions stop at RECURSIVE_LIMIT
//
@@ -798,6 +832,90 @@ static void test_decision_depth(testing & t) {
});
}
+//
+// server_decision_context: the joint head reads media grouped by kind (images, then audio, then video)
+//
+
+static std::vector<uint8_t> make_wav_16khz(size_t n_samples) {
+ std::vector<uint8_t> b(44 + 2 * n_samples, 0);
+ const auto put32 = [&](size_t o, uint32_t v) { b[o] = v; b[o + 1] = v >> 8; b[o + 2] = v >> 16; b[o + 3] = v >> 24; };
+ const auto put16 = [&](size_t o, uint16_t v) { b[o] = v; b[o + 1] = v >> 8; };
+ memcpy(b.data(), "RIFF", 4);
+ put32(4, 36 + (uint32_t) (2 * n_samples));
+ memcpy(b.data() + 8, "WAVEfmt ", 8);
+ put32(16, 16); // fmt chunk size
+ put16(20, 1); // PCM
+ put16(22, 1); // channels
+ put32(24, 16000); // sample rate
+ put32(28, 16000 * 2); // byte rate
+ put16(32, 2); // block align
+ put16(34, 16); // bits per sample
+ memcpy(b.data() + 36, "data", 4);
+ put32(40, (uint32_t) (2 * n_samples));
+ return b;
+}
+
+static void test_decision_media_order(testing & t) {
+ const mtmd_helper_init_opt opt = mtmd_helper_init_opt_default();
+
+ const std::vector<uint8_t> png = { // a 1x1 grayscale PNG
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x7e, 0x9b,
+ 0x55, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x00, 0x00, 0x00,
+ 0x02, 0x00, 0x01, 0x48, 0xaf, 0xa4, 0x71, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
+ 0x42, 0x60, 0x82,
+ };
+ const raw_buffer image = png;
+ const raw_buffer audio_a = make_wav_16khz(16);
+ const raw_buffer audio_b = make_wav_16khz(32);
+
+ // the detector recognizes the buffers, so the test exercises the real grouping
+ mtmd_helper_media_meta meta;
+ t.assert_true("image detected", mtmd_helper_get_media_meta(image.data(), image.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_IMAGE);
+ t.assert_true("audio detected", mtmd_helper_get_media_meta(audio_a.data(), audio_a.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_AUDIO);
+
+ // images come first even when the request lists audio first
+ const std::vector<raw_buffer> grouped = decision_order_media({audio_a, image}, opt);
+ t.assert_equal("count", (size_t) 2, grouped.size());
+ t.assert_true("image first", grouped[0] == image);
+ t.assert_true("audio last", grouped[1] == audio_a);
+
+ // the order within a kind is kept
+ const std::vector<raw_buffer> stable = decision_order_media({audio_b, image, audio_a}, opt);
+ t.assert_equal("stable count", (size_t) 3, stable.size());
+ t.assert_true("stable image first", stable[0] == image);
+ t.assert_true("stable audio order", stable[1] == audio_b && stable[2] == audio_a);
+
+ // a decoder that reads any buffer as a video, the built-in one needs ffmpeg
+ static int decoder_state = 0;
+ mtmd_helper_video_decoder decoder = {};
+ decoder.open = [](void *, const char *, const unsigned char *, size_t, mtmd_helper_video_stream_info * info) -> void * {
+ *info = {16, 16, 2.0f, 4, 2.0f};
+ return &decoder_state;
+ };
+ decoder.read_frame = [](void *, unsigned char *, uint32_t, uint32_t) { return false; };
+ decoder.close = [](void *) {};
+
+ mtmd_helper_init_opt opt_video = opt;
+ opt_video.video_params.decoder = &decoder;
+
+ const raw_buffer video = {'v', 'i', 'd', 'e', 'o'};
+ t.assert_true("video detected", mtmd_helper_get_media_meta(video.data(), video.size(), opt_video, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_VIDEO);
+
+ const std::vector<raw_buffer> with_video = decision_order_media({video, audio_a, image}, opt_video);
+ t.assert_true("video last", with_video.size() == 3 && with_video[0] == image && with_video[1] == audio_a && with_video[2] == video);
+
+ // cloudflare-clef-omni
+ std::string error;
+ try {
+ decision_order_media({image, video}, opt_video, false);
+ } catch (const std::invalid_argument & e) {
+ error = e.what();
+ }
+ t.assert_true("video rejected: " + error, error.find("video input is not supported") != std::string::npos);
+ t.assert_equal("no video, nothing rejected", (size_t) 2, decision_order_media({audio_a, image}, opt_video, false).size());
+}
+
// DRY sequence breakers
//
@@ -992,7 +1110,9 @@ int main(int argc, char ** argv) {
t.test("rerank_template", test_rerank_template);
t.test("decision_class_scores", test_decision_class_scores);
t.test("decision_ocr_jev_validation", test_decision_ocr_jev_validation);
+ t.test("decision_media_fields", test_decision_media_fields);
t.test("decision_depth", test_decision_depth);
+ t.test("decision_media_order", test_decision_media_order);
t.test("glob_match", test_glob_match);
t.test("dry_sequence_breakers", test_dry_sequence_breakers);
t.test("stop_strings", test_stop_strings);
diff --git a/tools/server/README.md b/tools/server/README.md
index f690d7c04..6dda4de48 100644
--- a/tools/server/README.md
+++ b/tools/server/README.md
@@ -1932,6 +1932,8 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo
`images`: Optional. An alias of `files`.
+`audio`: Optional. An alias of `files`.
+
`questions`: An object that maps a question id to a question. Each question has these fields:
- `type`: One of `choice`, `score`, `noul`.
@@ -1941,11 +1943,11 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo
- `score`: An array of 2 to 10 level descriptions, lowest level first.
- `noul`: Optional. An object with the descriptions of `true` and `false`.
-The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef, which reads all the questions in one prompt and decides them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass).
+The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef and cloudflare-clef-omni, which read all the questions in one prompt and decide them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass).
-The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with.
+The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, cloudflare-clef-omni, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with.
-For laya, clef, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`.
+For laya, clef, cloudflare-clef-omni, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef or cloudflare-clef-omni only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`.
openbmb-minicpm-ocr-jev answers one fixed question: is an OCR text, rendered as an image, consistent with the original image? `state` is the OCR text, as a string, special tokens written in it are escaped. `files` (or `images`) has exactly 2 images: the original, then the rendered one, both are required. The request has one question and no `instructions`: the task is part of the prompt of the model, so a request that sends one is rejected. It is either a `choice` with the `criteria` `{"0": null, "1": null}`, where `1` means consistent, or a `noul` without `criteria`, which returns the probability of `1`. The model has no LM head, so text generation is not available.
@@ -1953,14 +1955,16 @@ Its prompt carries two images, so it is much longer than a text-only one: size t
*Image input:*
-Image input needs a model that supports it (for example: openjev, clef, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`.
+Image input needs a model that supports it (for example: openjev, clef, cloudflare-clef-omni, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`.
Images can be given in two ways, and both can be used in the same request:
-- The `files` field, or its alias `images`.
+- The `files` field, or its aliases `images` and `audio`.
- A `state` made of chat messages, either an array of messages or an object with a `messages` array. An `image_url` part in the `content` of a message is taken as an image, in the same format as chat completions. Only data URLs are accepted. For lfm2-d1-omni, an `input_audio` part is taken as an audio clip, as base64 data.
-All the images are placed before the state in the prompt, the ones from `files` and `images` first. The image parts are removed from the state.
+All the images are placed before the state in the prompt, the ones from `files`, `images` and `audio` first. The image parts are removed from the state.
+
+For clef and cloudflare-clef-omni, the files are grouped by kind, as the models were trained: images, then audio clips, then videos. A video is rejected by cloudflare-clef-omni.
*Response:*
diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp
index 18564b6e4..5097c60ca 100644
--- a/tools/server/server-common.cpp
+++ b/tools/server/server-common.cpp
@@ -241,6 +241,7 @@ std::vector<std::string> server_model_output_modalities(common_decision_type dec
case COMMON_DECISION_TYPE_MINICPM_OCR_JEV:
case COMMON_DECISION_TYPE_LFM3_D1:
case COMMON_DECISION_TYPE_LFM3_D1_OMNI:
+ case COMMON_DECISION_TYPE_CLEF_OMNI:
out = {"decisions"};
break;
case COMMON_DECISION_TYPE_GRANITE_SWITCH:
diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp
index 32eeec361..0db4d53c0 100644
--- a/tools/server/server-decision.cpp
+++ b/tools/server/server-decision.cpp
@@ -153,7 +153,7 @@ void server_decision_context::init(const llama_model * model) {
throw std::runtime_error("decision model has no valid max_head_tokens");
}
n_options_max = 255;
- } else if (model_type == COMMON_DECISION_TYPE_CLEF) {
+ } else if (model_type == COMMON_DECISION_TYPE_CLEF || model_type == COMMON_DECISION_TYPE_CLEF_OMNI) {
n_options_max = 255;
noul_true_first = true;
choice_sorted = true;
@@ -410,6 +410,40 @@ static void decision_load_audio(const json & data, std::vector<raw_buffer> & fil
handle_media(files, data.get<std::string>(), "");
}
+// the joint head reads media grouped by kind, as the model was trained: images, then audio, then video
+std::vector<raw_buffer> decision_order_media(const std::vector<raw_buffer> & files, const mtmd_helper_init_opt & init_opt, bool allow_video) {
+ auto rank_of = [&](const raw_buffer & file) -> int {
+ mtmd_helper_media_meta meta;
+ if (mtmd_helper_get_media_meta(file.data(), file.size(), init_opt, &meta) == 0) {
+ switch (meta.type) {
+ case MTMD_HELPER_MEDIA_TYPE_IMAGE: return 0;
+ case MTMD_HELPER_MEDIA_TYPE_AUDIO: return 1;
+ case MTMD_HELPER_MEDIA_TYPE_VIDEO:
+ if (!allow_video) {
+ throw std::invalid_argument("video input is not supported by this model");
+ }
+ return 2;
+ default: break;
+ }
+ }
+ return 3; // mtmd reports the error when the prompt is tokenized
+ };
+
+ std::vector<std::pair<int, const raw_buffer *>> ranked;
+ ranked.reserve(files.size());
+ for (const auto & file : files) {
+ ranked.emplace_back(rank_of(file), &file);
+ }
+ std::stable_sort(ranked.begin(), ranked.end(), [](const auto & a, const auto & b) { return a.first < b.first; });
+
+ std::vector<raw_buffer> out;
+ out.reserve(files.size());
+ for (const auto & entry : ranked) {
+ out.push_back(*entry.second);
+ }
+ return out;
+}
+
json server_decision_context::parse_state(const json & body, std::vector<raw_buffer> & files) const {
if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && !body.at("state").is_string()) {
throw std::invalid_argument("\"state\" must be the OCR text");
@@ -417,8 +451,8 @@ json server_decision_context::parse_state(const json & body, std::vector<raw_buf
if (body.contains("videos") && !body.at("videos").is_null() && !body.at("videos").empty()) {
throw std::invalid_argument("\"videos\" is not supported");
}
- // "images" is an alias of "files"
- for (const char * key : {"files", "images"}) {
+ // "images" and "audio" are aliases of "files"
+ for (const char * key : {"files", "images", "audio"}) {
if (!body.contains(key) || body.at(key).is_null()) {
continue;
}
@@ -1553,11 +1587,15 @@ void server_decision_context::fill_task_joint(
};
inp = decision_replace_text(decision_sort_keys(inp), CLEF_MARKER, "<<clef ");
- // the template puts one media marker per image
+ // the model reads media grouped by kind: images, then audio, then video
+ // clef-omni: mtmd lays out a video as Qwen3-VL does, the model was trained with the layout of the Qwen3-Omni processor
+ const std::vector<raw_buffer> media = decision_order_media(files, init_opt, type != COMMON_DECISION_TYPE_CLEF_OMNI);
+
+ // the template puts one media marker per file
json images = json::array();
- if (!files.empty()) {
+ if (!media.empty()) {
inp = decision_replace_text(inp, get_media_marker(), " ");
- for (size_t i = 0; i < files.size(); i++) {
+ for (size_t i = 0; i < media.size(); i++) {
images.push_back(get_media_marker());
}
}
@@ -1579,7 +1617,7 @@ void server_decision_context::fill_task_joint(
size_t i_piece = 0;
task.tokens = server_tokens(llama_tokens(), false);
- if (!files.empty()) {
+ if (!media.empty()) {
// the text before the images is tokenized with them, a vision token separates the pieces anyway
std::string head;
while (i_piece < pieces.size() && head.find(get_media_marker()) == std::string::npos) {
@@ -1588,7 +1626,7 @@ void server_decision_context::fill_task_joint(
if (head.find(get_media_marker()) == std::string::npos || head.find(CLEF_MARKER) != std::string::npos) {
throw invalid;
}
- task.tokens = process_mtmd_prompt(mctx, head, files, init_opt);
+ task.tokens = process_mtmd_prompt(mctx, head, media, init_opt);
task.decision.order.resize(task.tokens.size(), LLAMA_DECISION_ORDER_NONE);
}
diff --git a/tools/server/server-decision.h b/tools/server/server-decision.h
index 175aa46eb..a02c7b9ee 100644
--- a/tools/server/server-decision.h
+++ b/tools/server/server-decision.h
@@ -56,7 +56,7 @@ struct server_decision_context {
// true if all the questions of a request go in one prompt, see fill_task_joint()
bool is_joint() const {
- return type == COMMON_DECISION_TYPE_CLEF;
+ return type == COMMON_DECISION_TYPE_CLEF || type == COMMON_DECISION_TYPE_CLEF_OMNI;
}
bool is_lfm3_d1() const {
@@ -76,6 +76,7 @@ struct server_decision_context {
case COMMON_DECISION_TYPE_MINICPM_OCR_JEV:
case COMMON_DECISION_TYPE_LFM3_D1:
case COMMON_DECISION_TYPE_LFM3_D1_OMNI:
+ case COMMON_DECISION_TYPE_CLEF_OMNI:
return true;
default:
return false;
@@ -96,7 +97,7 @@ struct server_decision_context {
json prepare_state(const json & state) const;
// returns the state without its images, they are appended to files in order
- // images come from "files" (alias "images") and from the image_url and input_audio parts of a state made of chat messages
+ // images come from "files" (aliases "images" and "audio") and from the image_url and input_audio parts of a state made of chat messages
// an image can be an audio clip if the model supports it
json parse_state(const json & body, std::vector<raw_buffer> & files) const;
@@ -207,5 +208,9 @@ private:
// note: the order of the tasks is preserved
std::vector<server_task> server_decision_group_tasks(std::vector<server_task> && tasks, size_t n_slots);
+// order the media as the joint head reads them: images, then audio, then video
+// throw std::invalid_argument on a video if allow_video is false
+std::vector<raw_buffer> decision_order_media(const std::vector<raw_buffer> & files, const mtmd_helper_init_opt & init_opt, bool allow_video = true);
+
// write "<|name|>" with U+00A6 in place of "|", so text from the request is not parsed as special tokens
std::string server_decision_escape_special_tokens(const std::string & text);