utils.py 11.7 KB
Newer Older
1
2
3
import warnings
from typing import Dict, List, Optional, Sequence, Tuple, Union

4
5
import torch

6
from vllm.config import ModelConfig, TaskOption
7
from vllm.inputs import InputContext
8
from vllm.sequence import Logprob, PromptLogprobs, SampleLogprobs
9
from vllm.utils import is_cpu
10
11
12
13

TokensText = Tuple[List[int], str]


14
15
16
17
18
19
20
def check_outputs_equal(
    *,
    outputs_0_lst: Sequence[TokensText],
    outputs_1_lst: Sequence[TokensText],
    name_0: str,
    name_1: str,
):
21
22
23
24
25
26
27
28
29
30
31
32
    """
    Compare the two sequences generated by different models, 
    which should be equal.
    """
    assert len(outputs_0_lst) == len(outputs_1_lst)

    for prompt_idx, (outputs_0,
                     outputs_1) in enumerate(zip(outputs_0_lst,
                                                 outputs_1_lst)):
        output_ids_0, output_str_0 = outputs_0
        output_ids_1, output_str_1 = outputs_1

33
34
35
36
37
38
39
        # The text and token outputs should exactly match
        fail_msg = (f"Test{prompt_idx}:"
                    f"\n{name_0}:\t{output_str_0!r}"
                    f"\n{name_1}:\t{output_str_1!r}")

        assert output_str_0 == output_str_1, fail_msg
        assert output_ids_0 == output_ids_1, fail_msg
40
41


42
43
44
45
46
47
# Representation of generated sequence as a tuple of
# * Token ID list
# * String
# * List of top sample logprobs for each sampled token
#
# Assumes prompt logprobs were not requested.
48
49
50
TokensTextLogprobs = Tuple[List[int], str, Optional[Union[List[Dict[int,
                                                                    float]],
                                                          SampleLogprobs]]]
51

52
53
54
55
56
57
58
# Allow for tokens to be represented as str's rather than IDs;
# tuple of
# * Token string representations list
# * String
# * Optional list of top sample logprobs for each sampled token
#
# Assumes prompt logprobs were not requested.
59
60
61
62
TextTextLogprobs = Tuple[List[str], str, Optional[Union[List[Dict[str, float]],
                                                        List[Dict[str,
                                                                  Logprob]]]]]

63
64
65
66
67
68
69
70
71
72
73
# Representation of generated sequence as a tuple of
# * Token ID list
# * String
# * Optional list of top sample logprobs for each sampled token
# * Optional list of top prompt logprobs for each prompt token
#
# Allows prompt logprobs to be requested.
TokensTextLogprobsPromptLogprobs = Tuple[
    List[int], str, Optional[Union[List[Dict[int, float]], SampleLogprobs]],
    Optional[Union[List[Optional[Dict[int, float]]], PromptLogprobs]]]

74

75
76
def check_logprobs_close(
    *,
77
78
79
80
81
82
    outputs_0_lst: Sequence[Union[TokensTextLogprobs,
                                  TokensTextLogprobsPromptLogprobs,
                                  TextTextLogprobs]],
    outputs_1_lst: Sequence[Union[TokensTextLogprobs,
                                  TokensTextLogprobsPromptLogprobs,
                                  TextTextLogprobs]],
83
84
    name_0: str,
    name_1: str,
85
    num_outputs_0_skip_tokens: int = 0,
86
    warn_on_mismatch: bool = True,
87
88
89
    always_check_logprobs: bool = False,
) -> None:
    """Compare the logprobs of two sequences generated by different models,
90
    which should be similar but not necessarily equal.
91

92
93
94
95
96
97
98
99
100
101
102
103
    How sample logprobs are compared:
    * `always_check_logprobs == True`: set of highest-logprob token ids
      must match between seq0 and seq1 at all sampled token offsets
    * `always_check_logprobs == False`: highest-logprob token ids are
      only compared at sampled token offsets for which generated token
      ids don't match

    Prompt logprobs must be provided either for both input sequences, or
    for neither. If prompt logprobs are provided, then highest-logprob
    prompt token ids must match between seq0 and seq1 at all prompt token
    offsets.

104
105
106
107
108
109
    Args:
      outputs_0_lst: First sequence to compare
      outputs_0_lst: Second sequence to compare
      name_0: sequence #0 name
      name_1: sequence #1 name
      num_outputs_0_skip_tokens: If > 0, specifies the number of initial
110
111
112
113
114
                                 sequence #0 tokens & logprobs to discard
                                 before comparison, i.e. all
                                 of sequence #1 will be compared to
                                 sequence #0 beginning at index
                                 num_outputs_0_skip_tokens
115
      warn_on_mismatch: Issue a warning if there is token-wise or text-wise
116
                        mismatch between the two sequences
117
      always_check_logprobs: If true, check logprobs even when tokens match
118
    """
