reference_hf.py 6.12 KB
Newer Older
1
"""
2
3
4
5
6
7
Usage: python3 scripts/playground/reference_hf.py --model-path MODEL_PATH --model-type {text,vlm} [--max-new-tokens NUM] [--dtype DTYPE]
  --model-path MODEL_PATH: Path to model (default: TinyLlama/TinyLlama-1.1B-Chat-v0.4)
  --model-type {text,vlm}: Model type, text or vlm (default: text)
  --max-new-tokens NUM: Max new tokens to generate (default: 16)
  --dtype DTYPE: Data type for computation (default: float16)
Note: '--model' is deprecated; use '--model-path'. Runs normal_text() for text, vlm_text_with_image() for vlm.
8
9

Reference output:
10
11
12
========== Prompt 0 ==========
prefill logits (final) tensor([-8.3125, -7.1172,  3.3398,  ..., -4.9531, -4.1328, -3.4141],
       device='cuda:0')
13
14
<s> The capital of France is Paris.
The capital of the United States is Washington, D.C.
15
16
17

========== Prompt 1 ==========
prefill logits (final) tensor([-8.9062, -9.0156,  4.1484,  ..., -4.9922, -4.4961, -4.0742],
18
19
20
       device='cuda:0')
<s> The capital of the United Kindom is London.
The capital of the United Kingdom is London.
21
22
23
24
The capital of

========== Prompt 2 ==========
prefill logits (final) tensor([-9.6328, -9.0547,  4.0234,  ..., -5.3047, -4.7148, -4.4609],
25
26
       device='cuda:0')
<s> Today is a sunny day and I like to go for a walk in the park.
27
I'm going to the
28
29
"""

Lianmin Zheng's avatar
Lianmin Zheng committed
30
31
import argparse

32
import requests
Lianmin Zheng's avatar
Lianmin Zheng committed
33
import torch
Yineng Zhang's avatar
Yineng Zhang committed
34
from PIL import Image
35
from transformers import (
Yineng Zhang's avatar
Yineng Zhang committed
36
37
38
    AutoModelForCausalLM,
    AutoModelForImageTextToText,
    AutoProcessor,
39
)
40

41
from sglang.srt.utils.hf_transformers_utils import get_tokenizer
Lianmin Zheng's avatar
Lianmin Zheng committed
42
43


44
45
46
@torch.no_grad()
def vlm_text_with_image(args):
    # Load the processor and model for ImageTextToText tasks
Yineng Zhang's avatar
Yineng Zhang committed
47
    processor = AutoProcessor.from_pretrained(args.model_path, trust_remote_code=True)
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    model = AutoModelForImageTextToText.from_pretrained(
        args.model_path,
        torch_dtype=args.dtype,
        low_cpu_mem_usage=True,
        device_map="auto",
        trust_remote_code=True,
    )

    torch.cuda.set_device(0)

    # List of image URLs to process
    image_urls = [
        "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
    ]

    # Conversation template for the processor
    conversation = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                },
Yineng Zhang's avatar
Yineng Zhang committed
71
72
                {"type": "text", "text": "Describe this image."},
            ],
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        }
    ]

    max_new_tokens = args.max_new_tokens

    for i, url in enumerate(image_urls):
        # Load the image from the URL
        image = Image.open(requests.get(url, stream=True).raw)

        # Apply the chat template to the text prompt
        # Notice that not all processors support chat templates.
        # LLaVA and QWen are two processors that support chat templates.
        if not hasattr(processor, "apply_chat_template"):
            raise ValueError("The processor does not support chat templates.")
        text_prompt = processor.apply_chat_template(
Yineng Zhang's avatar
Yineng Zhang committed
88
89
            conversation, add_generation_prompt=True
        )
90
91

        # Prepare inputs for the model
