test_embedding.py 14 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
6
import base64

import numpy as np
7
8
import openai
import pytest
9
import os
10
import pytest_asyncio
11
import requests
12
13
import torch
import torch.nn.functional as F
14

15
16
17
18
from tests.models.language.pooling.embed_utils import (
    run_embedding_correctness_test)
from tests.models.utils import check_embeddings_close
from tests.utils import RemoteOpenAIServer
19
from vllm.entrypoints.openai.protocol import EmbeddingResponse
20
from vllm.transformers_utils.tokenizer import get_tokenizer
21

22
from utils import RemoteOpenAIServer, models_path_prefix
23

zhuwenwen's avatar
zhuwenwen committed
24

zhuwenwen's avatar
zhuwenwen committed
25
MODEL_NAME = os.path.join(models_path_prefix, "intfloat/multilingual-e5-small")
26
DUMMY_CHAT_TEMPLATE = """{% for message in messages %}{{message['role'] + ': ' + message['content'] + '\\n'}}{% endfor %}"""  # noqa: E501
27
DTYPE = "bfloat16"
28
29
30


@pytest.fixture(scope="module")
31
def server():
32
    args = [
33
34
        "--runner",
        "pooling",
35
36
        # use half precision for speed and memory savings in CI environment
        "--dtype",
37
        DTYPE,
38
39
        "--enforce-eager",
        "--max-model-len",
40
        "512",
41
42
        "--chat-template",
        DUMMY_CHAT_TEMPLATE,
43
44
    ]

45
    with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
46
        yield remote_server
47
48


49
@pytest_asyncio.fixture
50
51
async def client(server):
    async with server.get_async_client() as async_client:
52
        yield async_client
53
54


55
56
57
58
59
60
61
@pytest.fixture(scope="module")
def hf_model(hf_runner):
    with hf_runner(MODEL_NAME, dtype=DTYPE,
                   is_sentence_transformer=True) as hf_model:
        yield hf_model


62
@pytest.mark.asyncio
63
@pytest.mark.parametrize("model_name", [MODEL_NAME])
64
65
async def test_single_embedding(hf_model, client: openai.AsyncOpenAI,
                                model_name: str):
66
67
68
69
70
    input_texts = [
        "The chef prepared a delicious meal.",
    ]

    # test single embedding
71
    embedding_response = await client.embeddings.create(
72
73
74
75
        model=model_name,
        input=input_texts,
        encoding_format="float",
    )
76
77
78
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

79
80
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
81
    assert len(embeddings.data[0].embedding) == 384
82
    assert embeddings.usage.completion_tokens == 0
83
84
    assert embeddings.usage.prompt_tokens == 11
    assert embeddings.usage.total_tokens == 11
85

86
    vllm_outputs = [d.embedding for d in embeddings.data]
87
    run_embedding_correctness_test(hf_model, input_texts, vllm_outputs)
88

89
90
    # test using token IDs
    input_tokens = [1, 1, 1, 1, 1]
91
    embedding_response = await client.embeddings.create(
92
93
94
95
        model=model_name,
        input=input_tokens,
        encoding_format="float",
    )
96
97
98
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

99
100
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
101
    assert len(embeddings.data[0].embedding) == 384
102
103
104
105
106
107
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 5
    assert embeddings.usage.total_tokens == 5


@pytest.mark.asyncio
108
@pytest.mark.parametrize("model_name", [MODEL_NAME])
109
110
async def test_batch_embedding(hf_model, client: openai.AsyncOpenAI,
                               model_name: str):
111
    # test list[str]
112
113
114
115
    input_texts = [
        "The cat sat on the mat.", "A feline was resting on a rug.",
        "Stars twinkle brightly in the night sky."
    ]
116
    embedding_response = await client.embeddings.create(
117
118
119
120
        model=model_name,
        input=input_texts,
        encoding_format="float",
    )
121
122
123
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

124
125
    assert embeddings.id is not None
    assert len(embeddings.data) == 3
126
    assert len(embeddings.data[0].embedding) == 384
127
    assert embeddings.usage.completion_tokens == 0
128
129
    assert embeddings.usage.prompt_tokens == 33
    assert embeddings.usage.total_tokens == 33
130

131
    vllm_outputs = [d.embedding for d in embeddings.data]
132
    run_embedding_correctness_test(hf_model, input_texts, vllm_outputs)
133

134
    # test list[list[int]]
