lorasa-policy / agent_server.py
Syeam Bin Abdullah
Upload folder using huggingface_hub
7858a1a verified
Raw History Blame Contribute Delete
5.6 kB
#!/usr/bin/env python3
"""
Cap'n Proto RPC Server for Agent Interface.
Receives observations as structured Observation messages containing Tensor entries
so agents can work with both state vectors and rich sensory data without pickle.
"""
import asyncio
import os
import capnp
import numpy as np
import torch
# Load the schema
schema_file = os.path.join(os.path.dirname(__file__), "agent.capnp")
agent_capnp = capnp.load(schema_file)
# Default network configuration
DEFAULT_RPC_ADDRESS = "127.0.0.1"
DEFAULT_RPC_PORT = 8000
_TRAVERSAL_WORDS = 100 * 1024 * 1024 # match client; tune appropriately
class AgentServer(agent_capnp.Agent.Server):
"""Cap'n Proto server implementation for AgentInterface"""
def __init__(self, agent):
self.agent = agent
async def act(self, obs, **kwargs):
"""Handle act RPC call. 'obs' is an Observation struct containing Tensor entries."""
try:
entries = list(obs.entries)
def tensor_to_numpy(tensor_msg) -> np.ndarray:
"""Convert Cap'n Proto tensor to numpy array with proper dtype handling."""
try:
dtype = np.dtype(tensor_msg.dtype)
array = np.frombuffer(
tensor_msg.data, dtype=dtype
).reshape(tuple(tensor_msg.shape))
# Ensure contiguous array for better performance
array = np.ascontiguousarray(array.copy())
return array
except Exception as e:
raise
if len(entries) == 1 and entries[0].key == "__value__":
obs_payload = tensor_to_numpy(entries[0].tensor)
else:
obs_payload = {
entry.key: tensor_to_numpy(entry.tensor) for entry in entries
}
# call the underlying agent synchronously
try:
action_tensor = self.agent.act(obs_payload)
except Exception as e:
raise
# convert to numpy
if isinstance(action_tensor, torch.Tensor):
action_np = action_tensor.detach().cpu().numpy()
else:
action_np = np.array(action_tensor)
# CRITICAL: Remove batch dimension and ensure proper shape
# The evaluator expects a 1D array with shape (4,), not (1, 4) or (4, 1)
original_shape = action_np.shape
if action_np.ndim == 2:
# 2D array: remove batch dimension
if action_np.shape[0] == 1:
action_np = action_np[0] # Take first row: [1, 4] -> [4]
elif action_np.shape[1] == 1:
action_np = action_np[:, 0] # Take first column: [4, 1] -> [4]
else:
# Flatten if neither dimension is 1
action_np = action_np.flatten()
elif action_np.ndim > 2:
# Higher dimensional: flatten
action_np = action_np.flatten()
elif action_np.ndim == 0:
# Scalar: convert to 1D array
action_np = np.array([action_np])
# Final check: ensure it's 1D
if action_np.ndim != 1:
action_np = action_np.flatten()
# Validate action shape (should be 4 for Meta-World)
if action_np.shape[0] != 4:
if action_np.size >= 4:
action_np = action_np[:4] # Take first 4 elements
else:
# Pad with zeros if too small
padded = np.zeros(4, dtype=action_np.dtype)
padded[:action_np.size] = action_np
action_np = padded
# Build response Tensor
response = agent_capnp.Tensor.new_message()
response.data = action_np.tobytes()
response.shape = [int(s) for s in action_np.shape]
response.dtype = str(action_np.dtype)
return response
except Exception as e:
raise
async def reset(self, **kwargs):
try:
self.agent.reset()
except Exception:
raise
async def ping(self, message, **kwargs):
return "pong"
async def serve(agent, address=DEFAULT_RPC_ADDRESS, port=DEFAULT_RPC_PORT):
"""Serve the agent using asyncio approach"""
async def new_connection(stream):
try:
server = capnp.TwoPartyServer(
stream,
bootstrap=AgentServer(agent),
traversal_limit_in_words=_TRAVERSAL_WORDS,
)
await server.on_disconnect()
except Exception:
pass
server = await capnp.AsyncIoStream.create_server(new_connection, address, port)
print(f"Server running on {address}:{port}")
try:
async with server:
await server.serve_forever()
except Exception:
pass
def start_server(agent, address=DEFAULT_RPC_ADDRESS, port=DEFAULT_RPC_PORT):
async def run_server_with_kj():
async with capnp.kj_loop():
await serve(agent, address, port)
try:
asyncio.run(run_server_with_kj())
except KeyboardInterrupt:
pass
def run_server_in_process(agent, address=DEFAULT_RPC_ADDRESS, port=DEFAULT_RPC_PORT):
async def run_with_kj():
async with capnp.kj_loop():
await serve(agent, address, port)
asyncio.run(run_with_kj())