119
120
    assert len(outputs_0_lst) == len(outputs_1_lst)

121
122
123
124
    # Loop through responses to each prompt.
    for prompt_idx, (outputs_0,
                     outputs_1) in enumerate(zip(outputs_0_lst,
                                                 outputs_1_lst)):
125
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
177
178
179
180
181
182
183
        assert len(outputs_0) == len(outputs_1)
        if len(outputs_0) == 3:
            assert len(outputs_1) == 3
            # Break out tokens, text & sample logprobs
            # (prompt logprobs were not provided)
            output_ids_0, output_str_0, logprobs_0 = outputs_0
            output_ids_1, output_str_1, logprobs_1 = outputs_1
        elif len(outputs_0) == 4:
            assert len(outputs_1) == 4
            # Break out tokens, text, sample logprobs & prompt logprobs
            (
                output_ids_0,
                output_str_0,
                logprobs_0,
                prompt_logprobs_0,
            ) = outputs_0
            (
                output_ids_1,
                output_str_1,
                logprobs_1,
                prompt_logprobs_1,
            ) = outputs_1

            # Test prompt logprobs closeness
            if (prompt_logprobs_0 is not None
                    and prompt_logprobs_1 is not None):
                # Both sequences' prompt logprobs lists are not `None``
                # (although individual list elements may be `None`);
                # for each token's logprobs:
                for idx, (logprobs_elem_0, logprobs_elem_1) in enumerate(
                        zip(prompt_logprobs_0, prompt_logprobs_1)):
                    fail_msg = (
                        f"Prompt logprobs test:"
                        f"\n{name_0}:\tPrompt index {idx}\t{logprobs_elem_0}"
                        f"\n{name_1}:\tPrompt index {idx}\t{logprobs_elem_1}")

                    if logprobs_elem_0 is None:
                        # If the seq 0 token's logprobs are `None`,
                        # the seq 1 token's logprobs must be `None`
                        assert logprobs_elem_1 is None, fail_msg
                    else:
                        # If the seq 0 token's logprobs are not `None`,
                        # the seq 1 token's logprobs must not be `None`
                        assert logprobs_elem_1 is not None, fail_msg
                        # Logprobs check: top-k token choices must be the same
                        assert (set(logprobs_elem_0.keys()) == set(
                            logprobs_elem_1.keys())), fail_msg
            else:
                # Both sequence logprobs lists must be `None`
                fail_msg = (f"Prompt logprobs test:"
                            f"\n{name_0}:\tlogprobs\t{prompt_logprobs_0}"
                            f"\n{name_1}:\tlogprobs\t{prompt_logprobs_1}")

                assert (prompt_logprobs_0 is None
                        and prompt_logprobs_1 is None), fail_msg
        else:
            raise ValueError(f"Outputs tuple must have 3 or 4 elements but "
                             f"{len(outputs_0)} elements were provided: "
                             f"{outputs_0}")
184

185
186
187
188
189
        if logprobs_0 is None:
            logprobs_0 = [None] * len(output_ids_0)
        if logprobs_1 is None:
            logprobs_1 = [None] * len(output_ids_1)

