| """ |
| A simple example showing how to add custom observation modalities, and custom |
| observation networks (EncoderCore, ObservationRandomizer, etc.) as well. |
| We also show how to use your custom classes directly in a config, and link them to |
| your environment's observations |
| """ |
|
|
| import numpy as np |
| import torch |
| import robomimic |
| from robomimic.models import EncoderCore, Randomizer |
| from robomimic.utils.obs_utils import Modality, ScanModality |
| from robomimic.config.bc_config import BCConfig |
| import robomimic.utils.tensor_utils as TensorUtils |
|
|
|
|
| |
| |
| class CustomImageModality(Modality): |
| |
| name = "custom_image" |
|
|
| |
| |
| |
| @classmethod |
| def _default_obs_processor(cls, obs): |
| |
| return (obs / 255.0 - 0.5) * 2 |
|
|
| @classmethod |
| def _default_obs_unprocessor(cls, obs): |
| |
| return ((obs / 2) + 0.5) * 255.0 |
|
|
|
|
| |
| |
| |
| def custom_scan_processor(obs): |
| |
| return obs[1:-1] |
|
|
|
|
| def custom_scan_unprocessor(obs): |
| |
| |
| return np.concatenate([np.zeros(1), obs, np.zeros(1)]) if isinstance(obs, np.ndarray) else \ |
| torch.concat([torch.zeros(1), obs, torch.zeros(1)]) |
|
|
|
|
| |
| ScanModality.set_obs_processor(processor=custom_scan_processor) |
| ScanModality.set_obs_unprocessor(unprocessor=custom_scan_unprocessor) |
|
|
|
|
| |
| class CustomImageEncoderCore(EncoderCore): |
| |
| def __init__( |
| self, |
| input_shape, |
| |
| |
| welcome_str, |
| ): |
| |
| super().__init__(input_shape=input_shape) |
|
|
| |
| |
| print(f"Welcome! {welcome_str}") |
|
|
| |
| def output_shape(self, input_shape=None): |
| |
| return input_shape |
|
|
| |
| def forward(self, inputs): |
| |
| return inputs |
|
|
|
|
| |
| class CustomImageRandomizer(Randomizer): |
| """ |
| A simple example of a randomizer - we make @num_rand copies of each image in the batch, |
| and add some small uniform noise to each. All randomized images will then get passed |
| through the network, resulting in outputs corresponding to each copy - we will pool |
| these outputs across the copies with a simple average. |
| """ |
| def __init__( |
| self, |
| input_shape, |
| num_rand=1, |
| noise_scale=0.01, |
| ): |
| """ |
| Args: |
| input_shape (tuple, list): shape of input (not including batch dimension) |
| num_rand (int): number of random images to create on each forward pass |
| noise_scale (float): magnitude of uniform noise to apply |
| """ |
| super(CustomImageRandomizer, self).__init__() |
|
|
| assert len(input_shape) == 3 |
|
|
| self.input_shape = input_shape |
| self.num_rand = num_rand |
| self.noise_scale = noise_scale |
|
|
| def output_shape_in(self, input_shape=None): |
| """ |
| Function to compute output shape from inputs to this module. Corresponds to |
| the @forward_in operation, where raw inputs (usually observation modalities) |
| are passed in. |
| |
| Args: |
| input_shape (iterable of int): shape of input. Does not include batch dimension. |
| Some modules may not need this argument, if their output does not depend |
| on the size of the input, or if they assume fixed size input. |
| |
| Returns: |
| out_shape ([int]): list of integers corresponding to output shape |
| """ |
|
|
| |
| |
| |
| return list(input_shape) |
|
|
| def output_shape_out(self, input_shape=None): |
| """ |
| Function to compute output shape from inputs to this module. Corresponds to |
| the @forward_out operation, where processed inputs (usually encoded observation |
| modalities) are passed in. |
| |
| Args: |
| input_shape (iterable of int): shape of input. Does not include batch dimension. |
| Some modules may not need this argument, if their output does not depend |
| on the size of the input, or if they assume fixed size input. |
| |
| Returns: |
| out_shape ([int]): list of integers corresponding to output shape |
| """ |
| |
| |
| |
| |
| return list(input_shape) |
|
|
| def forward_in(self, inputs): |
| """ |
| Make N copies of each image, add random noise to each, and move |
| copies into batch dimension to ensure compatibility with rest |
| of network. |
| """ |
|
|
| |
| if self.training: |
|
|
| |
| out = TensorUtils.unsqueeze_expand_at(inputs, size=self.num_rand, dim=1) |
|
|
| |
| out = out + self.noise_scale * (2. * torch.rand_like(out) - 1.) |
|
|
| |
| return TensorUtils.join_dimensions(out, 0, 1) |
| return inputs |
|
|
| def forward_out(self, inputs): |
| """ |
| Pools outputs across the copies by averaging them. It does this by splitting |
| the outputs from shape [B * N, ...] -> [B, N, ...] and then averaging across N |
| to result in shape [B, ...] to make sure the network output is consistent with |
| what would have happened if there were no randomization. |
| """ |
|
|
| |
| if self.training: |
| batch_size = (inputs.shape[0] // self.num_rand) |
| out = TensorUtils.reshape_dimensions(inputs, begin_axis=0, end_axis=0, |
| target_dims=(batch_size, self.num_rand)) |
| return out.mean(dim=1) |
| return inputs |
|
|
| def __repr__(self): |
| """Pretty print network.""" |
| header = '{}'.format(str(self.__class__.__name__)) |
| msg = header + "(input_shape={}, num_rand={}, noise_scale={})".format( |
| self.input_shape, self.num_rand, self.noise_scale) |
| return msg |
|
|
|
|
| if __name__ == "__main__": |
| |
| config = BCConfig() |
| config.observation.encoder.custom_image.core_class = "CustomImageEncoderCore" |
| config.observation.encoder.custom_image.core_kwargs.welcome_str = "hi there!" |
| config.observation.encoder.custom_image.obs_randomizer_class = "CustomImageRandomizer" |
| config.observation.encoder.custom_image.obs_randomizer_kwargs.num_rand = 3 |
| config.observation.encoder.custom_image.obs_randomizer_kwargs.noise_scale = 0.05 |
|
|
| |
| config.observation.modalities.obs.custom_image = ["my_image1", "my_image2"] |
| config.observation.modalities.goal.custom_image = ["my_image2", "my_image3"] |
|
|
| |
| print(config) |
|
|
| |
| |
|
|