File size: 13,840 Bytes
22e0325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# SPDX-License-Identifier: Apache-2.0
"""PaddleOCR-VL device pipeline (one element per call, batch 1): ttnn vision stage (traced per patch bucket) -> image
rows read back and assembled with the text embeddings on the host -> ttnn prefill (traced per bucket) -> decode with
the DEC megakernel (device sampling, ``engine["dec"] = "mk"``) or the ttnn decode step (host sampling, ``"ttnn"``).

    pipe = DevicePipeline(device, weights_dir, cfg, settings)   # settings: see DEFAULTS
    pipe.prepare()                                               # warm-up + trace capture (all buckets)
    res = pipe.run(img, ids, GenParams(...), on_token=print)     # -> RunResult (tokens, stop, timings in ms)

Contract: tt/model_types.py. Decode engines per request: the DEC megakernel with device sampling ("mk"); the same
megakernel producing logits only with the host sampler choosing ("mk-host": repetition_penalty, top_k > K_MAX); the
ttnn decode step ("ttnn") for requests whose prompt + max_new_tokens exceed the megakernel's KV capacity (4096
positions), when that engine is built (``settings["ttnn_fallback"]``: None = auto = built only when the profile's
DEFAULT request at its largest prompt does not fit 4096 positions (vl), True, False).
"""

from __future__ import annotations

import time
from typing import Callable, Dict, List, Optional

import numpy as np
import torch

from ..config import IMAGE_PLACEHOLDER, WEIGHTS, ModelConfig, derive_pre_buckets
from ..frontend import ImageInput, mrope_cos_sin, rope_index
from .model_types import GenParams, Limits, RunResult
from .sampling import HostSampler

MK_MAX_POS = 4096

DEFAULTS = {
    "engine": {"vis": "ttnn", "pre": "ttnn", "dec": "mk"},
    "vis_buckets": (1024, 2048, 3072, 4096, 5120),
    "pre_buckets": None,  # None: derived from the vision buckets
    "max_positions": 4096,
    "precision": {"vis": "bf16", "vis_mlp": "bf16", "pre_attn": "bf16", "pre_mlp": "bfp8", "pre_head": "bf16",
                  "mk": "bfp8h8", "vis_fid": "HiFi2", "pre_fid": "HiFi4"},
    # extra TtnnVision kwargs (rope_mode, sdpa_chunks, fuse_gelu, device_tilize); gated defaults (vis_precision_16)
    "vision": {"rope_mode": "llama96", "device_tilize": True},
    "trace": True,
    "warmup": True,
    "ttnn_fallback": None,
    "mk_batch": 8,
    "k_max": 64,
    "source": None,  # mk arena cache key (checkpoint revision); None: the profile's pinned revision
    "cache_dir": None,  # mk arena cache root (PADDLEOCR_MK_CACHE = <cache_dir>/mk_dec)
    "warmup_buckets": None,  # None: all vision buckets warmed + captured; else only these (others run eager)
}


