test_lora.py 11.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
# Copyright 2023-2024 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
14
15
16
17
18
19
20

import multiprocessing as mp
import unittest

import torch

from sglang.test.runners import HFRunner, SRTRunner
21
from sglang.test.test_utils import CustomTestCase
22
23
24
25
26
27
28

LORA_SETS = [
    # {
    #     "base": "meta-llama/Llama-2-7b-hf",
    #     "loras": ["RuterNorway/Llama-2-7b-chat-norwegian-LoRa"],
    # },
    {"base": "meta-llama/Llama-2-7b-hf", "loras": ["winddude/wizardLM-LlaMA-LoRA-7B"]},
29
    # {"base": "Qwen/Qwen2.5-14B-Instruct", "loras": ["mssongit/Qwen2.5-14B-SFT-LoRA"]},
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    # {"base": "mistralai/Mistral-7B-Instruct-v0.3", "loras": ["/home/ying/test_lora"]},
    # {
    #     "base": "mistralai/Mistral-7B-Instruct-v0.3",
    #     "loras": [
    #         "/home/ying/test_lora",
    #         "/home/ying/test_lora_1",
    #         "/home/ying/test_lora_2",
    #         "/home/ying/test_lora_3",
    #         "/home/ying/test_lora_4",
    #     ],
    # },
    # {"base": "meta-llama/Llama-2-7b-hf", "loras": ["yard1/llama-2-7b-sql-lora-test"]},
]
TORCH_DTYPES = [torch.float16]

PROMPTS = [
    """
### Instruction:
48
Write a poem about the transformers Python library.
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
Mention the word "large language models" in that poem.
### Response:
The Transformers are large language models,
They're used to make predictions on text.
""",
    """
### Instruction:
Tell me about llamas and alpacas
### Response:
Llamas are large, long-necked animals with a woolly coat. They have two toes on each foot instead of three like other camelids (camels, dromedaries). Llamas live in the Andean mountains of South America where they graze on grasses and shrubs. Alpaca is another name for domesticated llama. The word "alpaca" comes from an Incan language meaning "golden fleece." Alpacas look very similar to llamas but are smaller than their wild relatives. Both species were used by ancient people as pack animals and for meat. Today both llamas and alpacas are raised primarily for their fiber which can be spun into yarn or knitted into clothing.
### Question 2:
What do you know about llamas?
### Answer:
""",
]

# import json
#
# with open("/home/ying/test_prompt/dialogue_choice_prompts.json", "r") as f:
#     samples = json.load(f)
# for sample in samples[:5]:
#     assert sample[0]["role"] == "user"
#     PROMPTS.append(sample[0]["content"][:2000])


74
class TestLoRA(CustomTestCase):
75
76
77
78
79
80
81
82
83
84
85
86
87
88

    def inference(self, prompts, lora_set, tp_size, torch_dtype, max_new_tokens):
        print("=================== testing inference =======================")
        base_path = lora_set["base"]
        all_lora_paths = lora_set["loras"]
        batch_lora_paths = [None]
        i = 0
        for _ in range(len(prompts) - 1):
            batch_lora_paths.append(all_lora_paths[i])
            i = (i + 1) % len(all_lora_paths)

        with SRTRunner(
            base_path,
            torch_dtype=torch_dtype,
89
90
            model_type="generation",
            tp_size=tp_size,
91
92
93
94
95
96
97
98
            lora_paths=all_lora_paths,
            max_loras_per_batch=3,
            disable_cuda_graph=True,
            disable_radix_cache=True,
        ) as srt_runner:
            srt_outputs = srt_runner.forward(
                prompts, max_new_tokens=max_new_tokens, lora_paths=batch_lora_paths
            )
99
100
101
102
103
            srt_outputs_lora_path_none = srt_runner.forward(
                prompts,
                max_new_tokens=max_new_tokens,
                lora_paths=[None] * len(prompts),
            )
