File size: 5,065 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Decoder engine ``mk``: the ttnn traced prefill (K / V written straight into the DEC megakernel's KV tensor) + the
GLM-OCR DEC megakernel (one launch per token: on-device greedy / sampling / repetition penalty, circular token ring and
the stop rule in STATE). Adapted from this workspace's Qwen3-ASR DEC engine (Apache-2.0).

    eng = MkDecoder(device, W, buckets, max_pos)
    eng.capture()                                   # prefill traces per bucket + a trace of BATCH DEC launches
    lg = eng.prefill(rows, pos3d, L)                # host logits of row L - 1 (token 0 is chosen on the host)
    eng.start(L, token0, max_new, delta, ...)
    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 Optional, Sequence, Tuple

import numpy as np
import torch

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


class MkDecoder:
    device_sampling = True

    def __init__(self, device, W, buckets: Sequence[int], max_pos: int, recipe=None, batch: int = 8,
                 source: str = "", k_max: int = 64, attk: Optional[int] = None, pre_precision=None, log=print):
        from ..ttnn_decoder import TtnnDecoder

        self.ttnn = __import__("ttnn")
        self.device, self.log = device, log
        self.recipe = dict(recipe or {"attn": "bfp8", "mlp": "bfp8", "head": "bf16"})
        self.batch = int(batch)
        t0 = time.time()
        w = load_dec(W)
        self.tlk = DecTLK(device, self.recipe, w, max_pos=max_pos, source=source, k_max=k_max, attk=attk, 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, buckets, self.tlk.max_pos, attn_dtype=pp["attn"], mlp_dtype=pp["mlp"],
                               head_dtype=pp["head"], kv=self.tlk.kv, 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 bucket(self, L: int) -> int:
        return self.pre.bucket(L)

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

    def start(self, L: int, token0: int, max_new: int, delta: int, temperature: float = 0.0, top_k: int = 0,
              top_p: float = 1.0, seed: Optional[int] = None, penalty: float = 1.0, seen_ids=None,
              eos=(59246, 59253)):
        seed = int(seed) if seed is not None else int.from_bytes(os.urandom(8), "little")
        if penalty != 1.0:
            self.tlk.write_seen(seen_ids or [])
        self.tlk.write_state(self.tlk.state_host(L, token0, max_new, eos, temperature, top_k, top_p, seed,
                                                 delta=delta, penalty=penalty))

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

    def run_batch(self):
        if self.trace is not None:
            self.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]:
        """(tokens so far, done, stop code, the ring [S_TOKENS_MAX] (token n at n % 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()

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

    def warmup(self, prefill: bool = True):
        self.pre.warmup(prefill)
        self.tlk.write_state(self.tlk.state_host(1, 59253, 1, done=True))
        self._launches(1)
        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()