File size: 5,593 Bytes
1c2cd3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)