Exemple #1
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str, type(nn.Module)], hidden_units: List[int]):
        self.obs_shapes = obs_shapes

        # Maze relies on dictionaries to represent the inference graph
        self.perception_dict = OrderedDict()

        # build latent feature embedding block
        self.perception_dict['latent_inventory'] = DenseBlock(
            in_keys='observation_inventory', out_keys='latent_inventory', in_shapes=obs_shapes['observation_inventory'],
            hidden_units=[128], non_lin=non_lin)

        # build latent pixel embedding block
        self.perception_dict['latent_screen'] = VGGConvolutionDenseBlock(
            in_keys='observation_screen', out_keys='latent_screen', in_shapes=obs_shapes['observation_screen'],
            non_lin=non_lin, hidden_channels=[8, 16, 32], hidden_units=[32])

        # Concatenate latent features
        self.perception_dict['latent_concat'] = ConcatenationBlock(
            in_keys=['latent_inventory', 'latent_screen'], out_keys='latent_concat',
            in_shapes=self.perception_dict['latent_inventory'].out_shapes() +
            self.perception_dict['latent_screen'].out_shapes(), concat_dim=-1)

        # Add latent dense block
        self.perception_dict['latent_dense'] = DenseBlock(
            in_keys='latent_concat', out_keys='latent_dense', hidden_units=hidden_units, non_lin=non_lin,
            in_shapes=self.perception_dict['latent_concat'].out_shapes()
        )

        # Add recurrent block
        self.perception_dict['latent'] = LSTMLastStepBlock(
            in_keys='latent_dense', out_keys='latent', in_shapes=self.perception_dict['latent_dense'].out_shapes(),
            hidden_size=32, num_layers=1, bidirectional=False, non_lin=non_lin
        )
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str,
                                type(nn.Module)], hidden_units: List[int]):
        nn.Module.__init__(self)

        # Maze relies on dictionaries to represent the inference graph
        self.perception_dict = OrderedDict()

        # build latent feature embedding block
        self.perception_dict['latent_inventory'] = DenseBlock(
            in_keys='observation_inventory',
            out_keys='latent_inventory',
            in_shapes=obs_shapes['observation_inventory'],
            hidden_units=[128],
            non_lin=non_lin)

        # Concatenate latent features
        self.perception_dict['latent_concat'] = ConcatenationBlock(
            in_keys=['latent_inventory', 'latent_screen'],
            out_keys='latent_concat',
            in_shapes=self.perception_dict['latent_inventory'].out_shapes() +
            [obs_shapes['latent_screen']],
            concat_dim=-1)

        # Add latent dense block
        self.perception_dict['latent_dense'] = DenseBlock(
            in_keys='latent_concat',
            out_keys='latent_dense',
            hidden_units=hidden_units,
            non_lin=non_lin,
            in_shapes=self.perception_dict['latent_concat'].out_shapes())

        # Add recurrent block
        self.perception_dict['latent'] = LSTMLastStepBlock(
            in_keys='latent_dense',
            out_keys='latent',
            in_shapes=self.perception_dict['latent_dense'].out_shapes(),
            hidden_size=32,
            num_layers=1,
            bidirectional=False,
            non_lin=non_lin)

        # build action heads
        self.perception_dict['value'] = LinearOutputBlock(
            in_keys='latent',
            out_keys='value',
            in_shapes=self.perception_dict['latent'].out_shapes(),
            output_units=1)

        # build inference block
        in_keys = list(obs_shapes.keys())
        self.perception_net = InferenceBlock(
            in_keys=in_keys,
            out_keys='value',
            in_shapes=[obs_shapes[key] for key in in_keys],
            perception_blocks=self.perception_dict)

        # apply weight init
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['value'].apply(make_module_init_normc(0.01))
Exemple #3
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]], non_lin: Union[str, type(nn.Module)]):
        nn.Module.__init__(self)
        self.obs_shapes = obs_shapes

        hidden_units = 32

        self.perception_dict = OrderedDict()

        self.perception_dict['order_feat'] = DenseBlock(
            in_keys='ordered_piece', out_keys='order_feat', in_shapes=self.obs_shapes['ordered_piece'],
            hidden_units=[hidden_units], non_lin=non_lin)

        self.perception_dict['selected_feat'] = DenseBlock(
            in_keys='selected_piece', out_keys='selected_feat', in_shapes=self.obs_shapes['selected_piece'],
            hidden_units=[hidden_units], non_lin=non_lin)

        self.perception_dict['latent'] = ConcatenationBlock(
            in_keys=['order_feat', 'selected_feat'], out_keys='latent',
            in_shapes=[[hidden_units], [hidden_units], [hidden_units]], concat_dim=-1)

        self.perception_dict['value'] = LinearOutputBlock(
            in_keys='latent', out_keys='value', in_shapes=self.perception_dict['latent'].out_shapes(), output_units=1)

        in_keys = ['ordered_piece', 'selected_piece']
        self.perception_net = InferenceBlock(
            in_keys=in_keys, out_keys='value',
            in_shapes=[self.obs_shapes[key] for key in in_keys],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['value'].apply(make_module_init_normc(0.01))
class ValueNet(nn.Module):
    """Simple feed forward value network.
    """

    def __init__(self, obs_shapes, non_lin=nn.Tanh):
        super().__init__()

        # build perception part
        self.perception_network = DenseBlock(in_keys="observation", out_keys="latent",
                                             in_shapes=obs_shapes['observation'],
                                             hidden_units=[32, 32], non_lin=non_lin)

        module_init = make_module_init_normc(std=1.0)
        self.perception_network.apply(module_init)

        # build action head
        self.value_head = LinearOutputBlock(in_keys="latent", out_keys="value",
                                            in_shapes=self.perception_network.out_shapes(),
                                            output_units=1)

        module_init = make_module_init_normc(std=0.01)
        self.value_head.apply(module_init)

        # compile inference model
        self.net = InferenceBlock(in_keys="observation", out_keys="value", in_shapes=list(obs_shapes.values()),
                                  perception_blocks={"latent": self.perception_network,
                                                     "value": self.value_head})

    def forward(self, x):
        """ forward pass. """
        return self.net(x)
Exemple #5
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 action_spaces_dict: Dict[Union[str, int], spaces.Space],
                 non_lin: Union[str, type(nn.Module)]):
        super().__init__()
        self.obs_shapes = obs_shapes
        # build perception part
        self.perception_dict = OrderedDict()
        self.perception_dict['latent-obs'] = DenseBlock(
            in_keys="observation",
            out_keys="latent-obs",
            in_shapes=obs_shapes['observation'],
            hidden_units=[256],
            non_lin=non_lin)
        self.perception_dict['latent-act'] = DenseBlock(
            in_keys="action",
            out_keys="latent-act",
            in_shapes=obs_shapes['action'],
            hidden_units=[256],
            non_lin=non_lin)

        self.perception_dict['concat'] = ConcatenationBlock(
            in_keys=['latent-obs', 'latent-act'],
            in_shapes=self.perception_dict['latent-obs'].out_shapes() +
            self.perception_dict['latent-act'].out_shapes(),
            concat_dim=-1,
            out_keys='concat')

        self.perception_dict['latent'] = DenseBlock(
            in_keys="concat",
            out_keys="latent",
            in_shapes=self.perception_dict['concat'].out_shapes(),
            hidden_units=[256],
            non_lin=non_lin)

        # build action head
        self.perception_dict['q_value'] = LinearOutputBlock(
            in_keys="latent",
            out_keys="q_value",
            in_shapes=self.perception_dict['latent'].out_shapes(),
            output_units=1)

        self.perception_net = InferenceBlock(
            in_keys=['observation', 'action'],
            out_keys='q_value',
            in_shapes=[
                self.obs_shapes['observation'], self.obs_shapes['action']
            ],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['q_value'].apply(make_module_init_normc(0.01))
Exemple #6
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 action_logits_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str, type(nn.Module)]):
        super().__init__()
        self.obs_shapes = obs_shapes
        action_key = list(action_logits_shapes.keys())[0]
        # build perception part
        self.perception_dict = OrderedDict()
        self.perception_dict['embedding'] = DenseBlock(
            in_keys="observation",
            out_keys="embedding",
            in_shapes=obs_shapes['observation'],
            hidden_units=[256, 256],
            non_lin=non_lin)

        # build action head
        self.perception_dict[action_key] = LinearOutputBlock(
            in_keys="embedding",
            out_keys=action_key,
            in_shapes=self.perception_dict['embedding'].out_shapes(),
            output_units=action_logits_shapes[action_key][0])

        self.perception_net = InferenceBlock(
            in_keys='observation',
            out_keys=action_key,
            in_shapes=[self.obs_shapes['observation']],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict[action_key].apply(make_module_init_normc(0.01))
Exemple #7
0
    def __init__(self, in_keys: Union[str,
                                      List[str]], out_keys: Union[str,
                                                                  List[str]],
                 in_shapes: Union[Sequence[int], List[Sequence[int]]],
                 hidden_channels: List[int], hidden_units: List[int],
                 non_lin: Union[str, type(nn.Module)]):
        super().__init__(in_keys=in_keys,
                         out_keys=out_keys,
                         in_shapes=in_shapes)

        out_keys_conv = [f"{k}_conv" for k in self.out_keys]
        self.conv_block = VGGConvolutionBlock(in_keys=in_keys,
                                              out_keys=out_keys_conv,
                                              in_shapes=in_shapes,
                                              hidden_channels=hidden_channels,
                                              non_lin=non_lin)

        out_keys_flatten = [f"{k}_flat" for k in out_keys_conv
                            ] if len(hidden_units) > 0 else out_keys
        self.flatten_block = FlattenBlock(
            in_keys=out_keys_conv,
            out_keys=out_keys_flatten,
            in_shapes=self.conv_block.out_shapes(),
            num_flatten_dims=3)

        self.dense_block = None
        if len(hidden_units) > 0:
            self.dense_block = DenseBlock(
                in_keys=out_keys_flatten,
                out_keys=out_keys,
                in_shapes=self.flatten_block.out_shapes(),
                hidden_units=hidden_units,
                non_lin=non_lin)
Exemple #8
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 non_lin: type(nn.Module)):
        super().__init__(obs_shapes, non_lin)

        self.perception_dict['value_head_net'] = DenseBlock(
            in_keys='hidden_out',
            in_shapes=self.perception_dict['hidden_out'].out_shapes(),
            out_keys='value_head_net',
            hidden_units=[5, 2],
            non_lin=non_lin)

        self.perception_dict['value'] = LinearOutputBlock(
            in_keys='value_head_net',
            in_shapes=self.perception_dict['value_head_net'].out_shapes(),
            out_keys='value',
            output_units=1)

        # Set up inference block
        self.perception_net = InferenceBlock(
            in_keys=list(self.obs_shapes.keys()),
            out_keys='value',
            in_shapes=[self.obs_shapes[key] for key in self.obs_shapes.keys()],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['value'].apply(make_module_init_normc(0.01))
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 head_units: List[int], non_lin: nn.Module):
        super().__init__()

        self.perception_dict: Dict[str, PerceptionBlock] = dict()
        # build action head

        # build perception part
        self.perception_dict["head"] = DenseBlock(
            in_keys="latent",
            out_keys="head",
            in_shapes=obs_shapes["latent"],
            hidden_units=head_units,
            non_lin=non_lin)

        self.perception_dict["value"] = LinearOutputBlock(
            in_keys="head",
            out_keys="value",
            in_shapes=self.perception_dict["head"].out_shapes(),
            output_units=1)

        self.perception_dict['head'].apply(make_module_init_normc(std=1.0))
        self.perception_dict["value"].apply(make_module_init_normc(std=0.01))

        # compile inference model
        self.net = InferenceBlock(in_keys=list(obs_shapes.keys()),
                                  out_keys="value",
                                  in_shapes=list(obs_shapes.values()),
                                  perception_blocks=self.perception_dict)
    def __init__(self,
                 obs_shapes: Dict[str, Sequence[int]],
                 action_logits_shapes: Dict[str, Sequence[int]],
                 hidden_units: List[int],
                 head_units: List[int],
                 non_lin=nn.Module):
        super().__init__(obs_shapes, hidden_units, non_lin)

        # build perception part
        self.perception_dict["head"] = DenseBlock(
            in_keys="latent",
            out_keys="head",
            in_shapes=self.perception_dict["latent"].out_shapes(),
            hidden_units=head_units,
            non_lin=self.non_lin)

        self.perception_dict['head'].apply(make_module_init_normc(std=1.0))

        # build action head
        for action, shape in action_logits_shapes.items():
            self.perception_dict[action] = LinearOutputBlock(
                in_keys="head",
                out_keys=action,
                in_shapes=self.perception_dict["head"].out_shapes(),
                output_units=action_logits_shapes[action][-1])

            module_init = make_module_init_normc(std=0.01)
            self.perception_dict[action].apply(module_init)

        # compile inference model
        self.net = InferenceBlock(in_keys=list(obs_shapes.keys()),
                                  out_keys=list(action_logits_shapes.keys()) +
                                  ['latent'],
                                  in_shapes=list(obs_shapes.values()),
                                  perception_blocks=self.perception_dict)
    def __init__(self, obs_shapes: Dict[str, Sequence[int]], action_logits_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str, type(nn.Module)], hidden_units: List[int]):
        super().__init__()

        # Maze relies on dictionaries to represent the inference graph
        self.perception_dict = OrderedDict()

        # build latent embedding block
        self.perception_dict['latent'] = DenseBlock(
            in_keys='observation', out_keys='latent', in_shapes=obs_shapes['observation'],
            hidden_units=hidden_units,non_lin=non_lin)

        # build action head
        self.perception_dict['action'] = LinearOutputBlock(
            in_keys='latent', out_keys='action', in_shapes=self.perception_dict['latent'].out_shapes(),
            output_units=int(np.prod(action_logits_shapes["action"])))

        # build inference block
        self.perception_net = InferenceBlock(
            in_keys='observation', out_keys='action', in_shapes=obs_shapes['observation'],
            perception_blocks=self.perception_dict)

        # apply weight init
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['action'].apply(make_module_init_normc(0.01))
Exemple #12
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]], action_logits_shapes: Dict[str, Sequence[int]],
                 non_lin: type(nn.Module)):
        super().__init__(obs_shapes, non_lin)

        for action_head_name in action_logits_shapes.keys():
            head_hidden_units = [lambda out_shape: out_shape[0] * 5,
                                 lambda out_shape: out_shape[0] * 2,
                                 lambda out_shape: out_shape[0]]
            head_hidden_units = [func(action_logits_shapes[action_head_name]) for func in head_hidden_units]

            self.perception_dict[f'{action_head_name}_net'] = DenseBlock(
                in_keys='hidden_out', in_shapes=self.perception_dict['hidden_out'].out_shapes(),
                out_keys=f'{action_head_name}_net', hidden_units=head_hidden_units[:-1], non_lin=non_lin)

            self.perception_dict[f'{action_head_name}'] = LinearOutputBlock(
                in_keys=f'{action_head_name}_net',
                in_shapes=self.perception_dict[f'{action_head_name}_net'].out_shapes(),
                out_keys=action_head_name, output_units=head_hidden_units[-1]
            )

        # Set up inference block
        self.perception_net = InferenceBlock(
            in_keys=list(self.obs_shapes.keys()), out_keys=list(action_logits_shapes.keys()),
            in_shapes=[self.obs_shapes[key] for key in self.obs_shapes.keys()],
            perception_blocks=self.perception_dict)

        self.perception_net.apply(make_module_init_normc(1.0))
        for action_head_name in action_logits_shapes.keys():
            self.perception_dict[f'{action_head_name}'].apply(make_module_init_normc(0.01))
