File size: 4,501 Bytes
0ec7a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CUDA kernels for the OpenThai 2.2 single-token decoder."""

from __future__ import annotations

from functools import cache
from pathlib import Path

import torch
from torch.utils.cpp_extension import load_inline

from graph_step import EOS, GraphedStep

_CPP = """
at::Tensor decode_attention(const at::Tensor&, const at::Tensor&, const at::Tensor&,
                            const at::Tensor&, const at::Tensor&, const at::Tensor&);
at::Tensor vectorized_gemv(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&);
"""


@cache
def kernels():
    return load_inline(
        name="openthai_pascal_decode",
        cpp_sources=_CPP,
        cuda_sources=Path(__file__).with_suffix(".cu").read_text(encoding="utf-8"),
        functions=["decode_attention", "vectorized_gemv"],
        extra_cuda_cflags=["-O3"],
    )


class GreedySampler:
    """Device-side token history and first-EOS position for one graph."""

    def __init__(self, vocab_size: int, capacity: int):
        self.seen = torch.zeros(vocab_size, dtype=torch.bool, device="cuda")
        self.tokens = torch.empty(capacity, dtype=torch.long, device="cuda")
        self.count = torch.zeros(1, dtype=torch.long, device="cuda")
        self.stop = torch.full((), capacity, dtype=torch.long, device="cuda")
        self.penalty = torch.tensor(1.05, device="cuda")

    def reset(self, prompt: torch.Tensor, limit: int, penalty: float) -> None:
        length = prompt.numel()
        self.seen.zero_().index_fill_(0, prompt, True)
        self.tokens[:length].copy_(prompt)
        self.count.fill_(length)
        self.stop.fill_(length + limit + 1)
        self.penalty.fill_(penalty)

    def copy_from(self, other: GreedySampler) -> None:
        self.seen.copy_(other.seen)
        self.tokens.copy_(other.tokens)
        self.count.copy_(other.count)
        self.stop.copy_(other.stop)
        self.penalty.copy_(other.penalty)

    def choose(self, logits: torch.Tensor) -> torch.Tensor:
        adjusted = torch.where(logits < 0, logits * self.penalty, logits / self.penalty)
        token = torch.where(self.seen, adjusted, logits).argmax().view(1)
        self.seen.index_fill_(0, token, True)
        self.tokens.index_copy_(0, self.count, token)
        self.count.add_(1)
        torch.minimum(self.stop, torch.where(token[0] == EOS, self.count[0], self.stop), out=self.stop)
        return token.view(1, 1)


class PascalStep(GraphedStep):
    """Attention and greedy feedback captured in one decode graph."""

    def __init__(self, model, bucket: int, *, kv_dtype=torch.float16):
        self.sampler = GreedySampler(model.lm_head.weight.shape[0], model.config.max_sequence_length)
        super().__init__(model, bucket, attention_kernel=kernels().decode_attention, kv_dtype=kv_dtype)

    def _step(self) -> torch.Tensor:
        logits = super()._step()
        self.token.copy_(self.sampler.choose(logits))
        self.pos.add_(1)
        return logits

    def inherit(self, step: PascalStep, length: int) -> None:
        super().inherit(step, length)
        self.sampler.copy_from(step.sampler)
        self.token.copy_(step.token)
        self.pos.fill_(length)


@torch.no_grad()
def generate_chunked(decoder, model, inputs, limit: int, penalty: float) -> torch.Tensor:
    """Replay up to eight steps per host check, then keep tokens up to the first EOS."""
    prompt = inputs["input_ids"][0]
    end = prompt.numel() + limit
    if limit < 1 or end > model.config.max_sequence_length:
        raise ValueError("Invalid OCR generation limit")
    prefill = model(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        image_sizes=inputs["image_sizes"],
        content_sizes=inputs["content_sizes"],
        use_cache=True,
    )
    length = prefill.past_key_values.get_seq_length()
    step = decoder.load(prefill.past_key_values, length)
    step.sampler.reset(prompt, limit, penalty)
    step.token.copy_(step.sampler.choose(prefill.logits[0, -1]))
    del prefill

    count = prompt.numel() + 1
    stop = int(step.sampler.stop)
    while count < end and stop > end:
        if length >= step.bucket:
            step = decoder.promote(step, length)
        replays = min(8, step.bucket - length, end - count)
        for _ in range(replays):
            step.graph.replay()
        length += replays
        count += replays
        stop = int(step.sampler.stop)
    return step.sampler.tokens[:min(count, stop)].view(1, -1).clone()