Download code_src/ifql/impls/utils/networks.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/ifql/impls/utils/networks.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/ifql/impls/utils/networks.py
-
curl -L -o networks.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/ifql/impls/utils/networks.py
12.2 kB
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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) | |
| 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 | |