Exemple #13
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str, type(nn.Module)]):
        nn.Module.__init__(self)

        # initialize the perception dictionary
        self.perception_dict = OrderedDict()

        # concatenate all observations in dictionary
        self.perception_dict['concat'] = ConcatenationBlock(
            in_keys=[
                'cart_position', 'cart_velocity', 'pole_angle',
                'pole_angular_velocity'
            ],
            out_keys='concat',
            in_shapes=[
                obs_shapes['cart_position'], obs_shapes['cart_velocity'],
                obs_shapes['pole_angle'], obs_shapes['pole_angular_velocity']
            ],
            concat_dim=-1)

        # process concatenated representation with two dense layers
        self.perception_dict['embedding'] = DenseBlock(
            in_keys='concat',
            in_shapes=self.perception_dict['concat'].out_shapes(),
            hidden_units=[128, 128],
            non_lin=non_lin,
            out_keys='embedding')

        # add a linear output block
        self.perception_dict['value'] = LinearOutputBlock(
            in_keys='embedding',
            out_keys='value',
            in_shapes=self.perception_dict['embedding'].out_shapes(),
            output_units=1)

        # compile an inference block
        self.perception_net = InferenceBlock(
            in_keys=[
                'cart_position', 'cart_velocity', 'pole_angle',
                'pole_angular_velocity'
            ],
            out_keys='value',
            in_shapes=[
                obs_shapes[key] for key in [
                    'cart_position', 'cart_velocity', 'pole_angle',
                    'pole_angular_velocity'
                ]
            ],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['value'].apply(make_module_init_normc(0.01))
Exemple #14
0
    def __init__(self, obs_shapes, action_logits_shapes, non_lin=nn.Tanh):
        super().__init__()

        # build perception part
        self.perception_network = DenseBlock(in_keys="observation", out_keys="latent",
                                             in_shapes=obs_shapes['observation'],
                                             hidden_units=[32, 32], non_lin=non_lin)

        module_init = make_module_init_normc(std=1.0)
        self.perception_network.apply(module_init)

        # build action head
        self.action_head = LinearOutputBlock(in_keys="latent", out_keys="action",
                                             in_shapes=self.perception_network.out_shapes(),
                                             output_units=action_logits_shapes['action'][-1])

        module_init = make_module_init_normc(std=0.01)
        self.action_head.apply(module_init)

        # compile inference model
        self.net = InferenceBlock(in_keys="observation", out_keys="action", in_shapes=list(obs_shapes.values()),
                                  perception_blocks={"latent": self.perception_network,
                                                     "action": self.action_head})
Exemple #15
0
    def __init__(self, in_keys: Union[str,
                                      List[str]], out_keys: Union[str,
                                                                  List[str]],
                 in_shapes: Union[Sequence[int], List[Sequence[int]]],
                 hidden_channels: List[int],
                 hidden_kernels: List[Union[int, Tuple[int, ...]]],
                 convolution_dimension: int,
                 hidden_strides: Optional[List[Union[int, Tuple[int, ...]]]],
                 hidden_dilations: Optional[List[Union[int, Tuple[int, ...]]]],
                 hidden_padding: Optional[List[Union[int, Tuple[int, ...]]]],
                 padding_mode: Optional[str], hidden_units: List[int],
                 non_lin: Union[str, type(nn.Module)]):
        super().__init__(in_keys=in_keys,
                         out_keys=out_keys,
                         in_shapes=in_shapes)

        out_keys_conv = [f"{k}_conv" for k in self.out_keys]
        self.conv_block = StridedConvolutionBlock(
            in_keys=in_keys,
            out_keys=out_keys_conv,
            in_shapes=in_shapes,
            hidden_channels=hidden_channels,
            hidden_kernels=hidden_kernels,
            convolution_dimension=convolution_dimension,
            hidden_strides=hidden_strides,
            hidden_dilations=hidden_dilations,
            hidden_padding=hidden_padding,
            padding_mode=padding_mode,
            non_lin=non_lin)

        out_keys_flatten = [f"{k}_flat" for k in out_keys_conv
                            ] if len(hidden_units) > 0 else out_keys
        self.flatten_block = FlattenBlock(
            in_keys=out_keys_conv,
            out_keys=out_keys_flatten,
            in_shapes=self.conv_block.out_shapes(),
            num_flatten_dims=3)

        if len(hidden_units) > 0:
            self.dense_block = DenseBlock(
                in_keys=out_keys_flatten,
                out_keys=out_keys,
                in_shapes=self.flatten_block.out_shapes(),
                hidden_units=hidden_units,
                non_lin=non_lin)
        else:
            self.dense_block = None
Exemple #16
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 non_lin: type(nn.Module)):
        nn.Module.__init__(self)
        self.obs_shapes = obs_shapes
        perception_dict: Dict[str, PerceptionBlock] = dict()

        for in_key, in_shape in self.obs_shapes.items():
            if len(in_shape) > 1:
                next_in_key = f'{in_key}_flat'
                perception_dict[next_in_key] = FlattenBlock(
                    in_keys=in_key,
                    in_shapes=in_shape,
                    out_keys=next_in_key,
                    num_flatten_dims=len(in_shape))
                next_in_shape = perception_dict[next_in_key].out_shapes()
            else:
                next_in_key = in_key
                next_in_shape = in_shape

            perception_dict[f'{in_key}_encoded_feat'] = DenseBlock(
                in_keys=next_in_key,
                in_shapes=next_in_shape,
                out_keys=f'{in_key}_encoded_feat',
                non_lin=non_lin,
                hidden_units=[16])
            perception_dict[f'{in_key}_encoded_layer'] = LinearOutputBlock(
                in_keys=f'{in_key}_encoded_feat',
                in_shapes=perception_dict[f'{in_key}_encoded_feat'].out_shapes(
                ),
                out_keys=f'{in_key}_encoded_layer',
                output_units=8)

        concat_in_keys = [
            key for key in perception_dict.keys() if '_encoded_layer' in key
        ]
        perception_dict['hidden_out'] = ConcatenationBlock(
            in_keys=concat_in_keys,
            in_shapes=sum(
                [perception_dict[key].out_shapes() for key in concat_in_keys],
                []),
            out_keys='hidden_out',
            concat_dim=-1)

        self.perception_dict = perception_dict
