File size: 7,977 Bytes
c262b4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
Chutes Deployment for LoRASA Policy

This chute wraps the LoRASA agent for deployment on the Chutes platform
for evaluation in the kinitro robotics subnet.

Usage:
    # Set environment variables
    export CHUTE_USER="your-username"
    export CHUTES_API_KEY="your-api-key"

    # Deploy directly
    chutes deploy chute:chute --accept-fee

    # Or use kinitro CLI (recommended)
    kinitro chutes-push --repo YOUR_HF_REPO --revision YOUR_REVISION
"""

import os
from typing import Optional

import numpy as np
from pydantic import BaseModel

from chutes.chute import Chute, NodeSelector
from chutes.image import Image

# =============================================================================
# Configuration
# =============================================================================

CHUTES_USER = os.environ.get("CHUTE_USER", "shr1ftyy")
CHUTE_NAME = f"{CHUTES_USER}-lorasa-policy"

# HuggingFace repo (set by CLI or environment)
HF_REPO = os.environ.get("HF_REPO", "shr1ftyy/lorasa-policy")
HF_REVISION = os.environ.get("HF_REVISION", "main")

# GPU requirements
GPU_COUNT = 1
MIN_VRAM_GB = 16

# =============================================================================
# Image Configuration
# =============================================================================

image_tag = f"{HF_REVISION[:8]}" if HF_REVISION else "latest"
image = Image(
    CHUTES_USER,
    CHUTE_NAME,
    image_tag,
    readme=f"LoRASA policy for kinitro robotics subnet from {HF_REPO}",
)

# Install dependencies
image.run_command(
    "pip install --no-cache-dir "
    "torch "
    "numpy "
    "gymnasium "
    "pillow "
    "pydantic "
    "huggingface_hub"
)

# Download model from HuggingFace
if HF_REPO:
    image.run_command(
        f'python -c "from huggingface_hub import snapshot_download; '
        f"snapshot_download('{HF_REPO}', revision='{HF_REVISION}', local_dir='/app')\""
    )

image.set_workdir("/app")

# =============================================================================
# Chute Definition
# =============================================================================

chute = Chute(
    username=CHUTES_USER,
    name=CHUTE_NAME,
    image=image,
    readme=f"LoRASA policy for kinitro robotics subnet from {HF_REPO}",
    node_selector=NodeSelector(
        gpu_count=GPU_COUNT,
        min_vram_gb_per_gpu=MIN_VRAM_GB,
    ),
)

# =============================================================================
# Request/Response Models
# =============================================================================


class TaskConfig(BaseModel):
    """Task configuration for episode reset."""

    env_id: Optional[str] = None
    env_name: Optional[str] = None
    task_name: Optional[str] = None
    seed: Optional[int] = None
    task_id: Optional[int] = 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: Optional[str] = None


class ActRequest(BaseModel):
    """Request body for /act endpoint."""

    observation: list[float]
    images: Optional[dict[str, list]] = 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


# =============================================================================
# Global State
# =============================================================================

_agent = None
_current_task_config = None
_start_time = None


@chute.on_startup()
def initialize(app):
    """Initialize the LoRASA agent on startup."""
    import time
    from pathlib import Path

    global _agent, _start_time
    _start_time = time.time()

    # Import agent code (downloaded to /app from HuggingFace)
    import sys

    if "/app" not in sys.path:
        sys.path.insert(0, "/app")

    from agent import LoRASAAgent

    agent_dir = Path("/app")
    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}")


# =============================================================================
# Endpoints
# =============================================================================


@chute.cord(
    public_api_path="/health",
    public_api_method="GET",
)
async def health() -> HealthResponse:
    """Health check endpoint."""
    import time

    global _agent, _start_time

    return HealthResponse(
        status="healthy" if _agent is not None else "unhealthy",
        model_loaded=_agent is not None,
        uptime_seconds=time.time() - _start_time if _start_time else 0,
    )


@chute.cord(
    public_api_path="/reset",
    public_api_method="POST",
)
async def reset(request: ResetRequest) -> ResetResponse:
    """Reset policy for a new episode."""
    import uuid

    global _agent, _current_task_config

    if _agent is None:
        return ResetResponse(status="error", episode_id=None)

    _agent.reset()
    _current_task_config = request.task_config.model_dump()
    episode_id = uuid.uuid4().hex

    return ResetResponse(status="ok", episode_id=episode_id)


@chute.cord(
    public_api_path="/act",
    public_api_method="POST",
)
async def act(request: ActRequest) -> ActResponse:
    """Get action for current observation."""
    global _agent, _current_task_config

    if _agent is None:
        return ActResponse(action=[0.0, 0.0, 0.0, 0.0])

    # Import helper functions
    import sys

    if "/app" not in sys.path:
        sys.path.insert(0, "/app")
    from model_loader import get_task_index

    # Build observation dict for LoRASAAgent
    obs_dict = {}

    # Proprioceptive observation
    proprio = np.array(request.observation, dtype=np.float32)

    # Get task name for one-hot encoding
    task_name = None
    if _current_task_config:
        task_name = _current_task_config.get("task_name")
        if not task_name and _current_task_config.get("env_id"):
            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
    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, one_hot_50]
    obs_dict["observation.state"] = np.concatenate([proprio, one_hot])

    # Include task_name for the agent
    if task_name:
        obs_dict["task_name"] = task_name

    # Convert images if provided
    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)
            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 list
    if hasattr(action_tensor, "numpy"):
        action = action_tensor.numpy()
    else:
        action = np.array(action_tensor)

    action = action.flatten().tolist()

    return ActResponse(action=action)