Download models.py from sbinabdullah/lorasa-policy: direct link, hf CLI and curl.
- Browser
- Download file 6.47 kB
-
https://huggingface.co/sbinabdullah/lorasa-policy/resolve/main/models.py
- Command line
-
hf download hf://sbinabdullah/lorasa-policy/models.py
-
curl -L -o models.py https://huggingface.co/sbinabdullah/lorasa-policy/resolve/main/models.py
6.47 kB
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| def weight_init(m): | |
| if isinstance(m, nn.Linear): | |
| nn.init.orthogonal_(m.weight.data) | |
| if hasattr(m.bias, 'data'): | |
| m.bias.data.fill_(0.0) | |
| elif isinstance(m, nn.Conv2d): | |
| gain = nn.init.calculate_gain('relu') | |
| nn.init.orthogonal_(m.weight.data, gain) | |
| if hasattr(m.bias, 'data'): | |
| m.bias.data.fill_(0.0) | |
| class RandomShiftsAug(nn.Module): | |
| def __init__(self, pad=4): | |
| super().__init__() | |
| self.pad = pad | |
| def forward(self, x): | |
| n, c, h, w = x.size() | |
| assert h == w | |
| padding = tuple([self.pad] * 4) | |
| x = F.pad(x, padding, 'replicate') | |
| eps = 1.0 / (h + 2 * self.pad) | |
| arange = torch.linspace(-1.0 + eps, 1.0 - eps, h + 2 * self.pad, | |
| device=x.device, dtype=x.dtype)[:h] | |
| arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2) | |
| base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2) | |
| base_grid = base_grid.unsqueeze(0).repeat(n, 1, 1, 1) | |
| shift = torch.randint(0, 2 * self.pad + 1, size=(n, 1, 1, 2), | |
| device=x.device, dtype=x.dtype) | |
| shift *= 2.0 / (h + 2 * self.pad) | |
| grid = base_grid + shift | |
| return F.grid_sample(x, grid, padding_mode='zeros', align_corners=False) | |
| class SquashedNormal: | |
| def __init__(self, mu, std): | |
| self.mu = mu | |
| self.std = std | |
| self.dist = torch.distributions.Normal(mu, std) | |
| def sample(self): | |
| return torch.tanh(self.dist.sample()) | |
| def mean(self): | |
| return torch.tanh(self.mu) | |
| class Encoder(nn.Module): | |
| def __init__(self, num_views=2, num_channels=3): | |
| super().__init__() | |
| self.num_views = num_views | |
| self.num_channels = num_channels | |
| self.repr_dim = 49 * 64 # For 84x84 input | |
| self.aug = RandomShiftsAug(pad=4) | |
| self.conv = nn.Sequential( | |
| nn.Conv2d(num_channels, 32, 8, stride=4), | |
| nn.ReLU(), | |
| nn.Conv2d(32, 64, 4, stride=2), | |
| nn.ReLU(), | |
| nn.Conv2d(64, 64, 3, stride=1), | |
| nn.ReLU(), | |
| nn.Flatten() | |
| ) | |
| self.apply(weight_init) | |
| def forward(self, state, images, augment=False): | |
| b, nv, c, h, w = images.shape | |
| x = images.view(b * nv, c, h, w).float() | |
| if augment and self.training: | |
| x = self.aug(x) | |
| x = x / 255.0 - 0.5 | |
| features = self.conv(x) | |
| features = features.view(b, nv, -1) | |
| features = features.sum(dim=1) | |
| return features | |
| class Actor(nn.Module): | |
| """Actor network with SquashedNormal output.""" | |
| def __init__(self, state_dim, repr_dim, action_dim, feature_dim=50, hidden_dim=1024, log_std_bounds=(-10.0, 2.0), one_hot_dim=50): | |
| super().__init__() | |
| self.log_std_bounds = log_std_bounds | |
| self.state_dim = state_dim | |
| self.one_hot_dim = one_hot_dim | |
| self.total_state_dim = state_dim + one_hot_dim # state + one_hot | |
| self.trunk = nn.Sequential( | |
| nn.Linear(repr_dim, feature_dim), | |
| nn.LayerNorm(feature_dim), | |
| nn.Tanh() | |
| ) | |
| self.policy = nn.Sequential( | |
| nn.Linear(feature_dim + self.total_state_dim, hidden_dim), | |
| nn.ReLU(inplace=True), | |
| nn.Linear(hidden_dim, hidden_dim), | |
| nn.ReLU(inplace=True), | |
| nn.Linear(hidden_dim, 2 * action_dim) | |
| ) | |
| self.apply(weight_init) | |
| def forward(self, obs_state, features): | |
| """ | |
| obs_state: (B, state_dim + one_hot_dim) - concatenated state and one-hot | |
| features: (B, repr_dim) | |
| Returns: SquashedNormal distribution | |
| """ | |
| hi = self.trunk(features) | |
| h = torch.cat([obs_state, hi], dim=1) # Concatenate full obs_state with features | |
| mu, ls = self.policy(h).chunk(2, dim=-1) | |
| ls = torch.tanh(ls) | |
| lmin, lmax = self.log_std_bounds | |
| ls = lmin + 0.5 * (lmax - lmin) * (ls + 1) | |
| std = ls.exp() | |
| return SquashedNormal(mu, std) | |
| class LoRALinear(nn.Module): | |
| """LoRA adapter for Linear layers.""" | |
| def __init__(self, base_layer: nn.Linear, rank: int = 8, alpha: float = 16.0): | |
| super().__init__() | |
| self.base_layer = base_layer | |
| self.rank = rank | |
| self.alpha = alpha | |
| self.scaling = alpha / rank | |
| self.lora_A = nn.Parameter(torch.zeros(rank, base_layer.in_features)) | |
| self.lora_B = nn.Parameter(torch.zeros(base_layer.out_features, rank)) | |
| nn.init.normal_(self.lora_B, std=0.02) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| # Base forward pass | |
| base_out = self.base_layer(x) | |
| lora_delta = F.linear(x, self.lora_B @ self.lora_A, None) * self.scaling | |
| return base_out + lora_delta | |
| class LoRAActor(nn.Module): | |
| """Actor with LoRA adapters on Linear layers.""" | |
| def __init__(self, base_actor: Actor, rank: int = 8, alpha: float = 16.0): | |
| super().__init__() | |
| self.rank = rank | |
| self.alpha = alpha | |
| self.log_std_bounds = base_actor.log_std_bounds | |
| # Replace Linear layers in trunk with LoRA versions | |
| self.trunk = nn.Sequential() | |
| for i, layer in enumerate(base_actor.trunk): | |
| if isinstance(layer, nn.Linear): | |
| lora_layer = LoRALinear(layer, rank=rank, alpha=alpha) | |
| self.trunk.add_module(str(i), lora_layer) | |
| else: | |
| self.trunk.add_module(str(i), layer) | |
| # Replace Linear layers in policy with LoRA versions | |
| self.policy = nn.Sequential() | |
| for i, layer in enumerate(base_actor.policy): | |
| if isinstance(layer, nn.Linear): | |
| lora_layer = LoRALinear(layer, rank=rank, alpha=alpha) | |
| self.policy.add_module(str(i), lora_layer) | |
| else: | |
| self.policy.add_module(str(i), layer) | |
| def forward(self, x, y): | |
| hi = self.trunk(y) | |
| h = torch.cat([x, hi], dim=1) | |
| mu, ls = self.policy(h).chunk(2, dim=-1) | |
| ls = torch.tanh(ls) | |
| lmin, lmax = self.log_std_bounds | |
| ls = lmin + 0.5 * (lmax - lmin) * (ls + 1) | |
| std = ls.exp() | |
| return SquashedNormal(mu, std) | |