File size: 12,236 Bytes
d18db74 | 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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | from typing import Any, Optional, Sequence
try: # rsm_rise: the project's JAX env (third_party/openpi/.venv) has no distrax. IFQL uses only
# MLP / ResidualMLP / CategoricalValue / ActorVectorField, none of which need it, so the import
# is made optional rather than vendoring distrax. Anything that DOES need it fails at use time.
import distrax
except ModuleNotFoundError: # pragma: no cover
distrax = None
import flax.linen as nn
import jax.numpy as jnp
from utils.loss_utils import HL_GAUSS_NUM_BINS, hl_gauss_from_logits
def default_init(scale=1.0):
"""Default kernel initializer."""
return nn.initializers.variance_scaling(scale, 'fan_avg', 'uniform')
def ensemblize(cls, num_qs, in_axes=None, out_axes=0, **kwargs):
"""Ensemblize a module."""
return nn.vmap(
cls,
variable_axes={'params': 0, 'intermediates': 0},
split_rngs={'params': True},
in_axes=in_axes,
out_axes=out_axes,
axis_size=num_qs,
**kwargs,
)
class Identity(nn.Module):
"""Identity layer."""
def __call__(self, x):
return x
class MLP(nn.Module):
"""Multi-layer perceptron.
Attributes:
hidden_dims: Hidden layer dimensions.
activations: Activation function.
activate_final: Whether to apply activation to the final layer.
kernel_init: Kernel initializer.
layer_norm: Whether to apply layer normalization.
"""
hidden_dims: Sequence[int]
activations: Any = nn.gelu
activate_final: bool = False
kernel_init: Any = default_init()
layer_norm: bool = True
@nn.compact
def __call__(self, x):
for i, size in enumerate(self.hidden_dims):
x = nn.Dense(size, kernel_init=self.kernel_init)(x)
if i + 1 < len(self.hidden_dims) or self.activate_final:
x = self.activations(x)
if self.layer_norm:
x = nn.LayerNorm()(x)
if i == len(self.hidden_dims) - 2:
self.sow('intermediates', 'feature', x)
return x
class ResidualMLPBlock(nn.Module):
"""Residual dense block for vector features."""
hidden_dim: int
activations: Any = nn.gelu
kernel_init: Any = default_init()
layer_norm: bool = True
@nn.compact
def __call__(self, x: Any) -> Any:
residual = x
x = nn.Dense(self.hidden_dim, kernel_init=self.kernel_init)(x)
x = self.activations(x)
if self.layer_norm:
x = nn.LayerNorm()(x)
x = nn.Dense(self.hidden_dim, kernel_init=self.kernel_init)(x)
x = residual + x
x = self.activations(x)
if self.layer_norm:
x = nn.LayerNorm()(x)
return x
class ResidualMLP(nn.Module):
"""Residual MLP for vector inputs."""
hidden_dims: Sequence[int]
output_dim: int
activations: Any = nn.gelu
kernel_init: Any = default_init()
layer_norm: bool = True
@nn.compact
def __call__(self, x: Any) -> Any:
if not self.hidden_dims:
return nn.Dense(self.output_dim, kernel_init=self.kernel_init)(x)
x = nn.Dense(self.hidden_dims[0], kernel_init=self.kernel_init)(x)
x = self.activations(x)
if self.layer_norm:
x = nn.LayerNorm()(x)
for hidden_dim in self.hidden_dims:
if hidden_dim != x.shape[-1]:
raise ValueError(
'ResidualMLP requires constant hidden widths after the input projection; '
f'got current width {x.shape[-1]} and requested width {hidden_dim}.'
)
x = ResidualMLPBlock(
hidden_dim=hidden_dim,
activations=self.activations,
kernel_init=self.kernel_init,
layer_norm=self.layer_norm,
)(x)
return nn.Dense(self.output_dim, kernel_init=self.kernel_init)(x)
MLP_CLASSES = dict(
mlp=MLP,
resmlp=ResidualMLP,
)
class LogParam(nn.Module):
"""Scalar parameter module with log scale."""
init_value: float = 1.0
@nn.compact
def __call__(self):
log_value = self.param('log_value', init_fn=lambda key: jnp.full((), jnp.log(self.init_value)))
return jnp.exp(log_value)
class TransformedWithMode(distrax.Transformed if distrax is not None else object):
"""Transformed distribution with mode calculation."""
def mode(self):
return self.bijector.forward(self.distribution.mode())
class Actor(nn.Module):
"""Gaussian actor network.
Attributes:
hidden_dims: Hidden layer dimensions.
action_dim: Action dimension.
mlp_class: MLP class.
layer_norm: Whether to apply layer normalization.
log_std_min: Minimum value of log standard deviation.
log_std_max: Maximum value of log standard deviation.
tanh_squash: Whether to squash the action with tanh.
state_dependent_std: Whether to use state-dependent standard deviation.
const_std: Whether to use constant standard deviation.
final_fc_init_scale: Initial scale of the final fully-connected layer.
encoder: Optional encoder module to encode the inputs.
"""
hidden_dims: Sequence[int]
action_dim: int
mlp_class: Any = MLP
layer_norm: bool = True
log_std_min: Optional[float] = -5
log_std_max: Optional[float] = 2
tanh_squash: bool = False
state_dependent_std: bool = False
const_std: bool = True
final_fc_init_scale: float = 1e-2
encoder: nn.Module = None
def setup(self):
if self.mlp_class is ResidualMLP:
self.actor_net = self.mlp_class(
self.hidden_dims,
self.hidden_dims[-1],
layer_norm=self.layer_norm,
)
else:
self.actor_net = self.mlp_class(
self.hidden_dims,
activate_final=True,
layer_norm=self.layer_norm,
)
self.mean_net = nn.Dense(self.action_dim, kernel_init=default_init(self.final_fc_init_scale))
if self.state_dependent_std:
self.log_std_net = nn.Dense(self.action_dim, kernel_init=default_init(self.final_fc_init_scale))
else:
if not self.const_std:
self.log_stds = self.param('log_stds', nn.initializers.zeros, (self.action_dim,))
def __call__(
self,
observations,
temperature=1.0,
):
"""Return action distributions.
Args:
observations: Observations.
temperature: Scaling factor for the standard deviation.
"""
if self.encoder is not None:
inputs = self.encoder(observations)
else:
inputs = observations
outputs = self.actor_net(inputs)
means = self.mean_net(outputs)
if self.state_dependent_std:
log_stds = self.log_std_net(outputs)
else:
if self.const_std:
log_stds = jnp.zeros_like(means)
else:
log_stds = self.log_stds
log_stds = jnp.clip(log_stds, self.log_std_min, self.log_std_max)
distribution = distrax.MultivariateNormalDiag(loc=means, scale_diag=jnp.exp(log_stds) * temperature)
if self.tanh_squash:
distribution = TransformedWithMode(distribution, distrax.Block(distrax.Tanh(), ndims=1))
return distribution
class Value(nn.Module):
"""Value/critic network.
This module can be used for both value V(s, g) and critic Q(s, a, g) functions.
Attributes:
hidden_dims: Hidden layer dimensions.
layer_norm: Whether to apply layer normalization.
num_ensembles: Number of ensemble components.
encoder: Optional encoder module to encode the inputs.
"""
hidden_dims: Sequence[int]
layer_norm: bool = True
num_ensembles: int = 2
mlp_class: Any = MLP
encoder: nn.Module = None
def setup(self):
use_residual = self.mlp_class is ResidualMLP
mlp_class = self.mlp_class
if self.num_ensembles > 1:
mlp_class = ensemblize(mlp_class, self.num_ensembles)
if use_residual:
value_net = mlp_class(self.hidden_dims, 1, layer_norm=self.layer_norm)
else:
value_net = mlp_class((*self.hidden_dims, 1), activate_final=False, layer_norm=self.layer_norm)
self.value_net = value_net
def __call__(self, observations, actions=None):
"""Return values or critic values.
Args:
observations: Observations.
actions: Actions (optional).
"""
if self.encoder is not None:
inputs = [self.encoder(observations)]
else:
inputs = [observations]
if actions is not None:
inputs.append(actions)
inputs = jnp.concatenate(inputs, axis=-1)
v = self.value_net(inputs).squeeze(-1)
return v
class CategoricalValue(nn.Module):
"""Categorical value/critic network for HL-Gauss losses."""
hidden_dims: Sequence[int]
layer_norm: bool = True
num_ensembles: int = 2
num_bins: int = HL_GAUSS_NUM_BINS
mlp_class: Any = MLP
encoder: nn.Module = None
def setup(self):
use_residual = self.mlp_class is ResidualMLP
mlp_class = self.mlp_class
if self.num_ensembles > 1:
mlp_class = ensemblize(mlp_class, self.num_ensembles)
if use_residual:
self.value_net = mlp_class(self.hidden_dims, self.num_bins, layer_norm=self.layer_norm)
else:
self.value_net = mlp_class(
(*self.hidden_dims, self.num_bins),
activate_final=False,
layer_norm=self.layer_norm,
)
def __call__(self, observations, actions=None, output_logits=False):
"""Return scalar values or categorical logits."""
if self.encoder is not None:
inputs = [self.encoder(observations)]
else:
inputs = [observations]
if actions is not None:
inputs.append(actions)
inputs = jnp.concatenate(inputs, axis=-1)
logits = self.value_net(inputs)
if output_logits:
return logits
return hl_gauss_from_logits(logits)
class ActorVectorField(nn.Module):
"""Actor vector field network for flow matching.
Attributes:
hidden_dims: Hidden layer dimensions.
action_dim: Action dimension.
layer_norm: Whether to apply layer normalization.
encoder: Optional encoder module to encode the inputs.
"""
hidden_dims: Sequence[int]
action_dim: int
mlp_class: Any = MLP
layer_norm: bool = True
encoder: nn.Module = None
def setup(self) -> None:
if self.mlp_class is ResidualMLP:
self.mlp = self.mlp_class(self.hidden_dims, self.action_dim, layer_norm=self.layer_norm)
else:
self.mlp = self.mlp_class(
(*self.hidden_dims, self.action_dim),
activate_final=False,
layer_norm=self.layer_norm,
)
def _embed_times(self, times):
freqs = jnp.arange(1, 33, dtype=times.dtype)
angles = 2 * jnp.pi * times * freqs
return jnp.concatenate([times, jnp.cos(angles), jnp.sin(angles)], axis=-1)
@nn.compact
def __call__(self, observations, actions, times=None, conditions=None, is_encoded=False):
"""Return the vectors at the given states, actions, and times (optional).
Args:
observations: Observations.
actions: Actions.
times: Times (optional).
conditions: Additional conditioning variables (optional).
is_encoded: Whether the observations are already encoded.
"""
if not is_encoded and self.encoder is not None:
observations = self.encoder(observations)
inputs = [observations, actions]
if conditions is not None:
inputs.append(conditions)
if times is not None:
inputs.append(self._embed_times(times))
inputs = jnp.concatenate(inputs, axis=-1)
v = self.mlp(inputs)
return v
|