laya / code /tt_laya /text.py
changh95's picture
tt-model push laya (container)
f882f26 verified
Raw History Blame Contribute Delete
16 kB
# SPDX-License-Identifier: Apache-2.0
"""Questions and token sequences: the request half of laya's classic decision model, written for this port.
One model row per (state, question):
[CLS] "<type> question: <instructions>" [SEP] [MASK] opt_0 [MASK] opt_1 ... [SEP] <state> [SEP]
The question head (instructions + options) is budgeted by ``head_max_len`` (options capped at 48 tokens each; when
the options leave fewer than 16 tokens every option -- its [MASK] included -- is cut to ``max(4, (head_max_len - 16)
// n)`` tokens and the instructions get what is left, at least 8); the state fills the rest of ``max_len`` (its
start is kept, the end for a conversation list). The behaviour (validation messages included) follows the official
``laya`` 0.5.8 runtime so that answers are interchangeable; the code is this package's own.
"""
from __future__ import annotations
import json
import math
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
QTYPES = {"choice": 0, "score": 1, "noul": 2}
QTYPE_NAMES = {v: k for k, v in QTYPES.items()}
OPTION_TOKENS = 48 # tokens per rendered option (after its [MASK])
MIN_OPTION_BUDGET = 16 # below this many head tokens left for the instructions, options are cut evenly
MIN_OPTION_TOKENS = 4
MIN_INSTRUCTION_TOKENS = 8
NOUL_DEFAULT = ("no, the statement does not hold", "yes, the statement holds")
State = Union[str, dict, list]
class QuestionError(ValueError):
"""A malformed question or request (HTTP 422)."""
# ----------------------------------------------------------------------------- rendering
def serialize_state(state: State) -> str:
return state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
def render_criterion(value: Any) -> str:
if isinstance(value, str):
return value
return json.dumps(value, ensure_ascii=False, separators=(", ", ": "), default=str)
def noul_labels(labels: Optional[dict]) -> Tuple[str, str]:
if labels is None:
return "false", "true"
bad = QuestionError("noul labels must map exactly 'false' and 'true' to distinct non-empty strings")
if not isinstance(labels, dict) or set(labels) != {"false", "true"}:
raise bad
f, t = labels["false"], labels["true"]
if not isinstance(f, str) or not isinstance(t, str):
raise bad
f, t = f.strip(), t.strip()
if not f or not t or f == t:
raise bad
return f, t
@dataclass
class Question:
"""A validated, normalised question: ``t`` type, ``ins`` instruction text, ``crit`` criteria (choice: ordered
dict label -> description or None; score: list; noul: dict or None), ``labels`` (noul), ``order`` (slot -> option)."""
qid: str
t: str
ins: str
crit: Any
labels: Optional[dict] = None
order: Optional[List[int]] = None
@property
def qtype(self) -> int:
return QTYPES[self.t]
def options(self) -> List[str]:
"""Option texts in option order (noul: [false, true], so p[1] is P(true))."""
if self.t == "choice":
return [str(k) if v is None or v == "" else "%s: %s" % (k, render_criterion(v)) for k, v in self.crit.items()]
if self.t == "score":
return ["level %d: %s" % (i, render_criterion(c)) for i, c in enumerate(self.crit)]
crit = self.crit or {}
fl, tl = noul_labels(self.labels)
fc, tc = crit.get("false"), crit.get("true")
return [fl + ": " + (render_criterion(fc) if fc not in (None, "") else NOUL_DEFAULT[0]),
tl + ": " + (render_criterion(tc) if tc not in (None, "") else NOUL_DEFAULT[1])]
@property
def n_options(self) -> int:
return len(self.crit) if self.t in ("choice", "score") else 2
def answer_keys(self) -> List[Any]:
if self.t == "choice":
return list(self.crit.keys())
if self.t == "score":
return [str(i) for i in range(len(self.crit))]
return ["false", "true"]
def _option_count(qdef: dict) -> int:
t, crit = qdef.get("type"), qdef.get("criteria")
if t in ("choice", "score") and isinstance(crit, (list, dict)):
return len(crit)
return 2
def check_question(qid: Any, qdef: Any) -> None:
"""Refuse a question that cannot be answered, naming it and what to fix (the official rules)."""
if qid is None:
raise QuestionError("question id must not be None")
if not isinstance(qid, (str, int)) or (isinstance(qid, str) and not qid.strip()):
raise QuestionError("question id must be a non-empty string, got %r" % (qid,))
if not isinstance(qdef, dict):
raise QuestionError("question %r: definition must be a dict, got %s" % (qid, type(qdef).__name__))
t = qdef.get("type")
if not isinstance(t, str) or t not in QTYPES:
raise QuestionError("question %r: unknown type %r; use one of %s" % (qid, t, sorted(QTYPES)))
if "instructions" not in qdef:
raise QuestionError("question %r: no 'instructions'; add the text the model should answer" % (qid,))
ins = qdef["instructions"]
if ins is None:
raise QuestionError("question %r: 'instructions' must not be None; add the text the model should answer" % (qid,))
if (isinstance(ins, str) and not ins.strip()) or (isinstance(ins, (list, dict)) and not ins):
raise QuestionError("question %r: 'instructions' must not be empty; add the text the model should answer" % (qid,))
if not isinstance(ins, (str, dict, list, int, float)):
raise QuestionError("question %r: 'instructions' must be a string, dict, or list, got %s"
% (qid, type(ins).__name__))
crit = qdef.get("criteria")
if t == "choice":
if not isinstance(crit, (dict, list)):
raise QuestionError("question %r: a choice question takes 'criteria' as a dict of label -> description, "
"or a list of labels" % (qid,))
if not crit:
raise QuestionError("question %r: a choice question needs at least one criterion" % (qid,))
for i, label in enumerate(crit if isinstance(crit, list) else crit.keys()):
if label is None:
raise QuestionError("question %r: choice label %d is null; a label is rendered as option text and "
"used as the answer key, so it must be a string, number or bool" % (qid, i))
if not isinstance(label, (str, int, float, bool)):
raise QuestionError("question %r: choice label %d is a %s; a label is rendered as option text and "
"used as the answer key, so it must be a scalar (a string, number or bool), got %r"
% (qid, i, type(label).__name__, label))
if isinstance(crit, list):
seen: Dict[Any, int] = {}
for i, label in enumerate(crit):
if label in seen:
raise QuestionError("question %r: choice label %d (%r) repeats label %d; the labels are the "
"answer keys, so every option needs its own (1, 1.0 and True are one key)"
% (qid, i, label, seen[label]))
seen[label] = i
elif t == "score":
if not isinstance(crit, list):
raise QuestionError("question %r: a score question takes 'criteria' as a list of level descriptions, "
"index 0 first" % (qid,))
if not crit:
raise QuestionError("question %r: a score question needs at least one level" % (qid,))
if any(c is None for c in crit):
raise QuestionError("question %r: score level %d is null; give every level a description, index 0 first"
% (qid, [c is None for c in crit].index(True)))
elif crit is not None and not isinstance(crit, dict):
raise QuestionError("question %r: a noul question takes 'criteria' as a dict with optional 'true'/'false' "
"descriptions, or omits it" % (qid,))
elif isinstance(crit, dict):
keys = {str(k).lower() for k in crit}
if not keys <= {"true", "false"}:
raise QuestionError("question %r: a noul question takes 'criteria' keyed only 'true'/'false' (either or "
"both, and omitted is fine), got %s" % (qid, sorted(keys)))
if "option_order" in qdef:
order, n = qdef["option_order"], _option_count(qdef)
if (not isinstance(order, (list, tuple)) or len(order) != n
or sorted(i for i in order if isinstance(i, int) and not isinstance(i, bool)) != list(range(n))):
raise QuestionError("question %r: 'option_order' must be a permutation of range(%d) -- one slot per "
"option, each option once -- got %r" % (qid, n, order))
if "labels" in qdef:
if t != "noul":
raise QuestionError("question %r: 'labels' is only supported for noul questions" % (qid,))
try:
noul_labels(qdef["labels"])
except QuestionError as e:
raise QuestionError("question %r: %s" % (qid, e)) from e
def normalise_question(qid: Any, qdef: dict) -> Question:
check_question(qid, qdef)
t, crit = qdef["type"], qdef.get("criteria")
if t == "choice" and isinstance(crit, list):
crit = {c: None for c in crit}
elif t == "noul" and isinstance(crit, dict):
crit = {str(k).lower(): v for k, v in crit.items()}
ins = qdef["instructions"]
if not isinstance(ins, str):
ins = json.dumps(ins, ensure_ascii=False)
order = [int(i) for i in qdef["option_order"]] if "option_order" in qdef else None
return Question(qid=qid, t=t, ins=ins, crit=crit, labels=qdef.get("labels"), order=order)
def normalise_questions(questions: Any) -> List[Question]:
if not isinstance(questions, dict):
raise QuestionError("questions must be a dict of question id -> definition, got %s" % type(questions).__name__)
return [normalise_question(qid, q) for qid, q in questions.items()]
# ----------------------------------------------------------------------------- tokenizer
class Tokenizer:
"""The checkpoint's ``tokenizer.json`` through the ``tokenizers`` library (no special tokens added)."""
def __init__(self, tok_dir: str):
import os
from tokenizers import Tokenizer as _T
with open(os.path.join(tok_dir, "tokenizer_config.json")) as f:
cfg = json.load(f)
self._tok = _T.from_file(os.path.join(tok_dir, "tokenizer.json"))
self._tok.no_truncation()
self._tok.no_padding()
self.mask_token = cfg["mask_token"]
ids = {}
for name in ("cls_token", "sep_token", "mask_token", "pad_token"):
tid = self._tok.token_to_id(cfg[name])
if tid is None:
raise ValueError("tokenizer: %s %r is not in the vocabulary" % (name, cfg[name]))
ids[name] = tid
self.cls_id, self.sep_id, self.mask_id, self.pad_id = (ids["cls_token"], ids["sep_token"], ids["mask_token"],
ids["pad_token"])
self._cache: Dict[str, List[int]] = {}
def encode(self, text: str) -> List[int]:
return self._tok.encode(text, add_special_tokens=False).ids
def encode_cached(self, text: str) -> List[int]:
"""Question / option texts repeat across requests: a small bounded cache."""
ids = self._cache.get(text)
if ids is None:
ids = self.encode(text)
if len(self._cache) > 65536:
self._cache.clear()
self._cache[text] = ids
return list(ids)
# ----------------------------------------------------------------------------- sequences
@dataclass
class Row:
"""One model row: token ids, [MASK] marker positions (slot order), question type and bookkeeping."""
ids: List[int]
markers: List[int]
qtype: int
n_options: int
options_distinct: int
tokens_per_option: Optional[int]
state_tokens: int
state_used: int
@property
def truncated(self) -> bool:
return self.state_used < self.state_tokens
def build_head(tok: Tokenizer, q: Question, head_max_len: int) -> Tuple[List[int], List[int], dict]:
mask = tok.mask_token
opts = q.options()
order = q.order if q.order is not None else list(range(len(opts)))
head = tok.encode_cached("%s question: %s" % (q.t, str(q.ins).replace(mask, " ")))
opt_ids = [[tok.mask_id] + tok.encode_cached(" " + opts[i].replace(mask, " "))[:OPTION_TOKENS] for i in order]
budget = head_max_len - sum(len(o) for o in opt_ids)
per = None
if budget < MIN_OPTION_BUDGET:
per = max(MIN_OPTION_TOKENS, (head_max_len - MIN_OPTION_BUDGET) // max(1, len(opt_ids)))
opt_ids = [o[:per] for o in opt_ids]
budget = head_max_len - sum(len(o) for o in opt_ids)
head = head[:max(MIN_INSTRUCTION_TOKENS, budget)]
ids = [tok.cls_id] + head + [tok.sep_id]
markers = []
for o in opt_ids:
markers.append(len(ids))
ids.extend(o)
ids.append(tok.sep_id)
stats = {"options": len(opt_ids), "options_distinct": len({tuple(o) for o in opt_ids}), "tokens_per_option": per}
return ids, markers, stats
def build_rows(tok: Tokenizer, state: State, questions: Sequence[Question], max_len: int,
head_max_len: int) -> List[Row]:
"""One row per question for one state (the state is tokenized once)."""
if state is None:
raise QuestionError("state must not be None; pass a string, dict, or list")
left = isinstance(state, list)
st = tok.encode(serialize_state(state).replace(tok.mask_token, " "))
rows = []
for q in questions:
ids, markers, stats = build_head(tok, q, head_max_len)
room = max(0, max_len - len(ids) - 1)
used = st[max(0, len(st) - room):] if left else st[:room]
ids = (ids + used + [tok.sep_id])[:max_len]
markers = [m for m in markers if m < max_len]
if len(markers) != stats["options"]:
raise QuestionError(
"question %r: only %d of its %d option markers fit in max_len=%d with head_max_len=%d spent on the "
"question; lower head_max_len, raise max_len, or use fewer options"
% (q.qid, len(markers), stats["options"], max_len, head_max_len))
rows.append(Row(ids=ids, markers=markers, qtype=q.qtype, n_options=stats["options"],
options_distinct=stats["options_distinct"], tokens_per_option=stats["tokens_per_option"],
state_tokens=len(st), state_used=len(used)))
return rows
HEAD_MAX_LEN_CAP = 8192 # the official laya-serve's per-request budget ceiling (LAYA_MAX_TOKEN_BUDGET default)
def check_lengths(max_len: Any, head_max_len: Any, limit: int) -> Tuple[int, int]:
"""Per-request budgets, as the official runtime takes them: any positive integers (max_len up to this server's
LAYA_MAX_LEN). The head is built with its own budget and the row is then clamped to max_len, so a max_len below
head_max_len is fine as long as every option marker still fits (build_rows refuses the question otherwise, with
the official message)."""
for name, v in (("max_len", max_len), ("head_max_len", head_max_len)):
if isinstance(v, bool) or not isinstance(v, int):
raise QuestionError("%s must be an integer, got %r" % (name, v))
if v <= 0:
raise QuestionError("%s must be a positive integer" % name)
if max_len > limit:
raise QuestionError("max_len=%d exceeds this server's LAYA_MAX_LEN (%d)" % (max_len, limit))
if head_max_len > HEAD_MAX_LEN_CAP:
raise QuestionError("head_max_len=%d exceeds the server limit (%d)" % (head_max_len, HEAD_MAX_LEN_CAP))
return max_len, head_max_len