File size: 5,585 Bytes
8796ba9 | 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 |
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn as nn
from torch.distributions import Normal
from transformers import PreTrainedModel
from transformers.utils import ModelOutput
from .configuration_mrbalance import MrBalanceConfig
@dataclass
class MrBalanceOutput(ModelOutput):
"""
Outputs returned by MrBalance.
"""
action: Optional[torch.FloatTensor] = None
action_mean: Optional[torch.FloatTensor] = None
action_std: Optional[torch.FloatTensor] = None
value: Optional[torch.FloatTensor] = None
log_prob: Optional[torch.FloatTensor] = None
class MrBalanceMLPForRL(PreTrainedModel):
"""
Hugging Face-compatible MrBalance Actor-Critic network.
Exact architecture:
64 -> 128 -> 128 -> 64
with:
actor: 64 -> 2
critic: 64 -> 1
and:
learned log_std: 2
"""
config_class = MrBalanceConfig
base_model_prefix = "mrbalance"
main_input_name = "observation"
def __init__(self, config: MrBalanceConfig):
super().__init__(config)
self.backbone = nn.Sequential(
nn.Linear(
config.observation_size,
config.hidden_size,
),
nn.SiLU(),
nn.Linear(
config.hidden_size,
config.intermediate_size,
),
nn.SiLU(),
nn.Linear(
config.intermediate_size,
config.bottleneck_size,
),
nn.SiLU(),
)
self.actor = nn.Linear(
config.bottleneck_size,
config.action_size,
)
self.critic = nn.Linear(
config.bottleneck_size,
1,
)
self.log_std = nn.Parameter(
torch.full(
(config.action_size,),
config.actor_log_std_init,
)
)
self.post_init()
def _init_weights(self, module: nn.Module) -> None:
"""
Match the original MrBalance initialization.
These values are only relevant for a newly initialized model.
During export, the learned checkpoint weights overwrite them.
"""
if not isinstance(module, nn.Linear):
return
if module is self.actor:
gain = 0.01
elif module is self.critic:
gain = 1.0
else:
gain = 2.0 ** 0.5
nn.init.orthogonal_(
module.weight,
gain=gain,
)
if module.bias is not None:
nn.init.zeros_(module.bias)
def _stats(
self,
observation: torch.Tensor,
) -> Tuple[
torch.Tensor,
torch.Tensor,
torch.Tensor,
]:
hidden = self.backbone(observation)
mean = self.actor(hidden)
value = self.critic(hidden).squeeze(-1)
std = self.log_std.exp().expand_as(mean)
return mean, std, value
def get_value(
self,
observation: torch.Tensor,
) -> torch.Tensor:
_, _, value = self._stats(observation)
return value
def get_action_and_value(
self,
observation: torch.Tensor,
raw_action: Optional[torch.Tensor] = None,
deterministic: bool = False,
):
mean, std, value = self._stats(observation)
dist = Normal(mean, std)
if raw_action is None:
raw_action = (
mean
if deterministic
else dist.sample()
)
action = torch.tanh(raw_action)
# Exact same Tanh log-probability correction
# as the original PPO implementation.
log_prob = dist.log_prob(
raw_action
).sum(-1)
log_prob -= torch.log(
torch.clamp(
1.0 - action.pow(2),
min=1e-6,
)
).sum(-1)
entropy = dist.entropy().sum(-1)
return (
action,
log_prob,
entropy,
value,
raw_action,
)
def forward(
self,
observation: torch.Tensor,
deterministic: bool = False,
raw_action: Optional[torch.Tensor] = None,
return_dict: bool = True,
**kwargs,
):
action, log_prob, _, value, _ = (
self.get_action_and_value(
observation=observation,
raw_action=raw_action,
deterministic=deterministic,
)
)
mean, std, _ = self._stats(observation)
if not return_dict:
return (
action,
mean,
std,
value,
log_prob,
)
return MrBalanceOutput(
action=action,
action_mean=mean,
action_std=std,
value=value,
log_prob=log_prob,
)
@torch.no_grad()
def predict_action(
self,
observation: torch.Tensor,
deterministic: bool = True,
) -> torch.Tensor:
output = self.forward(
observation,
deterministic=deterministic,
)
return output.action
MrBalanceModel = MrBalanceMLPForRL
|