File size: 13,859 Bytes
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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""
LoRASA Agent for MetaWorld MT50 tasks.
"""

import os
import sys
from pathlib import Path
from typing import Optional, Dict, Tuple, Any
from collections import deque

import torch
import torch.nn as nn
import numpy as np
import gymnasium as gym

# Use local imports (self-contained agent folder)
try:
    from .model_loader import load_lorasa_model, get_task_index, MT50_TASK_ORDER
except ImportError:
    from model_loader import load_lorasa_model, get_task_index, MT50_TASK_ORDER

try:
    from .agent_interface import AgentInterface
except ImportError:
    from agent_interface import AgentInterface


class LoRASAAgent(AgentInterface):


    def __init__(
        self,
        backbone_path: str,
        adapter_dir: str,
        device: str = "cpu",
        state_dim: int = 8,
        action_dim: int = 4,
        num_views: int = 2,
        one_hot_dim: int = 50,
        lora_rank: int = 64,
        lora_alpha: float = 128.0,
        observation_space: Optional[gym.Space] = None,
        action_space: Optional[gym.Space] = None,
        seed: Optional[int] = None,
        **kwargs,
    ):
        """Initialize LoRASA agent."""
        # Set up default spaces if not provided
        if observation_space is None:
            observation_space = gym.spaces.Dict({
                "base": gym.spaces.Box(
                    low=-np.inf, high=np.inf, shape=(39,), dtype=np.float32
                ),
                "observation.image": gym.spaces.Box(
                    low=0, high=255, shape=(3, 84, 84), dtype=np.uint8
                ),
                "observation.image2": gym.spaces.Box(
                    low=0, high=255, shape=(3, 84, 84), dtype=np.uint8
                ),
            })
        
        if action_space is None:
            action_space = gym.spaces.Box(
                low=-1, high=1, shape=(action_dim,), dtype=np.float32
            )

        super().__init__(observation_space, action_space, seed)

        self.backbone_path = Path(backbone_path)
        self.adapter_dir = Path(adapter_dir)
        self.device = torch.device(device if torch.cuda.is_available() else "cpu")
        self.state_dim = state_dim
        self.action_dim = action_dim
        self.num_views = num_views
        self.one_hot_dim = one_hot_dim
        self.lora_rank = lora_rank
        self.lora_alpha = lora_alpha

        # State history for building 8-dim state (current + previous)
        self.state_history = deque(maxlen=3)

        # Load models per task (lazy loading)
        self.encoders = {}  # Shared encoder (same for all tasks)
        self.actors = {}    # Task-specific actors with LoRA adapters

        # Load shared backbone once
        if not self.backbone_path.exists():
            raise FileNotFoundError(f"Backbone not found: {self.backbone_path}")
        
        print(f"LoRASA Agent initialized")
        print(f"  - Backbone: {self.backbone_path}")
        print(f"  - Adapter dir: {self.adapter_dir}")
        print(f"  - Device: {self.device}")

    def _extract_obs_state(self, obs: Dict) -> Optional[np.ndarray]:
        """Extract observation.state as numpy array."""
        if 'observation.state' not in obs:
            return None
        obs_state = obs['observation.state']
        if isinstance(obs_state, torch.Tensor):
            obs_state = obs_state.cpu().numpy()
        return np.asarray(obs_state, dtype=np.float32).flatten()

    def _extract_base_obs(self, obs: Dict) -> Optional[np.ndarray]:
        """Extract 'base' observation as numpy array."""
        if 'base' not in obs:
            return None
        base = obs['base']
        if isinstance(base, torch.Tensor):
            base = base.cpu().numpy()
        return np.asarray(base, dtype=np.float32).flatten()

    def _get_model_params(self) -> Dict[str, Any]:
        """Get common parameters for load_lorasa_model."""
        return {
            'backbone_path': str(self.backbone_path),
            'device': self.device,
            'state_dim': self.state_dim,
            'action_dim': self.action_dim,
            'num_views': self.num_views,
            'one_hot_dim': self.one_hot_dim,
            'lora_rank': self.lora_rank,
            'lora_alpha': self.lora_alpha,
        }

    def _get_task_name_from_obs(self, obs: Dict) -> str:
        """Extract task name from observation."""
        # Try to get task from observation
        if 'task_name' in obs:
            return obs['task_name']
        
        # Try to infer from one-hot encoding in observation.state
        obs_state = self._extract_obs_state(obs)
        if obs_state is not None and len(obs_state) >= 54:  # 4 (state) + 50 (one-hot)
            one_hot = obs_state[4:54]
            task_idx = np.argmax(one_hot)
            if 0 <= task_idx < len(MT50_TASK_ORDER):
                return MT50_TASK_ORDER[task_idx]
        
        # Fallback: old format
        base = self._extract_base_obs(obs)
        if base is not None and len(base) >= 39:
            one_hot = base[39:]
            if len(one_hot) >= 50:
                task_idx = np.argmax(one_hot[:50])
                if 0 <= task_idx < len(MT50_TASK_ORDER):
                    return MT50_TASK_ORDER[task_idx]
        
        # Default fallback
        return 'pick-place-v3'

    def _load_task_model(self, task_name: str):
        """Load model for a specific task (lazy loading)."""
        if task_name in self.actors:
            return  # Already loaded

        # Load shared encoder if not loaded
        if 'shared' not in self.encoders:
            params = self._get_model_params()
            encoder, _ = load_lorasa_model(adapter_path=None, **params)
            self.encoders['shared'] = encoder

        encoder = self.encoders['shared']

        # Load task-specific adapter
        adapter_path = self.adapter_dir / f"lorasa_adapter_{task_name}.pt"
        
        params = self._get_model_params()
        if not adapter_path.exists():
            print(f"Warning: Adapter not found for {task_name}, using base actor")
            _, actor = load_lorasa_model(adapter_path=None, **params)
        else:
            encoder, actor = load_lorasa_model(adapter_path=str(adapter_path), **params)

        self.actors[task_name] = actor
        print(f"Loaded model for task: {task_name}")

    def _process_observation(self, obs: Dict) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """
        Process observation to match training format.
        Returns: (state, one_hot, images)
        
        Evaluation framework provides:
        - 'observation.state': concatenated [state_4, one_hot_50] (54 dims total)
        - 'observation.image', 'observation.image2', etc.: images in CHW format
        """
        # Extract state from observation.state (evaluation framework format)
        obs_state = self._extract_obs_state(obs)
        if obs_state is not None and len(obs_state) >= 4:
            state_current_4 = obs_state[:4]
        else:
            # Fallback: old format
            base = self._extract_base_obs(obs)
            if base is not None and len(base) >= 4:
                state_current_4 = base[:4]
            else:
                # Last resort fallback
                state_current_4 = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32)

        # Update state history
        self.state_history.append(state_current_4)

        # Build 8-dim state (current + previous)
        if len(self.state_history) >= 2:
            prev_state_4 = self.state_history[-2]
        else:
            prev_state_4 = state_current_4.copy()
        
        state = np.concatenate([state_current_4, prev_state_4]).astype(np.float32)

        # Extract one-hot task encoding from observation.state
        obs_state = self._extract_obs_state(obs)
        if obs_state is not None:
            # One-hot starts at index 4 (after state_4)
            if len(obs_state) >= 54:  # 4 (state) + 50 (one-hot)
                one_hot = obs_state[4:54].astype(np.float32)
            elif len(obs_state) > 4:
                # Partial one-hot, pad to 50
                one_hot = np.zeros(50, dtype=np.float32)
                one_hot[:len(obs_state)-4] = obs_state[4:].astype(np.float32)
            else:
                one_hot = np.zeros(50, dtype=np.float32)
        else:
            # Fallback: old format (one-hot at index 39)
            base = self._extract_base_obs(obs)
            if base is not None and len(base) >= 39:
                one_hot = base[39:39+50].astype(np.float32)
                if len(one_hot) < 50:
                    one_hot_padded = np.zeros(50, dtype=np.float32)
                    one_hot_padded[:len(one_hot)] = one_hot
                    one_hot = one_hot_padded
            else:
                # Create from task name as last resort
                task_name = self._get_task_name_from_obs(obs)
                task_idx = get_task_index(task_name)
                one_hot = np.zeros(50, dtype=np.float32)
                if 0 <= task_idx < 50:
                    one_hot[task_idx] = 1.0

        # Extract images
        images_list = []
        for i in range(self.num_views):
            if i == 0:
                img_key = 'observation.image'
            else:
                img_key = f'observation.image{i+1}'
            
            if img_key in obs:
                img = obs[img_key]
                # Ensure correct format: (C, H, W) uint8
                if isinstance(img, torch.Tensor):
                    img = img.cpu().numpy()
                
                if img.dtype != np.uint8:
                    img = np.clip(img, 0, 255).astype(np.uint8)
                
                # Ensure shape is (C, H, W)
                if len(img.shape) == 3:
                    if img.shape[0] != 3:
                        # Assume HWC, convert to CHW
                        img = img.transpose(2, 0, 1)
                elif len(img.shape) == 2:
                    # Grayscale, convert to RGB
                    img = np.stack([img, img, img], axis=0)
                
                # Resize if needed (should be 84x84)
                if img.shape[1] != 84 or img.shape[2] != 84:
                    from PIL import Image
                    img_hwc = img.transpose(1, 2, 0)
                    img_resized = np.array(Image.fromarray(img_hwc).resize((84, 84)))
                    img = img_resized.transpose(2, 0, 1)
                
                images_list.append(img)
            else:
                # Missing image, use zeros
                images_list.append(np.zeros((3, 84, 84), dtype=np.uint8))

        # Stack images: (num_views, C, H, W)
        images = np.stack(images_list[:self.num_views], axis=0)

        # Convert to tensors
        state_tensor = torch.as_tensor(state, dtype=torch.float32, device=self.device).unsqueeze(0)
        one_hot_tensor = torch.as_tensor(one_hot, dtype=torch.float32, device=self.device).unsqueeze(0)
        images_tensor = torch.as_tensor(images, dtype=torch.uint8, device=self.device).unsqueeze(0)

        return state_tensor, one_hot_tensor, images_tensor

    def act(self, obs: Dict, **kwargs) -> torch.Tensor:
        """Get action from observation."""
        # Get task name and load model if needed
        task_name = self._get_task_name_from_obs(obs)
        self._load_task_model(task_name)

        # Process observation
        state, one_hot, images = self._process_observation(obs)

        # Get encoder and actor for this task
        encoder = self.encoders['shared']
        actor = self.actors[task_name]

        # Forward pass
        with torch.no_grad():
            # Concatenate state and one_hot
            obs_state = torch.cat([state, one_hot], dim=1)  # (B, state_dim + one_hot_dim)

            # Encode images
            features = encoder(obs_state, images, False)  # (B, repr_dim)

            # Get action distribution
            dist = actor(obs_state, features)
            action = dist.mean.cpu().numpy()  # Should be (B, action_dim) or (action_dim,)
            
            # Debug: Log shape for troubleshooting
            # print(f"DEBUG: dist.mean shape: {action.shape}, action_dim: {self.action_dim}")
            
            # Handle different possible shapes
            if action.ndim == 2:
                # Batch dimension present: (B, action_dim)
                if action.shape[0] == 1:
                    action = action[0]  # Remove batch: (action_dim,)
                else:
                    raise ValueError(f"Unexpected batch size: {action.shape[0]}, expected 1")
            elif action.ndim == 1:
                # Already 1D: should be (action_dim,)
                if len(action) != self.action_dim:
                    # This shouldn't happen, but handle it
                    raise ValueError(f"Action has wrong length: expected {self.action_dim}, got {len(action)}, shape: {action.shape}")
            elif action.ndim == 0:
                # Scalar - this is wrong, should not happen
                raise ValueError(f"Action is scalar (shape: {action.shape}), expected ({self.action_dim},)")
            else:
                raise ValueError(f"Unexpected action ndim: {action.ndim}, shape: {action.shape}")

            # Final shape check
            if action.shape != (self.action_dim,):
                raise ValueError(f"Final action shape mismatch: got {action.shape}, expected ({self.action_dim},)")

            # Clip to [-1, 1]
            action = np.clip(action, -1.0, 1.0)
            
            # Ensure action is shape (action_dim,) - this should be redundant but safe
            action = np.reshape(action, (self.action_dim,))

        return torch.tensor(action, dtype=torch.float32)

    def reset(self) -> None:
        """Reset agent state."""
        self.state_history.clear()


RLAgent = LoRASAAgent