lorasa-policy / server.py
Syeam Bin Abdullah
Add Chutes deployment support (chute.py) and update requirements
c262b4d verified
Raw History Blame Contribute Delete
7.2 kB
"""
Kinitro Miner Server for LoRASA Policy
This FastAPI server wraps the LoRASA agent to match the kinitro
miner interface for evaluation.
Usage:
uvicorn server:app --host 0.0.0.0 --port 8000
"""
import time
import uuid
from pathlib import Path
import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
# Import the LoRASA agent
from agent import LoRASAAgent
app = FastAPI(
title="LoRASA Policy Server",
description="Miner policy endpoint for kinitro robotics subnet",
version="1.0.0",
)
# Global agent instance
_agent: LoRASAAgent | None = None
_current_task_config: dict | None = None
_start_time = time.time()
def get_agent() -> LoRASAAgent:
"""Get or initialize the agent."""
global _agent
if _agent is None:
# Use local checkpoints directory
agent_dir = Path(__file__).parent
backbone_path = agent_dir / "checkpoints" / "lorasa_shared_backbone.pt"
adapter_dir = agent_dir / "checkpoints"
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
_agent = LoRASAAgent(
backbone_path=str(backbone_path),
adapter_dir=str(adapter_dir),
device=device,
)
print(f"LoRASA Agent initialized on {device}")
return _agent
# =============================================================================
# Request/Response Models
# =============================================================================
class TaskConfig(BaseModel):
"""Task configuration for episode reset."""
env_id: str | None = None
env_name: str | None = None
task_name: str | None = None
seed: int | None = None
task_id: int | None = None
class ResetRequest(BaseModel):
"""Request body for /reset endpoint."""
task_config: TaskConfig
class ResetResponse(BaseModel):
"""Response body for /reset endpoint."""
status: str = "ok"
episode_id: str | None = None
class ActRequest(BaseModel):
"""Request body for /act endpoint."""
observation: list[float]
images: dict[str, list] | None = None
class ActResponse(BaseModel):
"""Response body for /act endpoint."""
action: list[float]
class HealthResponse(BaseModel):
"""Response body for /health endpoint."""
status: str
model_loaded: bool
uptime_seconds: float
# =============================================================================
# Endpoints
# =============================================================================
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""Health check endpoint."""
try:
agent = get_agent()
return HealthResponse(
status="healthy",
model_loaded=True,
uptime_seconds=time.time() - _start_time,
)
except Exception as e:
return HealthResponse(
status="unhealthy",
model_loaded=False,
uptime_seconds=time.time() - _start_time,
)
@app.post("/reset", response_model=ResetResponse)
async def reset(request: ResetRequest):
"""Reset policy for a new episode."""
global _current_task_config
try:
agent = get_agent()
agent.reset()
_current_task_config = request.task_config.model_dump()
episode_id = uuid.uuid4().hex
return ResetResponse(status="ok", episode_id=episode_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/act", response_model=ActResponse)
async def act(request: ActRequest):
"""Get action for current observation."""
try:
agent = get_agent()
# Build observation dict in the format LoRASAAgent expects
obs_dict = {}
# Proprioceptive observation -> observation.state
# The agent expects [state_4, one_hot_50] in observation.state
proprio = np.array(request.observation, dtype=np.float32)
# Build observation.state: concat proprio with one-hot task encoding
# Get task name to create one-hot
task_name = None
if _current_task_config:
task_name = _current_task_config.get("task_name")
if not task_name:
# Extract from env_id like "metaworld/pick-place-v3"
env_id = _current_task_config.get("env_id")
if env_id and "/" in env_id:
task_name = env_id.split("/")[-1]
# Create one-hot encoding
from model_loader import MT50_TASK_ORDER, get_task_index
one_hot = np.zeros(50, dtype=np.float32)
if task_name:
task_idx = get_task_index(task_name)
if 0 <= task_idx < 50:
one_hot[task_idx] = 1.0
# observation.state = [proprio_4, one_hot_50]
obs_dict["observation.state"] = np.concatenate([proprio, one_hot])
# Also include task_name for the agent
if task_name:
obs_dict["task_name"] = task_name
# Convert images if provided
# Images come as HWC uint8, agent expects CHW uint8
if request.images:
for i, (cam_name, img_data) in enumerate(request.images.items()):
img = np.array(img_data, dtype=np.uint8)
# Convert HWC -> CHW if needed
if img.ndim == 3 and img.shape[-1] == 3:
img = img.transpose(2, 0, 1)
# Store with expected key names
if i == 0:
obs_dict["observation.image"] = img
else:
obs_dict[f"observation.image{i+1}"] = img
else:
# Provide dummy images if not provided (agent expects 2 views)
obs_dict["observation.image"] = np.zeros((3, 84, 84), dtype=np.uint8)
obs_dict["observation.image2"] = np.zeros((3, 84, 84), dtype=np.uint8)
# Get action from agent
action_tensor = agent.act(obs_dict)
# Convert to numpy
if hasattr(action_tensor, 'numpy'):
action = action_tensor.numpy()
else:
action = np.array(action_tensor)
# Ensure 1D
action = action.flatten()
return ActResponse(action=action.tolist())
except Exception as e:
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
# =============================================================================
# Startup/Shutdown
# =============================================================================
@app.on_event("startup")
async def startup():
"""Initialize agent on startup."""
get_agent()
@app.on_event("shutdown")
async def shutdown():
"""Cleanup on shutdown."""
global _agent
_agent = None
# =============================================================================
# Run with uvicorn
# =============================================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)