135
136
    input_tokens = [[4, 5, 7, 9, 20], [15, 29, 499], [24, 24, 24, 24, 24],
                    [25, 32, 64, 77]]
137
    embedding_response = await client.embeddings.create(
138
139
140
141
        model=model_name,
        input=input_tokens,
        encoding_format="float",
    )
142
143
144
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

145
146
    assert embeddings.id is not None
    assert len(embeddings.data) == 4
147
    assert len(embeddings.data[0].embedding) == 384
148
149
150
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 17
    assert embeddings.usage.total_tokens == 17
151
152
153


@pytest.mark.asyncio
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_conversation_embedding(server: RemoteOpenAIServer,
                                      client: openai.AsyncOpenAI,
                                      model_name: str):
    messages = [{
        "role": "user",
        "content": "The cat sat on the mat.",
    }, {
        "role": "assistant",
        "content": "A feline was resting on a rug.",
    }, {
        "role": "user",
        "content": "Stars twinkle brightly in the night sky.",
    }]

169
170
171
172
173
174
175
176
    chat_response = requests.post(
        server.url_for("v1/embeddings"),
        json={
            "model": model_name,
            "messages": messages,
            "encoding_format": "float",
        },
    )
177
    chat_response.raise_for_status()
178
    chat_embeddings = EmbeddingResponse.model_validate(chat_response.json())
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

    tokenizer = get_tokenizer(tokenizer_name=model_name, tokenizer_mode="fast")
    prompt = tokenizer.apply_chat_template(
        messages,
        chat_template=DUMMY_CHAT_TEMPLATE,
        add_generation_prompt=True,
        continue_final_message=False,
        tokenize=False,
    )
    completion_response = await client.embeddings.create(
        model=model_name,
        input=prompt,
        encoding_format="float",
        # To be consistent with chat
        extra_body={"add_special_tokens": False},
    )
195
196
    completion_embeddings = EmbeddingResponse.model_validate(
        completion_response.model_dump(mode="json"))
197

198
199
200
201
202
203
    assert chat_embeddings.id is not None
    assert completion_embeddings.id is not None
    assert chat_embeddings.created <= completion_embeddings.created
    assert chat_embeddings.model_dump(
        exclude={"id", "created"}) == (completion_embeddings.model_dump(
            exclude={"id", "created"}))
204
205
206
207


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
208
async def test_batch_base64_embedding(hf_model, client: openai.AsyncOpenAI,
209
210
211
212
213
214
                                      model_name: str):
    input_texts = [
        "Hello my name is",
        "The best thing about vLLM is that it supports many different models"
    ]

215
216
217
    responses_float = await client.embeddings.create(input=input_texts,
                                                     model=model_name,
                                                     encoding_format="float")
218
    float_data = [d.embedding for d in responses_float.data]
219
    run_embedding_correctness_test(hf_model, input_texts, float_data)
220

221
222
223
    responses_base64 = await client.embeddings.create(input=input_texts,
                                                      model=model_name,
                                                      encoding_format="base64")
224
    base64_data = []
225
    for data in responses_base64.data:
226
        base64_data.append(
227
            np.frombuffer(base64.b64decode(data.embedding),
228
                          dtype="float32").tolist())
229

230
    run_embedding_correctness_test(hf_model, input_texts, base64_data)
231
232

    # Default response is float32 decoded from base64 by OpenAI Client
233
234
    responses_default = await client.embeddings.create(input=input_texts,
                                                       model=model_name)
235
    default_data = [d.embedding for d in responses_default.data]
236
    run_embedding_correctness_test(hf_model, input_texts, default_data)
237
238
239


@pytest.mark.asyncio
240
241
242
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_single_embedding_truncation(client: openai.AsyncOpenAI,
                                           model_name: str):
243
244
245
246
247
    input_texts = [
        "Como o Brasil pode fomentar o desenvolvimento de modelos de IA?",
    ]

    # test single embedding
248
    embedding_response = await client.embeddings.create(
249
250
251
        model=model_name,
        input=input_texts,
        extra_body={"truncate_prompt_tokens": 10})
252
253
254
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

255
256
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
257
    assert len(embeddings.data[0].embedding) == 384
258
259
260
261
262
263
264
265
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 10
    assert embeddings.usage.total_tokens == 10

    input_tokens = [
        1, 24428, 289, 18341, 26165, 285, 19323, 283, 289, 26789, 3871, 28728,
        9901, 340, 2229, 385, 340, 315, 28741, 28804, 2
    ]
