From 00887823aa1f20bbfc04aa6cd39e6b5517e5911c Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Mon, 16 Nov 2026 23:09:16 +0530 Subject: [PATCH 1/7] feat: add system_one decision model support to Llama and server --- llama_cpp/llama.py | 191 ++++++++++++++++++++++++++++++++++++++ llama_cpp/llama_types.py | 63 +++++++++++++ llama_cpp/server/app.py | 18 ++++ llama_cpp/server/types.py | 37 ++++++++ tests/test_system_one.py | 72 ++++++++++++++ 5 files changed, 381 insertions(+) create mode 100644 tests/test_system_one.py diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 14e2f8500f..50757de666 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2140,6 +2140,197 @@ def create_chat_completion_openai_v1( "You can install it with `pip install openai`." ) + def create_system_one( + self, + state: Union[str, Dict[str, Any], List[Any]], + questions: Dict[str, SystemOneQuestion], + temperature: float = 1.0, + model: Optional[str] = None, + ) -> SystemOneResponse: + """Evaluate a state and questions using a decision model in a single forward pass. + + Args: + state: The input context or state (text string or JSON object/list). + questions: Dictionary mapping question names to typed question specs. + temperature: Softmax temperature for normalizing probabilities. + model: Optional model name for the response payload. + + Returns: + A SystemOneResponse containing calibrated probabilities and choices. + """ + model_name: str = model if model is not None else self.model_path + + # 1. Reset context state + self.reset() + + # 2. Format the prompt + systemone_template = None + try: + tmpl_bytes = llama_cpp.llama_model_chat_template( + self._model.model, b"systemone" + ) + if tmpl_bytes: + systemone_template = tmpl_bytes.decode("utf-8") + except Exception: + pass + + if ( + systemone_template is None + and "tokenizer.chat_template.systemone" in self.metadata + ): + systemone_template = self.metadata["tokenizer.chat_template.systemone"] + + formatted_prompt: str + if systemone_template: + import jinja2 + from jinja2.sandbox import ImmutableSandboxedEnvironment + + env = ImmutableSandboxedEnvironment( + loader=jinja2.BaseLoader(), + trim_blocks=True, + lstrip_blocks=True, + ) + template = env.from_string(systemone_template) + formatted_prompt = template.render(state=state, questions=questions) + else: + state_str = json.dumps(state) if not isinstance(state, str) else state + lines = [f"State:\n{state_str}\n\nQuestions:"] + for q_name, q_val in questions.items(): + q_type = q_val.get("type", "choice") + lines.append(f'- Question "{q_name}" (type: {q_type}):') + if "instructions" in q_val: + lines.append(f" Instructions: {q_val['instructions']}") + if "criteria" in q_val: + crit = q_val["criteria"] + lines.append(" Criteria:") + if isinstance(crit, dict): + for k, v in crit.items(): + lines.append(f" * {k}: {v}") + elif isinstance(crit, list): + for idx, v in enumerate(crit): + lines.append(f" {idx}: {v}") + formatted_prompt = "\n".join(lines) + + # 3. Tokenize prompt + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=True) + if len(tokens) >= self.n_ctx(): + raise ValueError( + f"Requested tokens ({len(tokens)}) exceed context window of {self.n_ctx()}" + ) + + # 4. Single forward pass evaluation + self.eval(tokens) + + # 5. Extract output logits from the final token position + logits = llama_cpp.llama_get_logits(self._ctx.ctx) + n_vocab = self.n_vocab() + logits_arr = np.ctypeslib.as_array(logits, shape=(n_vocab,)) + + temp = max(temperature, 1e-4) + answers: Dict[str, SystemOneAnswer] = {} + + for q_name, q_spec in questions.items(): + q_type = q_spec.get("type", "choice") + + if q_type == "choice": + criteria = q_spec.get("criteria", {}) + choice_keys = list(criteria.keys()) + choice_logits: List[float] = [] + + for k in choice_keys: + toks = self.tokenize(k.encode("utf-8"), add_bos=False) + if not toks: + toks = self.tokenize(f" {k}".encode("utf-8"), add_bos=False) + tok_id = toks[0] if toks else 0 + choice_logits.append(float(logits_arr[tok_id])) + + max_l = max(choice_logits) if choice_logits else 0.0 + exp_logits = [np.exp((l - max_l) / temp) for l in choice_logits] + sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 + probs = { + k: float(e / sum_exp) for k, e in zip(choice_keys, exp_logits) + } + + best_choice = max(probs.items(), key=lambda x: x[1])[0] if probs else "" + confidence = probs.get(best_choice, 0.0) + + answers[q_name] = { + "type": "choice", + "choice": best_choice, + "confidence": confidence, + "probabilities": probs, + } + + elif q_type == "score": + criteria_list = q_spec.get("criteria", []) + n_levels = len(criteria_list) + score_logits: List[float] = [] + + for idx in range(n_levels): + toks = self.tokenize(str(idx).encode("utf-8"), add_bos=False) + if not toks: + toks = self.tokenize(f" {idx}".encode("utf-8"), add_bos=False) + tok_id = toks[0] if toks else 0 + score_logits.append(float(logits_arr[tok_id])) + + max_l = max(score_logits) if score_logits else 0.0 + exp_logits = [np.exp((l - max_l) / temp) for l in score_logits] + sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 + probs_dict = { + str(i): float(e / sum_exp) for i, e in enumerate(exp_logits) + } + + weighted_score = sum( + i * probs_dict[str(i)] for i in range(n_levels) + ) + max_conf = max(probs_dict.values()) if probs_dict else 0.0 + legend = {str(i): crit for i, crit in enumerate(criteria_list)} + + answers[q_name] = { + "type": "score", + "score": round(weighted_score, 4), + "confidence": round(max_conf, 4), + "legend": legend, + "probabilities": probs_dict, + } + + elif q_type == "noul": + true_toks = self.tokenize(b"true", add_bos=False) + false_toks = self.tokenize(b"false", add_bos=False) + if not true_toks: + true_toks = self.tokenize(b" true", add_bos=False) + if not false_toks: + false_toks = self.tokenize(b" false", add_bos=False) + + t_id = true_toks[0] if true_toks else 0 + f_id = false_toks[0] if false_toks else 1 + + l_true = float(logits_arr[t_id]) + l_false = float(logits_arr[f_id]) + + max_l = max(l_true, l_false) + e_true = np.exp((l_true - max_l) / temp) + e_false = np.exp((l_false - max_l) / temp) + p_true = float(e_true / (e_true + e_false)) + + answers[q_name] = { + "type": "noul", + "noul": round(p_true, 4), + } + + return { + "model": model_name, + "answers": answers, + "usage": { + "input_tokens": len(tokens), + "output_tokens": 0, + }, + } + + # Alias to match HuggingFace Transformers model.system_one(state, questions) convention + system_one = create_system_one + + def __getstate__(self): return dict( model_path=self.model_path, diff --git a/llama_cpp/llama_types.py b/llama_cpp/llama_types.py index f647822ff5..c736197e88 100644 --- a/llama_cpp/llama_types.py +++ b/llama_cpp/llama_types.py @@ -314,3 +314,66 @@ class ChatCompletionNamedToolChoice(TypedDict): ChatCompletionStreamResponse = CreateChatCompletionStreamResponse ChatCompletionResponseFunction = ChatCompletionFunction ChatCompletionFunctionCall = ChatCompletionResponseFunctionCall + + +# System One / Decision Model types + + +class SystemOneChoiceQuestion(TypedDict): + type: Literal["choice"] + instructions: str + criteria: Dict[str, str] + + +class SystemOneScoreQuestion(TypedDict): + type: Literal["score"] + instructions: str + criteria: List[str] + + +class SystemOneNoulQuestion(TypedDict): + type: Literal["noul"] + instructions: str + criteria: NotRequired[Dict[str, str]] + + +SystemOneQuestion = Union[ + SystemOneChoiceQuestion, SystemOneScoreQuestion, SystemOneNoulQuestion +] + + +class SystemOneChoiceAnswer(TypedDict): + type: Literal["choice"] + choice: str + confidence: float + probabilities: Dict[str, float] + + +class SystemOneScoreAnswer(TypedDict): + type: Literal["score"] + score: float + confidence: float + probabilities: Dict[str, float] + legend: NotRequired[Dict[str, str]] + + +class SystemOneNoulAnswer(TypedDict): + type: Literal["noul"] + noul: float + + +SystemOneAnswer = Union[ + SystemOneChoiceAnswer, SystemOneScoreAnswer, SystemOneNoulAnswer +] + + +class SystemOneUsage(TypedDict): + input_tokens: int + output_tokens: int + + +class SystemOneResponse(TypedDict): + model: str + answers: Dict[str, SystemOneAnswer] + usage: SystemOneUsage + diff --git a/llama_cpp/server/app.py b/llama_cpp/server/app.py index f776fe159c..ce8722837d 100644 --- a/llama_cpp/server/app.py +++ b/llama_cpp/server/app.py @@ -41,6 +41,7 @@ TokenizeInputCountResponse, DetokenizeInputRequest, DetokenizeInputResponse, + SystemOneRequest, ) from llama_cpp.server.errors import RouteErrorHandler @@ -373,6 +374,23 @@ async def create_embedding( ) +@router.post( + "/v1/systemone", + summary="System One Decision Evaluation", + dependencies=[Depends(authenticate)], + response_model=llama_cpp.SystemOneResponse, +) +async def create_system_one( + request: SystemOneRequest, + llama_proxy: LlamaProxy = Depends(get_llama_proxy), +): + return await run_in_threadpool( + llama_proxy(request.model).create_system_one, + **request.model_dump(), + ) + + + @router.post( "/v1/chat/completions", summary="Chat", diff --git a/llama_cpp/server/types.py b/llama_cpp/server/types.py index eda2b92801..61220b68f2 100644 --- a/llama_cpp/server/types.py +++ b/llama_cpp/server/types.py @@ -314,3 +314,40 @@ class DetokenizeInputResponse(BaseModel): model_config = { "json_schema_extra": {"example": {"text": "How many tokens in this query?"}} } + + +class SystemOneRequest(BaseModel): + model: Optional[str] = model_field + state: Union[str, Dict[str, Any], List[Any]] = Field( + description="The context or input state to evaluate." + ) + questions: Dict[str, Dict[str, Any]] = Field( + description="Dictionary mapping question keys to typed questions." + ) + temperature: Optional[float] = Field( + default=1.0, + description="Softmax temperature for scaling decision logits.", + ) + + model_config = { + "json_schema_extra": { + "example": { + "state": "The user reported an error on the checkout page.", + "questions": { + "is_bug": { + "type": "noul", + "instructions": "Is the user reporting a bug?", + }, + "team": { + "type": "choice", + "instructions": "Which department should handle this?", + "criteria": { + "billing": "Payment and checkout issues", + "support": "General questions", + }, + }, + }, + } + } + } + diff --git a/tests/test_system_one.py b/tests/test_system_one.py new file mode 100644 index 0000000000..5d338213e6 --- /dev/null +++ b/tests/test_system_one.py @@ -0,0 +1,72 @@ +import json +from typing import Dict +from llama_cpp.llama_types import ( + SystemOneQuestion, + SystemOneResponse, +) + + +def test_system_one_types(): + questions: Dict[str, SystemOneQuestion] = { + "intent": { + "type": "choice", + "instructions": "Identify the primary topic.", + "criteria": { + "shipping": "Lost, delayed, or missing packages", + "refund": "Requesting money back", + }, + }, + "is_urgent": { + "type": "noul", + "instructions": "Is this urgent?", + }, + "severity": { + "type": "score", + "instructions": "Rate severity 0 to 2.", + "criteria": ["Low", "Medium", "High"], + }, + } + + payload = json.dumps({"state": "My order is delayed", "questions": questions}) + loaded = json.loads(payload) + assert loaded["questions"]["intent"]["type"] == "choice" + assert loaded["questions"]["is_urgent"]["type"] == "noul" + assert loaded["questions"]["severity"]["type"] == "score" + + +def test_system_one_response_structure(): + response: SystemOneResponse = { + "model": "d1-Omni-2B-GGUF", + "answers": { + "intent": { + "type": "choice", + "choice": "shipping", + "confidence": 0.94, + "probabilities": {"shipping": 0.94, "refund": 0.06}, + }, + "is_urgent": { + "type": "noul", + "noul": 0.82, + }, + "severity": { + "type": "score", + "score": 1.2, + "confidence": 0.7, + "legend": {"0": "Low", "1": "Medium", "2": "High"}, + "probabilities": {"0": 0.1, "1": 0.6, "2": 0.3}, + }, + }, + "usage": { + "input_tokens": 85, + "output_tokens": 0, + }, + } + assert response["answers"]["intent"]["choice"] == "shipping" + assert response["answers"]["is_urgent"]["noul"] == 0.82 + assert response["usage"]["output_tokens"] == 0 + + +if __name__ == "__main__": + test_system_one_types() + test_system_one_response_structure() + print("All System One unit tests passed successfully!") From 4878fc3ba22b2ffb9b76bfcceb13084f20a8c21b Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Tue, 17 Nov 2026 22:51:06 +0530 Subject: [PATCH 2/7] fix: align system_one evaluation with model template and calibrated temperature --- llama_cpp/llama.py | 212 ++++++++++++++++++++++++++------------------- 1 file changed, 123 insertions(+), 89 deletions(-) diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 50757de666..b0e7f45190 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2144,7 +2144,7 @@ def create_system_one( self, state: Union[str, Dict[str, Any], List[Any]], questions: Dict[str, SystemOneQuestion], - temperature: float = 1.0, + temperature: Optional[float] = None, model: Optional[str] = None, ) -> SystemOneResponse: """Evaluate a state and questions using a decision model in a single forward pass. @@ -2152,7 +2152,8 @@ def create_system_one( Args: state: The input context or state (text string or JSON object/list). questions: Dictionary mapping question names to typed question specs. - temperature: Softmax temperature for normalizing probabilities. + temperature: Softmax temperature for normalizing probabilities. If None, + uses calibrated temperature from model metadata if available. model: Optional model name for the response payload. Returns: @@ -2160,10 +2161,7 @@ def create_system_one( """ model_name: str = model if model is not None else self.model_path - # 1. Reset context state - self.reset() - - # 2. Format the prompt + # 1. Look for a "systemone" chat template in model metadata systemone_template = None try: tmpl_bytes = llama_cpp.llama_model_chat_template( @@ -2180,76 +2178,83 @@ def create_system_one( ): systemone_template = self.metadata["tokenizer.chat_template.systemone"] - formatted_prompt: str + jinja_template = None if systemone_template: import jinja2 from jinja2.sandbox import ImmutableSandboxedEnvironment + def _tojson(val: Any, indent: Optional[int] = None) -> str: + return json.dumps(val, indent=indent) + env = ImmutableSandboxedEnvironment( loader=jinja2.BaseLoader(), trim_blocks=True, lstrip_blocks=True, ) - template = env.from_string(systemone_template) - formatted_prompt = template.render(state=state, questions=questions) - else: - state_str = json.dumps(state) if not isinstance(state, str) else state - lines = [f"State:\n{state_str}\n\nQuestions:"] - for q_name, q_val in questions.items(): - q_type = q_val.get("type", "choice") - lines.append(f'- Question "{q_name}" (type: {q_type}):') - if "instructions" in q_val: - lines.append(f" Instructions: {q_val['instructions']}") - if "criteria" in q_val: - crit = q_val["criteria"] - lines.append(" Criteria:") - if isinstance(crit, dict): - for k, v in crit.items(): - lines.append(f" * {k}: {v}") - elif isinstance(crit, list): - for idx, v in enumerate(crit): - lines.append(f" {idx}: {v}") - formatted_prompt = "\n".join(lines) - - # 3. Tokenize prompt - tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=True) - if len(tokens) >= self.n_ctx(): - raise ValueError( - f"Requested tokens ({len(tokens)}) exceed context window of {self.n_ctx()}" - ) - - # 4. Single forward pass evaluation - self.eval(tokens) + env.filters["tojson"] = _tojson + jinja_template = env.from_string(systemone_template) - # 5. Extract output logits from the final token position - logits = llama_cpp.llama_get_logits(self._ctx.ctx) - n_vocab = self.n_vocab() - logits_arr = np.ctypeslib.as_array(logits, shape=(n_vocab,)) - - temp = max(temperature, 1e-4) + total_input_tokens = 0 answers: Dict[str, SystemOneAnswer] = {} + def _get_candidate_logit(logits_arr: np.ndarray, text: str) -> float: + cand_logits = [] + bare_toks = self.tokenize(text.encode("utf-8"), add_bos=False) + if bare_toks: + cand_logits.append(float(logits_arr[bare_toks[0]])) + space_toks = self.tokenize(f" {text}".encode("utf-8"), add_bos=False) + if space_toks: + cand_logits.append(float(logits_arr[space_toks[0]])) + return max(cand_logits) if cand_logits else float("-inf") + for q_name, q_spec in questions.items(): q_type = q_spec.get("type", "choice") + # Determine temperature + if temperature is not None: + temp = max(temperature, 1e-4) + else: + meta_temp = self.metadata.get(f"lfm3.decision.temperature.{q_type}") or self.metadata.get(f"decision.temperature.{q_type}") + temp = float(meta_temp) if meta_temp is not None else 1.0 + temp = max(temp, 1e-4) + if q_type == "choice": criteria = q_spec.get("criteria", {}) choice_keys = list(criteria.keys()) - choice_logits: List[float] = [] - - for k in choice_keys: - toks = self.tokenize(k.encode("utf-8"), add_bos=False) - if not toks: - toks = self.tokenize(f" {k}".encode("utf-8"), add_bos=False) - tok_id = toks[0] if toks else 0 - choice_logits.append(float(logits_arr[tok_id])) - - max_l = max(choice_logits) if choice_logits else 0.0 - exp_logits = [np.exp((l - max_l) / temp) for l in choice_logits] + options = [] + for idx, k in enumerate(choice_keys): + label = chr(65 + idx) if idx < 26 else str(idx) + desc = criteria[k] + options.append({"label": label, "key": k, "description": desc}) + + if jinja_template is not None: + formatted_prompt = jinja_template.render( + images=[], + state=state, + instructions=q_spec.get("instructions", ""), + type="choice", + options=options, + ) + else: + lines = [f"State:\n{state}\n\nQuestion:\n{q_spec.get('instructions', '')}\n\nOptions:"] + for o in options: + lines.append(f"{o['label']} {o['description']}") + lines.append("\nReply with the option code only.") + formatted_prompt = "\n".join(lines) + + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) + total_input_tokens += len(tokens) + self.reset() + self.eval(tokens) + + logits = llama_cpp.llama_get_logits(self._ctx.ctx) + logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) + + label_logits = [_get_candidate_logit(logits_arr, o["label"]) for o in options] + max_l = max(label_logits) if label_logits else 0.0 + exp_logits = [np.exp((l - max_l) / temp) for l in label_logits] sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 - probs = { - k: float(e / sum_exp) for k, e in zip(choice_keys, exp_logits) - } + probs = {o["key"]: float(e / sum_exp) for o, e in zip(options, exp_logits)} best_choice = max(probs.items(), key=lambda x: x[1])[0] if probs else "" confidence = probs.get(best_choice, 0.0) @@ -2257,32 +2262,45 @@ def create_system_one( answers[q_name] = { "type": "choice", "choice": best_choice, - "confidence": confidence, - "probabilities": probs, + "confidence": round(confidence, 4), + "probabilities": {k: round(v, 4) for k, v in probs.items()}, } elif q_type == "score": criteria_list = q_spec.get("criteria", []) n_levels = len(criteria_list) - score_logits: List[float] = [] + options = [{"key": str(i), "description": desc} for i, desc in enumerate(criteria_list)] + + if jinja_template is not None: + formatted_prompt = jinja_template.render( + images=[], + state=state, + instructions=q_spec.get("instructions", ""), + type="score", + options=options, + ) + else: + lines = [f"State:\n{state}\n\nQuestion:\n{q_spec.get('instructions', '')}\n\n"] + for o in options: + lines.append(f"{o['key']} {o['description']}") + lines.append(f"\nReply with a single digit 0-{n_levels - 1} only.") + formatted_prompt = "\n".join(lines) - for idx in range(n_levels): - toks = self.tokenize(str(idx).encode("utf-8"), add_bos=False) - if not toks: - toks = self.tokenize(f" {idx}".encode("utf-8"), add_bos=False) - tok_id = toks[0] if toks else 0 - score_logits.append(float(logits_arr[tok_id])) + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) + total_input_tokens += len(tokens) + self.reset() + self.eval(tokens) + logits = llama_cpp.llama_get_logits(self._ctx.ctx) + logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) + + score_logits = [_get_candidate_logit(logits_arr, str(i)) for i in range(n_levels)] max_l = max(score_logits) if score_logits else 0.0 exp_logits = [np.exp((l - max_l) / temp) for l in score_logits] sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 - probs_dict = { - str(i): float(e / sum_exp) for i, e in enumerate(exp_logits) - } + probs_dict = {str(i): float(e / sum_exp) for i, e in enumerate(exp_logits)} - weighted_score = sum( - i * probs_dict[str(i)] for i in range(n_levels) - ) + weighted_score = sum(i * probs_dict[str(i)] for i in range(n_levels)) max_conf = max(probs_dict.values()) if probs_dict else 0.0 legend = {str(i): crit for i, crit in enumerate(criteria_list)} @@ -2291,38 +2309,54 @@ def create_system_one( "score": round(weighted_score, 4), "confidence": round(max_conf, 4), "legend": legend, - "probabilities": probs_dict, + "probabilities": {k: round(v, 4) for k, v in probs_dict.items()}, } elif q_type == "noul": - true_toks = self.tokenize(b"true", add_bos=False) - false_toks = self.tokenize(b"false", add_bos=False) - if not true_toks: - true_toks = self.tokenize(b" true", add_bos=False) - if not false_toks: - false_toks = self.tokenize(b" false", add_bos=False) + criteria = q_spec.get("criteria", {}) + options = [ + {"key": "true", "description": criteria.get("true", None)}, + {"key": "false", "description": criteria.get("false", None)}, + ] + + if jinja_template is not None: + formatted_prompt = jinja_template.render( + images=[], + state=state, + instructions=q_spec.get("instructions", ""), + type="noul", + options=options, + ) + else: + lines = [f"State:\n{state}\n\nQuestion:\n{q_spec.get('instructions', '')}\n\nReply with yes or no only."] + formatted_prompt = "\n".join(lines) + + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) + total_input_tokens += len(tokens) + self.reset() + self.eval(tokens) - t_id = true_toks[0] if true_toks else 0 - f_id = false_toks[0] if false_toks else 1 + logits = llama_cpp.llama_get_logits(self._ctx.ctx) + logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) - l_true = float(logits_arr[t_id]) - l_false = float(logits_arr[f_id]) + l_yes = max(_get_candidate_logit(logits_arr, "yes"), _get_candidate_logit(logits_arr, "Yes")) + l_no = max(_get_candidate_logit(logits_arr, "no"), _get_candidate_logit(logits_arr, "No")) - max_l = max(l_true, l_false) - e_true = np.exp((l_true - max_l) / temp) - e_false = np.exp((l_false - max_l) / temp) - p_true = float(e_true / (e_true + e_false)) + max_l = max(l_yes, l_no) + e_yes = np.exp((l_yes - max_l) / temp) + e_no = np.exp((l_no - max_l) / temp) + p_yes = float(e_yes / (e_yes + e_no)) answers[q_name] = { "type": "noul", - "noul": round(p_true, 4), + "noul": round(p_yes, 4), } return { "model": model_name, "answers": answers, "usage": { - "input_tokens": len(tokens), + "input_tokens": total_input_tokens, "output_tokens": 0, }, } From 08c598742aa75023f2d6a7b0f0ad68eeb5a2ef15 Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Tue, 17 Nov 2026 22:57:54 +0530 Subject: [PATCH 3/7] fix: support non-causal attention models without KV cache in system_one --- llama_cpp/_internals.py | 12 ++++++++---- llama_cpp/llama.py | 19 +++++++++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/llama_cpp/_internals.py b/llama_cpp/_internals.py index b45d34b2c4..5c4c0c3e6f 100644 --- a/llama_cpp/_internals.py +++ b/llama_cpp/_internals.py @@ -298,20 +298,24 @@ def kv_cache_clear(self): llama_cpp.llama_memory_clear(self.memory, True) def kv_cache_seq_rm(self, seq_id: int, p0: int, p1: int) -> bool: - assert self.memory is not None, "Memory is not initialized" + if self.memory is None: + return True seq_id = seq_id if seq_id >= 0 else 0 return llama_cpp.llama_memory_seq_rm(self.memory, seq_id, p0, p1) def kv_cache_seq_cp(self, seq_id_src: int, seq_id_dst: int, p0: int, p1: int): - assert self.memory is not None, "Memory is not initialized" + if self.memory is None: + return llama_cpp.llama_memory_seq_cp(self.memory, seq_id_src, seq_id_dst, p0, p1) def kv_cache_seq_keep(self, seq_id: int): - assert self.memory is not None, "Memory is not initialized" + if self.memory is None: + return llama_cpp.llama_memory_seq_keep(self.memory, seq_id) def kv_cache_seq_shift(self, seq_id: int, p0: int, p1: int, shift: int): - assert self.memory is not None, "Memory is not initialized" + if self.memory is None: + return llama_cpp.llama_memory_seq_add(self.memory, seq_id, p0, p1, shift) def get_state_size(self) -> int: diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index b0e7f45190..94a9dac6ee 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2207,6 +2207,16 @@ def _get_candidate_logit(logits_arr: np.ndarray, text: str) -> float: cand_logits.append(float(logits_arr[space_toks[0]])) return max(cand_logits) if cand_logits else float("-inf") + def _decode_prompt(tokens: Sequence[int]): + self._ctx.kv_cache_clear() + self._batch.reset() + self._batch.set_batch( + batch=tokens, + n_past=0, + logits_all=False, + ) + self._ctx.decode(self._batch) + for q_name, q_spec in questions.items(): q_type = q_spec.get("type", "choice") @@ -2244,8 +2254,7 @@ def _get_candidate_logit(logits_arr: np.ndarray, text: str) -> float: tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) total_input_tokens += len(tokens) - self.reset() - self.eval(tokens) + _decode_prompt(tokens) logits = llama_cpp.llama_get_logits(self._ctx.ctx) logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) @@ -2288,8 +2297,7 @@ def _get_candidate_logit(logits_arr: np.ndarray, text: str) -> float: tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) total_input_tokens += len(tokens) - self.reset() - self.eval(tokens) + _decode_prompt(tokens) logits = llama_cpp.llama_get_logits(self._ctx.ctx) logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) @@ -2333,8 +2341,7 @@ def _get_candidate_logit(logits_arr: np.ndarray, text: str) -> float: tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) total_input_tokens += len(tokens) - self.reset() - self.eval(tokens) + _decode_prompt(tokens) logits = llama_cpp.llama_get_logits(self._ctx.ctx) logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) From 22b41c8a62dba8c4f1bad64a3087cc70715da1de Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Tue, 17 Nov 2026 23:08:11 +0530 Subject: [PATCH 4/7] feat: add multiple choices support to choice questions in system_one --- llama_cpp/llama.py | 12 +++++++++++- llama_cpp/llama_types.py | 2 ++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 94a9dac6ee..9543e5e45c 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2268,12 +2268,22 @@ def _decode_prompt(tokens: Sequence[int]): best_choice = max(probs.items(), key=lambda x: x[1])[0] if probs else "" confidence = probs.get(best_choice, 0.0) - answers[q_name] = { + # For multi-choice, pick all options above threshold (>= 0.15) + is_multiple = bool(q_spec.get("multiple", False)) + selected_choices = [k for k, p in probs.items() if p >= 0.15] + if not selected_choices and best_choice: + selected_choices = [best_choice] + + ans_dict: SystemOneChoiceAnswer = { "type": "choice", "choice": best_choice, "confidence": round(confidence, 4), "probabilities": {k: round(v, 4) for k, v in probs.items()}, } + if is_multiple: + ans_dict["choices"] = selected_choices + + answers[q_name] = ans_dict elif q_type == "score": criteria_list = q_spec.get("criteria", []) diff --git a/llama_cpp/llama_types.py b/llama_cpp/llama_types.py index c736197e88..7f962f3b53 100644 --- a/llama_cpp/llama_types.py +++ b/llama_cpp/llama_types.py @@ -323,6 +323,7 @@ class SystemOneChoiceQuestion(TypedDict): type: Literal["choice"] instructions: str criteria: Dict[str, str] + multiple: NotRequired[bool] class SystemOneScoreQuestion(TypedDict): @@ -345,6 +346,7 @@ class SystemOneNoulQuestion(TypedDict): class SystemOneChoiceAnswer(TypedDict): type: Literal["choice"] choice: str + choices: NotRequired[List[str]] confidence: float probabilities: Dict[str, float] From ae1319d9b2c8d75ac6df23d0c0c89f0930eba96e Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Tue, 17 Nov 2026 23:14:13 +0530 Subject: [PATCH 5/7] feat: add direct label and level fields to score answers in system_one --- llama_cpp/llama.py | 5 +++++ llama_cpp/llama_types.py | 2 ++ 2 files changed, 7 insertions(+) diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 9543e5e45c..f4dfe1ba98 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2320,11 +2320,16 @@ def _decode_prompt(tokens: Sequence[int]): weighted_score = sum(i * probs_dict[str(i)] for i in range(n_levels)) max_conf = max(probs_dict.values()) if probs_dict else 0.0 + top_idx_str = max(probs_dict.items(), key=lambda x: x[1])[0] if probs_dict else "0" + top_idx = int(top_idx_str) + top_label = criteria_list[top_idx] if top_idx < len(criteria_list) else "" legend = {str(i): crit for i, crit in enumerate(criteria_list)} answers[q_name] = { "type": "score", "score": round(weighted_score, 4), + "level": top_idx, + "label": top_label, "confidence": round(max_conf, 4), "legend": legend, "probabilities": {k: round(v, 4) for k, v in probs_dict.items()}, diff --git a/llama_cpp/llama_types.py b/llama_cpp/llama_types.py index 7f962f3b53..2015ac58af 100644 --- a/llama_cpp/llama_types.py +++ b/llama_cpp/llama_types.py @@ -354,6 +354,8 @@ class SystemOneChoiceAnswer(TypedDict): class SystemOneScoreAnswer(TypedDict): type: Literal["score"] score: float + level: NotRequired[int] + label: NotRequired[str] confidence: float probabilities: Dict[str, float] legend: NotRequired[Dict[str, str]] From 3f172396a67f3a3a41273728207043db3a83cdce Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Wed, 18 Nov 2026 00:06:31 +0530 Subject: [PATCH 6/7] fix: align decision option labels and candidate token extraction with server-decision --- llama_cpp/llama.py | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index f4dfe1ba98..cf8c11ef84 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2197,6 +2197,22 @@ def _tojson(val: Any, indent: Optional[int] = None) -> str: total_input_tokens = 0 answers: Dict[str, SystemOneAnswer] = {} + def _get_candidate_logits(logits_arr: np.ndarray, candidates: List[str]) -> List[float]: + bare_list: List[float] = [] + space_list: List[float] = [] + for c in candidates: + b_tok = self.tokenize(c.encode("utf-8"), add_bos=False) + s_tok = self.tokenize(f" {c}".encode("utf-8"), add_bos=False) + bare_list.append(float(logits_arr[b_tok[0]]) if b_tok else float("-inf")) + space_list.append(float(logits_arr[s_tok[0]]) if s_tok else float("-inf")) + + # Use the token format (bare vs space-prefixed) that has higher overall probability mass + valid_bare = [x for x in bare_list if x != float("-inf")] + valid_space = [x for x in space_list if x != float("-inf")] + mean_bare = sum(valid_bare) / len(valid_bare) if valid_bare else float("-inf") + mean_space = sum(valid_space) / len(valid_space) if valid_space else float("-inf") + return space_list if mean_space > mean_bare else bare_list + def _get_candidate_logit(logits_arr: np.ndarray, text: str) -> float: cand_logits = [] bare_toks = self.tokenize(text.encode("utf-8"), add_bos=False) @@ -2259,7 +2275,7 @@ def _decode_prompt(tokens: Sequence[int]): logits = llama_cpp.llama_get_logits(self._ctx.ctx) logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) - label_logits = [_get_candidate_logit(logits_arr, o["label"]) for o in options] + label_logits = _get_candidate_logits(logits_arr, [o["label"] for o in options]) max_l = max(label_logits) if label_logits else 0.0 exp_logits = [np.exp((l - max_l) / temp) for l in label_logits] sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 @@ -2288,7 +2304,7 @@ def _decode_prompt(tokens: Sequence[int]): elif q_type == "score": criteria_list = q_spec.get("criteria", []) n_levels = len(criteria_list) - options = [{"key": str(i), "description": desc} for i, desc in enumerate(criteria_list)] + options = [{"label": str(i), "key": str(i), "description": desc} for i, desc in enumerate(criteria_list)] if jinja_template is not None: formatted_prompt = jinja_template.render( @@ -2312,7 +2328,7 @@ def _decode_prompt(tokens: Sequence[int]): logits = llama_cpp.llama_get_logits(self._ctx.ctx) logits_arr = np.ctypeslib.as_array(logits, shape=(self.n_vocab(),)) - score_logits = [_get_candidate_logit(logits_arr, str(i)) for i in range(n_levels)] + score_logits = _get_candidate_logits(logits_arr, [str(i) for i in range(n_levels)]) max_l = max(score_logits) if score_logits else 0.0 exp_logits = [np.exp((l - max_l) / temp) for l in score_logits] sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 @@ -2338,8 +2354,8 @@ def _decode_prompt(tokens: Sequence[int]): elif q_type == "noul": criteria = q_spec.get("criteria", {}) options = [ - {"key": "true", "description": criteria.get("true", None)}, - {"key": "false", "description": criteria.get("false", None)}, + {"label": "true", "key": "true", "description": criteria.get("true", None)}, + {"label": "false", "key": "false", "description": criteria.get("false", None)}, ] if jinja_template is not None: From 2be2a65db3a4e84c8ede7ac44b6fe1152d47b9c2 Mon Sep 17 00:00:00 2001 From: Kirti Pogra Date: Wed, 18 Nov 2026 00:36:45 +0530 Subject: [PATCH 7/7] fix: parse special control tokens in system_one and align score readout with median spec --- llama_cpp/llama.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index cf8c11ef84..a0022fbcb4 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2268,7 +2268,7 @@ def _decode_prompt(tokens: Sequence[int]): lines.append("\nReply with the option code only.") formatted_prompt = "\n".join(lines) - tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False, special=True) total_input_tokens += len(tokens) _decode_prompt(tokens) @@ -2321,7 +2321,7 @@ def _decode_prompt(tokens: Sequence[int]): lines.append(f"\nReply with a single digit 0-{n_levels - 1} only.") formatted_prompt = "\n".join(lines) - tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False, special=True) total_input_tokens += len(tokens) _decode_prompt(tokens) @@ -2334,17 +2334,26 @@ def _decode_prompt(tokens: Sequence[int]): sum_exp = sum(exp_logits) if sum(exp_logits) > 0 else 1.0 probs_dict = {str(i): float(e / sum_exp) for i, e in enumerate(exp_logits)} - weighted_score = sum(i * probs_dict[str(i)] for i in range(n_levels)) + # Calculate median score level matching Liquid AI / server-decision spec + total_prob = sum(probs_dict.values()) or 1.0 + mass = 0.0 + median_idx = n_levels - 1 + for i in range(n_levels): + mass += probs_dict[str(i)] / total_prob + if mass >= 0.5: + median_idx = i + break + max_conf = max(probs_dict.values()) if probs_dict else 0.0 top_idx_str = max(probs_dict.items(), key=lambda x: x[1])[0] if probs_dict else "0" top_idx = int(top_idx_str) - top_label = criteria_list[top_idx] if top_idx < len(criteria_list) else "" + top_label = criteria_list[median_idx] if median_idx < len(criteria_list) else "" legend = {str(i): crit for i, crit in enumerate(criteria_list)} answers[q_name] = { "type": "score", - "score": round(weighted_score, 4), - "level": top_idx, + "score": float(median_idx), + "level": median_idx, "label": top_label, "confidence": round(max_conf, 4), "legend": legend, @@ -2370,7 +2379,7 @@ def _decode_prompt(tokens: Sequence[int]): lines = [f"State:\n{state}\n\nQuestion:\n{q_spec.get('instructions', '')}\n\nReply with yes or no only."] formatted_prompt = "\n".join(lines) - tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False) + tokens = self.tokenize(formatted_prompt.encode("utf-8"), add_bos=False, special=True) total_input_tokens += len(tokens) _decode_prompt(tokens)