File size: 5,737 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
# SPDX-License-Identifier: Apache-2.0
"""Decoder engine ``mk`` (adapted from this workspace's Qwen3-ASR DEC engine, Apache-2.0): ttnn traced prefill (K / V
of ERNIE's 2 kv heads repeated to the kernel's 8 groups, written straight into the DEC megakernel's KV tensor) + the
DEC megakernel (one launch per token, on-device greedy / sampling, token ring and stop rule in STATE).

    eng = MkDecoder(device, W, cfg, pre_buckets=(...), max_pos=4096, recipe={...})
    eng.capture()                                   # prefill traces per bucket + a trace of BATCH DEC launches
    lg = eng.prefill(rows, cos, sin, L)             # host logits of row L - 1 (token 0 is sampled on the host)
    eng.start(L, token0, max_new, rope_delta, temperature, top_k, top_p, seed)
    while True:
        eng.run_batch()                             # BATCH launches (no-ops once STATE says done)
        ntok, done, stop, toks = eng.poll()         # one 8 KB D2H read of STATE
"""

from __future__ import annotations

import os
import time
from typing import Dict, Optional, Sequence, Tuple

import numpy as np
import torch

from . import geometry as G
from . import weights as E
from .program import DecTLK
from .weights import load_dec


class MkDecoder:
    device_sampling = True

    def __init__(self, device, W: Dict[str, torch.Tensor], cfg, *, pre_buckets: Sequence[int], max_pos: int,
                 recipe: Optional[Dict[str, str]] = None, batch: int = 8, source: str = "", profile: str = "1.6",
                 k_max: int = 64, pre_precision: Optional[Dict[str, str]] = None, log=print):
        """``cfg``: config.DecoderConfig; ``W``: the checkpoint dict; ``source``: the checkpoint revision (arena cache
        key); ``profile``: the serve profile (arena cache key)."""
        from ..ttnn_decoder import TtnnDecoder

        self.ttnn = __import__("ttnn")
        self.device, self.cfg, self.log = device, cfg, log
        self.recipe = dict(recipe or E.RECIPES["bfp8"])
        self.batch = int(batch)
        t0 = time.time()
        w = load_dec(W)
        self.tlk = DecTLK(device, profile, self.recipe, w, max_pos=max_pos, source=source, k_max=k_max, log=log)
        del w
        pp = dict(attn="bf16", mlp="bfp8", head="bf16", pre_fid="HiFi4")
        pp.update(pre_precision or {})
        self.pre = TtnnDecoder(device, W, cfg, pre_buckets, max_pos, attn_dtype=pp["attn"], mlp_dtype=pp["mlp"],
                               head_dtype=pp["head"], kv=self.tlk.kv, kv_rep=E.KV_REP, decode=False,
                               pre_fidelity=pp["pre_fid"])
        self.trace = None
        log(f"[mk_dec] engine ready in {time.time() - t0:.1f}s (recipe {self.recipe}, batch {self.batch})")

    @property
    def buckets(self):
        return self.pre.buckets

    @property
    def max_pos(self) -> int:
        return self.tlk.max_pos

    def prefill(self, rows: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, L: int) -> torch.Tensor:
        self.pre.prefill(rows, cos, sin, L)
        return self.pre.logits_host()

    def start(self, L: int, token0: int, max_new: int, rope_delta: int, temperature: float = 0.0, top_k: int = 0,
              top_p: float = 1.0, seed: Optional[int] = None, eos=(2,)):
        seed = int(seed) if seed is not None else int.from_bytes(os.urandom(8), "little")
        self.tlk.write_state(self.tlk.state_host(L, token0, max_new, eos, temperature, top_k, top_p, seed,
                                                 rope_delta=rope_delta))

    def _launches(self, n: int):
        for _ in range(n):
            self.tlk.run()

    def run_batch(self):
        ttnn = self.ttnn
        if self.trace is not None:
            ttnn.execute_trace(self.device, self.trace, cq_id=0, blocking=False)
        else:
            self._launches(self.batch)

    def poll(self) -> Tuple[int, bool, int, np.ndarray]:
        """(n tokens so far, done, stop code, ring [S_TOKENS_MAX]: token i at ring[i % S_TOKENS_MAX])."""
        st = self.tlk.read_state()
        n = int(st[G.S_NTOK])
        return n, bool(st[G.S_DONE]), int(st[G.S_STOP]), st[G.S_TOKENS:G.S_TOKENS + G.S_TOKENS_MAX].copy()

    @staticmethod
    def ring_tokens(ring: np.ndarray, start: int, n: int):
        return [int(ring[i % G.S_TOKENS_MAX]) for i in range(start, n)]

    def tf_step(self, L: int, s: int, token_in: int, rope_delta: int) -> torch.Tensor:
        """Teacher-forced step s >= 1 (input = token_in at KV position L + s - 1): logits [V] (host), no sampling."""
        self.tlk.write_state(self.tlk.state_host(L, token_in, 1 << 20, ntok=s, rope_delta=rope_delta))
        self.tlk.run(flags=G.F_NOSAMPLE)
        return self.tlk.read_logits()

    def warmup(self, prefill: bool = True):
        """Compile the prefill buckets and the DEC program (a no-op launch: STATE done) before any trace capture."""
        self.pre.warmup(prefill)
        self.tlk.write_state(self.tlk.state_host(1, 2, 1, done=True))
        self._launches(1)
        self.tlk.run(flags=G.F_NOSAMPLE)  # the logits-only program of host-sampled requests (tf_step), built now
        self.ttnn.synchronize_device(self.device)
        self._warm = True

    def capture(self, prefill: bool = True):
        ttnn = self.ttnn
        if not getattr(self, "_warm", False):
            self.warmup(prefill)
        self.pre.capture(prefill=prefill)
        self.trace = ttnn.begin_trace_capture(self.device, cq_id=0)
        self._launches(self.batch)
        ttnn.end_trace_capture(self.device, self.trace, cq_id=0)
        ttnn.synchronize_device(self.device)

    def release(self):
        if self.trace is not None:
            self.ttnn.release_trace(self.device, self.trace)
            self.trace = None
        self.pre.release()