Exemple #17
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 hidden_units: List[int], non_lin: nn.Module):
        super().__init__()
        self.hidden_units = hidden_units
        self.non_lin = non_lin

        self.perception_dict: Dict[str, PerceptionBlock] = dict()

        # first, flatten all observations
        flat_keys = []
        for obs, shape in obs_shapes.items():
            out_key = f'{obs}_flat'
            flat_keys.append(out_key)
            self.perception_dict[out_key] = FlattenBlock(
                in_keys=obs,
                out_keys=out_key,
                in_shapes=shape,
                num_flatten_dims=len(shape))

        # next, concatenate flat observations
        in_shapes = [
            self.perception_dict[k].out_shapes()[0] for k in flat_keys
        ]
        self.perception_dict["concat"] = ConcatenationBlock(
            in_keys=flat_keys,
            out_keys='concat',
            in_shapes=in_shapes,
            concat_dim=-1)

        # build perception part
        self.perception_dict["latent"] = DenseBlock(
            in_keys="concat",
            out_keys="latent",
            in_shapes=self.perception_dict["concat"].out_shapes(),
            hidden_units=self.hidden_units,
            non_lin=self.non_lin)

        # initialize model weights
        module_init = make_module_init_normc(std=1.0)
        for key in self.perception_dict.keys():
            self.perception_dict[key].apply(module_init)
