ryanli-me's picture
Logits Sigma-1: staged (private)
f1448a6 verified
Raw History Blame Contribute Delete
13.1 kB
"""The one prompt template and the option codes, shared by preparation, training, evaluation and serving.
Two layouts. An adapter's decision_config.json names the one it was trained with ("layout"; missing = "v1"), and
decision.encode / evaluate / engine / engine_vllm render with it.
v1 (default; question first, each question of a request rendered alone):
<instruction>
Question: <question> # header: the state is read already knowing the question
State: <state>
Question: <question>
Options: A. … B. …
[Read the state and question again. # read-twice copy when the single read fits `twice_max_tokens`
State / Question / Options again]
→ model turn: "Answer:" and the next token is an option code (" A", " B", …, then two-letter codes),
each verified to be a single token in that position.
v5 (shared block: every question of the request listed before the state, as FlexDM / Sieve / Turion; docs/18):
<instruction v5>
Questions about this state: # every question of the request, request order, instructions text only
1. <question 1>
2. <question 2> …
State: <state>
[Read the questions and the state again. # read-twice copy when the block above, read once, is at most
Questions about this state: … State: …] # `twice_max_tokens` tokens (chat-template head included)
Question: <this question>
Options: A. … B. …
→ model turn: "Answer:".
Everything before "Question: <this question>" depends only on the request (its state and all its question texts),
so it is one token prefix shared by all of a request's prompts (vLLM prefix caching; docs/11 "shared block"). The
prefix (template head + block) and the suffix (this question + template tail + "Answer:") are tokenized separately
and concatenated at a blank line before "Question:", where neither backbone's tokenizer merges across; the content
has no leading or trailing whitespace, so the templates' trim is a no-op and the ids equal the tokenization of the
whole rendered chat template (tests/test_layout.py). A single-question request lists its one question, which keeps
v1's "question before the state".
Header cap. The list has a budget of HEADER_MAX_CHARS characters (~4k tokens) split evenly over the request's n
questions: each is shown up to max(HEADER_MAX_CHARS // n, HEADER_MIN_CHARS) characters ("…" marks a cut; continuation
lines of a multi-line question are indented under its number). Every suite request (≤ 64 questions) is listed in
full count: a 64-question ACOS request at up to 250 characters per question (ACOS questions are shorter), a
32-candidate ToolRet/BRIGHT request at up to 500 (each prompt still carries its own candidate in full after the
block), a single question up to 16,000. Past HEADER_MAX_CHARS // HEADER_MIN_CHARS = 80 questions only the first 80
are listed, followed by "(and N more questions)".
Evidence for the layouts: listing questions before the state (Aleria 1.0.1 → 1.1.1, +2.6 private same-skill; FlexDM's
ablation on stock Gemma, decider layout 55.39 → header 60.98) and reading twice (KnowLine Gen1 → Gen1.5, same
weights, +4.6 Full) on the Jev Decision Index.
"""
import json
import pathlib
import string
INSTRUCTION = "Decide the question about the state below. Reply with the letter of one option."
ANSWER_PREFIX = "Answer:"
MAX_OPTIONS = 255
TWICE_MAX_TOKENS = 3000 # KnowLine reads twice up to 3k tokens; longer requests are read once with the header
LAYOUTS = ("v1", "v5")
DEFAULT_LAYOUT = "v1"
INSTRUCTION_V5 = ("Read the questions and the state below, then decide the question at the end. "
"Reply with the letter of one option.")
HEADER_V5 = "Questions about this state:"
AGAIN_V5 = "Read the questions and the state again."
HEADER_MAX_CHARS = 16_000
HEADER_MIN_CHARS = 200
def option_codes(tokenizer, n_max=MAX_OPTIONS):
"""Codes in a fixed order and their token ids: A..Z, then two-letter codes that tokenize as one token
right after ANSWER_PREFIX. Raises if fewer than n_max exist or two codes share a token."""
base = tokenizer.encode(ANSWER_PREFIX, add_special_tokens=False)
letters = string.ascii_uppercase
codes, ids = [], []
for code in list(letters) + [a + b for a in letters for b in letters]:
enc = tokenizer.encode(ANSWER_PREFIX + " " + code, add_special_tokens=False)
if enc[: len(base)] == base and len(enc) == len(base) + 1:
codes.append(code)
ids.append(enc[-1])
if len(codes) == n_max:
break
if len(codes) < n_max:
raise ValueError(f"only {len(codes)} single-token option codes, need {n_max}")
if len(set(ids)) != len(ids):
raise ValueError("two option codes map to the same token")
return codes, ids
def check_layout(layout):
if layout not in LAYOUTS:
raise ValueError(f"unknown prompt layout {layout!r}: expected one of {LAYOUTS}")
return layout
def trained_layout(adapter=None, model=None):
"""The layout an adapter was trained with (its decision_config.json, written by decision.train) or, without an
adapter, the one a merged checkpoint's merge.json records; DEFAULT_LAYOUT when neither names one."""
if adapter:
path = pathlib.Path(adapter) / "decision_config.json"
config = json.loads(path.read_text()) if path.exists() else {}
else:
path = pathlib.Path(model) / "merge.json" if model else None
config = json.loads(path.read_text()).get("decision_config", {}) if path and path.exists() else {}
return check_layout(config.get("layout") or DEFAULT_LAYOUT)
# ---------------------------------------------------------------- v1
def _body(state, question, options, codes):
state = state if state and state.strip() else "(empty)"
lines = ["State:", state, "", f"Question: {question}", "Options:"]
lines += [f"{code}. {option}" for code, option in zip(codes, options)]
return "\n".join(lines)
def user_message(state, question, options, codes, twice=False):
body = _body(state, question, options, codes)
parts = [INSTRUCTION, "", f"Question: {question}", "", body]
if twice:
parts += ["", "Read the state and the question again.", "", body]
return "\n".join(parts)
def _ids(tokenizer, message):
text = tokenizer.apply_chat_template(
[{"role": "user", "content": message}], tokenize=False, add_generation_prompt=True, enable_thinking=False
)
return tokenizer.encode(text + ANSWER_PREFIX, add_special_tokens=False)
# ---------------------------------------------------------------- v5
def header_v5(questions):
"""The numbered list of the request's questions, within the HEADER_MAX_CHARS budget (module docstring)."""
n = max(len(questions), 1)
per = max(HEADER_MAX_CHARS // n, HEADER_MIN_CHARS)
shown = questions[: HEADER_MAX_CHARS // per]
lines = [HEADER_V5]
for i, question in enumerate(shown, 1):
text = question.strip()
if len(text) > per:
text = text[:per].rstrip() + "…"
first, *rest = text.split("\n")
lines.append(f"{i}. {first}")
lines += [f" {line}" if line.strip() else "" for line in rest]
if len(shown) < len(questions):
lines.append(f"(and {len(questions) - len(shown)} more questions)")
return "\n".join(lines)
def shared_message_v5(state, questions, twice=False):
"""The request's shared block (user-message text up to this question), ending in a blank line."""
state = state.strip() if state and state.strip() else "(empty)"
block = "\n".join([header_v5(questions), "", "State:", state])
parts = [INSTRUCTION_V5, "", block]
if twice:
parts += ["", AGAIN_V5, "", block]
return "\n".join(parts) + "\n\n"
def question_message_v5(question, options, codes):
"""This question's part of the user message (after the shared block); no trailing whitespace."""
lines = [f"Question: {question}", "Options:"] + [f"{code}. {option}" for code, option in zip(codes, options)]
return "\n".join(lines).rstrip()
def user_message_v5(state, questions, question, options, codes, twice=False):
return shared_message_v5(state, questions, twice) + question_message_v5(question, options, codes)
_TEMPLATE_PARTS = {}
_SENTINEL = "decision-prompt"
def template_parts(tokenizer):
"""(head, tail): the chat template's text before and after the user message (generation prompt, thinking off)."""
key = (type(tokenizer).__name__, tokenizer.chat_template, str(tokenizer.bos_token), str(tokenizer.eos_token))
if key not in _TEMPLATE_PARTS:
text = tokenizer.apply_chat_template([{"role": "user", "content": _SENTINEL}], tokenize=False,
add_generation_prompt=True, enable_thinking=False)
head, sep, tail = text.partition(_SENTINEL)
if not sep or _SENTINEL in tail:
raise ValueError("the chat template does not render the user message verbatim once")
_TEMPLATE_PARTS[key] = (head, tail)
return _TEMPLATE_PARTS[key]
def prefix_ids_v5(tokenizer, state, questions, twice_max_tokens=TWICE_MAX_TOKENS):
"""Token ids of the shared prefix of a request's v5 prompts (template head + block, read twice when the block
read once is at most `twice_max_tokens` tokens; 0 disables it). Depends only on the state and the questions."""
head, _ = template_parts(tokenizer)
ids = tokenizer.encode(head + shared_message_v5(state, questions), add_special_tokens=False)
if twice_max_tokens and len(ids) <= twice_max_tokens:
ids = tokenizer.encode(head + shared_message_v5(state, questions, twice=True), add_special_tokens=False)
return ids
def suffix_ids_v5(tokenizer, question, options, codes):
_, tail = template_parts(tokenizer)
return tokenizer.encode(question_message_v5(question, options, codes) + tail + ANSWER_PREFIX,
add_special_tokens=False)
# ---------------------------------------------------------------- both
def request_prefix(tokenizer, state, questions, layout=DEFAULT_LAYOUT, twice_max_tokens=TWICE_MAX_TOKENS):
"""The prefix shared by a request's prompts, to pass to prompt_ids(prefix=…): v5 only (None for v1)."""
return prefix_ids_v5(tokenizer, state, questions, twice_max_tokens) if check_layout(layout) == "v5" else None
def prompt_ids(tokenizer, state, question, options, codes, twice_max_tokens=TWICE_MAX_TOKENS, layout=DEFAULT_LAYOUT,
questions=None, prefix=None):
"""Token ids of the full prompt, ending where the next token is the option code.
v1: the read-twice copy is added when the single read is at most `twice_max_tokens` tokens (0 disables it);
`questions` and `prefix` are ignored. v5: `questions` are the texts of all the request's questions in request
order (default: this question alone); `prefix` is request_prefix(...) of the same state, questions and
twice_max_tokens, computed once per request (computed here when not given)."""
if check_layout(layout) == "v1":
once = _ids(tokenizer, user_message(state, question, options, codes))
if twice_max_tokens and len(once) <= twice_max_tokens:
return _ids(tokenizer, user_message(state, question, options, codes, twice=True))
return once
if prefix is None:
prefix = prefix_ids_v5(tokenizer, state, list(questions) if questions else [question], twice_max_tokens)
return list(prefix) + suffix_ids_v5(tokenizer, question, options, codes)
# ---------------------------------------------------------------- option orders (engines)
def option_orders(n, k):
"""Up to k distinct orders of n options (lists of original indices, position -> option): as given, reversed, then
rotations (by n // 2 first, then 1, 2, …), then reversed rotations. k <= 1 or n < 2: as given only."""
base = list(range(n))
orders = [base]
if k <= 1 or n < 2:
return orders
shifts = [n // 2] + [s for s in range(1, n) if s != n // 2]
candidates = [base[::-1]] + [base[s:] + base[:s] for s in shifts] + [(base[s:] + base[:s])[::-1] for s in shifts]
for order in candidates:
if len(orders) == k:
break
if order not in orders:
orders.append(order)
return orders
def average_orders(n_questions, items, probs):
"""Per question, the mean over its option orders of the probabilities mapped back to the original option order.
items[j] = (question index, order, …) and probs[j] the probabilities read in that order. A question read in one
order gets its probabilities unchanged."""
sums, counts = [None] * n_questions, [0] * n_questions
for (i, order, *_), p in zip(items, probs):
if counts[i] == 0:
sums[i] = [0.0] * len(order)
for position, option in enumerate(order):
sums[i][option] += p[position]
counts[i] += 1
return [s if c == 1 else [x / c for x in s] for s, c in zip(sums, counts)]