-
Notifications
You must be signed in to change notification settings - Fork 596
[Feature] add dealer manager to reuse the connection #3471
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ltd0924
wants to merge
22
commits into
PaddlePaddle:develop
Choose a base branch
from
ltd0924:api_server
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+360
−25
Open
Changes from 9 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
1867646
[BugFix] fix control signal release failed
ltd0924 f479902
[BugFix] fix control signal release failed
ltd0924 64ba4bb
update
ltd0924 1b775ad
update
ltd0924 6ba2618
update
ltd0924 35218c2
Merge branch 'develop' into api_server
ltd0924 314ad93
Merge branch 'PaddlePaddle:develop' into api_server
ltd0924 7ccd241
[Feature] add dealer manager to reuse the connection
ltd0924 4d4c4cb
fix
ltd0924 91d8a5f
fix
ltd0924 faef052
fix
ltd0924 a18cdb6
fix
ltd0924 e7458d3
Merge branch 'develop' into api_server
ltd0924 b9841a9
fix
ltd0924 23e922a
fix
ltd0924 3de3687
Merge branch 'develop' into api_server
ltd0924 51bd8a2
Create test_dealer_connection_manager.py
ltd0924 99bec19
Delete test/entrypoints/openai directory
ltd0924 d921e1f
Merge branch 'develop' into api_server
ltd0924 62115e5
Update test_dealer_connection_manager.py
ltd0924 a306acd
Update test_dealer_connection_manager.py
ltd0924 0947726
Merge branch 'develop' into api_server
ltd0924 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
|
@@ -19,10 +19,7 @@ | |||
import uuid | ||||
from typing import List, Optional | ||||
|
||||
import aiozmq | ||||
import msgpack | ||||
import numpy as np | ||||
from aiozmq import zmq | ||||
|
||||
from fastdeploy.engine.request import RequestOutput | ||||
from fastdeploy.entrypoints.openai.protocol import ( | ||||
|
@@ -52,6 +49,12 @@ def __init__(self, engine_client, pid, ips, max_waiting_time): | |||
else: | ||||
self.master_ip = self.master_ip.split(",")[0] | ||||
|
||||
async def _ensure_connection_manager(self): | ||||
"""ensure connection manager initialized""" | ||||
if not self.engine_client.connection_initialized: | ||||
await self.engine_client.connection_manager.initialize() | ||||
self.engine_client.connection_initialized = True | ||||
|
||||
def _check_master(self): | ||||
if self.master_ip is None: | ||||
return True | ||||
|
@@ -169,7 +172,8 @@ async def completion_full_generator( | |||
try: | ||||
request_ids = [f"{request_id}-{i}" for i in range(num_choices)] | ||||
# create dealer | ||||
dealer = await aiozmq.create_zmq_stream(zmq.DEALER, connect=f"ipc:///dev/shm/router_{self.pid}.ipc") | ||||
await self._ensure_connection_manager() | ||||
dealer, response_queue = await self.engine.connection_manager.get_connection(request_id) | ||||
|
||||
for rid in request_ids: | ||||
dealer.write([b"", rid.encode("utf-8")]) | ||||
|
@@ -182,7 +186,7 @@ async def completion_full_generator( | |||
current_waiting_time = 0 | ||||
while num_choices > 0: | ||||
try: | ||||
raw_data = await asyncio.wait_for(dealer.read(), timeout=10) | ||||
response = await asyncio.wait_for(response_queue.get(), timeout=10) | ||||
current_waiting_time = 0 | ||||
except asyncio.TimeoutError: | ||||
current_waiting_time += 10 | ||||
|
@@ -194,7 +198,7 @@ async def completion_full_generator( | |||
current_waiting_time = 0 | ||||
await asyncio.sleep(0.1) | ||||
continue | ||||
response = msgpack.unpackb(raw_data[-1]) | ||||
|
||||
for data in response: | ||||
rid = int(data["request_id"].split("-")[-1]) | ||||
if data.get("error_code", 200) != 200: | ||||
|
@@ -239,7 +243,8 @@ async def completion_full_generator( | |||
finally: | ||||
self.engine_client.semaphore.release() | ||||
if dealer is not None: | ||||
dealer.close() | ||||
await self.engine_client.connection_manager.cleanup_request(request_id) | ||||
self.engine_client.semaphore.release() | ||||
ltd0924 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||
|
||||
async def _echo_back_prompt(self, request, res, idx): | ||||
if res["outputs"].get("send_idx", -1) == 0 and request.echo: | ||||
|
@@ -272,7 +277,9 @@ async def completion_stream_generator( | |||
Process the stream completion request. | ||||
""" | ||||
try: | ||||
dealer = await aiozmq.create_zmq_stream(zmq.DEALER, connect=f"ipc:///dev/shm/router_{self.pid}.ipc") | ||||
await self._ensure_connection_manager() | ||||
dealer, response_queue = await self.engine_client.connection_manager.get_connection(request_id) | ||||
dealer.write([b"", request_id.encode("utf-8")]) | ||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This write operation appears to be misplaced. The write should happen after the loop that creates multiple request IDs (lines 284-290), not before it.
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||
|
||||
for i in range(num_choices): | ||||
req_id = f"{request_id}-{i}" | ||||
|
@@ -296,7 +303,7 @@ async def completion_stream_generator( | |||
current_waiting_time = 0 | ||||
while num_choices > 0: | ||||
try: | ||||
raw_data = await asyncio.wait_for(dealer.read(), timeout=10) | ||||
response = await asyncio.wait_for(response_queue.get(), timeout=10) | ||||
current_waiting_time = 0 | ||||
except asyncio.TimeoutError: | ||||
current_waiting_time += 10 | ||||
|
@@ -309,7 +316,6 @@ async def completion_stream_generator( | |||
await asyncio.sleep(0.1) | ||||
continue | ||||
|
||||
response = msgpack.unpackb(raw_data[-1]) | ||||
for res in response: | ||||
idx = int(res["request_id"].split("-")[-1]) | ||||
if res.get("error_code", 200) != 200: | ||||
|
@@ -436,7 +442,8 @@ async def completion_stream_generator( | |||
del request | ||||
self.engine_client.semaphore.release() | ||||
if dealer is not None: | ||||
dealer.close() | ||||
await self.engine_client.connection_manager.cleanup_request(request_id) | ||||
self.engine_client.semaphore.release() | ||||
ltd0924 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||
yield "data: [DONE]\n\n" | ||||
|
||||
def request_output_to_completion_response( | ||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
""" | ||
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License" | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
""" | ||
|
||
import asyncio | ||
import heapq | ||
import random | ||
|
||
import aiozmq | ||
import msgpack | ||
import zmq | ||
|
||
from fastdeploy.utils import api_server_logger | ||
|
||
|
||
class DealerConnectionManager: | ||
""" | ||
Manager for dealer connections, supporting multiplexing and connection reuse | ||
""" | ||
|
||
def __init__(self, pid, max_connections=10): | ||
self.pid = pid | ||
self.max_connections = max(max_connections, 10) | ||
self.connections = [] | ||
self.connection_load = [] | ||
self.connection_heap = [] | ||
self.request_map = {} # request_id -> response_queue | ||
self.lock = asyncio.Lock() | ||
self.connection_tasks = [] | ||
self.running = False | ||
|
||
async def initialize(self): | ||
"""initialize all connections""" | ||
self.running = True | ||
for index in range(self.max_connections): | ||
await self._add_connection(index) | ||
api_server_logger.info(f"Started {self.max_connections} connections") | ||
|
||
async def _add_connection(self, index): | ||
"""create a new connection and start listening task""" | ||
try: | ||
dealer = await aiozmq.create_zmq_stream( | ||
zmq.DEALER, | ||
connect=f"ipc:///dev/shm/router_{self.pid}.ipc", | ||
) | ||
async with self.lock: | ||
self.connections.append(dealer) | ||
self.connection_load.append(0) | ||
heapq.heappush(self.connection_heap, (0, index)) | ||
|
||
# start listening | ||
task = asyncio.create_task(self._listen_connection(dealer, index)) | ||
self.connection_tasks.append(task) | ||
return True | ||
except Exception as e: | ||
api_server_logger.error(f"Failed to create dealer: {str(e)}") | ||
return False | ||
|
||
async def _listen_connection(self, dealer, conn_index): | ||
""" | ||
listen for messages from the dealer connection | ||
""" | ||
while self.running: | ||
try: | ||
raw_data = await dealer.read() | ||
response = msgpack.unpackb(raw_data[-1]) | ||
request_id = response[-1]["request_id"] | ||
async with self.lock: | ||
if request_id in self.request_map: | ||
await self.request_map[request_id].put(response) | ||
if response[-1]["finished"]: | ||
ltd0924 marked this conversation as resolved.
Show resolved
Hide resolved
ltd0924 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self._update_load(conn_index, -1) | ||
except Exception as e: | ||
api_server_logger.error(f"Listener error: {str(e)}") | ||
break | ||
|
||
def _update_load(self, conn_index, delta): | ||
"""Update connection load and maintain the heap""" | ||
self.connection_load[conn_index] += delta | ||
heapq.heapify(self.connection_heap) | ||
|
||
# For Debugging purposes | ||
if random.random() < 0.01: | ||
min_load = self.connection_heap[0][0] if self.connection_heap else 0 | ||
max_load = max(self.connection_load) if self.connection_load else 0 | ||
api_server_logger.debug(f"Connection load update: min={min_load}, max={max_load}") | ||
|
||
def _get_least_loaded_connection(self): | ||
""" | ||
Get the least loaded connection | ||
""" | ||
if not self.connection_heap: | ||
return None | ||
|
||
load, conn_index = self.connection_heap[0] | ||
self._update_load(conn_index, 1) | ||
|
||
return self.connections[conn_index] | ||
|
||
async def get_connection(self, request_id): | ||
"""get a connection for the request""" | ||
|
||
response_queue = asyncio.Queue() | ||
|
||
async with self.lock: | ||
self.request_map[request_id] = response_queue | ||
dealer = self._get_least_loaded_connection() | ||
if not dealer: | ||
raise RuntimeError("No available connections") | ||
|
||
return dealer, response_queue | ||
|
||
async def cleanup_request(self, request_id): | ||
""" | ||
clean up the request after it is finished | ||
""" | ||
async with self.lock: | ||
if request_id in self.request_map: | ||
del self.request_map[request_id] | ||
|
||
async def close(self): | ||
""" | ||
close all connections and tasks | ||
""" | ||
self.running = False | ||
|
||
for task in self.connection_tasks: | ||
task.cancel() | ||
|
||
async with self.lock: | ||
for dealer in self.connections: | ||
try: | ||
dealer.close() | ||
except: | ||
pass | ||
self.connections.clear() | ||
self.connection_load.clear() | ||
self.request_map.clear() | ||
|
||
api_server_logger.info("All connections and tasks closed") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
workers
parameter is not defined in the init method. This will cause a NameError when initializing the EngineClient.Copilot uses AI. Check for mistakes.