Exemple #18
0
def build_perception_dict():
    """ helper function """
    in_dict = build_multi_input_dict(dims=[[100, 1, 16], [100, 1, 8]])

    perception_dict = dict()
    for in_key, in_tensor in in_dict.items():
        # compile network block
        net = DenseBlock(in_keys=in_key,
                         out_keys=f"{in_key}_feat",
                         in_shapes=[in_tensor.shape[-1:]],
                         hidden_units=[32, 32],
                         non_lin=nn.ReLU)
        perception_dict[f"{in_key}_feat"] = net

    net = ConcatenationBlock(in_keys=list(perception_dict.keys()),
                             out_keys="concat",
                             in_shapes=[(32, ), (32, )],
                             concat_dim=-1)
    perception_dict["concat"] = net

    return in_dict, perception_dict
def build_perception_dict():
    """ helper function """
    obs_keys = ["obs_inventory", "obs_screen"]
    in_dict = build_multi_input_dict(dims=[[1, 16], [1, 3, 64, 64]],
                                     names=obs_keys)

    perception_dict = dict()

    # --- block ---
    net = DenseBlock(in_keys="obs_inventory", out_keys="obs_inventory_latent",
                     in_shapes=[in_dict["obs_inventory"].shape[-1:]],
                     hidden_units=[32, 32],
                     non_lin=nn.ReLU)
    perception_dict["obs_inventory_latent"] = net

    # --- block ---
    net = VGGConvolutionDenseBlock(in_keys="obs_screen", out_keys="obs_screen_latent",
                                   in_shapes=[in_dict["obs_screen"].shape[-3:]],
                                   hidden_channels=[8, 16, 32],
                                   hidden_units=[32],
                                   non_lin=nn.ReLU)
    perception_dict["obs_screen_latent"] = net

    # --- block ---
    net = ConcatenationBlock(in_keys=list(perception_dict.keys()), out_keys="concat",
                             in_shapes=[(32,), (32,)], concat_dim=-1)
    perception_dict["concat"] = net

    # --- block ---
    net = LinearOutputBlock(in_keys=["concat"], out_keys="action_move",
                            in_shapes=[(64,)], output_units=4)
    perception_dict["action_move"] = net

    # --- block ---
    net = LinearOutputBlock(in_keys=["concat"], out_keys="action_use",
                            in_shapes=[(64,)], output_units=16)
    perception_dict["action_use"] = net

    return in_dict, perception_dict
