Download source/src/deepedu_decision/model.py from DeepEduVN/bungpt-open: direct link, hf CLI and curl.
- Browser
- Download file 5.44 kB
-
https://huggingface.co/DeepEduVN/bungpt-open/resolve/main/source/src/deepedu_decision/model.py
- Command line
-
hf download hf://DeepEduVN/bungpt-open/source/src/deepedu_decision/model.py
-
curl -L -o model.py https://huggingface.co/DeepEduVN/bungpt-open/resolve/main/source/src/deepedu_decision/model.py
5.44 kB
| """``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 | |
| def readout(self) -> str: | |
| return self.engine.config.readout | |
| def temperature(self) -> float: | |
| return self.engine.config.temperature | |
| 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} | |