Syeam Bin Abdullah commited on
Upload folder using huggingface_hub
Browse files- __init__.py +3 -0
- __pycache__/agent.cpython-312.pyc +0 -0
- __pycache__/agent_interface.cpython-312.pyc +0 -0
- __pycache__/agent_server.cpython-312.pyc +0 -0
- __pycache__/main.cpython-312.pyc +0 -0
- __pycache__/model_loader.cpython-312.pyc +0 -0
- __pycache__/models.cpython-312.pyc +0 -0
- __pycache__/server.cpython-312.pyc +0 -0
- agent.capnp +24 -0
- agent.py +351 -0
- agent_interface.py +52 -0
- agent_server.py +167 -0
- checkpoints/lorasa_adapter_assembly-v3.pt +3 -0
- checkpoints/lorasa_adapter_basketball-v3.pt +3 -0
- checkpoints/lorasa_adapter_bin-picking-v3.pt +3 -0
- checkpoints/lorasa_adapter_box-close-v3.pt +3 -0
- checkpoints/lorasa_adapter_button-press-topdown-v3.pt +3 -0
- checkpoints/lorasa_adapter_button-press-topdown-wall-v3.pt +3 -0
- checkpoints/lorasa_adapter_button-press-v3.pt +3 -0
- checkpoints/lorasa_adapter_button-press-wall-v3.pt +3 -0
- checkpoints/lorasa_adapter_coffee-button-v3.pt +3 -0
- checkpoints/lorasa_adapter_coffee-pull-v3.pt +3 -0
- checkpoints/lorasa_adapter_coffee-push-v3.pt +3 -0
- checkpoints/lorasa_adapter_dial-turn-v3.pt +3 -0
- checkpoints/lorasa_adapter_disassemble-v3.pt +3 -0
- checkpoints/lorasa_adapter_door-close-v3.pt +3 -0
- checkpoints/lorasa_adapter_door-lock-v3.pt +3 -0
- checkpoints/lorasa_adapter_door-open-v3.pt +3 -0
- checkpoints/lorasa_adapter_door-unlock-v3.pt +3 -0
- checkpoints/lorasa_adapter_drawer-close-v3.pt +3 -0
- checkpoints/lorasa_adapter_drawer-open-v3.pt +3 -0
- checkpoints/lorasa_adapter_faucet-close-v3.pt +3 -0
- checkpoints/lorasa_adapter_faucet-open-v3.pt +3 -0
- checkpoints/lorasa_shared_backbone.pt +3 -0
- main.py +106 -0
- model_loader.py +124 -0
- models.py +196 -0
- requirements.txt +11 -0
- server.py +240 -0
__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LoRASA agent submission."""
|
| 2 |
+
|
| 3 |
+
|
__pycache__/agent.cpython-312.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
__pycache__/agent_interface.cpython-312.pyc
ADDED
|
Binary file (2.39 kB). View file
|
|
|
__pycache__/agent_server.cpython-312.pyc
ADDED
|
Binary file (8.09 kB). View file
|
|
|
__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (3.89 kB). View file
|
|
|
__pycache__/model_loader.cpython-312.pyc
ADDED
|
Binary file (5.16 kB). View file
|
|
|
__pycache__/models.cpython-312.pyc
ADDED
|
Binary file (12.5 kB). View file
|
|
|
__pycache__/server.cpython-312.pyc
ADDED
|
Binary file (8.55 kB). View file
|
|
|
agent.capnp
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@0xbf5147e1a2a3a3b1;
|
| 2 |
+
|
| 3 |
+
interface Agent {
|
| 4 |
+
ping @0 (message :Text) -> (response :Text);
|
| 5 |
+
act @1 (obs :Observation) -> (action :Tensor);
|
| 6 |
+
reset @2 ();
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
struct Tensor {
|
| 10 |
+
data @0 :Data;
|
| 11 |
+
shape @1 :List(Int32);
|
| 12 |
+
dtype @2 :Text;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
struct ObservationEntry {
|
| 16 |
+
key @0 :Text;
|
| 17 |
+
tensor @1 :Tensor;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
struct Observation {
|
| 21 |
+
entries @0 :List(ObservationEntry);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
agent.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LoRASA Agent for MetaWorld MT50 tasks.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional, Dict, Tuple, Any
|
| 9 |
+
from collections import deque
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import numpy as np
|
| 14 |
+
import gymnasium as gym
|
| 15 |
+
|
| 16 |
+
# Use local imports (self-contained agent folder)
|
| 17 |
+
try:
|
| 18 |
+
from .model_loader import load_lorasa_model, get_task_index, MT50_TASK_ORDER
|
| 19 |
+
except ImportError:
|
| 20 |
+
from model_loader import load_lorasa_model, get_task_index, MT50_TASK_ORDER
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from .agent_interface import AgentInterface
|
| 24 |
+
except ImportError:
|
| 25 |
+
from agent_interface import AgentInterface
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class LoRASAAgent(AgentInterface):
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
backbone_path: str,
|
| 34 |
+
adapter_dir: str,
|
| 35 |
+
device: str = "cpu",
|
| 36 |
+
state_dim: int = 8,
|
| 37 |
+
action_dim: int = 4,
|
| 38 |
+
num_views: int = 2,
|
| 39 |
+
one_hot_dim: int = 50,
|
| 40 |
+
lora_rank: int = 64,
|
| 41 |
+
lora_alpha: float = 128.0,
|
| 42 |
+
observation_space: Optional[gym.Space] = None,
|
| 43 |
+
action_space: Optional[gym.Space] = None,
|
| 44 |
+
seed: Optional[int] = None,
|
| 45 |
+
**kwargs,
|
| 46 |
+
):
|
| 47 |
+
"""Initialize LoRASA agent."""
|
| 48 |
+
# Set up default spaces if not provided
|
| 49 |
+
if observation_space is None:
|
| 50 |
+
observation_space = gym.spaces.Dict({
|
| 51 |
+
"base": gym.spaces.Box(
|
| 52 |
+
low=-np.inf, high=np.inf, shape=(39,), dtype=np.float32
|
| 53 |
+
),
|
| 54 |
+
"observation.image": gym.spaces.Box(
|
| 55 |
+
low=0, high=255, shape=(3, 84, 84), dtype=np.uint8
|
| 56 |
+
),
|
| 57 |
+
"observation.image2": gym.spaces.Box(
|
| 58 |
+
low=0, high=255, shape=(3, 84, 84), dtype=np.uint8
|
| 59 |
+
),
|
| 60 |
+
})
|
| 61 |
+
|
| 62 |
+
if action_space is None:
|
| 63 |
+
action_space = gym.spaces.Box(
|
| 64 |
+
low=-1, high=1, shape=(action_dim,), dtype=np.float32
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
super().__init__(observation_space, action_space, seed)
|
| 68 |
+
|
| 69 |
+
self.backbone_path = Path(backbone_path)
|
| 70 |
+
self.adapter_dir = Path(adapter_dir)
|
| 71 |
+
self.device = torch.device(device if torch.cuda.is_available() else "cpu")
|
| 72 |
+
self.state_dim = state_dim
|
| 73 |
+
self.action_dim = action_dim
|
| 74 |
+
self.num_views = num_views
|
| 75 |
+
self.one_hot_dim = one_hot_dim
|
| 76 |
+
self.lora_rank = lora_rank
|
| 77 |
+
self.lora_alpha = lora_alpha
|
| 78 |
+
|
| 79 |
+
# State history for building 8-dim state (current + previous)
|
| 80 |
+
self.state_history = deque(maxlen=3)
|
| 81 |
+
|
| 82 |
+
# Load models per task (lazy loading)
|
| 83 |
+
self.encoders = {} # Shared encoder (same for all tasks)
|
| 84 |
+
self.actors = {} # Task-specific actors with LoRA adapters
|
| 85 |
+
|
| 86 |
+
# Load shared backbone once
|
| 87 |
+
if not self.backbone_path.exists():
|
| 88 |
+
raise FileNotFoundError(f"Backbone not found: {self.backbone_path}")
|
| 89 |
+
|
| 90 |
+
print(f"LoRASA Agent initialized")
|
| 91 |
+
print(f" - Backbone: {self.backbone_path}")
|
| 92 |
+
print(f" - Adapter dir: {self.adapter_dir}")
|
| 93 |
+
print(f" - Device: {self.device}")
|
| 94 |
+
|
| 95 |
+
def _extract_obs_state(self, obs: Dict) -> Optional[np.ndarray]:
|
| 96 |
+
"""Extract observation.state as numpy array."""
|
| 97 |
+
if 'observation.state' not in obs:
|
| 98 |
+
return None
|
| 99 |
+
obs_state = obs['observation.state']
|
| 100 |
+
if isinstance(obs_state, torch.Tensor):
|
| 101 |
+
obs_state = obs_state.cpu().numpy()
|
| 102 |
+
return np.asarray(obs_state, dtype=np.float32).flatten()
|
| 103 |
+
|
| 104 |
+
def _extract_base_obs(self, obs: Dict) -> Optional[np.ndarray]:
|
| 105 |
+
"""Extract 'base' observation as numpy array."""
|
| 106 |
+
if 'base' not in obs:
|
| 107 |
+
return None
|
| 108 |
+
base = obs['base']
|
| 109 |
+
if isinstance(base, torch.Tensor):
|
| 110 |
+
base = base.cpu().numpy()
|
| 111 |
+
return np.asarray(base, dtype=np.float32).flatten()
|
| 112 |
+
|
| 113 |
+
def _get_model_params(self) -> Dict[str, Any]:
|
| 114 |
+
"""Get common parameters for load_lorasa_model."""
|
| 115 |
+
return {
|
| 116 |
+
'backbone_path': str(self.backbone_path),
|
| 117 |
+
'device': self.device,
|
| 118 |
+
'state_dim': self.state_dim,
|
| 119 |
+
'action_dim': self.action_dim,
|
| 120 |
+
'num_views': self.num_views,
|
| 121 |
+
'one_hot_dim': self.one_hot_dim,
|
| 122 |
+
'lora_rank': self.lora_rank,
|
| 123 |
+
'lora_alpha': self.lora_alpha,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
def _get_task_name_from_obs(self, obs: Dict) -> str:
|
| 127 |
+
"""Extract task name from observation."""
|
| 128 |
+
# Try to get task from observation
|
| 129 |
+
if 'task_name' in obs:
|
| 130 |
+
return obs['task_name']
|
| 131 |
+
|
| 132 |
+
# Try to infer from one-hot encoding in observation.state
|
| 133 |
+
obs_state = self._extract_obs_state(obs)
|
| 134 |
+
if obs_state is not None and len(obs_state) >= 54: # 4 (state) + 50 (one-hot)
|
| 135 |
+
one_hot = obs_state[4:54]
|
| 136 |
+
task_idx = np.argmax(one_hot)
|
| 137 |
+
if 0 <= task_idx < len(MT50_TASK_ORDER):
|
| 138 |
+
return MT50_TASK_ORDER[task_idx]
|
| 139 |
+
|
| 140 |
+
# Fallback: old format
|
| 141 |
+
base = self._extract_base_obs(obs)
|
| 142 |
+
if base is not None and len(base) >= 39:
|
| 143 |
+
one_hot = base[39:]
|
| 144 |
+
if len(one_hot) >= 50:
|
| 145 |
+
task_idx = np.argmax(one_hot[:50])
|
| 146 |
+
if 0 <= task_idx < len(MT50_TASK_ORDER):
|
| 147 |
+
return MT50_TASK_ORDER[task_idx]
|
| 148 |
+
|
| 149 |
+
# Default fallback
|
| 150 |
+
return 'pick-place-v3'
|
| 151 |
+
|
| 152 |
+
def _load_task_model(self, task_name: str):
|
| 153 |
+
"""Load model for a specific task (lazy loading)."""
|
| 154 |
+
if task_name in self.actors:
|
| 155 |
+
return # Already loaded
|
| 156 |
+
|
| 157 |
+
# Load shared encoder if not loaded
|
| 158 |
+
if 'shared' not in self.encoders:
|
| 159 |
+
params = self._get_model_params()
|
| 160 |
+
encoder, _ = load_lorasa_model(adapter_path=None, **params)
|
| 161 |
+
self.encoders['shared'] = encoder
|
| 162 |
+
|
| 163 |
+
encoder = self.encoders['shared']
|
| 164 |
+
|
| 165 |
+
# Load task-specific adapter
|
| 166 |
+
adapter_path = self.adapter_dir / f"lorasa_adapter_{task_name}.pt"
|
| 167 |
+
|
| 168 |
+
params = self._get_model_params()
|
| 169 |
+
if not adapter_path.exists():
|
| 170 |
+
print(f"Warning: Adapter not found for {task_name}, using base actor")
|
| 171 |
+
_, actor = load_lorasa_model(adapter_path=None, **params)
|
| 172 |
+
else:
|
| 173 |
+
encoder, actor = load_lorasa_model(adapter_path=str(adapter_path), **params)
|
| 174 |
+
|
| 175 |
+
self.actors[task_name] = actor
|
| 176 |
+
print(f"Loaded model for task: {task_name}")
|
| 177 |
+
|
| 178 |
+
def _process_observation(self, obs: Dict) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 179 |
+
"""
|
| 180 |
+
Process observation to match training format.
|
| 181 |
+
Returns: (state, one_hot, images)
|
| 182 |
+
|
| 183 |
+
Evaluation framework provides:
|
| 184 |
+
- 'observation.state': concatenated [state_4, one_hot_50] (54 dims total)
|
| 185 |
+
- 'observation.image', 'observation.image2', etc.: images in CHW format
|
| 186 |
+
"""
|
| 187 |
+
# Extract state from observation.state (evaluation framework format)
|
| 188 |
+
obs_state = self._extract_obs_state(obs)
|
| 189 |
+
if obs_state is not None and len(obs_state) >= 4:
|
| 190 |
+
state_current_4 = obs_state[:4]
|
| 191 |
+
else:
|
| 192 |
+
# Fallback: old format
|
| 193 |
+
base = self._extract_base_obs(obs)
|
| 194 |
+
if base is not None and len(base) >= 4:
|
| 195 |
+
state_current_4 = base[:4]
|
| 196 |
+
else:
|
| 197 |
+
# Last resort fallback
|
| 198 |
+
state_current_4 = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32)
|
| 199 |
+
|
| 200 |
+
# Update state history
|
| 201 |
+
self.state_history.append(state_current_4)
|
| 202 |
+
|
| 203 |
+
# Build 8-dim state (current + previous)
|
| 204 |
+
if len(self.state_history) >= 2:
|
| 205 |
+
prev_state_4 = self.state_history[-2]
|
| 206 |
+
else:
|
| 207 |
+
prev_state_4 = state_current_4.copy()
|
| 208 |
+
|
| 209 |
+
state = np.concatenate([state_current_4, prev_state_4]).astype(np.float32)
|
| 210 |
+
|
| 211 |
+
# Extract one-hot task encoding from observation.state
|
| 212 |
+
obs_state = self._extract_obs_state(obs)
|
| 213 |
+
if obs_state is not None:
|
| 214 |
+
# One-hot starts at index 4 (after state_4)
|
| 215 |
+
if len(obs_state) >= 54: # 4 (state) + 50 (one-hot)
|
| 216 |
+
one_hot = obs_state[4:54].astype(np.float32)
|
| 217 |
+
elif len(obs_state) > 4:
|
| 218 |
+
# Partial one-hot, pad to 50
|
| 219 |
+
one_hot = np.zeros(50, dtype=np.float32)
|
| 220 |
+
one_hot[:len(obs_state)-4] = obs_state[4:].astype(np.float32)
|
| 221 |
+
else:
|
| 222 |
+
one_hot = np.zeros(50, dtype=np.float32)
|
| 223 |
+
else:
|
| 224 |
+
# Fallback: old format (one-hot at index 39)
|
| 225 |
+
base = self._extract_base_obs(obs)
|
| 226 |
+
if base is not None and len(base) >= 39:
|
| 227 |
+
one_hot = base[39:39+50].astype(np.float32)
|
| 228 |
+
if len(one_hot) < 50:
|
| 229 |
+
one_hot_padded = np.zeros(50, dtype=np.float32)
|
| 230 |
+
one_hot_padded[:len(one_hot)] = one_hot
|
| 231 |
+
one_hot = one_hot_padded
|
| 232 |
+
else:
|
| 233 |
+
# Create from task name as last resort
|
| 234 |
+
task_name = self._get_task_name_from_obs(obs)
|
| 235 |
+
task_idx = get_task_index(task_name)
|
| 236 |
+
one_hot = np.zeros(50, dtype=np.float32)
|
| 237 |
+
if 0 <= task_idx < 50:
|
| 238 |
+
one_hot[task_idx] = 1.0
|
| 239 |
+
|
| 240 |
+
# Extract images
|
| 241 |
+
images_list = []
|
| 242 |
+
for i in range(self.num_views):
|
| 243 |
+
if i == 0:
|
| 244 |
+
img_key = 'observation.image'
|
| 245 |
+
else:
|
| 246 |
+
img_key = f'observation.image{i+1}'
|
| 247 |
+
|
| 248 |
+
if img_key in obs:
|
| 249 |
+
img = obs[img_key]
|
| 250 |
+
# Ensure correct format: (C, H, W) uint8
|
| 251 |
+
if isinstance(img, torch.Tensor):
|
| 252 |
+
img = img.cpu().numpy()
|
| 253 |
+
|
| 254 |
+
if img.dtype != np.uint8:
|
| 255 |
+
img = np.clip(img, 0, 255).astype(np.uint8)
|
| 256 |
+
|
| 257 |
+
# Ensure shape is (C, H, W)
|
| 258 |
+
if len(img.shape) == 3:
|
| 259 |
+
if img.shape[0] != 3:
|
| 260 |
+
# Assume HWC, convert to CHW
|
| 261 |
+
img = img.transpose(2, 0, 1)
|
| 262 |
+
elif len(img.shape) == 2:
|
| 263 |
+
# Grayscale, convert to RGB
|
| 264 |
+
img = np.stack([img, img, img], axis=0)
|
| 265 |
+
|
| 266 |
+
# Resize if needed (should be 84x84)
|
| 267 |
+
if img.shape[1] != 84 or img.shape[2] != 84:
|
| 268 |
+
from PIL import Image
|
| 269 |
+
img_hwc = img.transpose(1, 2, 0)
|
| 270 |
+
img_resized = np.array(Image.fromarray(img_hwc).resize((84, 84)))
|
| 271 |
+
img = img_resized.transpose(2, 0, 1)
|
| 272 |
+
|
| 273 |
+
images_list.append(img)
|
| 274 |
+
else:
|
| 275 |
+
# Missing image, use zeros
|
| 276 |
+
images_list.append(np.zeros((3, 84, 84), dtype=np.uint8))
|
| 277 |
+
|
| 278 |
+
# Stack images: (num_views, C, H, W)
|
| 279 |
+
images = np.stack(images_list[:self.num_views], axis=0)
|
| 280 |
+
|
| 281 |
+
# Convert to tensors
|
| 282 |
+
state_tensor = torch.as_tensor(state, dtype=torch.float32, device=self.device).unsqueeze(0)
|
| 283 |
+
one_hot_tensor = torch.as_tensor(one_hot, dtype=torch.float32, device=self.device).unsqueeze(0)
|
| 284 |
+
images_tensor = torch.as_tensor(images, dtype=torch.uint8, device=self.device).unsqueeze(0)
|
| 285 |
+
|
| 286 |
+
return state_tensor, one_hot_tensor, images_tensor
|
| 287 |
+
|
| 288 |
+
def act(self, obs: Dict, **kwargs) -> torch.Tensor:
|
| 289 |
+
"""Get action from observation."""
|
| 290 |
+
# Get task name and load model if needed
|
| 291 |
+
task_name = self._get_task_name_from_obs(obs)
|
| 292 |
+
self._load_task_model(task_name)
|
| 293 |
+
|
| 294 |
+
# Process observation
|
| 295 |
+
state, one_hot, images = self._process_observation(obs)
|
| 296 |
+
|
| 297 |
+
# Get encoder and actor for this task
|
| 298 |
+
encoder = self.encoders['shared']
|
| 299 |
+
actor = self.actors[task_name]
|
| 300 |
+
|
| 301 |
+
# Forward pass
|
| 302 |
+
with torch.no_grad():
|
| 303 |
+
# Concatenate state and one_hot
|
| 304 |
+
obs_state = torch.cat([state, one_hot], dim=1) # (B, state_dim + one_hot_dim)
|
| 305 |
+
|
| 306 |
+
# Encode images
|
| 307 |
+
features = encoder(obs_state, images, False) # (B, repr_dim)
|
| 308 |
+
|
| 309 |
+
# Get action distribution
|
| 310 |
+
dist = actor(obs_state, features)
|
| 311 |
+
action = dist.mean.cpu().numpy() # Should be (B, action_dim) or (action_dim,)
|
| 312 |
+
|
| 313 |
+
# Debug: Log shape for troubleshooting
|
| 314 |
+
# print(f"DEBUG: dist.mean shape: {action.shape}, action_dim: {self.action_dim}")
|
| 315 |
+
|
| 316 |
+
# Handle different possible shapes
|
| 317 |
+
if action.ndim == 2:
|
| 318 |
+
# Batch dimension present: (B, action_dim)
|
| 319 |
+
if action.shape[0] == 1:
|
| 320 |
+
action = action[0] # Remove batch: (action_dim,)
|
| 321 |
+
else:
|
| 322 |
+
raise ValueError(f"Unexpected batch size: {action.shape[0]}, expected 1")
|
| 323 |
+
elif action.ndim == 1:
|
| 324 |
+
# Already 1D: should be (action_dim,)
|
| 325 |
+
if len(action) != self.action_dim:
|
| 326 |
+
# This shouldn't happen, but handle it
|
| 327 |
+
raise ValueError(f"Action has wrong length: expected {self.action_dim}, got {len(action)}, shape: {action.shape}")
|
| 328 |
+
elif action.ndim == 0:
|
| 329 |
+
# Scalar - this is wrong, should not happen
|
| 330 |
+
raise ValueError(f"Action is scalar (shape: {action.shape}), expected ({self.action_dim},)")
|
| 331 |
+
else:
|
| 332 |
+
raise ValueError(f"Unexpected action ndim: {action.ndim}, shape: {action.shape}")
|
| 333 |
+
|
| 334 |
+
# Final shape check
|
| 335 |
+
if action.shape != (self.action_dim,):
|
| 336 |
+
raise ValueError(f"Final action shape mismatch: got {action.shape}, expected ({self.action_dim},)")
|
| 337 |
+
|
| 338 |
+
# Clip to [-1, 1]
|
| 339 |
+
action = np.clip(action, -1.0, 1.0)
|
| 340 |
+
|
| 341 |
+
# Ensure action is shape (action_dim,) - this should be redundant but safe
|
| 342 |
+
action = np.reshape(action, (self.action_dim,))
|
| 343 |
+
|
| 344 |
+
return torch.tensor(action, dtype=torch.float32)
|
| 345 |
+
|
| 346 |
+
def reset(self) -> None:
|
| 347 |
+
"""Reset agent state."""
|
| 348 |
+
self.state_history.clear()
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
RLAgent = LoRASAAgent
|
agent_interface.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Abstract base class defining the standard interface for all agents.
|
| 3 |
+
|
| 4 |
+
All miner-submitted agents must implement this interface to be evaluated.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from abc import ABC, abstractmethod
|
| 8 |
+
|
| 9 |
+
import gymnasium as gym
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AgentInterface(ABC):
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
observation_space: gym.Space | None = None,
|
| 22 |
+
action_space: gym.Space | None = None,
|
| 23 |
+
seed: int | None = None,
|
| 24 |
+
**kwargs,
|
| 25 |
+
):
|
| 26 |
+
self.observation_space = observation_space or gym.spaces.Box(
|
| 27 |
+
low=-1, high=1, shape=(100,), dtype=np.float32
|
| 28 |
+
)
|
| 29 |
+
self.action_space = action_space or gym.spaces.Box(
|
| 30 |
+
low=-1, high=1, shape=(4,), dtype=np.float32
|
| 31 |
+
)
|
| 32 |
+
self.seed = seed or np.random.randint(0, 1000000)
|
| 33 |
+
self.rng = np.random.default_rng(seed)
|
| 34 |
+
|
| 35 |
+
@abstractmethod
|
| 36 |
+
def act(self, obs: dict, **kwargs) -> torch.Tensor:
|
| 37 |
+
"""
|
| 38 |
+
Take action given current observation and any additional arguments.
|
| 39 |
+
"""
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
def reset(self) -> None:
|
| 43 |
+
"""
|
| 44 |
+
Reset agent state for new episode.
|
| 45 |
+
|
| 46 |
+
This is called at the beginning of each episode. Stateless agents
|
| 47 |
+
can implement this as a no-op. Agents with internal memory/history
|
| 48 |
+
should reset their state here.
|
| 49 |
+
"""
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
|
agent_server.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Cap'n Proto RPC Server for Agent Interface.
|
| 4 |
+
|
| 5 |
+
Receives observations as structured Observation messages containing Tensor entries
|
| 6 |
+
so agents can work with both state vectors and rich sensory data without pickle.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import asyncio
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
import capnp
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
# Load the schema
|
| 17 |
+
schema_file = os.path.join(os.path.dirname(__file__), "agent.capnp")
|
| 18 |
+
agent_capnp = capnp.load(schema_file)
|
| 19 |
+
|
| 20 |
+
# Default network configuration
|
| 21 |
+
DEFAULT_RPC_ADDRESS = "127.0.0.1"
|
| 22 |
+
DEFAULT_RPC_PORT = 8000
|
| 23 |
+
|
| 24 |
+
_TRAVERSAL_WORDS = 100 * 1024 * 1024 # match client; tune appropriately
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class AgentServer(agent_capnp.Agent.Server):
|
| 28 |
+
"""Cap'n Proto server implementation for AgentInterface"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, agent):
|
| 31 |
+
self.agent = agent
|
| 32 |
+
|
| 33 |
+
async def act(self, obs, **kwargs):
|
| 34 |
+
"""Handle act RPC call. 'obs' is an Observation struct containing Tensor entries."""
|
| 35 |
+
try:
|
| 36 |
+
entries = list(obs.entries)
|
| 37 |
+
|
| 38 |
+
def tensor_to_numpy(tensor_msg) -> np.ndarray:
|
| 39 |
+
"""Convert Cap'n Proto tensor to numpy array with proper dtype handling."""
|
| 40 |
+
try:
|
| 41 |
+
dtype = np.dtype(tensor_msg.dtype)
|
| 42 |
+
array = np.frombuffer(
|
| 43 |
+
tensor_msg.data, dtype=dtype
|
| 44 |
+
).reshape(tuple(tensor_msg.shape))
|
| 45 |
+
# Ensure contiguous array for better performance
|
| 46 |
+
array = np.ascontiguousarray(array.copy())
|
| 47 |
+
return array
|
| 48 |
+
except Exception as e:
|
| 49 |
+
raise
|
| 50 |
+
|
| 51 |
+
if len(entries) == 1 and entries[0].key == "__value__":
|
| 52 |
+
obs_payload = tensor_to_numpy(entries[0].tensor)
|
| 53 |
+
else:
|
| 54 |
+
obs_payload = {
|
| 55 |
+
entry.key: tensor_to_numpy(entry.tensor) for entry in entries
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# call the underlying agent synchronously
|
| 60 |
+
try:
|
| 61 |
+
action_tensor = self.agent.act(obs_payload)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
raise
|
| 64 |
+
|
| 65 |
+
# convert to numpy
|
| 66 |
+
if isinstance(action_tensor, torch.Tensor):
|
| 67 |
+
action_np = action_tensor.detach().cpu().numpy()
|
| 68 |
+
else:
|
| 69 |
+
action_np = np.array(action_tensor)
|
| 70 |
+
|
| 71 |
+
# CRITICAL: Remove batch dimension and ensure proper shape
|
| 72 |
+
# The evaluator expects a 1D array with shape (4,), not (1, 4) or (4, 1)
|
| 73 |
+
original_shape = action_np.shape
|
| 74 |
+
|
| 75 |
+
if action_np.ndim == 2:
|
| 76 |
+
# 2D array: remove batch dimension
|
| 77 |
+
if action_np.shape[0] == 1:
|
| 78 |
+
action_np = action_np[0] # Take first row: [1, 4] -> [4]
|
| 79 |
+
elif action_np.shape[1] == 1:
|
| 80 |
+
action_np = action_np[:, 0] # Take first column: [4, 1] -> [4]
|
| 81 |
+
else:
|
| 82 |
+
# Flatten if neither dimension is 1
|
| 83 |
+
action_np = action_np.flatten()
|
| 84 |
+
elif action_np.ndim > 2:
|
| 85 |
+
# Higher dimensional: flatten
|
| 86 |
+
action_np = action_np.flatten()
|
| 87 |
+
elif action_np.ndim == 0:
|
| 88 |
+
# Scalar: convert to 1D array
|
| 89 |
+
action_np = np.array([action_np])
|
| 90 |
+
|
| 91 |
+
# Final check: ensure it's 1D
|
| 92 |
+
if action_np.ndim != 1:
|
| 93 |
+
action_np = action_np.flatten()
|
| 94 |
+
|
| 95 |
+
# Validate action shape (should be 4 for Meta-World)
|
| 96 |
+
if action_np.shape[0] != 4:
|
| 97 |
+
if action_np.size >= 4:
|
| 98 |
+
action_np = action_np[:4] # Take first 4 elements
|
| 99 |
+
else:
|
| 100 |
+
# Pad with zeros if too small
|
| 101 |
+
padded = np.zeros(4, dtype=action_np.dtype)
|
| 102 |
+
padded[:action_np.size] = action_np
|
| 103 |
+
action_np = padded
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# Build response Tensor
|
| 107 |
+
response = agent_capnp.Tensor.new_message()
|
| 108 |
+
response.data = action_np.tobytes()
|
| 109 |
+
response.shape = [int(s) for s in action_np.shape]
|
| 110 |
+
response.dtype = str(action_np.dtype)
|
| 111 |
+
return response
|
| 112 |
+
except Exception as e:
|
| 113 |
+
raise
|
| 114 |
+
|
| 115 |
+
async def reset(self, **kwargs):
|
| 116 |
+
try:
|
| 117 |
+
self.agent.reset()
|
| 118 |
+
except Exception:
|
| 119 |
+
raise
|
| 120 |
+
|
| 121 |
+
async def ping(self, message, **kwargs):
|
| 122 |
+
return "pong"
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
async def serve(agent, address=DEFAULT_RPC_ADDRESS, port=DEFAULT_RPC_PORT):
|
| 126 |
+
"""Serve the agent using asyncio approach"""
|
| 127 |
+
|
| 128 |
+
async def new_connection(stream):
|
| 129 |
+
try:
|
| 130 |
+
server = capnp.TwoPartyServer(
|
| 131 |
+
stream,
|
| 132 |
+
bootstrap=AgentServer(agent),
|
| 133 |
+
traversal_limit_in_words=_TRAVERSAL_WORDS,
|
| 134 |
+
)
|
| 135 |
+
await server.on_disconnect()
|
| 136 |
+
except Exception:
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
server = await capnp.AsyncIoStream.create_server(new_connection, address, port)
|
| 140 |
+
print(f"Server running on {address}:{port}")
|
| 141 |
+
|
| 142 |
+
try:
|
| 143 |
+
async with server:
|
| 144 |
+
await server.serve_forever()
|
| 145 |
+
except Exception:
|
| 146 |
+
pass
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def start_server(agent, address=DEFAULT_RPC_ADDRESS, port=DEFAULT_RPC_PORT):
|
| 150 |
+
async def run_server_with_kj():
|
| 151 |
+
async with capnp.kj_loop():
|
| 152 |
+
await serve(agent, address, port)
|
| 153 |
+
|
| 154 |
+
try:
|
| 155 |
+
asyncio.run(run_server_with_kj())
|
| 156 |
+
except KeyboardInterrupt:
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def run_server_in_process(agent, address=DEFAULT_RPC_ADDRESS, port=DEFAULT_RPC_PORT):
|
| 161 |
+
async def run_with_kj():
|
| 162 |
+
async with capnp.kj_loop():
|
| 163 |
+
await serve(agent, address, port)
|
| 164 |
+
|
| 165 |
+
asyncio.run(run_with_kj())
|
| 166 |
+
|
| 167 |
+
|
checkpoints/lorasa_adapter_assembly-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:108e77129e45b17cbd63dabac9799e32efcbb13752a082f968f38374a2cdf8f9
|
| 3 |
+
size 1897380
|
checkpoints/lorasa_adapter_basketball-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3240de614ce3a576529e049becf70dba720cd3b8b73e56db18b8a3c6add91398
|
| 3 |
+
size 1897404
|
checkpoints/lorasa_adapter_bin-picking-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:da8c0cf83023849ca48c3e99b3e340a9e52eaacfa820d618831ca3a02277aeb1
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_adapter_box-close-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:68f93033edbad669bab1dd23b0079db8f6c4dec06ca46531816eb5568133340e
|
| 3 |
+
size 1897392
|
checkpoints/lorasa_adapter_button-press-topdown-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:95dd6bcc0fad70e4af228808325f9b04d005d794b32feac43977efd84ce07858
|
| 3 |
+
size 1897524
|
checkpoints/lorasa_adapter_button-press-topdown-wall-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:22dce1cb6dc22874d50bd60b0eeea9df2dd477a47f0b51d99a457a56291c6bbb
|
| 3 |
+
size 1897584
|
checkpoints/lorasa_adapter_button-press-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:11e15eef08baad3827331cd2726c77f696783fecc7a1ab57b2c95d9bb4ff4f5d
|
| 3 |
+
size 1897428
|
checkpoints/lorasa_adapter_button-press-wall-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:79c119498cd0b8173322c005892a2cd6f43d2a58288f5c0e0318407cb42e588f
|
| 3 |
+
size 1897488
|
checkpoints/lorasa_adapter_coffee-button-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:215aa345f93e2eb68d1f2c29f54277333def9408e8e83f7f910ba12a125ac250
|
| 3 |
+
size 1897440
|
checkpoints/lorasa_adapter_coffee-pull-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:71c34df09d0b8df8ef76d3153f500f41dd03a13f82224aba84da1b269b66baa0
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_adapter_coffee-push-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:120387f4d9c1b195265cf9f3460d0d1041f7f3f89d65bea25d9f9c352726ab82
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_adapter_dial-turn-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9750ece6100a33c14c265d13e02158fc7aeedf0782588253bbcc638d5d5c8dc8
|
| 3 |
+
size 1897392
|
checkpoints/lorasa_adapter_disassemble-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c2f578326392f2902266d9cab7865cc2b03f7aa94aa87a55ab95297371951f16
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_adapter_door-close-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5204c58f45c7c3b328d7a2ac7205cbac58c4e99f38a544b408667b51ea830022
|
| 3 |
+
size 1897404
|
checkpoints/lorasa_adapter_door-lock-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:29149723fb788e96f1d28b74ce5021fb583d513736c5aa92d62220b5318f857b
|
| 3 |
+
size 1897392
|
checkpoints/lorasa_adapter_door-open-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:649100e73aeac5d8074f580c58adf8d2a6f103078c6412c14c5871e383235b02
|
| 3 |
+
size 1897392
|
checkpoints/lorasa_adapter_door-unlock-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aa84d8e825ae2a963ddbe60af27ae781caa5eb1665eeea297d5830266965d868
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_adapter_drawer-close-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4b95917af6c6ad99dea31d99e5b451033bc312183864b1baf094e6598717a70e
|
| 3 |
+
size 1897428
|
checkpoints/lorasa_adapter_drawer-open-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3fb62bc3f679fc72cb1a0301232e5b3e1a2c1f85b405a8bef764763f23e3ef29
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_adapter_faucet-close-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fef4ca93602c25fd3bbb68f14c31ead01d837cc62ef0f85da0fb2cfb4df39ee8
|
| 3 |
+
size 1897428
|
checkpoints/lorasa_adapter_faucet-open-v3.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3c05c471b8e013f82c4e1c415ad94576aadde2113e84e0f191cae03afa6aa991
|
| 3 |
+
size 1897416
|
checkpoints/lorasa_shared_backbone.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:824e4133bc2aa5a2a6f89b80c98fdace4a7324ce22c18983bbb6ce8c8fa2dcd3
|
| 3 |
+
size 5615442
|
main.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Main entry point for the LoRASA agent server.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from agent import LoRASAAgent, RLAgent
|
| 14 |
+
from agent_server import start_server
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
"""Main entry point."""
|
| 19 |
+
parser = argparse.ArgumentParser(description="Start the LoRASA agent server")
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"--host", type=str, default="0.0.0.0", help="Host to bind the server to"
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--port", type=int, default=8000, help="Port to bind the server to"
|
| 25 |
+
)
|
| 26 |
+
parser.add_argument(
|
| 27 |
+
"--backbone-path",
|
| 28 |
+
type=str,
|
| 29 |
+
default=None,
|
| 30 |
+
help="Path to backbone checkpoint (default: checkpoints/lorasa_shared_backbone.pt)",
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
"--adapter-dir",
|
| 34 |
+
type=str,
|
| 35 |
+
default=None,
|
| 36 |
+
help="Path to adapter directory (default: checkpoints)",
|
| 37 |
+
)
|
| 38 |
+
parser.add_argument(
|
| 39 |
+
"--device",
|
| 40 |
+
type=str,
|
| 41 |
+
default=None,
|
| 42 |
+
help="Device to use (cuda/cpu, default: auto-detect)",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
args = parser.parse_args()
|
| 46 |
+
|
| 47 |
+
# Determine device
|
| 48 |
+
if args.device is None:
|
| 49 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 50 |
+
else:
|
| 51 |
+
device = args.device
|
| 52 |
+
|
| 53 |
+
# Determine paths (use local checkpoints directory in agent folder)
|
| 54 |
+
agent_dir = Path(__file__).parent
|
| 55 |
+
|
| 56 |
+
if args.backbone_path is None:
|
| 57 |
+
backbone_path = agent_dir / "checkpoints" / "lorasa_shared_backbone.pt"
|
| 58 |
+
else:
|
| 59 |
+
backbone_path = Path(args.backbone_path)
|
| 60 |
+
|
| 61 |
+
if args.adapter_dir is None:
|
| 62 |
+
adapter_dir = agent_dir / "checkpoints"
|
| 63 |
+
else:
|
| 64 |
+
adapter_dir = Path(args.adapter_dir)
|
| 65 |
+
|
| 66 |
+
if not backbone_path.exists():
|
| 67 |
+
print(f"Error: Backbone file not found: {backbone_path}")
|
| 68 |
+
sys.exit(1)
|
| 69 |
+
|
| 70 |
+
if not adapter_dir.exists():
|
| 71 |
+
print(f"Error: Adapter directory not found: {adapter_dir}")
|
| 72 |
+
sys.exit(1)
|
| 73 |
+
|
| 74 |
+
# Create the LoRASA Agent
|
| 75 |
+
try:
|
| 76 |
+
agent = LoRASAAgent(
|
| 77 |
+
backbone_path=str(backbone_path),
|
| 78 |
+
adapter_dir=str(adapter_dir),
|
| 79 |
+
device=device,
|
| 80 |
+
)
|
| 81 |
+
print(f"✓ LoRASA Agent initialized")
|
| 82 |
+
print(f" - Backbone: {backbone_path}")
|
| 83 |
+
print(f" - Adapter dir: {adapter_dir}")
|
| 84 |
+
print(f" - Device: {device}")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print(f"Error initializing agent: {e}")
|
| 87 |
+
import traceback
|
| 88 |
+
traceback.print_exc()
|
| 89 |
+
sys.exit(1)
|
| 90 |
+
|
| 91 |
+
# Start the server
|
| 92 |
+
print(f"Starting server on {args.host}:{args.port}...")
|
| 93 |
+
try:
|
| 94 |
+
start_server(agent, args.host, args.port)
|
| 95 |
+
except KeyboardInterrupt:
|
| 96 |
+
print("\nServer stopped by user")
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"Server error: {e}")
|
| 99 |
+
import traceback
|
| 100 |
+
traceback.print_exc()
|
| 101 |
+
sys.exit(1)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
| 106 |
+
|
model_loader.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Model loading utilities for LoRASA agent (self-contained).
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import torch
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
# Handle both package and direct imports
|
| 10 |
+
try:
|
| 11 |
+
from .models import Encoder, Actor, LoRAActor, LoRALinear
|
| 12 |
+
except ImportError:
|
| 13 |
+
from models import Encoder, Actor, LoRAActor, LoRALinear
|
| 14 |
+
|
| 15 |
+
# MT50 Canonical Task Order
|
| 16 |
+
MT50_TASK_ORDER = [
|
| 17 |
+
'assembly-v3', 'basketball-v3', 'bin-picking-v3', 'box-close-v3',
|
| 18 |
+
'button-press-topdown-v3', 'button-press-topdown-wall-v3', 'button-press-v3',
|
| 19 |
+
'button-press-wall-v3', 'coffee-button-v3', 'coffee-pull-v3', 'coffee-push-v3',
|
| 20 |
+
'dial-turn-v3', 'disassemble-v3', 'door-close-v3', 'door-lock-v3',
|
| 21 |
+
'door-open-v3', 'door-unlock-v3', 'drawer-close-v3', 'drawer-open-v3',
|
| 22 |
+
'faucet-close-v3', 'faucet-open-v3', 'hammer-v3', 'hand-insert-v3',
|
| 23 |
+
'handle-press-side-v3', 'handle-press-v3', 'handle-pull-side-v3',
|
| 24 |
+
'handle-pull-v3', 'lever-pull-v3', 'peg-insert-side-v3', 'peg-unplug-side-v3',
|
| 25 |
+
'pick-out-of-hole-v3', 'pick-place-v3', 'pick-place-wall-v3',
|
| 26 |
+
'plate-slide-back-side-v3', 'plate-slide-back-v3', 'plate-slide-side-v3',
|
| 27 |
+
'plate-slide-v3', 'push-back-v3', 'push-v3', 'push-wall-v3',
|
| 28 |
+
'reach-v3', 'reach-wall-v3', 'shelf-place-v3', 'soccer-v3',
|
| 29 |
+
'stick-pull-v3', 'stick-push-v3', 'sweep-into-v3', 'sweep-v3',
|
| 30 |
+
'window-close-v3', 'window-open-v3'
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_task_index(task_name: str) -> int:
|
| 35 |
+
"""Get task index in MT50 canonical order."""
|
| 36 |
+
task_name = task_name.replace('.pkl', '').replace('_demos', '')
|
| 37 |
+
try:
|
| 38 |
+
return MT50_TASK_ORDER.index(task_name)
|
| 39 |
+
except ValueError:
|
| 40 |
+
# Try to find partial match
|
| 41 |
+
for i, t in enumerate(MT50_TASK_ORDER):
|
| 42 |
+
if task_name in t or t in task_name:
|
| 43 |
+
return i
|
| 44 |
+
return 0 # Default to first task
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_lorasa_model(backbone_path, adapter_path, device, state_dim=8, action_dim=4,
|
| 48 |
+
num_views=2, one_hot_dim=None, lora_rank=64, lora_alpha=128.0):
|
| 49 |
+
"""Load shared backbone and task-specific LoRA adapter."""
|
| 50 |
+
print(f"Loading backbone from {backbone_path}...")
|
| 51 |
+
backbone_ckpt = torch.load(backbone_path, map_location=device, weights_only=False)
|
| 52 |
+
|
| 53 |
+
# Infer one_hot_dim from checkpoint if not provided
|
| 54 |
+
if one_hot_dim is None:
|
| 55 |
+
if 'config' in backbone_ckpt and 'one_hot_dim' in backbone_ckpt['config']:
|
| 56 |
+
one_hot_dim = backbone_ckpt['config']['one_hot_dim']
|
| 57 |
+
elif 'actor' in backbone_ckpt and 'policy.0.weight' in backbone_ckpt['actor']:
|
| 58 |
+
# Infer from weight shape: policy.0 input = feature_dim + (state_dim + one_hot_dim)
|
| 59 |
+
weight_shape = backbone_ckpt['actor']['policy.0.weight'].shape
|
| 60 |
+
feature_dim = 50 # Default feature_dim
|
| 61 |
+
inferred = weight_shape[1] - feature_dim - state_dim
|
| 62 |
+
one_hot_dim = inferred
|
| 63 |
+
print(f"Inferred one_hot_dim={one_hot_dim} from checkpoint weight shape")
|
| 64 |
+
else:
|
| 65 |
+
one_hot_dim = 50 # Default fallback
|
| 66 |
+
print(f"Warning: Could not infer one_hot_dim, using default {one_hot_dim}")
|
| 67 |
+
|
| 68 |
+
# Create encoder and base actor
|
| 69 |
+
encoder = Encoder(num_views=num_views, num_channels=3).to(device)
|
| 70 |
+
actor = Actor(
|
| 71 |
+
state_dim=state_dim,
|
| 72 |
+
repr_dim=encoder.repr_dim,
|
| 73 |
+
action_dim=action_dim,
|
| 74 |
+
feature_dim=50,
|
| 75 |
+
hidden_dim=1024,
|
| 76 |
+
log_std_bounds=(-10.0, 2.0),
|
| 77 |
+
one_hot_dim=one_hot_dim
|
| 78 |
+
).to(device)
|
| 79 |
+
|
| 80 |
+
# Load backbone weights
|
| 81 |
+
encoder.load_state_dict(backbone_ckpt['encoder'])
|
| 82 |
+
actor.load_state_dict(backbone_ckpt['actor'])
|
| 83 |
+
|
| 84 |
+
# Freeze backbone
|
| 85 |
+
for param in encoder.parameters():
|
| 86 |
+
param.requires_grad = False
|
| 87 |
+
for param in actor.parameters():
|
| 88 |
+
param.requires_grad = False
|
| 89 |
+
|
| 90 |
+
# Load LoRA adapter if provided
|
| 91 |
+
if adapter_path and os.path.exists(adapter_path):
|
| 92 |
+
print(f"Loading LoRA adapter from {adapter_path}...")
|
| 93 |
+
adapter_ckpt = torch.load(adapter_path, map_location=device, weights_only=False)
|
| 94 |
+
|
| 95 |
+
# Get rank and alpha from checkpoint config if available
|
| 96 |
+
if 'config' in adapter_ckpt:
|
| 97 |
+
if 'rank' in adapter_ckpt['config']:
|
| 98 |
+
lora_rank = adapter_ckpt['config']['rank']
|
| 99 |
+
if 'alpha' in adapter_ckpt['config']:
|
| 100 |
+
lora_alpha = adapter_ckpt['config']['alpha']
|
| 101 |
+
|
| 102 |
+
# Create LoRA actor
|
| 103 |
+
lora_actor = LoRAActor(actor, rank=lora_rank, alpha=lora_alpha).to(device)
|
| 104 |
+
|
| 105 |
+
# Load LoRA adapters
|
| 106 |
+
if 'lora_adapters' in adapter_ckpt:
|
| 107 |
+
lora_adapters = adapter_ckpt['lora_adapters']
|
| 108 |
+
for name, module in lora_actor.named_modules():
|
| 109 |
+
if isinstance(module, LoRALinear) and name in lora_adapters:
|
| 110 |
+
module.lora_A.data = lora_adapters[name]['lora_A'].to(device)
|
| 111 |
+
module.lora_B.data = lora_adapters[name]['lora_B'].to(device)
|
| 112 |
+
else:
|
| 113 |
+
# Fallback: try loading as state_dict
|
| 114 |
+
lora_actor.load_state_dict(adapter_ckpt.get('lora_actor', {}))
|
| 115 |
+
|
| 116 |
+
encoder.eval()
|
| 117 |
+
lora_actor.eval()
|
| 118 |
+
return encoder, lora_actor
|
| 119 |
+
else:
|
| 120 |
+
# Use base actor (no adapter)
|
| 121 |
+
encoder.eval()
|
| 122 |
+
actor.eval()
|
| 123 |
+
return encoder, actor
|
| 124 |
+
|
models.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def weight_init(m):
|
| 7 |
+
|
| 8 |
+
if isinstance(m, nn.Linear):
|
| 9 |
+
nn.init.orthogonal_(m.weight.data)
|
| 10 |
+
if hasattr(m.bias, 'data'):
|
| 11 |
+
m.bias.data.fill_(0.0)
|
| 12 |
+
elif isinstance(m, nn.Conv2d):
|
| 13 |
+
gain = nn.init.calculate_gain('relu')
|
| 14 |
+
nn.init.orthogonal_(m.weight.data, gain)
|
| 15 |
+
if hasattr(m.bias, 'data'):
|
| 16 |
+
m.bias.data.fill_(0.0)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class RandomShiftsAug(nn.Module):
|
| 20 |
+
|
| 21 |
+
def __init__(self, pad=4):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.pad = pad
|
| 24 |
+
|
| 25 |
+
def forward(self, x):
|
| 26 |
+
n, c, h, w = x.size()
|
| 27 |
+
assert h == w
|
| 28 |
+
padding = tuple([self.pad] * 4)
|
| 29 |
+
x = F.pad(x, padding, 'replicate')
|
| 30 |
+
eps = 1.0 / (h + 2 * self.pad)
|
| 31 |
+
arange = torch.linspace(-1.0 + eps, 1.0 - eps, h + 2 * self.pad,
|
| 32 |
+
device=x.device, dtype=x.dtype)[:h]
|
| 33 |
+
arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2)
|
| 34 |
+
base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2)
|
| 35 |
+
base_grid = base_grid.unsqueeze(0).repeat(n, 1, 1, 1)
|
| 36 |
+
|
| 37 |
+
shift = torch.randint(0, 2 * self.pad + 1, size=(n, 1, 1, 2),
|
| 38 |
+
device=x.device, dtype=x.dtype)
|
| 39 |
+
shift *= 2.0 / (h + 2 * self.pad)
|
| 40 |
+
|
| 41 |
+
grid = base_grid + shift
|
| 42 |
+
return F.grid_sample(x, grid, padding_mode='zeros', align_corners=False)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SquashedNormal:
|
| 46 |
+
|
| 47 |
+
def __init__(self, mu, std):
|
| 48 |
+
self.mu = mu
|
| 49 |
+
self.std = std
|
| 50 |
+
self.dist = torch.distributions.Normal(mu, std)
|
| 51 |
+
|
| 52 |
+
def sample(self):
|
| 53 |
+
return torch.tanh(self.dist.sample())
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def mean(self):
|
| 57 |
+
return torch.tanh(self.mu)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Encoder(nn.Module):
|
| 61 |
+
|
| 62 |
+
def __init__(self, num_views=2, num_channels=3):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.num_views = num_views
|
| 65 |
+
self.num_channels = num_channels
|
| 66 |
+
self.repr_dim = 49 * 64 # For 84x84 input
|
| 67 |
+
self.aug = RandomShiftsAug(pad=4)
|
| 68 |
+
|
| 69 |
+
self.conv = nn.Sequential(
|
| 70 |
+
nn.Conv2d(num_channels, 32, 8, stride=4),
|
| 71 |
+
nn.ReLU(),
|
| 72 |
+
nn.Conv2d(32, 64, 4, stride=2),
|
| 73 |
+
nn.ReLU(),
|
| 74 |
+
nn.Conv2d(64, 64, 3, stride=1),
|
| 75 |
+
nn.ReLU(),
|
| 76 |
+
nn.Flatten()
|
| 77 |
+
)
|
| 78 |
+
self.apply(weight_init)
|
| 79 |
+
|
| 80 |
+
def forward(self, state, images, augment=False):
|
| 81 |
+
|
| 82 |
+
b, nv, c, h, w = images.shape
|
| 83 |
+
x = images.view(b * nv, c, h, w).float()
|
| 84 |
+
|
| 85 |
+
if augment and self.training:
|
| 86 |
+
x = self.aug(x)
|
| 87 |
+
|
| 88 |
+
x = x / 255.0 - 0.5
|
| 89 |
+
|
| 90 |
+
features = self.conv(x)
|
| 91 |
+
features = features.view(b, nv, -1)
|
| 92 |
+
features = features.sum(dim=1)
|
| 93 |
+
|
| 94 |
+
return features
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Actor(nn.Module):
|
| 98 |
+
"""Actor network with SquashedNormal output."""
|
| 99 |
+
def __init__(self, state_dim, repr_dim, action_dim, feature_dim=50, hidden_dim=1024, log_std_bounds=(-10.0, 2.0), one_hot_dim=50):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.log_std_bounds = log_std_bounds
|
| 102 |
+
self.state_dim = state_dim
|
| 103 |
+
self.one_hot_dim = one_hot_dim
|
| 104 |
+
self.total_state_dim = state_dim + one_hot_dim # state + one_hot
|
| 105 |
+
|
| 106 |
+
self.trunk = nn.Sequential(
|
| 107 |
+
nn.Linear(repr_dim, feature_dim),
|
| 108 |
+
nn.LayerNorm(feature_dim),
|
| 109 |
+
nn.Tanh()
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.policy = nn.Sequential(
|
| 113 |
+
nn.Linear(feature_dim + self.total_state_dim, hidden_dim),
|
| 114 |
+
nn.ReLU(inplace=True),
|
| 115 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 116 |
+
nn.ReLU(inplace=True),
|
| 117 |
+
nn.Linear(hidden_dim, 2 * action_dim)
|
| 118 |
+
)
|
| 119 |
+
self.apply(weight_init)
|
| 120 |
+
|
| 121 |
+
def forward(self, obs_state, features):
|
| 122 |
+
"""
|
| 123 |
+
obs_state: (B, state_dim + one_hot_dim) - concatenated state and one-hot
|
| 124 |
+
features: (B, repr_dim)
|
| 125 |
+
Returns: SquashedNormal distribution
|
| 126 |
+
"""
|
| 127 |
+
hi = self.trunk(features)
|
| 128 |
+
h = torch.cat([obs_state, hi], dim=1) # Concatenate full obs_state with features
|
| 129 |
+
mu, ls = self.policy(h).chunk(2, dim=-1)
|
| 130 |
+
ls = torch.tanh(ls)
|
| 131 |
+
lmin, lmax = self.log_std_bounds
|
| 132 |
+
ls = lmin + 0.5 * (lmax - lmin) * (ls + 1)
|
| 133 |
+
std = ls.exp()
|
| 134 |
+
return SquashedNormal(mu, std)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class LoRALinear(nn.Module):
|
| 138 |
+
"""LoRA adapter for Linear layers."""
|
| 139 |
+
|
| 140 |
+
def __init__(self, base_layer: nn.Linear, rank: int = 8, alpha: float = 16.0):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.base_layer = base_layer
|
| 143 |
+
self.rank = rank
|
| 144 |
+
self.alpha = alpha
|
| 145 |
+
self.scaling = alpha / rank
|
| 146 |
+
|
| 147 |
+
self.lora_A = nn.Parameter(torch.zeros(rank, base_layer.in_features))
|
| 148 |
+
self.lora_B = nn.Parameter(torch.zeros(base_layer.out_features, rank))
|
| 149 |
+
|
| 150 |
+
nn.init.normal_(self.lora_B, std=0.02)
|
| 151 |
+
|
| 152 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 153 |
+
# Base forward pass
|
| 154 |
+
base_out = self.base_layer(x)
|
| 155 |
+
lora_delta = F.linear(x, self.lora_B @ self.lora_A, None) * self.scaling
|
| 156 |
+
|
| 157 |
+
return base_out + lora_delta
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class LoRAActor(nn.Module):
|
| 161 |
+
"""Actor with LoRA adapters on Linear layers."""
|
| 162 |
+
|
| 163 |
+
def __init__(self, base_actor: Actor, rank: int = 8, alpha: float = 16.0):
|
| 164 |
+
super().__init__()
|
| 165 |
+
self.rank = rank
|
| 166 |
+
self.alpha = alpha
|
| 167 |
+
self.log_std_bounds = base_actor.log_std_bounds
|
| 168 |
+
|
| 169 |
+
# Replace Linear layers in trunk with LoRA versions
|
| 170 |
+
self.trunk = nn.Sequential()
|
| 171 |
+
for i, layer in enumerate(base_actor.trunk):
|
| 172 |
+
if isinstance(layer, nn.Linear):
|
| 173 |
+
lora_layer = LoRALinear(layer, rank=rank, alpha=alpha)
|
| 174 |
+
self.trunk.add_module(str(i), lora_layer)
|
| 175 |
+
else:
|
| 176 |
+
self.trunk.add_module(str(i), layer)
|
| 177 |
+
|
| 178 |
+
# Replace Linear layers in policy with LoRA versions
|
| 179 |
+
self.policy = nn.Sequential()
|
| 180 |
+
for i, layer in enumerate(base_actor.policy):
|
| 181 |
+
if isinstance(layer, nn.Linear):
|
| 182 |
+
lora_layer = LoRALinear(layer, rank=rank, alpha=alpha)
|
| 183 |
+
self.policy.add_module(str(i), lora_layer)
|
| 184 |
+
else:
|
| 185 |
+
self.policy.add_module(str(i), layer)
|
| 186 |
+
|
| 187 |
+
def forward(self, x, y):
|
| 188 |
+
hi = self.trunk(y)
|
| 189 |
+
h = torch.cat([x, hi], dim=1)
|
| 190 |
+
mu, ls = self.policy(h).chunk(2, dim=-1)
|
| 191 |
+
ls = torch.tanh(ls)
|
| 192 |
+
lmin, lmax = self.log_std_bounds
|
| 193 |
+
ls = lmin + 0.5 * (lmax - lmin) * (ls + 1)
|
| 194 |
+
std = ls.exp()
|
| 195 |
+
return SquashedNormal(mu, std)
|
| 196 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
numpy>=1.24.0
|
| 3 |
+
gymnasium>=0.29.0
|
| 4 |
+
metaworld>=1.0.0
|
| 5 |
+
Pillow>=9.0.0
|
| 6 |
+
tqdm>=4.65.0
|
| 7 |
+
pycapnp>=1.0.0
|
| 8 |
+
fastapi>=0.100.0
|
| 9 |
+
uvicorn>=0.23.0
|
| 10 |
+
pydantic>=2.0.0
|
| 11 |
+
|
server.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kinitro Miner Server for LoRASA Policy
|
| 3 |
+
|
| 4 |
+
This FastAPI server wraps the LoRASA agent to match the kinitro
|
| 5 |
+
miner interface for evaluation.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
uvicorn server:app --host 0.0.0.0 --port 8000
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import time
|
| 12 |
+
import uuid
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from fastapi import FastAPI, HTTPException
|
| 17 |
+
from pydantic import BaseModel
|
| 18 |
+
|
| 19 |
+
# Import the LoRASA agent
|
| 20 |
+
from agent import LoRASAAgent
|
| 21 |
+
|
| 22 |
+
app = FastAPI(
|
| 23 |
+
title="LoRASA Policy Server",
|
| 24 |
+
description="Miner policy endpoint for kinitro robotics subnet",
|
| 25 |
+
version="1.0.0",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Global agent instance
|
| 29 |
+
_agent: LoRASAAgent | None = None
|
| 30 |
+
_current_task_config: dict | None = None
|
| 31 |
+
_start_time = time.time()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_agent() -> LoRASAAgent:
|
| 35 |
+
"""Get or initialize the agent."""
|
| 36 |
+
global _agent
|
| 37 |
+
if _agent is None:
|
| 38 |
+
# Use local checkpoints directory
|
| 39 |
+
agent_dir = Path(__file__).parent
|
| 40 |
+
backbone_path = agent_dir / "checkpoints" / "lorasa_shared_backbone.pt"
|
| 41 |
+
adapter_dir = agent_dir / "checkpoints"
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 45 |
+
|
| 46 |
+
_agent = LoRASAAgent(
|
| 47 |
+
backbone_path=str(backbone_path),
|
| 48 |
+
adapter_dir=str(adapter_dir),
|
| 49 |
+
device=device,
|
| 50 |
+
)
|
| 51 |
+
print(f"LoRASA Agent initialized on {device}")
|
| 52 |
+
return _agent
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# =============================================================================
|
| 56 |
+
# Request/Response Models
|
| 57 |
+
# =============================================================================
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TaskConfig(BaseModel):
|
| 61 |
+
"""Task configuration for episode reset."""
|
| 62 |
+
env_id: str | None = None
|
| 63 |
+
env_name: str | None = None
|
| 64 |
+
task_name: str | None = None
|
| 65 |
+
seed: int | None = None
|
| 66 |
+
task_id: int | None = None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ResetRequest(BaseModel):
|
| 70 |
+
"""Request body for /reset endpoint."""
|
| 71 |
+
task_config: TaskConfig
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ResetResponse(BaseModel):
|
| 75 |
+
"""Response body for /reset endpoint."""
|
| 76 |
+
status: str = "ok"
|
| 77 |
+
episode_id: str | None = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ActRequest(BaseModel):
|
| 81 |
+
"""Request body for /act endpoint."""
|
| 82 |
+
observation: list[float]
|
| 83 |
+
images: dict[str, list] | None = None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ActResponse(BaseModel):
|
| 87 |
+
"""Response body for /act endpoint."""
|
| 88 |
+
action: list[float]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class HealthResponse(BaseModel):
|
| 92 |
+
"""Response body for /health endpoint."""
|
| 93 |
+
status: str
|
| 94 |
+
model_loaded: bool
|
| 95 |
+
uptime_seconds: float
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# =============================================================================
|
| 99 |
+
# Endpoints
|
| 100 |
+
# =============================================================================
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@app.get("/health", response_model=HealthResponse)
|
| 104 |
+
async def health_check():
|
| 105 |
+
"""Health check endpoint."""
|
| 106 |
+
try:
|
| 107 |
+
agent = get_agent()
|
| 108 |
+
return HealthResponse(
|
| 109 |
+
status="healthy",
|
| 110 |
+
model_loaded=True,
|
| 111 |
+
uptime_seconds=time.time() - _start_time,
|
| 112 |
+
)
|
| 113 |
+
except Exception as e:
|
| 114 |
+
return HealthResponse(
|
| 115 |
+
status="unhealthy",
|
| 116 |
+
model_loaded=False,
|
| 117 |
+
uptime_seconds=time.time() - _start_time,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@app.post("/reset", response_model=ResetResponse)
|
| 122 |
+
async def reset(request: ResetRequest):
|
| 123 |
+
"""Reset policy for a new episode."""
|
| 124 |
+
global _current_task_config
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
agent = get_agent()
|
| 128 |
+
agent.reset()
|
| 129 |
+
|
| 130 |
+
_current_task_config = request.task_config.model_dump()
|
| 131 |
+
episode_id = uuid.uuid4().hex
|
| 132 |
+
|
| 133 |
+
return ResetResponse(status="ok", episode_id=episode_id)
|
| 134 |
+
except Exception as e:
|
| 135 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@app.post("/act", response_model=ActResponse)
|
| 139 |
+
async def act(request: ActRequest):
|
| 140 |
+
"""Get action for current observation."""
|
| 141 |
+
try:
|
| 142 |
+
agent = get_agent()
|
| 143 |
+
|
| 144 |
+
# Build observation dict in the format LoRASAAgent expects
|
| 145 |
+
obs_dict = {}
|
| 146 |
+
|
| 147 |
+
# Proprioceptive observation -> observation.state
|
| 148 |
+
# The agent expects [state_4, one_hot_50] in observation.state
|
| 149 |
+
proprio = np.array(request.observation, dtype=np.float32)
|
| 150 |
+
|
| 151 |
+
# Build observation.state: concat proprio with one-hot task encoding
|
| 152 |
+
# Get task name to create one-hot
|
| 153 |
+
task_name = None
|
| 154 |
+
if _current_task_config:
|
| 155 |
+
task_name = _current_task_config.get("task_name")
|
| 156 |
+
if not task_name and _current_task_config.get("env_id"):
|
| 157 |
+
# Extract from env_id like "metaworld/pick-place-v3"
|
| 158 |
+
env_id = _current_task_config.get("env_id")
|
| 159 |
+
if "/" in env_id:
|
| 160 |
+
task_name = env_id.split("/")[-1]
|
| 161 |
+
|
| 162 |
+
# Create one-hot encoding
|
| 163 |
+
from model_loader import MT50_TASK_ORDER, get_task_index
|
| 164 |
+
one_hot = np.zeros(50, dtype=np.float32)
|
| 165 |
+
if task_name:
|
| 166 |
+
task_idx = get_task_index(task_name)
|
| 167 |
+
if 0 <= task_idx < 50:
|
| 168 |
+
one_hot[task_idx] = 1.0
|
| 169 |
+
|
| 170 |
+
# observation.state = [proprio_4, one_hot_50]
|
| 171 |
+
obs_dict["observation.state"] = np.concatenate([proprio, one_hot])
|
| 172 |
+
|
| 173 |
+
# Also include task_name for the agent
|
| 174 |
+
if task_name:
|
| 175 |
+
obs_dict["task_name"] = task_name
|
| 176 |
+
|
| 177 |
+
# Convert images if provided
|
| 178 |
+
# Images come as HWC uint8, agent expects CHW uint8
|
| 179 |
+
if request.images:
|
| 180 |
+
for i, (cam_name, img_data) in enumerate(request.images.items()):
|
| 181 |
+
img = np.array(img_data, dtype=np.uint8)
|
| 182 |
+
|
| 183 |
+
# Convert HWC -> CHW if needed
|
| 184 |
+
if img.ndim == 3 and img.shape[-1] == 3:
|
| 185 |
+
img = img.transpose(2, 0, 1)
|
| 186 |
+
|
| 187 |
+
# Store with expected key names
|
| 188 |
+
if i == 0:
|
| 189 |
+
obs_dict["observation.image"] = img
|
| 190 |
+
else:
|
| 191 |
+
obs_dict[f"observation.image{i+1}"] = img
|
| 192 |
+
else:
|
| 193 |
+
# Provide dummy images if not provided (agent expects 2 views)
|
| 194 |
+
obs_dict["observation.image"] = np.zeros((3, 84, 84), dtype=np.uint8)
|
| 195 |
+
obs_dict["observation.image2"] = np.zeros((3, 84, 84), dtype=np.uint8)
|
| 196 |
+
|
| 197 |
+
# Get action from agent
|
| 198 |
+
action_tensor = agent.act(obs_dict)
|
| 199 |
+
|
| 200 |
+
# Convert to numpy
|
| 201 |
+
if hasattr(action_tensor, 'numpy'):
|
| 202 |
+
action = action_tensor.numpy()
|
| 203 |
+
else:
|
| 204 |
+
action = np.array(action_tensor)
|
| 205 |
+
|
| 206 |
+
# Ensure 1D
|
| 207 |
+
action = action.flatten()
|
| 208 |
+
|
| 209 |
+
return ActResponse(action=action.tolist())
|
| 210 |
+
except Exception as e:
|
| 211 |
+
import traceback
|
| 212 |
+
traceback.print_exc()
|
| 213 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# =============================================================================
|
| 217 |
+
# Startup/Shutdown
|
| 218 |
+
# =============================================================================
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@app.on_event("startup")
|
| 222 |
+
async def startup():
|
| 223 |
+
"""Initialize agent on startup."""
|
| 224 |
+
get_agent()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@app.on_event("shutdown")
|
| 228 |
+
async def shutdown():
|
| 229 |
+
"""Cleanup on shutdown."""
|
| 230 |
+
global _agent
|
| 231 |
+
_agent = None
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# =============================================================================
|
| 235 |
+
# Run with uvicorn
|
| 236 |
+
# =============================================================================
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
import uvicorn
|
| 240 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|