File size: 3,516 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
#!/usr/bin/env python3
"""Time transformers.generate against a tight greedy loop. One median page."""

from __future__ import annotations

import time
from pathlib import Path

import torch

MODEL = Path(__file__).resolve().parents[2] / "models" / "original"

EOS = 2


def penalize(logits, seen, penalty):
    scores = torch.gather(logits, 0, seen)
    scores = torch.where(scores < 0, scores * penalty, scores / penalty)
    return logits.scatter(0, seen, scores)


@torch.inference_mode()
def tight(model, inputs, limit, penalty):
    token = torch.empty(1, 1, dtype=torch.long, device="cuda")
    seen = torch.empty(9000, dtype=torch.long, device="cuda")
    out = model(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        image_sizes=inputs["image_sizes"],
        content_sizes=inputs["content_sizes"],
        use_cache=True,
    )
    cache = out.past_key_values
    prompt = inputs["input_ids"][0]
    count = prompt.numel()
    seen[:count].copy_(prompt)
    logits = out.logits[0, -1]
    produced = 0
    while produced < limit:
        choice = int(penalize(logits, seen[:count], penalty).argmax())
        seen[count] = choice
        count += 1
        produced += 1
        if choice == EOS:
            break
        token.fill_(choice)
        out = model(input_ids=token, past_key_values=cache, use_cache=True)
        logits = out.logits[0, -1]
    return seen[:count].view(1, -1)


def main() -> None:
    import sys

    from datasets import load_dataset
    from transformers import AutoModel, AutoProcessor

    from fast_attn import install as install_attn
    from int8_gemv import install as install_int8

    sys.path.insert(0, str(MODEL))
    from nemotron_parse.inference import (
        PROMPT,
        DocumentParser,
        GenerationSettings,
        TransformersBackend,
        clean_raw_output,
    )
    from nemotron_parse.postprocessing import postprocess_document

    dataset = load_dataset("scb10x/ThaiOCRBench")["test"]
    image = next(row["image"] for row in dataset if row["Id"] == "84DF1F7D").convert("RGB")
    model = AutoModel.from_pretrained(
        MODEL, trust_remote_code=True, dtype=torch.float32, local_files_only=True
    ).to("cuda").eval()
    processor = AutoProcessor.from_pretrained(MODEL, trust_remote_code=True, local_files_only=True)
    install_attn(model)
    install_int8(model)
    inputs = processor(images=[image], text=PROMPT, return_tensors="pt", add_special_tokens=False)
    inputs = {k: v.to("cuda") if torch.is_tensor(v) else v for k, v in inputs.items()}
    parser = DocumentParser(
        backend=TransformersBackend(model, processor),
        fullpage=GenerationSettings(temperature=0.0, repetition_penalty=1.05, max_tokens=8744),
    )
    parser.parse(image, mode="single")
    tight(model, inputs, 8744, 1.05)
    torch.cuda.synchronize()
    started = time.perf_counter()
    stock = parser.parse(image, mode="single")["markdown"]
    torch.cuda.synchronize()
    stock_s = time.perf_counter() - started
    torch.cuda.synchronize()
    started = time.perf_counter()
    ids = tight(model, inputs, 8744, 1.05)
    torch.cuda.synchronize()
    fast_s = time.perf_counter() - started
    text = processor.batch_decode(ids, skip_special_tokens=False)[0]
    fast = postprocess_document(clean_raw_output(text), image_size=image.size)["markdown"]
    print(f"generate {stock_s:.2f}s loop {fast_s:.2f}s {stock_s / fast_s:.2f}x exact={stock == fast}")


if __name__ == "__main__":
    main()