"vscode:/vscode.git/clone" did not exist on "12cdfda79601b9075cb9616e738cb4b437566d6d"
test_embedding.py 13.5 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 pytest_asyncio
10
import requests
11
12
import torch
import torch.nn.functional as F
13

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

20
MODEL_NAME = "intfloat/multilingual-e5-small"
21
DUMMY_CHAT_TEMPLATE = """{% for message in messages %}{{message['role'] + ': ' + message['content'] + '\\n'}}{% endfor %}"""  # noqa: E501
22
DTYPE = "bfloat16"
23
24
25


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

40
    with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
41
        yield remote_server
42
43


44
@pytest_asyncio.fixture
45
46
async def client(server):
    async with server.get_async_client() as async_client:
47
        yield async_client
48
49


50
51
@pytest.fixture(scope="module")
def hf_model(hf_runner):
52
    with hf_runner(MODEL_NAME, dtype=DTYPE, is_sentence_transformer=True) as hf_model:
53
54
55
        yield hf_model


56
@pytest.mark.asyncio
57
@pytest.mark.parametrize("model_name", [MODEL_NAME])
58
async def test_single_embedding(hf_model, client: openai.AsyncOpenAI, model_name: str):
59
60
61
62
63
    input_texts = [
        "The chef prepared a delicious meal.",
    ]

    # test single embedding
64
    embedding_response = await client.embeddings.create(
65
66
67
68
        model=model_name,
        input=input_texts,
        encoding_format="float",
    )
69
    embeddings = EmbeddingResponse.model_validate(
70
71
        embedding_response.model_dump(mode="json")
    )
72

73
74
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
75
    assert len(embeddings.data[0].embedding) == 384
76
    assert embeddings.usage.completion_tokens == 0
77
78
    assert embeddings.usage.prompt_tokens == 11
    assert embeddings.usage.total_tokens == 11
79

80
    vllm_outputs = [d.embedding for d in embeddings.data]
81
    run_embedding_correctness_test(hf_model, input_texts, vllm_outputs)
82

83
84
    # test using token IDs
    input_tokens = [1, 1, 1, 1, 1]
85
    embedding_response = await client.embeddings.create(
86
87
88
89
        model=model_name,
        input=input_tokens,
        encoding_format="float",
    )
90
    embeddings = EmbeddingResponse.model_validate(
91
92
        embedding_response.model_dump(mode="json")
    )
93

94
95
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
96
    assert len(embeddings.data[0].embedding) == 384
97
98
99
100
101
102
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 5
    assert embeddings.usage.total_tokens == 5


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

120
121
    assert embeddings.id is not None
    assert len(embeddings.data) == 3
122
    assert len(embeddings.data[0].embedding) == 384
123
    assert embeddings.usage.completion_tokens == 0
124
125
    assert embeddings.usage.prompt_tokens == 33
    assert embeddings.usage.total_tokens == 33
126

127
    vllm_outputs = [d.embedding for d in embeddings.data]
128
    run_embedding_correctness_test(hf_model, input_texts, vllm_outputs)
129

130
    # test list[list[int]]
131
132
133
134
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
    embeddings = EmbeddingResponse.model_validate(
143
144
        embedding_response.model_dump(mode="json")
    )
145

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


@pytest.mark.asyncio
155
@pytest.mark.parametrize("model_name", [MODEL_NAME])
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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.",
        },
    ]
173

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

    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},
    )
200
    completion_embeddings = EmbeddingResponse.model_validate(
201
202
        completion_response.model_dump(mode="json")
    )
203

204
205
206
    assert chat_embeddings.id is not None
    assert completion_embeddings.id is not None
    assert chat_embeddings.created <= completion_embeddings.created
207
208
209
    assert chat_embeddings.model_dump(exclude={"id", "created"}) == (
        completion_embeddings.model_dump(exclude={"id", "created"})
    )
210
211
212
213


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
214
215
216
async def test_batch_base64_embedding(
    hf_model, client: openai.AsyncOpenAI, model_name: str
):
217
218
    input_texts = [
        "Hello my name is",
219
        "The best thing about vLLM is that it supports many different models",
220
221
    ]

222
223
224
    responses_float = await client.embeddings.create(
        input=input_texts, model=model_name, encoding_format="float"
    )
225
    float_data = [d.embedding for d in responses_float.data]
226
    run_embedding_correctness_test(hf_model, input_texts, float_data)
227

228
229
230
    responses_base64 = await client.embeddings.create(
        input=input_texts, model=model_name, encoding_format="base64"
    )
231
    base64_data = []
232
    for data in responses_base64.data:
233
        base64_data.append(
234
235
            np.frombuffer(base64.b64decode(data.embedding), dtype="float32").tolist()
        )
236

237
    run_embedding_correctness_test(hf_model, input_texts, base64_data)