Yineng Zhang's avatar
Yineng Zhang committed
92
93
94
        inputs = processor(text=[text_prompt], images=[image], return_tensors="pt").to(
            "cuda:0"
        )
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

        # Generate output from the model
        output_ids = model.generate(
            **inputs, do_sample=False, max_new_tokens=max_new_tokens
        )
        output_str = processor.decode(output_ids[0])

        # Get the logits from the model's forward pass
        outputs = model.forward(**inputs)
        logits = outputs.logits[0, -1, :]

        print(f"\n========== Image {i} ==========")
        print("prefill logits (final)", logits)
        # TODO(gaocegege): The output contains numerous <|image_pad|> tokens,
        # making it cluttered and difficult to read.
        # These tokens should be removed or cleaned up for better readability.
        print(output_str)


114
@torch.no_grad()
Lianmin Zheng's avatar
Lianmin Zheng committed
115
def normal_text(args):
116
    t = get_tokenizer(args.model_path, trust_remote_code=True)
Lianmin Zheng's avatar
Lianmin Zheng committed
117
    m = AutoModelForCausalLM.from_pretrained(
zhyncs's avatar
zhyncs committed
118
        args.model_path,
119
        torch_dtype=args.dtype,
zhyncs's avatar
zhyncs committed
120
        low_cpu_mem_usage=True,
121
        device_map="auto",
zhyncs's avatar
zhyncs committed
122
        trust_remote_code=True,
Lianmin Zheng's avatar
Lianmin Zheng committed
123
124
125
126
127
128
129
    )

    prompts = [
        "The capital of France is",
        "The capital of the United Kindom is",
        "Today is a sunny day and I like",
    ]
130
    max_new_tokens = args.max_new_tokens
131
132

    torch.cuda.set_device(0)
Lianmin Zheng's avatar
Lianmin Zheng committed
133

134
    for i, p in enumerate(prompts):
Lianmin Zheng's avatar
Lianmin Zheng committed
135
        if isinstance(p, str):
136
            input_ids = t.encode(p, return_tensors="pt").to("cuda:0")
Lianmin Zheng's avatar
Lianmin Zheng committed
137
        else:
138
            input_ids = torch.tensor([p], device="cuda:0")
Lianmin Zheng's avatar
Lianmin Zheng committed
139
140
141
142
143
144
145

        output_ids = m.generate(
            input_ids, do_sample=False, max_new_tokens=max_new_tokens
        )
        output_str = t.decode(output_ids[0])

        prefill_logits = m.forward(input_ids).logits[0][-1]
146

147
148
        print(f"\n========== Prompt {i} ==========")
        print("prefill logits (final)", prefill_logits)
149
        print(output_str)
Lianmin Zheng's avatar
Lianmin Zheng committed
150
151


152
@torch.no_grad()
Lianmin Zheng's avatar
Lianmin Zheng committed
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
def synthetic_tokens(args):
    m = AutoModelForCausalLM.from_pretrained(
        args.model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
    )
    m.cuda()
    print(m)

    input_len = 256
    output_len = 8
    prompts = [list(range(5, 5 + input_len))]

    for p in prompts:
        input_ids = p
        for i in range(output_len + 1):
            prefill_logits = m.forward(torch.tensor([input_ids], device="cuda")).logits[
                0
            ][-1]

            if i == 0:
                print("prefill logits", prefill_logits)
            else:
                print("decode", i - 1, prefill_logits)

            input_ids.append(torch.argmax(prefill_logits).item())


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--model-path",
        type=str,
        default="TinyLlama/TinyLlama-1.1B-Chat-v0.4",
    )
Chayenne's avatar
Chayenne committed
186
    parser.add_argument("--max-new-tokens", type=int, default=16)
187

Chayenne's avatar
Chayenne committed
188
    parser.add_argument("--dtype", type=str, default="float16")
189

190
191
    parser.add_argument("--model-type", type=str, default="text")

Lianmin Zheng's avatar
Lianmin Zheng committed
192
193
    args = parser.parse_args()

194
195
196
197
    if args.model_type == "vlm":
        vlm_text_with_image(args)
    else:
        normal_text(args)