File size: 6,472 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 | 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())
@property
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)
|