Download code/d1_engine.py from LiquidAI/d1-decision-index: direct link, hf CLI and curl.
- Browser
- Download file 5.59 kB
-
https://huggingface.co/datasets/LiquidAI/d1-decision-index/resolve/main/code/d1_engine.py
- Command line
-
hf download hf://datasets/LiquidAI/d1-decision-index/code/d1_engine.py
-
curl -L -o d1_engine.py https://huggingface.co/datasets/LiquidAI/d1-decision-index/resolve/main/code/d1_engine.py
5.59 kB
| """Decision Index engine for the LiquidAI d1 models (d1-3B, d1-omni-600M). | |
| The model is loaded from the Hub with its own code (`trust_remote_code=True`) and every request goes through | |
| its documented API, `model.system_one(state, questions, images=...)`, as on the model card. | |
| python -m decision_index pipeline --engine d1_engine:D1 \\ | |
| --option model=LiquidAI/d1-3B --option revision=<sha> --option dtype=bfloat16 --out runs/d1-3b | |
| Images, for the vision board, are PIL images, file paths, raw bytes or `data:` URLs, in order. | |
| """ | |
| import base64 | |
| import importlib | |
| import io | |
| from decision_index.engines.base import Engine, Unsupported | |
| class D1(Engine): | |
| name = "d1" | |
| latency = "Device-synchronized in-process request wall time through model.system_one; excludes model loading." | |
| def __init__(self, model, revision=None, dtype="bfloat16", device=None, compile=False, **options): | |
| super().__init__(**options) | |
| import torch | |
| from transformers import AutoModel | |
| self.torch = torch | |
| self.device = device or ("cuda" if torch.cuda.is_available() else "cpu") | |
| self.model = AutoModel.from_pretrained(model, revision=revision, trust_remote_code=True, | |
| dtype=getattr(torch, dtype)).to(self.device).eval() | |
| if compile: # CUDA graphs for single questions, as the d1-3B card describes | |
| self.model.compile(mode="reduce-overhead") | |
| self.model_id = model | |
| # d1-omni-600M cuts a text that does not fit its context; the index wants such a request unsupported | |
| self.omni = self.model.config.model_type == "d1_omni" | |
| if self.omni: | |
| package = type(self.model).__module__.rpartition(".")[0] | |
| self.prompt = importlib.import_module(package + ".prompt") | |
| self.vision = importlib.import_module(package + ".vision") | |
| self.yes_no = importlib.import_module(type(self.model).__module__).YES_NO | |
| self.provenance = {"kind": "transformers, trust_remote_code", "repo": model, | |
| "revision": revision or getattr(self.model.config, "_commit_hash", None), | |
| "device": self.device, "dtype": dtype, "compile": bool(compile), | |
| "policy": "model.system_one(state, questions, images) as on the model card; a request " | |
| "longer than the model's context is unsupported, never shortened."} | |
| def __call__(self, state, questions, images=None): | |
| images = [_image(x) for x in images] if images else None | |
| if self.omni: | |
| self._check_fits(state, questions, images) | |
| out = self.model.system_one(state, questions, images=images) | |
| return {"model": self.model_id, "answers": out["answers"], "usage": out["usage"]}, None | |
| def _check_fits(self, state, questions, images): | |
| """Unsupported when d1-omni-600M would read the request in part. Its own `prompt.encode` keeps an | |
| instruction to the option budget and each option text to a share of it, and cuts the state to the room | |
| left (`max_length`; with images, `image_text_length` or what the image positions leave).""" | |
| cfg, prompt, tok = self.model.config, self.prompt, self.model.tokenizer | |
| room, noul = cfg.max_length, None | |
| if images: | |
| positions = sum(self._positions(im) for im in images) | |
| room, noul = min(cfg.image_text_length, cfg.max_length - positions), self.yes_no | |
| if room < 64: | |
| raise Unsupported(f"the images take {positions:,} of the {cfg.max_length:,} positions") | |
| def enc(s): | |
| return tok(prompt.escape(s), add_special_tokens=False)["input_ids"] | |
| n = len(enc(prompt.serialize("" if state is None else state))) | |
| for q in map(prompt.as_question, questions.values()): | |
| try: | |
| ids, _ = prompt.encode(tok, "", q, room, noul) | |
| except ValueError as e: # the options alone do not fit | |
| raise Unsupported(f"prompt longer than the {room:,}-token context window: {e}") from e | |
| whole = 2 + len(enc(q.instructions)) + sum(3 + len(enc(" " + t)) for t in prompt.render_options(q, noul)) | |
| if len(ids) - 2 < whole: | |
| raise Unsupported("the model would read only part of this question's instructions or options") | |
| if n + len(ids) > room: | |
| raise Unsupported(f"prompt longer than the {room:,}-token context window") | |
| def _positions(self, image): | |
| """Prefix positions of one image in d1-omni-600M: 256 per 512 px tile, (h/32)(w/32) for the thumbnail.""" | |
| plan = self.vision.layout(*image.size) | |
| h, w = plan["thumbnail"] | |
| tiles = plan["grid"][0] * plan["grid"][1] if plan["tiled"] else 0 | |
| return tiles * 256 + (h // 32) * (w // 32) | |
| def runtime(self): | |
| import transformers | |
| info = {"torch": self.torch.__version__, "transformers": transformers.__version__, "device": self.device} | |
| if self.device == "cuda": | |
| info.update(hip=self.torch.version.hip, cuda=self.torch.version.cuda, | |
| gpu=self.torch.cuda.get_device_name()) | |
| return info | |
| def synchronize(self): | |
| if self.device == "cuda": | |
| self.torch.cuda.synchronize() | |
| def _image(x): | |
| from PIL import Image | |
| if hasattr(x, "convert"): | |
| return x | |
| if isinstance(x, str) and x.startswith("data:"): | |
| x = base64.b64decode(x.partition(",")[2]) | |
| return Image.open(io.BytesIO(x) if isinstance(x, bytes) else x) | |