266
    embedding_response = await client.embeddings.create(
267
268
269
        model=model_name,
        input=input_tokens,
        extra_body={"truncate_prompt_tokens": 10})
270
271
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))
272
273
274

    assert embeddings.id is not None
    assert len(embeddings.data) == 1
275
    assert len(embeddings.data[0].embedding) == 384
276
277
278
279
280
281
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 10
    assert embeddings.usage.total_tokens == 10


@pytest.mark.asyncio
282
283
284
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_single_embedding_truncation_invalid(client: openai.AsyncOpenAI,
                                                   model_name: str):
285
286
287
288
289
    input_texts = [
        "Como o Brasil pode fomentar o desenvolvimento de modelos de IA?",
    ]

    with pytest.raises(openai.BadRequestError):
290
        response = await client.embeddings.create(
291
292
293
            model=model_name,
            input=input_texts,
            extra_body={"truncate_prompt_tokens": 8193})
294
        assert "error" in response.object
295
        assert "truncate_prompt_tokens value is greater than max_model_len. "\
296
               "Please, select a smaller truncation size." in response.message
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321


@pytest.mark.asyncio
async def test_invocations(server: RemoteOpenAIServer,
                           client: openai.AsyncOpenAI):
    input_texts = [
        "The chef prepared a delicious meal.",
    ]

    request_args = {
        "model": MODEL_NAME,
        "input": input_texts,
        "encoding_format": "float",
    }

    completion_response = await client.embeddings.create(**request_args)

    invocation_response = requests.post(server.url_for("invocations"),
                                        json=request_args)
    invocation_response.raise_for_status()

    completion_output = completion_response.model_dump()
    invocation_output = invocation_response.json()

    assert completion_output.keys() == invocation_output.keys()
322
323
324
325
326
327
328
    for completion_data, invocation_data in zip(completion_output["data"],
                                                invocation_output["data"]):
        assert completion_data.keys() == invocation_data.keys()
        check_embeddings_close(embeddings_0_lst=[completion_data["embedding"]],
                               embeddings_1_lst=[invocation_data["embedding"]],
                               name_0="completion",
                               name_1="invocation")
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361


@pytest.mark.asyncio
async def test_invocations_conversation(server: RemoteOpenAIServer):
    messages = [{
        "role": "user",
        "content": "The cat sat on the mat.",
    }, {
        "role": "assistant",
        "content": "A feline was resting on a rug.",
    }, {
        "role": "user",
        "content": "Stars twinkle brightly in the night sky.",
    }]

    request_args = {
        "model": MODEL_NAME,
        "messages": messages,
        "encoding_format": "float",
    }

    chat_response = requests.post(server.url_for("v1/embeddings"),
                                  json=request_args)
    chat_response.raise_for_status()

    invocation_response = requests.post(server.url_for("invocations"),
                                        json=request_args)
    invocation_response.raise_for_status()

    chat_output = chat_response.json()
    invocation_output = invocation_response.json()

    assert chat_output.keys() == invocation_output.keys()
362
363
364
365
366
367
368
    for chat_data, invocation_data in zip(chat_output["data"],
                                          invocation_output["data"]):
        assert chat_data.keys() == invocation_data.keys()
        check_embeddings_close(embeddings_0_lst=[chat_data["embedding"]],
                               embeddings_1_lst=[invocation_data["embedding"]],
                               name_0="chat",
                               name_1="invocation")
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_normalize(server: RemoteOpenAIServer, model_name: str):
    input_text = ["The chef prepared a delicious meal."]

    async def get_outputs(normalize):
        request_args = {
            "model": MODEL_NAME,
            "input": input_text,
            "encoding_format": "float",
            "normalize": normalize
        }

        response = requests.post(server.url_for("v1/embeddings"),
                                 json=request_args)
        outputs = response.json()

        return torch.tensor([x['embedding'] for x in outputs["data"]])

    default = await get_outputs(normalize=None)
    w_normal = await get_outputs(normalize=True)
    wo_normal = await get_outputs(normalize=False)

    assert torch.allclose(default, w_normal,
                          atol=1e-2), "Default should use normal."
    assert not torch.allclose(w_normal, wo_normal,
                              atol=1e-2), "wo_normal should not use normal."
    assert torch.allclose(
        w_normal, F.normalize(wo_normal, p=2, dim=-1),
        atol=1e-2), "w_normal should be close to normal(wo_normal)."