Syeam Bin Abdullah commited on
Commit
d20de16
·
verified ·
1 Parent(s): 95fe882

Model update

Browse files
Files changed (6) hide show
  1. Dockerfile +37 -0
  2. chute.py +260 -0
  3. env.py +282 -0
  4. policy.py +238 -0
  5. requirements.txt +26 -0
  6. server.py +216 -0
Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile for Robotics Subnet Miner Policy Server
2
+ #
3
+ # This creates a FastAPI server that exposes your policy for validator queries.
4
+ #
5
+ # Build: docker build -t your-username/robo-policy:v1 .
6
+ # Test: docker run -p 8000:8000 your-username/robo-policy:v1
7
+ # Push: docker push your-username/robo-policy:v1
8
+ #
9
+ # Deploy to Chutes: see chute.py for configuration
10
+
11
+ FROM python:3.11-slim
12
+
13
+ WORKDIR /app
14
+
15
+ # Install system dependencies
16
+ RUN apt-get update && apt-get install -y --no-install-recommends \
17
+ libgl1 \
18
+ libglib2.0-0 \
19
+ && rm -rf /var/lib/apt/lists/*
20
+
21
+ # Install Python dependencies
22
+ COPY requirements.txt .
23
+ RUN pip install --no-cache-dir -r requirements.txt
24
+
25
+ # Copy policy server code
26
+ COPY server.py .
27
+ COPY policy.py .
28
+
29
+ # Copy model weights (uncomment and modify as needed)
30
+ # COPY model.pt .
31
+ # COPY models/ ./models/
32
+
33
+ # Expose port for FastAPI
34
+ EXPOSE 8000
35
+
36
+ # Run the FastAPI server
37
+ CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"]
chute.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chutes Deployment Configuration for Robotics Policy Server
3
+
4
+ This file defines a Chute that can be deployed to the Chutes platform.
5
+ The Chute wraps your policy as HTTP endpoints that validators can query.
6
+
7
+ Usage:
8
+ # Test locally using server.py (before deployment)
9
+ uvicorn server:app --host 0.0.0.0 --port 8001
10
+
11
+ # Deploy to Chutes
12
+ chutes deploy chute:chute --accept-fee
13
+
14
+ # Or use the kinitro CLI
15
+ kinitro chutes-push --repo YOUR_HF_REPO --revision YOUR_REVISION
16
+
17
+ For more info: https://docs.chutes.ai
18
+ """
19
+
20
+ import os
21
+
22
+ import numpy as np
23
+ from chutes.chute import Chute, NodeSelector
24
+ from chutes.image import Image
25
+ from pydantic import BaseModel
26
+
27
+ # =============================================================================
28
+ # Configuration - Update these for your policy
29
+ # =============================================================================
30
+
31
+ # Your Chutes username
32
+ CHUTES_USER = os.environ.get("CHUTE_USER", "your-username")
33
+
34
+ # Name for your chute (will appear in Chutes dashboard)
35
+ CHUTE_NAME = f"{CHUTES_USER}-robo-policy"
36
+
37
+ # HuggingFace repo containing your policy code (optional - for HF-based deployment)
38
+ HF_REPO = os.environ.get("HF_REPO", "")
39
+ HF_REVISION = os.environ.get("HF_REVISION", "main")
40
+
41
+ # GPU requirements
42
+ GPU_COUNT = 1
43
+ MIN_VRAM_GB = 16 # Adjust based on your model size
44
+
45
+ # =============================================================================
46
+ # Image Configuration
47
+ # =============================================================================
48
+
49
+ # Create image with dynamic tag
50
+ image_tag = f"{HF_REVISION[:8]}" if HF_REPO else "latest"
51
+ image = Image(
52
+ CHUTES_USER,
53
+ CHUTE_NAME,
54
+ image_tag,
55
+ readme="Robotics policy server for kinitro subnet",
56
+ )
57
+
58
+ # Install dependencies
59
+ image.run_command(
60
+ "pip install --no-cache-dir torch numpy gymnasium pillow pydantic huggingface_hub"
61
+ )
62
+
63
+ # If using HuggingFace repo, download the model
64
+ if HF_REPO:
65
+ image.run_command(
66
+ f'python -c "from huggingface_hub import snapshot_download; '
67
+ f"snapshot_download('{HF_REPO}', revision='{HF_REVISION}', local_dir='/app')\""
68
+ )
69
+
70
+ image.set_workdir("/app")
71
+
72
+ # =============================================================================
73
+ # Chute Definition
74
+ # =============================================================================
75
+
76
+ chute = Chute(
77
+ username=CHUTES_USER,
78
+ name=CHUTE_NAME,
79
+ image=image,
80
+ readme="Robotics policy for kinitro subnet evaluation",
81
+ node_selector=NodeSelector(
82
+ gpu_count=GPU_COUNT,
83
+ min_vram_gb_per_gpu=MIN_VRAM_GB,
84
+ ),
85
+ )
86
+
87
+ # =============================================================================
88
+ # Request/Response Models
89
+ # =============================================================================
90
+
91
+
92
+ class TaskConfig(BaseModel):
93
+ """Task configuration for episode reset."""
94
+
95
+ env_id: str | None = None
96
+ env_name: str | None = None
97
+ task_name: str | None = None
98
+ seed: int | None = None
99
+ task_id: int | None = None
100
+
101
+
102
+ class ResetRequest(BaseModel):
103
+ """Request body for /reset endpoint."""
104
+
105
+ task_config: TaskConfig
106
+
107
+
108
+ class ResetResponse(BaseModel):
109
+ """Response body for /reset endpoint."""
110
+
111
+ status: str = "ok"
112
+ episode_id: str | None = None
113
+
114
+
115
+ class ActRequest(BaseModel):
116
+ """Request body for /act endpoint."""
117
+
118
+ observation: list[float]
119
+ images: dict[str, list] | None = None
120
+
121
+
122
+ class ActResponse(BaseModel):
123
+ """Response body for /act endpoint."""
124
+
125
+ action: list[float]
126
+
127
+
128
+ class HealthResponse(BaseModel):
129
+ """Response body for /health endpoint."""
130
+
131
+ status: str
132
+ model_loaded: bool
133
+ uptime_seconds: float
134
+
135
+
136
+ # =============================================================================
137
+ # Global State (initialized on startup)
138
+ # =============================================================================
139
+
140
+ _policy = None
141
+ _current_task_config = None
142
+ _start_time = None
143
+
144
+
145
+ @chute.on_startup()
146
+ def initialize(app):
147
+ """Initialize the policy on startup."""
148
+ import time
149
+
150
+ global _policy, _start_time
151
+ _start_time = time.time()
152
+
153
+ # Import your policy implementation
154
+ # If using HuggingFace download, the code is at /app
155
+ import sys
156
+
157
+ if "/app" not in sys.path:
158
+ sys.path.insert(0, "/app")
159
+
160
+ # Import your policy class - update this import for your policy
161
+ try:
162
+ from policy import RobotPolicy
163
+
164
+ _policy = RobotPolicy()
165
+ print("Policy initialized successfully")
166
+ except Exception as e:
167
+ print(f"Failed to initialize policy: {e}")
168
+ _policy = None
169
+
170
+
171
+ # =============================================================================
172
+ # Endpoints
173
+ # =============================================================================
174
+
175
+
176
+ @chute.cord(
177
+ public_api_path="/health",
178
+ public_api_method="GET",
179
+ )
180
+ async def health() -> HealthResponse:
181
+ """Health check endpoint."""
182
+ import time
183
+
184
+ global _policy, _start_time
185
+
186
+ return HealthResponse(
187
+ status="healthy" if _policy is not None else "unhealthy",
188
+ model_loaded=_policy is not None and _policy.is_loaded(),
189
+ uptime_seconds=time.time() - _start_time if _start_time else 0,
190
+ )
191
+
192
+
193
+ @chute.cord(
194
+ public_api_path="/reset",
195
+ public_api_method="POST",
196
+ )
197
+ async def reset(request: ResetRequest) -> ResetResponse:
198
+ """Reset policy for a new episode."""
199
+
200
+ global _policy, _current_task_config
201
+
202
+ if _policy is None:
203
+ return ResetResponse(status="error", episode_id=None)
204
+
205
+ _current_task_config = request.task_config.model_dump()
206
+ episode_id = await _policy.reset(_current_task_config)
207
+
208
+ return ResetResponse(status="ok", episode_id=episode_id)
209
+
210
+
211
+ @chute.cord(
212
+ public_api_path="/act",
213
+ public_api_method="POST",
214
+ )
215
+ async def act(request: ActRequest) -> ActResponse:
216
+ """Get action for current observation."""
217
+ global _policy, _current_task_config
218
+
219
+ if _policy is None:
220
+ # Return zeros if policy not loaded
221
+ return ActResponse(action=[0.0, 0.0, 0.0, 0.0])
222
+
223
+ # Convert observation to numpy
224
+ obs = np.array(request.observation, dtype=np.float32)
225
+
226
+ # Convert images if provided
227
+ images = None
228
+ if request.images:
229
+ images = {}
230
+ for cam_name, img_data in request.images.items():
231
+ img = np.array(img_data, dtype=np.uint8)
232
+ # Convert HWC -> CHW if needed
233
+ if img.ndim == 3 and img.shape[-1] == 3:
234
+ img = img.transpose(2, 0, 1)
235
+ images[cam_name] = img
236
+
237
+ # Get action from policy
238
+ action = await _policy.act(obs, images)
239
+
240
+ # Ensure action is a list
241
+ if hasattr(action, "tolist"):
242
+ action = action.tolist()
243
+ elif hasattr(action, "numpy"):
244
+ action = action.numpy().tolist()
245
+
246
+ return ActResponse(action=action)
247
+
248
+
249
+ # =============================================================================
250
+ # Local Testing
251
+ # =============================================================================
252
+ # For local testing, use server.py instead:
253
+ # uvicorn server:app --host 0.0.0.0 --port 8001
254
+ #
255
+ # Then test with:
256
+ # curl http://localhost:8001/health
257
+ # curl -X POST http://localhost:8001/reset -H "Content-Type: application/json" \
258
+ # -d '{"task_config": {"task_name": "pick-place-v3", "seed": 42}}'
259
+ # curl -X POST http://localhost:8001/act -H "Content-Type: application/json" \
260
+ # -d '{"observation": [0.0, 0.0, 0.0, 1.0]}'
env.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Miner Policy Template for Robotics Subnet
3
+
4
+ This is the template for creating a policy that can be evaluated
5
+ by the robotics subnet validators.
6
+
7
+ Your policy must implement the RobotActor class with:
8
+ - reset(task_config): Called at the start of each episode
9
+ - act(observation): Called each timestep to get action
10
+ - cleanup(): Called when evaluation is complete
11
+
12
+ The policy will be run inside a container and queried by validators
13
+ across multiple MetaWorld robotics environments.
14
+
15
+ IMPORTANT: Observations are LIMITED to prevent overfitting:
16
+ - Proprioceptive: End-effector XYZ position + gripper state (4 values)
17
+ - Visual: RGB camera images from corner cameras (base64 encoded)
18
+ - Object positions are NOT exposed - you must learn from visual input!
19
+ """
20
+
21
+ import base64
22
+ import io
23
+ import os
24
+ from typing import Any
25
+
26
+ import numpy as np
27
+
28
+
29
+ def decode_image(b64_string: str) -> np.ndarray:
30
+ """Decode base64 PNG string to numpy array."""
31
+ from PIL import Image
32
+
33
+ buffer = io.BytesIO(base64.b64decode(b64_string))
34
+ img = Image.open(buffer)
35
+ return np.array(img)
36
+
37
+
38
+ class RobotActor:
39
+ """
40
+ Your robotics policy implementation.
41
+
42
+ This class is instantiated once when the container starts,
43
+ then reset() is called for each new episode, and act() is
44
+ called for each timestep.
45
+
46
+ Observation format (dict):
47
+ - end_effector_pos: [x, y, z] - Robot end-effector position
48
+ - gripper_state: float - Gripper open/close (0=closed, 1=open)
49
+ - camera_images: dict[str, str] - Camera views as base64 PNGs
50
+ - "corner": First corner camera view (84x84 RGB)
51
+ - "corner2": Second corner camera view (84x84 RGB)
52
+
53
+ Action format (list[float]):
54
+ - MetaWorld: 4 values [dx, dy, dz, gripper] in range [-1, 1]
55
+ """
56
+
57
+ def __init__(self):
58
+ """
59
+ Initialize your policy.
60
+
61
+ This is called once when the container starts.
62
+ Load your model weights, set up any required state, etc.
63
+ """
64
+ # Example: Load a trained policy
65
+ # self.policy = torch.load("policy.pt")
66
+
67
+ # For demonstration, we'll use a simple random policy
68
+ self.policy = None
69
+ self.current_env = None
70
+ self.current_task = None
71
+
72
+ # Track action dimensions per environment
73
+ self._action_dims = {
74
+ "metaworld": 4,
75
+ }
76
+
77
+ # Image preprocessing settings
78
+ self._image_size = (84, 84)
79
+ self._camera_names = ["corner", "corner2"]
80
+
81
+ async def reset(self, task_config: dict[str, Any]) -> None:
82
+ """
83
+ Reset policy for a new episode.
84
+
85
+ Called at the start of each episode with task information.
86
+ Use this to condition your policy on the task if needed.
87
+
88
+ Args:
89
+ task_config: Dict containing:
90
+ - env_name: Environment family (metaworld)
91
+ - task_name: Specific task (e.g., pick-place-v3)
92
+ - seed: Random seed for this episode
93
+ - object_positions: Procedural object positions (for env setup only)
94
+ - target_positions: Procedural target positions (for env setup only)
95
+ - physics_params: Randomized physics parameters
96
+ - domain_randomization: Visual randomization params
97
+ """
98
+ self.current_env = task_config.get("env_name", "")
99
+ self.current_task = task_config.get("task_name", "")
100
+
101
+ # Example: You might want to condition your policy on the task
102
+ # self.task_embedding = self.encode_task(task_config)
103
+
104
+ async def act(self, observation: dict[str, Any]) -> list[float]:
105
+ """
106
+ Get action for current observation.
107
+
108
+ This is called every timestep. You have ~100ms to respond.
109
+
110
+ Args:
111
+ observation: Dict containing:
112
+ - end_effector_pos: [x, y, z] - Robot end-effector position
113
+ - gripper_state: float - Gripper open/close state
114
+ - camera_images: dict[str, str] - Camera views as base64 PNGs
115
+
116
+ Returns:
117
+ action: Flat list of floats (joint positions/velocities)
118
+ Values should be in [-1, 1] range
119
+ """
120
+ # Extract proprioceptive observations
121
+ end_effector_pos = np.array(observation["end_effector_pos"], dtype=np.float32)
122
+ gripper_state = float(observation["gripper_state"])
123
+ _proprio = np.concatenate([end_effector_pos, [gripper_state]]) # noqa: F841
124
+
125
+ # Extract camera images (if available)
126
+ camera_images = observation.get("camera_images", {})
127
+ images = {}
128
+ for cam_name, b64_img in camera_images.items():
129
+ if b64_img:
130
+ images[cam_name] = decode_image(b64_img)
131
+
132
+ # =====================================================
133
+ # REPLACE THIS WITH YOUR POLICY
134
+ # =====================================================
135
+
136
+ # Determine action dimension based on environment
137
+ action_dim = self._action_dims.get(self.current_env, 4)
138
+
139
+ # Example: Random policy (replace with your trained policy!)
140
+ # action = self.policy(proprio, images)
141
+ action = np.random.uniform(-1, 1, size=action_dim)
142
+
143
+ # =====================================================
144
+
145
+ return action.tolist()
146
+
147
+ async def cleanup(self) -> None:
148
+ """
149
+ Clean up resources.
150
+
151
+ Called when evaluation is complete.
152
+ Free any resources, close connections, etc.
153
+ """
154
+ pass
155
+
156
+
157
+ # ==============================================================================
158
+ # EXAMPLE: Using a PyTorch Vision Policy
159
+ # ==============================================================================
160
+
161
+
162
+ class ExampleVisionPolicy:
163
+ """
164
+ Example of integrating a PyTorch vision-based policy.
165
+
166
+ This shows how you might load and use a trained neural network
167
+ that processes camera images + proprioceptive observations.
168
+ """
169
+
170
+ def __init__(self, model_path: str = "policy.pt"):
171
+ try:
172
+ import torch
173
+ import torchvision.transforms as transforms
174
+
175
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
176
+
177
+ # Image preprocessing
178
+ self.transform = transforms.Compose(
179
+ [
180
+ transforms.ToTensor(),
181
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
182
+ ]
183
+ )
184
+
185
+ # Load your trained model
186
+ if os.path.exists(model_path):
187
+ self.model = torch.load(model_path, map_location=self.device)
188
+ self.model.eval()
189
+ else:
190
+ self.model = None
191
+ print(f"Warning: Model not found at {model_path}")
192
+
193
+ except ImportError:
194
+ print("PyTorch not available")
195
+ self.model = None
196
+ self.transform = None
197
+
198
+ def preprocess_images(self, images: dict[str, np.ndarray]) -> "Any":
199
+ """Preprocess camera images for the policy."""
200
+ if self.transform is None or not images:
201
+ return None
202
+
203
+ import torch
204
+
205
+ processed = []
206
+ for cam_name in sorted(images.keys()):
207
+ img = images[cam_name]
208
+ img_tensor = self.transform(img)
209
+ processed.append(img_tensor)
210
+
211
+ if processed:
212
+ return torch.stack(processed).unsqueeze(0).to(self.device)
213
+ return None
214
+
215
+ def __call__(self, proprio: np.ndarray, images: dict[str, np.ndarray]) -> np.ndarray:
216
+ if self.model is None:
217
+ return np.zeros(4)
218
+
219
+ import torch
220
+
221
+ with torch.no_grad():
222
+ # Proprioceptive input
223
+ proprio_tensor = torch.FloatTensor(proprio).unsqueeze(0).to(self.device)
224
+
225
+ # Image input
226
+ images_tensor = self.preprocess_images(images)
227
+
228
+ # Forward pass
229
+ if images_tensor is not None:
230
+ action = self.model(proprio_tensor, images_tensor).cpu().numpy()[0]
231
+ else:
232
+ action = self.model(proprio_tensor).cpu().numpy()[0]
233
+
234
+ return action
235
+
236
+
237
+ # ==============================================================================
238
+ # EXAMPLE: Multi-Task Policy with Task Embeddings
239
+ # ==============================================================================
240
+
241
+
242
+ class ExampleMultiTaskPolicy:
243
+ """
244
+ Example of a multi-task policy that conditions on task info.
245
+
246
+ For generalizing across environments, you likely need to:
247
+ 1. Embed the task/environment information
248
+ 2. Process visual observations through CNN
249
+ 3. Concatenate with proprioceptive observations
250
+ 4. Feed to a shared policy network
251
+ """
252
+
253
+ def __init__(self):
254
+ self.task_embeddings = {
255
+ "metaworld/pick-place-v3": np.array([1, 0, 0, 0]),
256
+ "metaworld/push-v3": np.array([0, 1, 0, 0]),
257
+ "metaworld/reach-v3": np.array([0, 0, 1, 0]),
258
+ "metaworld/door-open-v3": np.array([0, 0, 0, 1]),
259
+ # ... add more as needed
260
+ }
261
+ self.current_embedding = np.zeros(4)
262
+
263
+ def reset(self, task_config: dict) -> None:
264
+ """Update task embedding based on current task."""
265
+ task_key = f"{task_config['env_name']}/{task_config['task_name']}"
266
+ self.current_embedding = self.task_embeddings.get(task_key, np.zeros(4))
267
+
268
+ def __call__(self, proprio: np.ndarray, images: dict[str, np.ndarray]) -> np.ndarray:
269
+ # Concatenate observation with task embedding
270
+ _augmented_obs = np.concatenate([proprio, self.current_embedding]) # noqa: F841
271
+
272
+ # Process images through CNN encoder
273
+ # image_features = self.cnn_encoder(images)
274
+
275
+ # Concatenate all features
276
+ # full_features = np.concatenate([augmented_obs, image_features])
277
+
278
+ # Feed to your policy network
279
+ # action = self.policy_network(full_features)
280
+
281
+ # Placeholder: random action
282
+ return np.random.uniform(-1, 1, size=4)
policy.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Miner Policy Implementation
3
+
4
+ This is where you implement your robotics policy.
5
+ The RobotPolicy class is imported by server.py and called during evaluation.
6
+
7
+ Your policy receives:
8
+ - Proprioceptive observations: end-effector position + gripper state
9
+ - Camera images (optional): RGB images from multiple viewpoints
10
+
11
+ Your policy returns:
12
+ - Action: joint commands as a numpy array
13
+
14
+ IMPORTANT: Object positions are NOT provided in observations!
15
+ You must learn to infer object locations from camera images.
16
+ """
17
+
18
+ import os
19
+ import uuid
20
+
21
+ import numpy as np
22
+
23
+
24
+ class RobotPolicy:
25
+ """
26
+ Your robotics policy implementation.
27
+
28
+ This class is instantiated once when the server starts.
29
+ Implement the following methods:
30
+ - reset(): Called at the start of each episode
31
+ - act(): Called every timestep to get action
32
+ - cleanup(): Called on shutdown
33
+ """
34
+
35
+ def __init__(self):
36
+ """
37
+ Initialize your policy.
38
+
39
+ Load model weights, set up preprocessing, etc.
40
+ This is called once when the server starts.
41
+ """
42
+ # Load your trained model here
43
+ # Example:
44
+ # self.model = torch.load("model.pt")
45
+ # self.model.eval()
46
+
47
+ self._model_loaded = False
48
+ self._current_task = None
49
+ self._episode_id = None
50
+
51
+ # Try to load model
52
+ self._load_model()
53
+
54
+ def _load_model(self):
55
+ """Load the trained model."""
56
+ model_path = os.environ.get("MODEL_PATH", "model.pt")
57
+
58
+ if os.path.exists(model_path):
59
+ try:
60
+ import torch
61
+
62
+ self.model = torch.load(model_path, map_location="cpu")
63
+ self.model.eval()
64
+ self._model_loaded = True
65
+ print(f"Loaded model from {model_path}")
66
+ except Exception as e:
67
+ print(f"Failed to load model: {e}")
68
+ self.model = None
69
+ else:
70
+ print(f"Model not found at {model_path}, using random policy")
71
+ self.model = None
72
+
73
+ def is_loaded(self) -> bool:
74
+ """Check if model is loaded."""
75
+ return self._model_loaded
76
+
77
+ async def reset(self, task_config: dict) -> str:
78
+ """
79
+ Reset policy for a new episode.
80
+
81
+ Called by the validator at the start of each evaluation episode.
82
+ Use this to reset any internal state.
83
+
84
+ Args:
85
+ task_config: Dict with env_id, task_name, seed, etc.
86
+
87
+ Returns:
88
+ Episode ID string
89
+ """
90
+ self._current_task = task_config
91
+ self._episode_id = uuid.uuid4().hex
92
+
93
+ # Reset any episode-specific state here
94
+ # Example: reset hidden state for RNN policies
95
+ # self.hidden_state = None
96
+
97
+ return self._episode_id
98
+
99
+ async def act(
100
+ self,
101
+ observation: np.ndarray,
102
+ images: dict[str, np.ndarray] | None = None,
103
+ ) -> np.ndarray:
104
+ """
105
+ Get action for current observation.
106
+
107
+ This is called every timestep during evaluation.
108
+ You have ~500ms to respond.
109
+
110
+ Args:
111
+ observation: Proprioceptive state as numpy array
112
+ [ee_x, ee_y, ee_z, gripper_state]
113
+ images: Optional dict of camera images
114
+ {"corner": (84, 84, 3), "gripper": (84, 84, 3)}
115
+
116
+ Returns:
117
+ Action as numpy array (typically 4D for MetaWorld)
118
+ """
119
+ # =====================================================
120
+ # REPLACE THIS WITH YOUR POLICY INFERENCE
121
+ # =====================================================
122
+
123
+ if self.model is not None:
124
+ # Example: PyTorch inference
125
+ import torch
126
+
127
+ with torch.no_grad():
128
+ obs_tensor = torch.FloatTensor(observation).unsqueeze(0)
129
+
130
+ # If using images
131
+ if images is not None and hasattr(self.model, "forward_with_images"):
132
+ img_tensors = {
133
+ k: torch.FloatTensor(v).permute(2, 0, 1).unsqueeze(0) / 255.0
134
+ for k, v in images.items()
135
+ }
136
+ action = self.model.forward_with_images(obs_tensor, img_tensors)
137
+ else:
138
+ action = self.model(obs_tensor)
139
+
140
+ return action.squeeze(0).numpy()
141
+
142
+ # Fallback: random action
143
+ return np.random.uniform(-1, 1, size=4).astype(np.float32)
144
+
145
+ async def cleanup(self):
146
+ """
147
+ Cleanup resources on shutdown.
148
+
149
+ Called when the server is shutting down.
150
+ """
151
+ # Free GPU memory, close connections, etc.
152
+ self.model = None
153
+
154
+
155
+ # =============================================================================
156
+ # Example: Vision-Language-Action Policy
157
+ # =============================================================================
158
+
159
+
160
+ class VLAPolicy(RobotPolicy):
161
+ """
162
+ Example Vision-Language-Action policy.
163
+
164
+ This shows how to implement a policy that:
165
+ 1. Encodes task description with language model
166
+ 2. Encodes images with vision encoder
167
+ 3. Predicts actions with a policy head
168
+ """
169
+
170
+ def __init__(self):
171
+ super().__init__()
172
+ self.task_embedding = None
173
+
174
+ async def reset(self, task_config: dict) -> str:
175
+ episode_id = await super().reset(task_config)
176
+
177
+ # Encode task description
178
+ _task_name = task_config.get("task_name", "manipulation") # noqa: F841
179
+ # self.task_embedding = self.encode_task(_task_name)
180
+
181
+ return episode_id
182
+
183
+ async def act(
184
+ self,
185
+ observation: np.ndarray,
186
+ images: dict[str, np.ndarray] | None = None,
187
+ ) -> np.ndarray:
188
+ # Encode images
189
+ # image_features = self.vision_encoder(images)
190
+
191
+ # Combine with task embedding and proprioception
192
+ # features = concat(observation, image_features, self.task_embedding)
193
+
194
+ # Predict action
195
+ # action = self.policy_head(features)
196
+
197
+ return np.random.uniform(-1, 1, size=4).astype(np.float32)
198
+
199
+
200
+ # =============================================================================
201
+ # Example: Diffusion Policy
202
+ # =============================================================================
203
+
204
+
205
+ class DiffusionPolicy(RobotPolicy):
206
+ """
207
+ Example Diffusion Policy implementation.
208
+
209
+ Diffusion policies generate action sequences through
210
+ iterative denoising, which can capture multi-modal
211
+ action distributions.
212
+ """
213
+
214
+ def __init__(self):
215
+ super().__init__()
216
+ self.action_horizon = 8 # Predict 8 actions at once
217
+ self.action_buffer = []
218
+
219
+ async def reset(self, task_config: dict) -> str:
220
+ episode_id = await super().reset(task_config)
221
+ self.action_buffer = []
222
+ return episode_id
223
+
224
+ async def act(
225
+ self,
226
+ observation: np.ndarray,
227
+ images: dict[str, np.ndarray] | None = None,
228
+ ) -> np.ndarray:
229
+ # If we have buffered actions, use them
230
+ if self.action_buffer:
231
+ return self.action_buffer.pop(0)
232
+
233
+ # Otherwise, generate new action sequence
234
+ # action_sequence = self.diffusion_model.sample(observation, images)
235
+ # self.action_buffer = list(action_sequence[1:]) # Buffer future actions
236
+ # return action_sequence[0]
237
+
238
+ return np.random.uniform(-1, 1, size=4).astype(np.float32)
requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core requirements for robotics policy server
2
+ numpy>=1.24.0
3
+
4
+ # FastAPI server (for local testing)
5
+ fastapi>=0.115.0
6
+ uvicorn>=0.34.0
7
+ pydantic>=2.0.0
8
+
9
+ # Chutes SDK (for Chutes deployment)
10
+ # Note: When deploying to Chutes, the SDK is automatically installed
11
+ # chutes>=0.4.0
12
+
13
+ # ML frameworks - uncomment as needed for your policy
14
+ torch>=2.0.0
15
+ # jax>=0.4.0
16
+ # tensorflow>=2.0.0
17
+
18
+ # Image processing
19
+ Pillow>=10.0.0
20
+
21
+ # HuggingFace (for model hosting)
22
+ huggingface_hub>=0.16.0
23
+ # transformers>=4.30.0
24
+
25
+ # Gymnasium (for environment compatibility)
26
+ gymnasium>=0.29.0
server.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Miner Policy Server for Robotics Subnet
3
+
4
+ This FastAPI server exposes your robotics policy as HTTP endpoints
5
+ that validators can query during evaluation.
6
+
7
+ DEPLOYMENT OPTIONS:
8
+
9
+ 1. Chutes Platform (Recommended):
10
+ - Use chute.py for Chutes deployment
11
+ - Run: chutes deploy chute:chute --accept-fee
12
+ - Or use kinitro CLI: kinitro chutes-push --repo YOUR_HF_REPO
13
+
14
+ 2. Self-Hosted:
15
+ - Run this server directly with uvicorn
16
+ - Ensure your endpoint is publicly accessible
17
+
18
+ After deployment, commit your policy on-chain:
19
+ kinitro commit --chute-id YOUR_CHUTE_ID --netuid YOUR_NETUID
20
+
21
+ Endpoints:
22
+ POST /reset - Reset policy for new episode
23
+ POST /act - Get action given observation
24
+ GET /health - Health check
25
+
26
+ Usage:
27
+ # Local testing
28
+ uvicorn server:app --host 0.0.0.0 --port 8000
29
+
30
+ # Deploy to Chutes (use chute.py instead)
31
+ chutes deploy chute:chute --accept-fee
32
+ """
33
+
34
+ import time
35
+
36
+ import numpy as np
37
+ from fastapi import FastAPI, HTTPException
38
+
39
+ # Import your policy implementation
40
+ from policy import RobotPolicy
41
+ from pydantic import BaseModel
42
+
43
+ app = FastAPI(
44
+ title="Robotics Policy Server",
45
+ description="Miner policy endpoint for robotics subnet evaluation",
46
+ version="1.0.0",
47
+ )
48
+
49
+ # Global policy instance
50
+ _policy: RobotPolicy | None = None
51
+
52
+
53
+ def get_policy() -> RobotPolicy:
54
+ """Get or initialize the policy."""
55
+ global _policy
56
+ if _policy is None:
57
+ _policy = RobotPolicy()
58
+ return _policy
59
+
60
+
61
+ # =============================================================================
62
+ # Request/Response Models
63
+ # =============================================================================
64
+
65
+
66
+ class TaskConfig(BaseModel):
67
+ """Task configuration for episode reset."""
68
+
69
+ env_id: str | None = None
70
+ env_name: str | None = None
71
+ task_name: str | None = None
72
+ seed: int | None = None
73
+ task_id: int | None = None
74
+
75
+
76
+ class ResetRequest(BaseModel):
77
+ """Request body for /reset endpoint."""
78
+
79
+ task_config: TaskConfig
80
+
81
+
82
+ class ResetResponse(BaseModel):
83
+ """Response body for /reset endpoint."""
84
+
85
+ status: str = "ok"
86
+ episode_id: str | None = None
87
+
88
+
89
+ class ActRequest(BaseModel):
90
+ """Request body for /act endpoint."""
91
+
92
+ observation: list[float]
93
+ images: dict[str, list] | None = None # Camera images as nested lists
94
+
95
+
96
+ class ActResponse(BaseModel):
97
+ """Response body for /act endpoint."""
98
+
99
+ action: list[float]
100
+
101
+
102
+ class HealthResponse(BaseModel):
103
+ """Response body for /health endpoint."""
104
+
105
+ status: str
106
+ model_loaded: bool
107
+ uptime_seconds: float
108
+
109
+
110
+ # =============================================================================
111
+ # Endpoints
112
+ # =============================================================================
113
+
114
+ _start_time = time.time()
115
+
116
+
117
+ @app.get("/health", response_model=HealthResponse)
118
+ async def health_check():
119
+ """
120
+ Health check endpoint.
121
+
122
+ Validators may call this to verify your endpoint is running.
123
+ """
124
+ policy = get_policy()
125
+ return HealthResponse(
126
+ status="healthy",
127
+ model_loaded=policy.is_loaded(),
128
+ uptime_seconds=time.time() - _start_time,
129
+ )
130
+
131
+
132
+ @app.post("/reset", response_model=ResetResponse)
133
+ async def reset(request: ResetRequest):
134
+ """
135
+ Reset policy for a new episode.
136
+
137
+ Called by validators at the start of each evaluation episode.
138
+ Use this to reset any internal state and optionally condition
139
+ your policy on the task configuration.
140
+
141
+ Args:
142
+ request: Contains task_config with environment/task info
143
+
144
+ Returns:
145
+ Status and optional episode ID
146
+ """
147
+ try:
148
+ policy = get_policy()
149
+ episode_id = await policy.reset(request.task_config.model_dump())
150
+ return ResetResponse(status="ok", episode_id=episode_id)
151
+ except Exception as e:
152
+ raise HTTPException(status_code=500, detail=str(e))
153
+
154
+
155
+ @app.post("/act", response_model=ActResponse)
156
+ async def act(request: ActRequest):
157
+ """
158
+ Get action for current observation.
159
+
160
+ Called by validators every timestep during evaluation.
161
+ You have approximately 500ms to respond (configurable by validator).
162
+
163
+ Args:
164
+ request: Contains observation (proprioceptive state) and
165
+ optional camera images
166
+
167
+ Returns:
168
+ Action as list of floats
169
+ """
170
+ try:
171
+ policy = get_policy()
172
+
173
+ # Convert observation to numpy
174
+ obs = np.array(request.observation, dtype=np.float32)
175
+
176
+ # Convert images if provided
177
+ images = None
178
+ if request.images:
179
+ images = {k: np.array(v) for k, v in request.images.items()}
180
+
181
+ # Get action from policy
182
+ action = await policy.act(obs, images)
183
+
184
+ return ActResponse(action=action.tolist())
185
+ except Exception as e:
186
+ raise HTTPException(status_code=500, detail=str(e))
187
+
188
+
189
+ # =============================================================================
190
+ # Startup/Shutdown
191
+ # =============================================================================
192
+
193
+
194
+ @app.on_event("startup")
195
+ async def startup():
196
+ """Initialize policy on startup."""
197
+ get_policy()
198
+
199
+
200
+ @app.on_event("shutdown")
201
+ async def shutdown():
202
+ """Cleanup on shutdown."""
203
+ global _policy
204
+ if _policy is not None:
205
+ await _policy.cleanup()
206
+ _policy = None
207
+
208
+
209
+ # =============================================================================
210
+ # Run with uvicorn
211
+ # =============================================================================
212
+
213
+ if __name__ == "__main__":
214
+ import uvicorn
215
+
216
+ uvicorn.run(app, host="0.0.0.0", port=8000)