104
105

        with HFRunner(
106
            base_path, torch_dtype=torch_dtype, model_type="generation"
107
108
109
110
111
112
113
114
        ) as hf_runner:
            hf_outputs = hf_runner.forward(
                prompts, max_new_tokens=max_new_tokens, lora_paths=batch_lora_paths
            )

        with HFRunner(
            base_path,
            torch_dtype=torch_dtype,
115
            model_type="generation",
116
117
118
119
120
121
122
123
124
        ) as hf_runner:
            hf_no_lora_outputs = hf_runner.forward(
                prompts, max_new_tokens=max_new_tokens
            )

        with SRTRunner(
            base_path,
            tp_size=tp_size,
            torch_dtype=torch_dtype,
125
            model_type="generation",
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
        ) as srt_runner:
            srt_no_lora_outputs = srt_runner.forward(
                prompts, max_new_tokens=max_new_tokens
            )

        for i in range(len(prompts)):
            # compare input logprobs
            hf_logprobs = torch.Tensor(hf_outputs.top_input_logprobs[i])
            srt_logprobs = torch.Tensor(srt_outputs.top_input_logprobs[i])
            hf_no_lora_logprobs = torch.Tensor(hf_no_lora_outputs.top_input_logprobs[i])
            srt_no_lora_logprobs = torch.Tensor(
                srt_no_lora_outputs.top_input_logprobs[i]
            )
            print(
                "max input diff between hf_lora and srt_lora",
                torch.max(abs(hf_logprobs - srt_logprobs)),
            )
            print(
                "max input diff between srt_base and srt_lora",
                torch.max(abs(srt_no_lora_logprobs - srt_logprobs)),
            )
            print(
                "max input diff between srt_base and hf_base",
                torch.max(abs(srt_no_lora_logprobs - hf_no_lora_logprobs)),
            )
            print(
                "max input diff between hf_lora and hf_base",
                torch.max(abs(hf_logprobs - hf_no_lora_logprobs)),
            )

            # compare output logprobs
            hf_logprobs = torch.Tensor(hf_outputs.top_output_logprobs[i])
            srt_logprobs = torch.Tensor(srt_outputs.top_output_logprobs[i])
            # print(
            #     "\noutput logprobs diff",
            #     [
            #         float(torch.max(abs(hf_logprobs[j] - srt_logprobs[j])))
            #         for j in range(max_new_tokens)
            #     ],
            # )
            print(
                "max output diff between hf_lora and srt_lora",
                torch.max(abs(hf_logprobs - srt_logprobs)),
                "\n",
            )

        # compare output strings
        print(f"{hf_outputs.output_strs=}")
        print(f"{srt_outputs.output_strs=}")
        print(f"{hf_no_lora_outputs.output_strs=}")
        print(f"{srt_no_lora_outputs.output_strs=}")
177
        print(f"{srt_outputs_lora_path_none.output_strs=}")
178
179
        for i in range(len(prompts)):
            assert srt_outputs.output_strs[i].strip(" ") == hf_outputs.output_strs[i], (
180
                srt_outputs.output_strs[i].strip(" "),
181
182
                hf_outputs.output_strs[i],
            )