190
191
192
193
194
195
196
197
198
        # Skip specified number of initial sequence #0 tokens
        # & logprobs, leaving output text as-is for simplicity
        # (text mismatches may generate warnings but do not
        # cause the test to fail.)
        if num_outputs_0_skip_tokens < 0:
            raise ValueError("num_outputs_0_skip_tokens must be non-negative")
        output_ids_0 = output_ids_0[num_outputs_0_skip_tokens:]
        logprobs_0 = logprobs_0[num_outputs_0_skip_tokens:]

199
200
201
202
        # Loop through generated tokens.
        for idx, (output_id_0,
                  output_id_1) in enumerate(zip(output_ids_0, output_ids_1)):

203
204
205
206
207
208
            is_tok_mismatch = output_id_0 != output_id_1

            # If generated tokens don't match
            # or it is desired to always check logprobs,
            # then
            if is_tok_mismatch or always_check_logprobs:
209
210
211
                logprobs_elem_0 = logprobs_0[idx]
                logprobs_elem_1 = logprobs_1[idx]

212
                # Each predicted token must be in top N logprobs of the other
213
                fail_msg = (
214
                    f"Test{prompt_idx}:"
215
                    f"\nMatched tokens:\t{output_ids_0[:idx]}"
216
217
218
219
220
221
222
223
                    f"\n{name_0}:\t{output_str_0!r}\t{logprobs_elem_0}"
                    f"\n{name_1}:\t{output_str_1!r}\t{logprobs_elem_1}")

                assert logprobs_elem_0 is not None, fail_msg
                assert logprobs_elem_1 is not None, fail_msg
                assert output_id_0 in logprobs_elem_1, fail_msg
                assert output_id_1 in logprobs_elem_0, fail_msg

224
                if warn_on_mismatch and is_tok_mismatch:
225
226
227
228
229
230
                    with warnings.catch_warnings():
                        # This ensures that repeated warnings are shown
                        # in the output, not just the first occurrence
                        warnings.simplefilter("always")

                        warnings.warn(fail_msg, stacklevel=2)
231
232
233

                # Break out since sequences will now diverge.
                break
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        else:
            if output_str_0 != output_str_1 and warn_on_mismatch:
                # The token outputs exactly match,
                # so the text outputs should exactly match as well
                fail_msg = (f"Test{prompt_idx}:"
                            f"\n{name_0}:\t{output_str_0!r}"
                            f"\n{name_1}:\t{output_str_1!r}")

                with warnings.catch_warnings():
                    # This ensures that repeated warnings are shown
                    # in the output, not just the first occurrence
                    warnings.simplefilter("always")

                    warnings.warn(fail_msg, stacklevel=2)
248
249
250


def build_model_context(model_name: str,
251
                        task: TaskOption = "auto",
252
253
                        tokenizer_name: Optional[str] = None,
                        trust_remote_code: bool = False,
254
                        dtype: Optional[Union[str, torch.dtype]] = None,
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
                        mm_processor_kwargs: Optional[Dict] = None,
                        limit_mm_per_prompt: Optional[Dict] = None):
    """Creates an InputContext for a given model.
    
    Args:
        model_name: Name of the model being considered.
        tokenizer_name: Name of the tokenizer being considered.
        trust_remote_code: Whether or not to allow loading remote code.
        mm_processor_kwargs: optional processor kwargs for to be leveraged
            in the input processor, mapper, dummy data creation, etc.
        limit_mm_per_prompt: Multimodal limits.

    Returns:
        InputContext for the model being considered.
    """
    if tokenizer_name is None:
        tokenizer_name = model_name
272
273
274
    if dtype is None:
        dtype = "bfloat16" if is_cpu() else "half"

275
276
    model_config = ModelConfig(
        model_name,
277
278
        task=task,
        tokenizer=tokenizer_name,
279
280
        tokenizer_mode="auto",
        trust_remote_code=trust_remote_code,
281
        dtype=dtype,
282
283
284
285
286
        seed=0,
        mm_processor_kwargs=mm_processor_kwargs,
        limit_mm_per_prompt=limit_mm_per_prompt,
    )
    return InputContext(model_config)