Download src/discerna/model/codec.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 5.19 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/codec.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/model/codec.py
-
curl -L -o codec.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/codec.py
5.19 kB
| """Prompt codec: one question about one state -> token ids and the position of each option's marker. | |
| Adapted from LiquidAI/d1-omni-600M `prompt.py` (LFM Open License v1.0, see LICENSE). | |
| Modified: works on Discerna's contract types; returns each model slot's canonical option | |
| index explicitly (a noul is read in [false, true] order, canonical order is [yes, no]) | |
| instead of reversing probabilities inside the forward pass. | |
| Every question is rendered against the state as one sequence: | |
| <bos> <state> state <q> instructions <opt> <mask> option_0 </opt> ... <decide> | |
| The model scores the hidden state at every `<mask>`. Delimiters come from the | |
| tokenizer's reserved block, and `<|name|>` in caller text is rewritten to | |
| `<¦name¦>`, so a state can never forge a delimiter or a marker. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| from dataclasses import dataclass | |
| from typing import Any | |
| from discerna.contract import Question, criterion_text | |
| QTYPES = {"choice": 0, "score": 1, "noul": 2} | |
| DELIMITERS = {"state": "<|reserved_7|>", "q": "<|reserved_8|>", "opt": "<|reserved_9|>", | |
| "opt_end": "<|reserved_10|>", "decide": "<|reserved_11|>"} | |
| MARKER = "<|mask|>" | |
| IMAGE_NOUL = {"false": "no", "true": "yes"} # the wording yes/no questions about images were trained with | |
| _SPECIAL = re.compile(r"<\|([A-Za-z0-9_]+)\|>") | |
| class Encoded: | |
| ids: list[int] | |
| markers: list[int] # position of each model slot's marker in `ids` | |
| canonical: list[int] # canonical option index (discerna.contract.option_keys order) of each model slot | |
| qtype: int | |
| def escape(text: str) -> str: | |
| return _SPECIAL.sub(r"<¦\1¦>", text) | |
| def serialize(state: Any) -> str: | |
| return state if isinstance(state, str) else json.dumps(state, ensure_ascii=False) | |
| def instructions_text(value: Any) -> str: | |
| """Instructions as text: anything that is not text goes through `str()` (a dict becomes its Python | |
| repr), the form the model was trained on.""" | |
| return value if isinstance(value, str) else str(value) | |
| def render_options(q: Question, noul_default: dict | None = None) -> tuple[list[str], list[int]]: | |
| """Option texts in the model's slot order, and each slot's canonical option index.""" | |
| if q.type == "choice": | |
| texts = [k if v is None or v == "" else f"{k}: {criterion_text(v)}" for k, v in q.criteria.items()] | |
| return texts, list(range(len(texts))) | |
| if q.type == "score": | |
| return [f"level {i}: {criterion_text(c)}" for i, c in enumerate(q.criteria)], list(range(len(q.criteria))) | |
| crit = q.criteria or noul_default or {} | |
| false, true = crit.get("false", crit.get("no")), crit.get("true", crit.get("yes")) | |
| texts = ["false: " + (criterion_text(false) if false not in (None, "") else "no, the statement does not hold"), | |
| "true: " + (criterion_text(true) if true not in (None, "") else "yes, the statement holds")] | |
| return texts, [1, 0] # slots [false, true] are canonical [no, yes] -> indices 1, 0 | |
| class MarkerCodec: | |
| """The prompt layout. `media="image"` writes nouls as trained after an image prefix.""" | |
| def __init__(self, tokenizer, per_option: int = 24, delimiters: dict | None = None, marker: str = MARKER): | |
| self.tok, self.per_option = tokenizer, per_option | |
| names = {**DELIMITERS, **(delimiters or {})} | |
| self.delim = {k: self._id(v) for k, v in names.items()} | |
| self.marker = self._id(marker) | |
| if tokenizer.bos_token_id is None: | |
| raise ValueError("the tokenizer has no BOS token") | |
| def _id(self, token: str) -> int: | |
| i = self.tok.convert_tokens_to_ids(token) | |
| if i is None or i == self.tok.unk_token_id: | |
| raise ValueError(f"token {token!r} is not in the vocabulary") | |
| return i | |
| def _text(self, s: str) -> list[int]: | |
| return self.tok(escape(s), add_special_tokens=False)["input_ids"] | |
| def encode(self, state: Any, q: Question, max_len: int, media: str | None = None) -> Encoded: | |
| if media not in (None, "image"): | |
| raise NotImplementedError(f"media {media!r} is not supported yet") | |
| texts, canonical = render_options(q, IMAGE_NOUL if media == "image" else None) | |
| budget = max(96, min(len(texts) * self.per_option + 32, max_len // 2)) | |
| per = max(2, (budget - 3 * len(texts)) // len(texts)) | |
| question = ([self.delim["q"], *self._text(instructions_text(q.instructions))])[: max(16, budget)] | |
| markers = [] | |
| for text in texts: | |
| markers.append(len(question) + 1) | |
| question += [self.delim["opt"], self.marker, *self._text(" " + text)[:per], self.delim["opt_end"]] | |
| question.append(self.delim["decide"]) | |
| room = max(0, max_len - len(question) - 2) | |
| state_ids = [self.delim["state"], *self._text(serialize("" if state is None else state))[:room]] | |
| ids = ([self.tok.bos_token_id, *state_ids, *question])[:max_len] | |
| markers = [m + 1 + len(state_ids) for m in markers] | |
| if markers[-1] >= max_len: | |
| raise ValueError("the options do not fit in the context") | |
| return Encoded(ids=ids, markers=markers, canonical=canonical, qtype=QTYPES[q.type]) | |