183
184
185
186
187
188
189
190
            assert (
                srt_no_lora_outputs.output_strs[i].strip(" ")
                == hf_no_lora_outputs.output_strs[i]
            ), (
                srt_no_lora_outputs.output_strs[i].strip(" "),
                hf_no_lora_outputs.output_strs[i],
            )
            assert srt_outputs_lora_path_none == srt_no_lora_outputs
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

    def serving(self, prompts, lora_set, tp_size, torch_dtype, max_new_tokens):
        print("=================== testing serving =======================")
        # test batch forward
        base_path = lora_set["base"]
        all_lora_paths = lora_set["loras"]
        batch_lora_paths = [None]
        i = 0
        for _ in range(len(prompts) - 1):
            batch_lora_paths.append(all_lora_paths[i])
            i = (i + 1) % len(all_lora_paths)

        with SRTRunner(
            base_path,
            tp_size=tp_size,
            torch_dtype=torch_dtype,
207
            model_type="generation",
208
209
210
211
212
213
214
215
216
217
218
219
            lora_paths=all_lora_paths,
            max_loras_per_batch=3,
            disable_cuda_graph=True,
            disable_radix_cache=True,
        ) as srt_runner:
            srt_outputs = srt_runner.batch_forward(
                prompts, max_new_tokens=max_new_tokens, lora_paths=batch_lora_paths
            )

        with HFRunner(
            base_path,
            torch_dtype=torch_dtype,
220
            model_type="generation",
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
            output_str_only=True,
        ) as hf_runner:
            hf_outputs = hf_runner.forward(
                prompts, max_new_tokens=max_new_tokens, lora_paths=batch_lora_paths
            )

        # compare output strings
        print(f"{hf_outputs.output_strs=}")
        print(f"{srt_outputs.output_strs=}")
        for i in range(len(prompts)):
            assert srt_outputs.output_strs[i].strip(" ") == hf_outputs.output_strs[i], (
                srt_outputs.output_strs[i].strip(" "),
                hf_outputs.output_strs[i],
            )

    def base_inference(self, prompts, lora_set, tp_size, torch_dtype, max_new_tokens):
        print("=================== testing base inference =======================")
        base_path = lora_set["base"]
        all_lora_paths = lora_set["loras"]
        batch_lora_paths = [None] * len(prompts)

        with SRTRunner(
            base_path,
            tp_size=tp_size,
            torch_dtype=torch_dtype,
246
            model_type="generation",
247
248
249
250
251
252
253
254
255
        ) as srt_runner:
            srt_no_lora_outputs = srt_runner.forward(
                prompts, max_new_tokens=max_new_tokens
            )

        with SRTRunner(
            base_path,
            tp_size=tp_size,
            torch_dtype=torch_dtype,
256
            model_type="generation",
257
258
259
260
261
262
263
264
265
266
            lora_paths=all_lora_paths,
        ) as srt_runner:
            srt_outputs = srt_runner.forward(
                prompts, max_new_tokens=max_new_tokens, lora_paths=batch_lora_paths
            )

        for i in range(len(prompts)):
            srt_no_lora_logprobs = torch.Tensor(
                srt_no_lora_outputs.top_input_logprobs[i]
            )
267
            srt_logprobs = torch.Tensor(srt_outputs.top_input_logprobs[i])
268
269
270
271
272
273
274
            print("max_diff", torch.max(abs(srt_no_lora_logprobs - srt_logprobs)))

        print(f"{srt_no_lora_outputs.output_strs=}")
        print(f"{srt_outputs.output_strs=}")

        for i in range(len(prompts)):
            assert srt_outputs.output_strs[i].strip(" ") == hf_outputs.output_strs[i], (
275
                srt_outputs.output_strs[i].strip(" "),
276
277
278
279
280
281
282
283
284
285
286
287
288
289
                hf_outputs.output_strs[i],
            )
            assert (
                srt_no_lora_outputs[i].output_strs.strip(" ")
                == hf_no_lora_outputs[i].output_strs
            )

    def test_all(self):
        for lora_set in LORA_SETS:
            # self.load_lora_adapter(lora_set, 1)
            for torch_dtype in TORCH_DTYPES:
                tp_size = 1
                max_new_tokens = 32
                self.inference(PROMPTS, lora_set, tp_size, torch_dtype, max_new_tokens)
290
                self.serving(PROMPTS, lora_set, tp_size, torch_dtype, max_new_tokens)
291
292
293
294
295
296
297
298
299
300
301
302
                # self.base_inference(
                #     PROMPTS, lora_set, tp_size, torch_dtype, max_new_tokens
                # )


if __name__ == "__main__":
    try:
        mp.set_start_method("spawn")
    except RuntimeError:
        pass

    unittest.main(warnings="ignore")