File size: 6,492 Bytes
4807d4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""Discerna as an engine: load a model once, then answer decision requests.

    import discerna
    model = discerna.load("<owner>/Discerna-v1-475M")  # a Hugging Face repo id, or a local folder
    response = model.decide({"state": "...", "questions": {...}})

Every request gets a response or an exception of its own: one bad request in a batch never fails
the others. A request beyond the model's limits (too many options, a text too long for the
context) raises `Unsupported`.
"""

from __future__ import annotations

import re
from collections.abc import Sequence
from pathlib import Path

import torch

from discerna.contract import MAX_OPTIONS, DecisionRequest, DecisionResponse, Usage, build_answer, option_keys
from discerna.device import resolve_device, resolve_dtype

_CAPACITY = ("do not fit in the context", "the media take")
_REPO_ID = re.compile(r"^[A-Za-z0-9][\w.-]*/[\w.-]+$")
# What loading by name downloads: the model and its license, not the code, examples or tests beside it.
MODEL_FILES = ["config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json", "LICENSE", "NOTICE"]


class Unsupported(Exception):
    """The request exceeds a limit of the model (option count or context length)."""


def resolve(model: str | Path, revision: str | None = None) -> Path:
    """A local model folder, or a Hugging Face repo id (`owner/name`), downloaded once and then cached.
    A folder that exists locally always wins over a repo of the same name."""
    path = Path(model).expanduser()
    if path.exists():
        return path
    if isinstance(model, str) and _REPO_ID.match(model):
        from huggingface_hub import snapshot_download

        return Path(snapshot_download(model, revision=revision, allow_patterns=MODEL_FILES))
    raise FileNotFoundError(f"no model folder at {model} (nor a Hugging Face repo id like owner/name)")


class Discerna:
    def __init__(self, path: str | Path, device: str = "auto", dtype: str = "auto", name: str | None = None,
                 revision: str | None = None):
        from discerna.model.weights import from_checkpoint

        self.path = resolve(path, revision)
        self.device = resolve_device(device)
        self.dtype = resolve_dtype(dtype, self.device)
        self.model = from_checkpoint(self.path).to(device=self.device, dtype=self.dtype).eval()
        self.name = name or self.model.spec.get("name") or self.path.name

    @property
    def accepts_images(self) -> bool:
        return self.model.vision is not None

    def decide(self, request: DecisionRequest | dict) -> DecisionResponse:
        """Answer one request (a DecisionRequest or a plain dict of the same shape)."""
        result = self.decide_batch([request])[0]
        if isinstance(result, Exception):
            raise result
        return result

    def decide_batch(self, requests: Sequence[DecisionRequest | dict]) -> list[DecisionResponse | Exception]:
        """Answer several requests together (faster on a GPU); each gets a response or its own exception."""
        parsed: list[DecisionRequest | Exception] = []
        for request in requests:
            try:
                parsed.append(request if isinstance(request, DecisionRequest)
                              else DecisionRequest.model_validate(request))
            except Exception as e:
                parsed.append(e)
        results: list[DecisionResponse | Exception | None] = [None] * len(parsed)
        todo = []
        for i, request in enumerate(parsed):
            if isinstance(request, Exception):
                results[i] = request
            elif reason := self._unsupported_reason(request):
                results[i] = Unsupported(reason)
            else:
                todo.append(i)
        if todo:
            try:
                for i, answer in zip(todo, self._answer([parsed[i] for i in todo]), strict=True):
                    results[i] = answer
            except Exception as batch_error:
                if len(todo) == 1:
                    results[todo[0]] = self._classify(batch_error)
                else:  # find out which requests fail, one at a time
                    for i in todo:
                        try:
                            results[i] = self._answer([parsed[i]])[0]
                        except Exception as e:
                            results[i] = self._classify(e)
        return results  # type: ignore[return-value]

    @torch.inference_mode()
    def _answer(self, requests: list[DecisionRequest]) -> list[DecisionResponse]:
        out = []
        for request, (dists, read) in zip(requests, self.model.probabilities(requests), strict=True):
            answers = {name: build_answer(q, p) for (name, q), p in zip(request.questions.items(), dists, strict=True)}
            out.append(DecisionResponse(model=self.name, answers=answers, usage=Usage(input_tokens=read)))
        return out

    def _unsupported_reason(self, request: DecisionRequest) -> str | None:
        if request.images and not self.accepts_images:
            return "this model does not accept images"
        for name, q in request.questions.items():
            if len(option_keys(q)) > MAX_OPTIONS:
                return f"question {name!r}: more than {MAX_OPTIONS} options"
        return None

    @staticmethod
    def _classify(error: Exception) -> Exception:
        if isinstance(error, ValueError) and any(p in str(error) for p in _CAPACITY):
            return Unsupported(f"{error} (the request exceeds the model's context window)")
        return error

    def close(self) -> None:
        """Free the model's memory. Safe to call twice."""
        if getattr(self, "model", None) is not None:
            self.model = None
            if self.device.type == "mps":
                torch.mps.empty_cache()
            elif self.device.type == "cuda":
                torch.cuda.empty_cache()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()


def load(model: str | Path, device: str = "auto", dtype: str = "auto", revision: str | None = None) -> Discerna:
    """Load a model: a Hugging Face repo id (`owner/name`, downloaded on first use and cached) or a local
    folder. `device`: auto (cuda > mps > cpu), cuda, mps or cpu. `dtype`: auto (float32 on CPU, float16
    on GPUs), float32, float16 or bfloat16. `revision` pins a Hub branch, tag or commit."""
    return Discerna(model, device=device, dtype=dtype, revision=revision)