238
239

    # Default response is float32 decoded from base64 by OpenAI Client
240
241
242
    responses_default = await client.embeddings.create(
        input=input_texts, model=model_name
    )
243
    default_data = [d.embedding for d in responses_default.data]
244
    run_embedding_correctness_test(hf_model, input_texts, default_data)
245
246
247


@pytest.mark.asyncio
248
@pytest.mark.parametrize("model_name", [MODEL_NAME])
249
async def test_single_embedding_truncation(client: openai.AsyncOpenAI, model_name: str):
250
251
252
253
254
    input_texts = [
        "Como o Brasil pode fomentar o desenvolvimento de modelos de IA?",
    ]

    # test single embedding
255
    embedding_response = await client.embeddings.create(
256
257
        model=model_name, input=input_texts, extra_body={"truncate_prompt_tokens": 10}
    )
258
    embeddings = EmbeddingResponse.model_validate(
259
260
        embedding_response.model_dump(mode="json")
    )
261

262
263
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
264
    assert len(embeddings.data[0].embedding) == 384
265
266
267
268
269
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 10
    assert embeddings.usage.total_tokens == 10

    input_tokens = [
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
        1,
        24428,
        289,
        18341,
        26165,
        285,
        19323,
        283,
        289,
        26789,
        3871,
        28728,
        9901,
        340,
        2229,
        385,
        340,
        315,
        28741,
        28804,
        2,
291
    ]
292
    embedding_response = await client.embeddings.create(
293
294
        model=model_name, input=input_tokens, extra_body={"truncate_prompt_tokens": 10}
    )
295
    embeddings = EmbeddingResponse.model_validate(
296
297
        embedding_response.model_dump(mode="json")
    )
298
299
300

    assert embeddings.id is not None
    assert len(embeddings.data) == 1
301
    assert len(embeddings.data[0].embedding) == 384
302
303
304
305
306
307
    assert embeddings.usage.completion_tokens == 0
    assert embeddings.usage.prompt_tokens == 10
    assert embeddings.usage.total_tokens == 10


@pytest.mark.asyncio
308
@pytest.mark.parametrize("model_name", [MODEL_NAME])
309
310
311
async def test_single_embedding_truncation_invalid(
    client: openai.AsyncOpenAI, model_name: str
):
312
313
314
315
316
    input_texts = [
        "Como o Brasil pode fomentar o desenvolvimento de modelos de IA?",
    ]

    with pytest.raises(openai.BadRequestError):
317
        response = await client.embeddings.create(
318
319
            model=model_name,
            input=input_texts,
320
321
            extra_body={"truncate_prompt_tokens": 8193},
        )
322
        assert "error" in response.object
323
324
325
326
        assert (
            "truncate_prompt_tokens value is greater than max_model_len. "
            "Please, select a smaller truncation size." in response.message
        )
327
328
329


@pytest.mark.asyncio
330
async def test_invocations(server: RemoteOpenAIServer, client: openai.AsyncOpenAI):
331
332
333
334
335
336
337
338
339
340
341
342
    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)

343
344
345
    invocation_response = requests.post(
        server.url_for("invocations"), json=request_args
    )
346
347
348
349
350
351
    invocation_response.raise_for_status()

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

    assert completion_output.keys() == invocation_output.keys()
352
353
354
    for completion_data, invocation_data in zip(
        completion_output["data"], invocation_output["data"]
    ):
355
        assert completion_data.keys() == invocation_data.keys()
356
357
358
359
360
361
        check_embeddings_close(
            embeddings_0_lst=[completion_data["embedding"]],
            embeddings_1_lst=[invocation_data["embedding"]],
            name_0="completion",
            name_1="invocation",
        )
362
363
364
365


@pytest.mark.asyncio
async def test_invocations_conversation(server: RemoteOpenAIServer):
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    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.",
        },
    ]
380
381
382
383
384
385
386

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

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

390
391
392
    invocation_response = requests.post(
        server.url_for("invocations"), json=request_args
    )
393
394
395
396
397
398
    invocation_response.raise_for_status()

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

    assert chat_output.keys() == invocation_output.keys()
399
400
401
    for chat_data, invocation_data in zip(
        chat_output["data"], invocation_output["data"]
    ):
402
        assert chat_data.keys() == invocation_data.keys()
403
404
405
406
407
408
        check_embeddings_close(
            embeddings_0_lst=[chat_data["embedding"]],
            embeddings_1_lst=[invocation_data["embedding"]],
            name_0="chat",
            name_1="invocation",
        )
409
410
411
412
413
414
415
416
417
418
419
420


@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",
421
            "normalize": normalize,
422
423
        }

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

427
        return torch.tensor([x["embedding"] for x in outputs["data"]])
428
429
430
431
432

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

433
434
435
436
437
438
439
    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)."
    )