class DevicePipeline:
    def __init__(self, device, weights_dir: str, cfg: ModelConfig, settings: Optional[dict] = None, log=print):
        import ttnn

        from .ttnn_decoder import TtnnDecoder
        from .ttnn_vision import TtnnVision
        from .weights import load_weights

        self.ttnn, self.device, self.cfg, self.log = ttnn, device, cfg, log
        s = dict(DEFAULTS)
        s.update({k: v for k, v in (settings or {}).items() if v is not None})
        s["engine"] = {**DEFAULTS["engine"], **(settings or {}).get("engine", {})}
        s["precision"] = {**DEFAULTS["precision"], **((settings or {}).get("precision") or {})}
        s["vision"] = {**DEFAULTS["vision"], **((settings or {}).get("vision") or {})}
        self.s = s
        if s.get("cache_dir"):
            import os

            os.environ.setdefault("PADDLEOCR_MK_CACHE", os.path.join(str(s["cache_dir"]), "mk_dec"))
        if not s.get("source"):
            s["source"] = WEIGHTS.get(cfg.profile, ("", ""))[1]
        t0 = time.time()
        W = load_weights(weights_dir)
        vb = sorted(int(b) for b in s["vis_buckets"])
        pb = sorted(int(b) for b in (s["pre_buckets"] or derive_pre_buckets(vb)))
        self.max_positions = int(s["max_positions"])
        pr = s["precision"]
        self.vis = TtnnVision(device, W, cfg.vision, vb, wdtype=pr["vis"], mlp_wdtype=pr["vis_mlp"],
                              fidelity=pr["vis_fid"], **dict(s.get("vision") or {}))
        self.dec_kind = s["engine"]["dec"]
        self.mk = None
        self.dec = None
        fb = s["ttnn_fallback"]
        if self.dec_kind == "mk":
            from .mk_dec import weights as E
            from .mk_dec.engine import MkDecoder

            mk_pos = min(self.max_positions, MK_MAX_POS)
            mk_pos = -(-mk_pos // 32) * 32
            self.mk = MkDecoder(device, W, cfg.dec, pre_buckets=pb, max_pos=mk_pos, recipe=E.RECIPES[pr["mk"]],
                                batch=int(s["mk_batch"]), source=s["source"], profile=cfg.profile,
                                k_max=int(s["k_max"]),
                                pre_precision=dict(attn=pr["pre_attn"], mlp=pr["pre_mlp"], head=pr["pre_head"],
                                                   pre_fid=pr["pre_fid"]),
                                log=log)
            if fb is None:
                # auto: only when the profile's DEFAULT request (largest prompt + default max_new_tokens) does not fit
                # the megakernel's KV (vl pages); longer requests are clipped to the KV capacity by the API
                fb = self.max_positions > mk_pos and pb[-1] + cfg.prof.default_max_new_tokens > mk_pos
        else:
            fb = True
        if fb:
            self.dec = TtnnDecoder(device, W, cfg.dec, pb, self.max_positions, attn_dtype=pr["pre_attn"],
                                   mlp_dtype=pr["pre_mlp"], head_dtype=pr["pre_head"], pre_fidelity=pr["pre_fid"])
        self.embed = W["model.embed_tokens.weight"]  # host bf16 [V, D]
        self.pre_buckets = pb
        del W
        self._prepared = False
        log(f"[paddleocr] pipeline built in {time.time() - t0:.1f}s: vision buckets {vb}, prefill buckets {pb}, "
            f"dec {self.dec_kind}{' + ttnn fallback' if (self.mk is not None and self.dec is not None) else ''}")

    # ------------------------------------------------------------------ lifecycle
    def prepare(self):
        """Warm-up (compile) every engine, then capture every trace (no device allocation after a capture)."""
        t0 = time.time()
        vb = self.s.get("warmup_buckets")
        vb = [b for b in self.vis.buckets if b in set(int(x) for x in vb)] if vb else None
        if self.s["warmup"] or self.s["trace"]:
            self.vis.warmup(vb)
            if self.mk is not None:
                self.mk.warmup()
            if self.dec is not None:
                self.dec.warmup()
        if self.s["trace"]:
            self.vis.capture(vb)
            if self.mk is not None:
                self.mk.capture()
            if self.dec is not None:
                self.dec.capture()
        self._prepared = True
        self.log(f"[paddleocr] prepared in {time.time() - t0:.1f}s (trace {self.s['trace']})")

    def close(self):
        for e in (self.vis, self.mk, self.dec):
            if e is not None:
                try:
                    e.release()
                except Exception:  # noqa: BLE001
                    pass

    def limits(self) -> Limits:
        mx = self.max_positions if self.dec is not None else min(self.max_positions, self.mk.max_pos)
        return Limits(max_patches=self.vis.buckets[-1], max_prompt=self.pre_buckets[-1], max_positions=mx)

    def info(self) -> dict:
        g = self.device.compute_with_storage_grid_size()
        return {"engine": dict(self.s["engine"]), "ttnn_fallback": self.dec is not None and self.mk is not None,
                "vis_buckets": list(self.vis.buckets), "pre_buckets": list(self.pre_buckets),
                "max_positions": self.limits().max_positions, "mk_max_positions": self.mk.max_pos if self.mk else 0,
                "precision": dict(self.s["precision"]), "trace": bool(self.s["trace"]), "grid": f"{g.x}x{g.y}"}

    # ------------------------------------------------------------------ one element
    def _rows(self, img: ImageInput, ids: List[int], timings: Dict[str, float]):
        ttnn = self.ttnn
        t0 = time.perf_counter()
        out, nt, _nb = self.vis.run(img)
        pe = ttnn.to_torch(out).reshape(-1, self.cfg.dec.d)[:nt]
        timings["vision"] = 1e3 * (time.perf_counter() - t0)
        idx = torch.tensor(ids)
        rows = self.embed[idx].float()
        m = idx == IMAGE_PLACEHOLDER
        if int(m.sum()) != nt:
            raise ValueError(f"prompt has {int(m.sum())} image placeholders, the image {nt} tokens")
        rows[m] = pe.to(torch.bfloat16).float()
        pos, delta = rope_index(ids, img.gh, img.gw)
        cs, sn = mrope_cos_sin(pos, self.cfg.dec.head_dim, self.cfg.dec.theta, self.cfg.dec.mrope_section)
        return rows, torch.from_numpy(cs), torch.from_numpy(sn), delta

    def run(self, img: ImageInput, ids: List[int], params: GenParams,
            on_token: Optional[Callable[[int], None]] = None, engine: Optional[str] = None) -> RunResult:
        """``engine``: force the decode engine ("mk" | "mk-host" | "ttnn"; benchmarks / tests), else chosen per
        request (mk; mk-host for repetition_penalty / top_k > K_MAX; ttnn beyond the megakernel's KV when built)."""
        L = len(ids)
        max_new = int(params.max_new_tokens)
        lim = self.limits()
        if img.n_patches > lim.max_patches:
            raise ValueError(f"image of {img.n_patches} patches exceeds the largest vision bucket {lim.max_patches}")
        if L > lim.max_prompt:
            raise ValueError(f"prompt of {L} tokens exceeds the largest prefill bucket {lim.max_prompt}")
        if L + max_new > lim.max_positions:
            raise ValueError(f"prompt {L} + max_new_tokens {max_new} exceeds the KV capacity {lim.max_positions}")
        # decode engine: "mk" = the megakernel with device sampling; "mk-host" = the megakernel producing logits only,
        # the host sampler choosing (repetition_penalty, top_k beyond the device sampler's K_MAX); "ttnn" = the tt-nn
        # decode step (requests beyond the megakernel's KV, when the fallback engine is built)
        fits_mk = self.mk is not None and L + max_new <= self.mk.max_pos
        host_sampling = (float(params.repetition_penalty or 1) != 1.0
                         or (self.mk is not None and int(params.top_k or 0) > self.mk.tlk.k_max))
        if engine == "ttnn" and self.dec is not None:
            mode = "ttnn"
        elif engine in ("mk", "mk-host") and fits_mk:
            mode = "mk-host" if (engine == "mk-host" or host_sampling) else "mk"
        elif fits_mk:
            mode = "mk-host" if host_sampling else "mk"
        elif self.dec is not None:
            mode = "ttnn"
        else:
            raise ValueError(f"prompt {L} + max_new_tokens {max_new} exceeds the decoder megakernel's KV capacity "
                             f"{self.mk.max_pos if self.mk else 0}")
        use_mk = mode in ("mk", "mk-host")
        timings: Dict[str, float] = {}
        t0 = time.perf_counter()
        rows, cs, sn, delta = self._rows(img, ids, timings)
        stops = tuple(int(x) for x in params.stop_ids) or (2,)
        sampler = HostSampler(params.temperature, params.top_k, params.top_p, params.repetition_penalty, params.seed)
        t1 = time.perf_counter()
        if use_mk:
            lg0 = self.mk.prefill(rows, cs, sn, L)
        else:
            self.dec.prefill(rows, cs, sn, L)
            lg0 = self.dec.logits_host()
        timings["prefill"] = 1e3 * (time.perf_counter() - t1)
        toks = [sampler(lg0, ids)]
        timings["first_token"] = 1e3 * (time.perf_counter() - t0)
        if on_token:
            on_token(toks[0])
        t2 = time.perf_counter()
        stop = "eos" if toks[0] in stops else ("length" if max_new <= 1 else "")
        if not stop and mode == "mk-host":
            for s_ in range(1, max_new):  # input token s_ - 1 at KV position L + s_ - 1, logits only, host sampler
                t = sampler(self.mk.tf_step(L, s_, toks[-1], delta), ids + toks)
                toks.append(t)
                if on_token:
                    on_token(t)
                if t in stops:
                    stop = "eos"
                    break
            else:
                stop = "length"
        elif not stop and mode == "mk":
            seed = params.seed if params.seed is not None else int(np.random.SeedSequence().generate_state(1)[0])
            eos = stops if len(stops) >= 2 else (stops[0], stops[0])
            self.mk.start(L, toks[0], max_new, delta, float(params.temperature or 0.0), int(params.top_k or 0),
                          float(params.top_p if params.top_p is not None else 1.0), seed, eos=eos[:2])
            while True:
                self.mk.run_batch()
                n, done, st, ring = self.mk.poll()
                for t in self.mk.ring_tokens(ring, len(toks), n):
                    toks.append(t)
                    if on_token:
                        on_token(t)
                if done:
                    stop = "eos" if st == 1 else "length"
                    break
        elif not stop:
            for s in range(max_new - 1):
                self.dec.step(self.embed[toks[-1]].float(), L + s, L + s + delta)
                t = sampler(self.dec.logits_host(), ids + toks)
                toks.append(t)
                if on_token:
                    on_token(t)
                if t in stops:
                    stop = "eos"
                    break
            else:
                stop = "length"
        timings["decode"] = 1e3 * (time.perf_counter() - t2)
        timings["total"] = 1e3 * (time.perf_counter() - t0)
        if len(toks) > 1:
            timings["ms_per_token"] = timings["decode"] / (len(toks) - 1)
        timings["engine_dec"] = mode  # type: ignore[assignment]
        return RunResult(tokens=toks, stop=stop, prompt_tokens=L, timings=timings)