forked from waybarrios/vllm-mlx
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathtest_simple_engine.py
More file actions
214 lines (170 loc) · 7.71 KB
/
test_simple_engine.py
File metadata and controls
214 lines (170 loc) · 7.71 KB
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
# SPDX-License-Identifier: Apache-2.0
"""Tests for SimpleEngine concurrency handling."""
import asyncio
from unittest.mock import MagicMock, patch
import pytest
class TestSimpleEngineConcurrency:
"""Test SimpleEngine lock behavior with concurrent requests."""
@pytest.fixture
def mock_model(self):
"""Create a mock model that tracks concurrent calls."""
model = MagicMock()
model.tokenizer = MagicMock()
model.tokenizer.encode = MagicMock(return_value=[1, 2, 3])
# Track concurrent executions
model._concurrent_count = 0
model._max_concurrent = 0
def generate_side_effect(**kwargs):
model._concurrent_count += 1
model._max_concurrent = max(model._max_concurrent, model._concurrent_count)
# Simulate some work
import time
time.sleep(0.05)
model._concurrent_count -= 1
result = MagicMock()
result.text = "test response"
result.tokens = [1, 2, 3]
result.finish_reason = "stop"
return result
model.generate = MagicMock(side_effect=generate_side_effect)
return model
@pytest.fixture
def mock_llm_model(self):
"""Create a mock LLM model."""
model = MagicMock()
model.tokenizer = MagicMock()
model.tokenizer.encode = MagicMock(return_value=[1, 2, 3])
# Track concurrent executions
model._concurrent_count = 0
model._max_concurrent = 0
def chat_side_effect(**kwargs):
model._concurrent_count += 1
model._max_concurrent = max(model._max_concurrent, model._concurrent_count)
import time
time.sleep(0.05)
model._concurrent_count -= 1
result = MagicMock()
result.text = "test response"
result.tokens = [1, 2, 3]
result.finish_reason = "stop"
return result
model.chat = MagicMock(side_effect=chat_side_effect)
return model
@pytest.mark.asyncio
async def test_lock_prevents_concurrent_generate(self, mock_model):
"""Test that the lock prevents concurrent generate calls."""
from vllm_mlx.engine.simple import SimpleEngine
with patch("vllm_mlx.engine.simple.is_mllm_model", return_value=False):
engine = SimpleEngine("test-model")
engine._model = mock_model
engine._loaded = True
# Launch multiple concurrent generate calls
tasks = [
engine.generate(prompt=f"test prompt {i}", max_tokens=10)
for i in range(5)
]
await asyncio.gather(*tasks)
# With the lock, max concurrent should be 1
assert mock_model._max_concurrent == 1, (
f"Expected max concurrent to be 1, but got {mock_model._max_concurrent}. "
"The lock is not working correctly."
)
@pytest.mark.asyncio
async def test_lock_prevents_concurrent_chat(self, mock_llm_model):
"""Test that the lock prevents concurrent chat calls."""
from vllm_mlx.engine.simple import SimpleEngine
with patch("vllm_mlx.engine.simple.is_mllm_model", return_value=True):
engine = SimpleEngine("test-model")
engine._model = mock_llm_model
engine._is_mllm = True
engine._loaded = True
# Launch multiple concurrent chat calls
tasks = [
engine.chat(
messages=[{"role": "user", "content": f"test {i}"}], max_tokens=10
)
for i in range(5)
]
await asyncio.gather(*tasks)
# With the lock, max concurrent should be 1
assert mock_llm_model._max_concurrent == 1, (
f"Expected max concurrent to be 1, but got {mock_llm_model._max_concurrent}. "
"The lock is not working correctly."
)
@pytest.mark.asyncio
async def test_lock_serializes_stream_generate(self, mock_model):
"""Test that stream_generate uses the same lock as other methods."""
from vllm_mlx.engine.simple import SimpleEngine
def stream_generate_side_effect(**kwargs):
# Yield a few chunks
for i in range(3):
chunk = MagicMock(spec=[])
chunk.text = f"chunk{i}"
chunk.prompt_tokens = 5
chunk.finished = i == 2
chunk.finish_reason = "stop" if i == 2 else None
yield chunk
mock_model.stream_generate = MagicMock(side_effect=stream_generate_side_effect)
with patch("vllm_mlx.engine.simple.is_mllm_model", return_value=False):
engine = SimpleEngine("test-model")
engine._model = mock_model
engine._loaded = True
# Test that stream_generate acquires the lock
# by checking if it blocks when lock is already held
lock_acquired = asyncio.Event()
stream_started = asyncio.Event()
async def hold_lock():
async with engine._generation_lock:
lock_acquired.set()
# Wait until stream tries to start
await asyncio.sleep(0.1)
async def try_stream():
# Wait for lock to be held
await lock_acquired.wait()
stream_started.set()
# This should block until hold_lock releases
result = []
async for chunk in engine.stream_generate(prompt="test", max_tokens=10):
result.append(chunk)
return result
# Start both tasks
hold_task = asyncio.create_task(hold_lock())
stream_task = asyncio.create_task(try_stream())
# Wait a bit for stream to try to acquire lock
await asyncio.sleep(0.05)
# Stream should have started but be blocked on the lock
assert stream_started.is_set(), "Stream should have attempted to start"
# Stream task should not be done yet (blocked on lock)
assert not stream_task.done(), "Stream should be blocked waiting for lock"
# Let hold_lock finish
await hold_task
# Now stream should complete
result = await stream_task
assert len(result) == 3, f"Expected 3 chunks, got {len(result)}"
@pytest.mark.asyncio
async def test_engine_initialization_creates_lock(self):
"""Test that SimpleEngine creates a lock on initialization."""
from vllm_mlx.engine.simple import SimpleEngine
with patch("vllm_mlx.engine.simple.is_mllm_model", return_value=False):
engine = SimpleEngine("test-model")
assert hasattr(engine, "_generation_lock")
assert isinstance(engine._generation_lock, asyncio.Lock)
@pytest.mark.asyncio
async def test_requests_complete_in_order(self, mock_model):
"""Test that concurrent requests complete (may be in any order due to lock)."""
from vllm_mlx.engine.simple import SimpleEngine
with patch("vllm_mlx.engine.simple.is_mllm_model", return_value=False):
engine = SimpleEngine("test-model")
engine._model = mock_model
engine._loaded = True
# Launch multiple concurrent generate calls
results = await asyncio.gather(
*[
engine.generate(prompt=f"test prompt {i}", max_tokens=10)
for i in range(3)
]
)
# All requests should complete
assert len(results) == 3
for result in results:
assert result.text == "test response"