test_embedding_long_text.py 13 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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
322
323
324
325
326
327
328
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
362
363
364
365
366
367
368
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Test cases for long text embedding with automatic chunking mechanism.

This test suite validates vLLM's automatic chunking functionality for handling
text inputs that exceed the model's maximum token length, specifically targeting
the intfloat/multilingual-e5-small model (max token length: 512).
"""

import random

import openai
import pytest
import pytest_asyncio

from vllm.entrypoints.openai.protocol import EmbeddingResponse

from ...utils import RemoteOpenAIServer


def _generate_random_text(word_count: int) -> str:
    """Generate random text with approximately the specified word count."""
    # Common English words with focus on verbs and nouns for realistic text
    common_words = [
        # Essential articles and pronouns (minimal)
        "the",
        "and",
        "you",
        "they",
        "this",
        "that",
        "these",
        "those",

        # Action verbs
        "create",
        "build",
        "develop",
        "design",
        "implement",
        "execute",
        "analyze",
        "process",
        "generate",
        "calculate",
        "evaluate",
        "optimize",
        "transform",
        "integrate",
        "configure",
        "deploy",
        "monitor",
        "manage",
        "discover",
        "explore",
        "investigate",
        "research",
        "study",
        "examine",
        "improve",
        "enhance",
        "upgrade",
        "modify",
        "update",
        "maintain",
        "solve",
        "resolve",
        "handle",
        "address",
        "tackle",
        "overcome",
        "communicate",
        "collaborate",
        "coordinate",
        "organize",
        "plan",
        "achieve",
        "accomplish",
        "complete",
        "finish",
        "deliver",
        "provide",

        # Technology and science nouns
        "system",
        "application",
        "software",
        "hardware",
        "network",
        "database",
        "algorithm",
        "model",
        "framework",
        "platform",
        "interface",
        "protocol",
        "architecture",
        "infrastructure",
        "component",
        "module",
        "service",
        "technology",
        "innovation",
        "solution",
        "methodology",
        "approach",
        "artificial",
        "intelligence",
        "machine",
        "learning",
        "neural",
        "network",
        "computer",
        "processor",
        "memory",
        "storage",
        "computation",
        "data",
        "information",
        "knowledge",
        "insight",
        "pattern",
        "trend",
        "analysis",
        "research",
        "development",
        "engineering",
        "science",
        "mathematics",
        "statistics",
        "probability",
        "optimization",
        "performance",
        "efficiency",

        # General nouns
        "project",
        "team",
        "organization",
        "company",
        "business",
        "industry",
        "market",
        "customer",
        "user",
        "client",
        "product",
        "feature",
        "function",
        "requirement",
        "specification",
        "documentation",
        "report",
        "result",
        "outcome",
        "impact",
        "benefit",
        "advantage",
        "challenge",
        "problem",
        "opportunity",
        "strategy",
        "goal",
        "objective",
        "target",
        "milestone",
        "process",
        "procedure",
        "workflow",
        "pipeline",
        "operation",
        "task",
        "activity",
        "event",
        "session",
        "meeting",
        "discussion",
        "decision"
    ]

    words = []
    for _ in range(word_count):
        words.append(random.choice(common_words))

    # Add some punctuation for more realistic text
    text = " ".join(words)
    # Add periods every 10-20 words
    words_list = text.split()
    result = []
    for i, word in enumerate(words_list):
        result.append(word)
        if ((i + 1) % random.randint(10, 20) == 0 and i < len(words_list) - 1):
            result[-1] += "."

    return " ".join(result)


MODEL_NAME = "intfloat/multilingual-e5-small"
DTYPE = "bfloat16"

# Test text: Generate text with approximately 1500 words to exceed 1024 tokens
LONG_TEXT_1500_WORDS = _generate_random_text(1500)

# Test text: Generate text with approximately 2500 words to exceed 2048 tokens
LONG_TEXT_2500_WORDS = _generate_random_text(2500)


@pytest.fixture(scope="module")
def server_with_chunked_processing():
    """Start server with automatic chunking processing enabled."""
    args = [
        "--runner",
        "pooling",
        "--dtype",
        DTYPE,
        "--enforce-eager",
        "--max-model-len",
        "512",  # Set smaller max_model_len to trigger chunking mechanism
        '--override-pooler-config',
        ('{"pooling_type": "MEAN", "normalize": true, '
         '"enable_chunked_processing": true, "max_embed_len": 10000}'),
        "--gpu-memory-utilization",
        "0.8",
    ]

    with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
        yield remote_server


@pytest_asyncio.fixture
async def client_with_chunked_processing(server_with_chunked_processing):
    """Create async client with chunking processing support."""
    async with server_with_chunked_processing.get_async_client(
    ) as async_client:
        yield async_client


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_long_text_embedding_1500_chars(
        client_with_chunked_processing: openai.AsyncOpenAI, model_name: str):
    """Test embedding processing for ~1500 character long text 
    (~1028 tokens, exceeding 512 token limit)."""

    # Verify text length
    # Verify text has sufficient word count (approximately 1500 words)
    word_count = len(LONG_TEXT_1500_WORDS.split())
    assert word_count >= 1400, (
        f"Test text word count insufficient: {word_count} words")

    # Send embedding request
    embedding_response = await client_with_chunked_processing.embeddings.create(
        model=model_name,
        input=[LONG_TEXT_1500_WORDS],
        encoding_format="float",
    )

    # Verify response structure
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

    assert embeddings.id is not None
    assert len(embeddings.data) == 1
    assert len(embeddings.data[0].embedding
               ) == 384  # multilingual-e5-small embedding dimension
    assert embeddings.usage.completion_tokens == 0
    # Due to chunked processing, token count should
    # reflect actual processed tokens
    # With ~1500 words, we expect roughly
    # 1024+ tokens (exceeding 512 token limit)
    # Should exceed single chunk limit of 512
    assert embeddings.usage.prompt_tokens > 800
    assert embeddings.usage.total_tokens == embeddings.usage.prompt_tokens

    # Verify embedding vector validity
    embedding_vector = embeddings.data[0].embedding
    assert all(
        isinstance(x, float)
        for x in embedding_vector), "Embedding vector should contain floats"
    assert not all(
        x == 0
        for x in embedding_vector), "Embedding vector should not be all zeros"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_long_text_embedding_2500_chars(
        client_with_chunked_processing: openai.AsyncOpenAI, model_name: str):
    """Test embedding processing for ~2500 character long text
    (~2048 tokens, requiring multiple chunks)."""

    # Verify text length
    # Verify text has sufficient word count (approximately 2500 words)
    word_count = len(LONG_TEXT_2500_WORDS.split())
    assert word_count >= 2300, (
        f"Test text word count insufficient: {word_count} words")

    # Send embedding request
    embedding_response = await client_with_chunked_processing.embeddings.create(
        model=model_name,
        input=[LONG_TEXT_2500_WORDS],
        encoding_format="float",
    )

    # Verify response structure
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

    assert embeddings.id is not None
    assert len(embeddings.data) == 1
    assert len(embeddings.data[0].embedding
               ) == 384  # multilingual-e5-small embedding dimension
    assert embeddings.usage.completion_tokens == 0
    # Due to chunked processing, token count should
    # reflect actual processed tokens
    # With ~2500 words, we expect
    # roughly 2048+ tokens (requiring multiple chunks)
    # Should require multiple chunks for processing
    assert embeddings.usage.prompt_tokens > 1500
    assert embeddings.usage.total_tokens == embeddings.usage.prompt_tokens

    # Verify embedding vector validity
    embedding_vector = embeddings.data[0].embedding
    assert all(
        isinstance(x, float)
        for x in embedding_vector), "Embedding vector should contain floats"
    assert not all(
        x == 0
        for x in embedding_vector), "Embedding vector should not be all zeros"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_batch_long_text_embedding(
        client_with_chunked_processing: openai.AsyncOpenAI, model_name: str):
    """Test batch long text embedding processing."""

    input_texts = [
        LONG_TEXT_1500_WORDS,
        LONG_TEXT_2500_WORDS,
        "This is a short text test.",  # Short text for comparison
    ]

    # Send batch embedding request
    embedding_response = await client_with_chunked_processing.embeddings.create(
        model=model_name,
        input=input_texts,
        encoding_format="float",
    )

    # Verify response structure
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

    assert embeddings.id is not None
    assert len(embeddings.data) == 3  # Three input texts

    # Verify each embedding dimension
    for i, embedding_data in enumerate(embeddings.data):
        assert len(embedding_data.embedding) == 384
        assert embedding_data.index == i

        # Verify embedding vector validity
        embedding_vector = embedding_data.embedding
        assert all(isinstance(x, float) for x in embedding_vector)
        assert not all(x == 0 for x in embedding_vector)

    # Verify token usage
    assert embeddings.usage.completion_tokens == 0
    # Total token count should be very substantial
    assert embeddings.usage.prompt_tokens > 1000
    assert embeddings.usage.total_tokens == embeddings.usage.prompt_tokens


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_chunked_vs_normal_consistency(
        client_with_chunked_processing: openai.AsyncOpenAI, model_name: str):
    """Test consistency between chunked and
    normal processing (using short text)."""

    # Use a short text within the 512 token limit
    short_text = ("Artificial intelligence technology is changing our world, "
                  "bringing unprecedented opportunities and challenges.")

    # Send embedding request
    embedding_response = await client_with_chunked_processing.embeddings.create(
        model=model_name,
        input=[short_text],
        encoding_format="float",
    )

    # Verify response structure
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

    assert embeddings.id is not None
    assert len(embeddings.data) == 1
    assert len(embeddings.data[0].embedding) == 384
    assert embeddings.usage.completion_tokens == 0
    # Short text should not require chunked processing
    assert embeddings.usage.prompt_tokens < 512
    assert embeddings.usage.total_tokens == embeddings.usage.prompt_tokens

    # 验证embedding向量的有效性
    embedding_vector = embeddings.data[0].embedding
    assert all(isinstance(x, float) for x in embedding_vector)
    assert not all(x == 0 for x in embedding_vector)


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_chunked_processing_response_format(
        client_with_chunked_processing: openai.AsyncOpenAI, model_name: str):
    """Test response format and structure during chunked processing."""

    # Test with long text to trigger chunking
    embedding_response = await client_with_chunked_processing.embeddings.create(
        model=model_name,
        input=[LONG_TEXT_1500_WORDS],
        encoding_format="float",
    )

    # Verify response structure
    embeddings = EmbeddingResponse.model_validate(
        embedding_response.model_dump(mode="json"))

    assert embeddings.id is not None
    assert len(embeddings.data) == 1
    assert embeddings.data[0].object == "embedding"
    assert embeddings.data[0].index == 0

    # Verify embedding vector properties
    embedding_vector = embeddings.data[0].embedding
    import math
    vector_norm = math.sqrt(sum(x * x for x in embedding_vector))
    # Check that the vector is normalized
    # (default behavior for most embedding models)
    assert 0.8 < vector_norm < 1.2, (
        f"Vector norm should be reasonable, actual: {vector_norm}")