Download src/discerna/engine.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 6.49 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/engine.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/engine.py
-
curl -L -o engine.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/engine.py
6.49 kB
| """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 | |
| 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] | |
| 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 | |
| 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) | |