File size: 5,437 Bytes
127ebd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""``DecisionModel``: load the checkpoint and answer decision requests.

    model = DecisionModel.from_pretrained("path/or/hub-id", device="cuda")
    out = model.decide(state, {"route": {"type": "choice", "criteria": {"a": "...", "b": "..."}},
                               "safe": {"type": "noul"}})
    out["answers"]["route"]    # {"type": "choice", "choice": "a", "probabilities": {"a": 0.7, "b": 0.3}}
    out["scores"]["route"]     # {"a": 1.2, "b": -0.4}   raw head scores z

Questions are ``{"type": "choice", "criteria": {key: description | null}, "instructions": str?}`` or
``{"type": "noul", "criteria": {"false": str?, "true": str?}?, "instructions": str?}``. The state is a string or any
JSON value.
"""
from __future__ import annotations

import uuid
from typing import Any

import torch

from .config import load_config
from .engine import Engine, Result
from .head import load_head
from .loading import load_text_model, resolve
from .prefix_cache import PrefixCache


class ContextLengthError(ValueError):
    """The request does not fit ``max_length`` / ``token_budget``, or contains a question this model cannot take."""


def format_answers(questions: dict[str, Any], result: Result) -> dict[str, dict[str, Any]]:
    """Wire-format answers: ``choice`` with its probabilities, or ``noul`` with the probability of "true"."""
    answers = {}
    for key, spec in questions.items():
        p = result.probs[key]
        answers[key] = ({"type": "noul", "noul": p["true"]} if spec["type"] == "noul" else
                        {"type": "choice", "choice": max(p, key=p.get), "probabilities": p})
    return answers


class DecisionModel:
    def __init__(self, engine: Engine, name: str, source: str):
        self.engine, self.name, self.source = engine, name, source

    @property
    def readout(self) -> str:
        return self.engine.config.readout

    @property
    def temperature(self) -> float:
        return self.engine.config.temperature

    @classmethod
    def from_pretrained(cls, path_or_id: str, device: str | torch.device = "cuda", *, revision: str | None = None,
                        name: str = "BunGPT-DeepEdu-Decision-4B-Open", fork: bool = True, cache_mb: int = 0,
                        cache_every: int = 1024, token_budget: int = 16384, max_length: int | None = None,
                        attention: str = "auto") -> DecisionModel:
        """``path_or_id``: a local checkpoint directory or a Hugging Face Hub repo id.

        ``fork``: score a request as one tree (the state is read once). ``cache_mb``: cross-request prefix cache cap in
        MB of GPU memory (fork only; 0 = off). ``token_budget``: real tokens per forward. ``max_length``: longest
        prefill (default ``token_budget``). ``attention``: ``flash``, ``sdpa`` or ``auto`` (flash when installed)."""
        device = torch.device(device)
        if device.type != "cuda":
            raise ValueError("the fused kernels need a CUDA device")
        if attention == "auto":
            try:
                import flash_attn  # noqa: F401

                attention = "flash"
            except ImportError:
                attention = "sdpa"
        source = resolve(path_or_id, revision)
        config = load_config(source)
        from transformers import AutoTokenizer

        tokenizer = AutoTokenizer.from_pretrained(str(source))
        lm = load_text_model(source).to(device).eval()
        head = load_head(source, lm.config.hidden_size).to(device).eval()
        cache = PrefixCache(cache_mb << 20, cache_every) if fork and cache_mb else None
        engine = Engine(lm, head, tokenizer, config, device, token_budget=token_budget, max_length=max_length,
                        attention=attention, fork=fork, cache=cache)
        return cls(engine, name, str(source))

    def run(self, requests: list[dict[str, Any]]) -> list[Result]:
        """Score requests ``{"id", "state", "questions"}`` together: low-level, one ``Result`` each (never raises for
        an unsupported request; see ``Result.error``)."""
        return self.engine.run(requests)

    def decide_batch(self, requests: list[dict[str, Any]]) -> list[dict[str, Any]]:
        """Requests ``{"state", "questions"}`` scored together; one ``{"answers", "scores"}`` each, or ``{"error"}``
        for a request that cannot be taken."""
        rows = [{"id": str(i), "state": r["state"], "questions": r["questions"]} for i, r in enumerate(requests)]
        out = []
        for row, result in zip(rows, self.run(rows)):
            if not result.ok:
                out.append({"error": result.error or f"questions over the token budget: {result.skipped}"})
            else:
                out.append({"answers": format_answers(row["questions"], result), "scores": result.scores})
        return out

    def decide(self, state: Any, questions: dict[str, Any]) -> dict[str, Any]:
        """-> ``{"answers": {key: choice | noul answer}, "scores": {key: {option: raw head score z}}}``.

        Raises ``ContextLengthError`` when the request does not fit or holds an unsupported question."""
        row = {"id": uuid.uuid4().hex, "state": state, "questions": questions}
        (result,) = self.run([row])
        if not result.ok:
            raise ContextLengthError(result.error or f"questions over the token budget: {result.skipped}")
        return {"answers": format_answers(questions, result), "scores": result.scores}