Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions verl/experimental/agent_loop/agent_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self, config: DictConfig, server_handles: list[ray.actor.ActorHandl
random.shuffle(self.server_handles)

# Least requests load balancing
self.weighted_serveres = [[0, (hash(server), server)] for server in server_handles]
self.weighted_serveres = [[0, idx, server] for idx, server in enumerate(self.server_handles)]
heapq.heapify(self.weighted_serveres)

# LRU cache to map request_id to server
Expand All @@ -81,7 +81,7 @@ def _choose_server(self, request_id: str) -> ray.actor.ActorHandle:
if request_id in self.request_id_to_server:
return self.request_id_to_server[request_id]

server = self.weighted_serveres[0][1][1]
_, _, server = self.weighted_serveres[0]
self.weighted_serveres[0][0] += 1
heapq.heapreplace(self.weighted_serveres, self.weighted_serveres[0])
self.request_id_to_server[request_id] = server
Comment on lines +84 to 87
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current implementation for updating the heap is a bit obscure. It modifies the top element of the heap in-place, which violates the heap invariant, and then uses heapq.heapreplace to restore it. While this works, it's not very readable and relies on implementation details of heapq.heapreplace.

A more idiomatic and clearer approach would be to use heapq.heappop followed by heapq.heappush. This makes the intent of the code much more explicit and improves maintainability.

Suggested change
_, _, server = self.weighted_serveres[0]
self.weighted_serveres[0][0] += 1
heapq.heapreplace(self.weighted_serveres, self.weighted_serveres[0])
self.request_id_to_server[request_id] = server
count, idx, server = heapq.heappop(self.weighted_serveres)
heapq.heappush(self.weighted_serveres, [count + 1, idx, server])
self.request_id_to_server[request_id] = server

Expand Down
Loading