File size: 7,203 Bytes
7858a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c262b4d
7858a1a
 
c262b4d
7858a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""
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)