""" 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)