Exemple #20
0
    def __init__(self, in_keys: Union[str,
                                      List[str]], out_keys: Union[str,
                                                                  List[str]],
                 in_shapes: Union[Sequence[int],
                                  List[Sequence[int]]], num_flatten_dims: int,
                 hidden_units: List[int], non_lin: Union[str,
                                                         type(nn.Module)]):
        super().__init__(in_keys=in_keys,
                         out_keys=out_keys,
                         in_shapes=in_shapes)

        out_keys_flatten = [f"{k}_flat" for k in self.out_keys]
        self.flatten_block = FlattenBlock(in_keys=self.in_keys,
                                          out_keys=out_keys_flatten,
                                          in_shapes=self.in_shapes,
                                          num_flatten_dims=num_flatten_dims)

        self.dense_block = DenseBlock(
            in_keys=out_keys_flatten,
            out_keys=out_keys,
            in_shapes=self.flatten_block.out_shapes(),
            hidden_units=hidden_units,
            non_lin=non_lin)
Exemple #21
0
def test_mlp_and_concat():
    """ perception test """

    in_dict = build_multi_input_dict(dims=[[100, 1, 16], [100, 1, 8]])

    feat_dict = dict()
    for in_key, in_tensor in in_dict.items():
        # compile network block
        net = DenseBlock(in_keys=in_key,
                         out_keys=f"{in_key}_feat",
                         in_shapes=(in_tensor.shape[-1], ),
                         hidden_units=[32, 32],
                         non_lin=nn.ReLU)

        # update output dictionary
        feat_dict.update(net(in_dict))

    net = ConcatenationBlock(in_keys=list(feat_dict.keys()),
                             out_keys="concat",
                             in_shapes=[(32, ), (32, )],
                             concat_dim=-1)
    out_dict = net(feat_dict)
    assert out_dict["concat"].ndim == 3
    assert out_dict["concat"].shape[-1] == 64
