"""Prompt layout: per question one prefill and one branch per option. For a question with options o_1..o_n the model reads, as separately tokenized pieces, chat head + "State:\\n" | state | "\\n\\nInstruction: {instr}\\n\\nOptions:\\n- {o_1}\\n- ...\\n\\nGrade this option: " and, for each option k, a branch ``o_k + chat tail`` continuing it, read at its last token by the score head. The chat head and tail are the chat template's fragments around one user message (generation prompt on, thinking off). ``<|name|>`` in user text is rewritten to ``<¦name¦>`` so it can never become a control token. Attention is causal: a branch never changes the prefill it continues, so a state prefix is the same token list whichever question follows. """ from __future__ import annotations import json import re from typing import Any SENTINEL = "@@CONTENT@@" SPECIAL = re.compile(r"<\|([A-Za-z0-9_]+)\|>") MAX_OPTIONS = 255 QUESTION_TYPES = ("choice", "noul") def describe(value: Any) -> str: """Text of a state, instruction or description: strings verbatim, anything else as JSON.""" return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) def option_keys(spec: dict[str, Any]) -> list[str]: """The answer keys of a question, in prompt order.""" kind = spec.get("type") if kind == "choice": criteria = spec.get("criteria") if not (isinstance(criteria, dict) and criteria): raise ValueError("choice criteria must map option keys to descriptions") return list(criteria) if kind == "noul": criteria = spec.get("criteria") if criteria is not None and (not isinstance(criteria, dict) or set(criteria) - {"false", "true"}): raise ValueError("noul criteria may only describe 'false' and 'true'") return ["false", "true"] raise ValueError(f"question type {kind!r} is not supported (expected one of {list(QUESTION_TYPES)})") def option_texts(spec: dict[str, Any]) -> list[str]: kind, criteria = spec["type"], spec.get("criteria") if kind == "choice": return [k if v is None else k + ": " + describe(v) for k, v in criteria.items()] given = criteria or {} return [describe(given.get("false") or "No / false"), describe(given.get("true") or "Yes / true")] def _ids(tokenizer, text: str) -> list[int]: return tokenizer(text, add_special_tokens=False)["input_ids"] class PromptBuilder: def __init__(self, tokenizer): self.tokenizer = tokenizer text = tokenizer.apply_chat_template([{"role": "user", "content": SENTINEL}], tokenize=False, add_generation_prompt=True, enable_thinking=False) if text.count(SENTINEL) != 1: raise ValueError("the chat template does not render the user content exactly once") self.head, self.tail = text.split(SENTINEL) @staticmethod def _user(value: Any) -> str: return SPECIAL.sub(r"<¦\1¦>", describe(value)) def prefix_ids(self, state: Any) -> list[int]: """The question-independent start of every prefill of a request.""" return _ids(self.tokenizer, self.head + "State:\n") + _ids(self.tokenizer, self._user(state)) def question_ids(self, spec: dict[str, Any]) -> tuple[list[int], list[list[int]]]: """-> (the question's tokens that follow the prefix, one branch's ids per option).""" options = [self._user(o) for o in option_texts(spec)] instructions = self._user(spec.get("instructions") or "Choose the best matching option.") listing = "\n".join(f"- {o}" for o in options) prompt = f"\n\nInstruction: {instructions}\n\nOptions:\n{listing}\n\nGrade this option: " return _ids(self.tokenizer, prompt), [_ids(self.tokenizer, o + self.tail) for o in options]