Exemple #22
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 action_logits_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str, type(nn.Module)], with_mask: bool):
        nn.Module.__init__(self)
        self.obs_shapes = obs_shapes

        hidden_units = 32

        self.perception_dict = OrderedDict()

        self.perception_dict['selected_feat'] = DenseBlock(
            in_keys='selected_piece',
            out_keys='selected_feat',
            in_shapes=self.obs_shapes['selected_piece'],
            hidden_units=[hidden_units],
            non_lin=non_lin)

        self.perception_dict['order_feat'] = DenseBlock(
            in_keys='ordered_piece',
            out_keys='order_feat',
            in_shapes=self.obs_shapes['ordered_piece'],
            hidden_units=[hidden_units],
            non_lin=non_lin)

        self.perception_dict['latent'] = ConcatenationBlock(
            in_keys=['selected_feat', 'order_feat'],
            out_keys='latent',
            in_shapes=[[hidden_units], [hidden_units]],
            concat_dim=-1)

        rotation_out_key = 'cut_rotation_logits' if with_mask else 'cut_rotation'
        self.perception_dict[rotation_out_key] = LinearOutputBlock(
            in_keys='latent',
            out_keys=rotation_out_key,
            in_shapes=self.perception_dict['latent'].out_shapes(),
            output_units=action_logits_shapes['cut_rotation'][0])

        if with_mask:
            self.perception_dict['cut_rotation'] = ActionMaskingBlock(
                in_keys=['cut_rotation_logits', 'cutting_mask'],
                out_keys='cut_rotation',
                in_shapes=self.perception_dict['cut_rotation_logits'].
                out_shapes() + [self.obs_shapes['cutting_mask']],
                num_actors=1,
                num_of_actor_actions=None)

        self.perception_dict['cut_order'] = LinearOutputBlock(
            in_keys='latent',
            out_keys='cut_order',
            in_shapes=self.perception_dict['latent'].out_shapes(),
            output_units=action_logits_shapes['cut_order'][0])

        in_keys = ['selected_piece', 'ordered_piece']
        if with_mask:
            in_keys.append('cutting_mask')
        self.perception_net = InferenceBlock(
            in_keys=in_keys,
            out_keys=['cut_rotation', 'cut_order'],
            in_shapes=[self.obs_shapes[key] for key in in_keys],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict[rotation_out_key].apply(
            make_module_init_normc(0.01))
        self.perception_dict['cut_order'].apply(make_module_init_normc(0.01))
Exemple #23
0
    def __init__(self, obs_shapes: Dict[str, Sequence[int]],
                 action_logits_shapes: Dict[str, Sequence[int]],
                 non_lin: Union[str, type(nn.Module)], with_mask: bool):
        nn.Module.__init__(self)
        self.obs_shapes = obs_shapes

        hidden_units, embedding_dim = 32, 7

        self.perception_dict = OrderedDict()

        # embed inventory
        # ---------------
        self.perception_dict['inventory_feat'] = DenseBlock(
            in_keys='inventory',
            out_keys='inventory_feat',
            in_shapes=self.obs_shapes['inventory'],
            hidden_units=[hidden_units],
            non_lin=non_lin)

        self.perception_dict['inventory_embed'] = LinearOutputBlock(
            in_keys='inventory_feat',
            out_keys='inventory_embed',
            in_shapes=self.perception_dict['inventory_feat'].out_shapes(),
            output_units=embedding_dim)

        # embed ordered_piece
        # ------------------_
        self.perception_dict['order_unsqueezed'] = FunctionalBlock(
            in_keys='ordered_piece',
            out_keys='order_unsqueezed',
            in_shapes=self.obs_shapes['ordered_piece'],
            func=lambda x: torch.unsqueeze(x, dim=-2))

        self.perception_dict['order_feat'] = DenseBlock(
            in_keys='order_unsqueezed',
            out_keys='order_feat',
            in_shapes=self.perception_dict['order_unsqueezed'].out_shapes(),
            hidden_units=[hidden_units],
            non_lin=non_lin)

        self.perception_dict['order_embed'] = LinearOutputBlock(
            in_keys='order_feat',
            out_keys='order_embed',
            in_shapes=self.perception_dict['order_feat'].out_shapes(),
            output_units=embedding_dim)

        # compute dot product score
        # -------------------------
        in_shapes = self.perception_dict['inventory_embed'].out_shapes()
        in_shapes += self.perception_dict['order_embed'].out_shapes()
        out_key = 'corr_score' if with_mask else 'piece_idx'
        self.perception_dict[out_key] = CorrelationBlock(
            in_keys=['inventory_embed', 'order_embed'],
            out_keys=out_key,
            in_shapes=in_shapes,
            reduce=True)

        # apply action masking
        if with_mask:
            self.perception_dict['piece_idx'] = ActionMaskingBlock(
                in_keys=['corr_score', 'inventory_mask'],
                out_keys='piece_idx',
                in_shapes=self.perception_dict['corr_score'].out_shapes() +
                [self.obs_shapes['inventory_mask']],
                num_actors=1,
                num_of_actor_actions=None)

        assert self.perception_dict['piece_idx'].out_shapes(
        )[0][0] == action_logits_shapes['piece_idx'][0]

        in_keys = ['ordered_piece', 'inventory']
        if with_mask:
            in_keys.append('inventory_mask')
        self.perception_net = InferenceBlock(
            in_keys=in_keys,
            out_keys='piece_idx',
            in_shapes=[self.obs_shapes[key] for key in in_keys],
            perception_blocks=self.perception_dict)

        # initialize model weights
        self.perception_net.apply(make_module_init_normc(1.0))
        self.perception_dict['inventory_embed'].apply(
            make_module_init_normc(0.01))
        self.perception_dict['order_embed'].apply(make_module_init_normc(0.01))