ding.model.common.encoder¶
ding.model.common.encoder
¶
ConvEncoder
¶
Bases: Module
Overview
The Convolution Encoder is used to encode 2-dim image observations.
Interfaces:
__init__, forward.
__init__(obs_shape, hidden_size_list=[32, 64, 64, 128], activation=nn.ReLU(), kernel_size=[8, 4, 3], stride=[4, 2, 1], padding=None, layer_norm=False, norm_type=None)
¶
Overview
Initialize the Convolution Encoder according to the provided arguments.
Arguments:
- obs_shape (:obj:SequenceType): Sequence of in_channel, plus one or more input size.
- hidden_size_list (:obj:SequenceType): Sequence of hidden_size of subsequent conv layers and the final dense layer.
- activation (:obj:nn.Module): Type of activation to use in the conv layers and ResBlock. Default is nn.ReLU().
- kernel_size (:obj:SequenceType): Sequence of kernel_size of subsequent conv layers.
- stride (:obj:SequenceType): Sequence of stride of subsequent conv layers.
- padding (:obj:SequenceType): Padding added to all four sides of the input for each conv layer. See nn.Conv2d for more details. Default is None.
- layer_norm (:obj:bool): Whether to use DreamerLayerNorm, which is kind of special trick proposed in DreamerV3.
- norm_type (:obj:str): Type of normalization to use. See ding.torch_utils.network.ResBlock for more details. Default is None.
forward(x)
¶
Overview
Return output 1D embedding tensor of the env's 2D image observation.
Arguments:
- x (:obj:torch.Tensor): Raw 2D observation of the environment.
Returns:
- outputs (:obj:torch.Tensor): Output embedding tensor.
Shapes:
- x : :math:(B, C, H, W), where B is batch size, C is channel, H is height, W is width.
- outputs: :math:(B, N), where N = hidden_size_list[-1] .
Examples:
>>> conv = ConvEncoder(
>>> obs_shape=(4, 84, 84),
>>> hidden_size_list=[32, 64, 64, 128],
>>> activation=nn.ReLU(),
>>> kernel_size=[8, 4, 3],
>>> stride=[4, 2, 1],
>>> padding=None,
>>> layer_norm=False,
>>> norm_type=None
>>> )
>>> x = torch.randn(1, 4, 84, 84)
>>> output = conv(x)
FCEncoder
¶
Bases: Module
Overview
The full connected encoder is used to encode 1-dim input variable.
Interfaces:
__init__, forward.
__init__(obs_shape, hidden_size_list, res_block=False, activation=nn.ReLU(), norm_type=None, dropout=None)
¶
Overview
Initialize the FC Encoder according to arguments.
Arguments:
- obs_shape (:obj:int): Observation shape.
- hidden_size_list (:obj:SequenceType): Sequence of hidden_size of subsequent FC layers.
- res_block (:obj:bool): Whether use res_block. Default is False.
- activation (:obj:nn.Module): Type of activation to use in ResFCBlock. Default is nn.ReLU().
- norm_type (:obj:str): Type of normalization to use. See ding.torch_utils.network.ResFCBlock for more details. Default is None.
- dropout (:obj:float): Dropout rate of the dropout layer. If None then default no dropout layer.
forward(x)
¶
Overview
Return output embedding tensor of the env observation.
Arguments:
- x (:obj:torch.Tensor): Env raw observation.
Returns:
- outputs (:obj:torch.Tensor): Output embedding tensor.
Shapes:
- x : :math:(B, M), where M = obs_shape.
- outputs: :math:(B, N), where N = hidden_size_list[-1].
Examples:
>>> fc = FCEncoder(
>>> obs_shape=4,
>>> hidden_size_list=[32, 64, 64, 128],
>>> activation=nn.ReLU(),
>>> norm_type=None,
>>> dropout=None
>>> )
>>> x = torch.randn(1, 4)
>>> output = fc(x)
IMPALACnnResidualBlock
¶
Bases: Module
Overview
This CNN encoder residual block is residual basic block used in IMPALA algorithm, which preserves the channel number and shape. IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures https://arxiv.org/pdf/1802.01561.pdf
Interfaces:
__init__, forward.
__init__(in_channnel, scale=1, batch_norm=False)
¶
Overview
Initialize the IMPALA CNN residual block according to arguments.
Arguments:
- in_channnel (:obj:int): Channel number of input features.
- scale (:obj:float): Scale of module, defaults to 1.
- batch_norm (:obj:bool): Whether use batch normalization, defaults to False.
residual(x)
¶
Overview
Return output tensor of the residual block, keep the shape and channel number unchanged. The inplace of activation function should be False for the first relu, so that it does not change the origin input tensor of the residual block.
Arguments:
- x (:obj:torch.Tensor): Input tensor.
Returns:
- output (:obj:torch.Tensor): Output tensor.
forward(x)
¶
Overview
Return output tensor of the residual block, keep the shape and channel number unchanged.
Arguments:
- x (:obj:torch.Tensor): Input tensor.
Returns:
- output (:obj:torch.Tensor): Output tensor.
Examples:
>>> block = IMPALACnnResidualBlock(16)
>>> x = torch.randn(1, 16, 84, 84)
>>> output = block(x)
IMPALACnnDownStack
¶
Bases: Module
Overview
Downsampling stack of CNN encoder used in IMPALA algorithmn. Every IMPALACnnDownStack consists n IMPALACnnResidualBlock, which reduces the spatial size by 2 with maxpooling. IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures https://arxiv.org/pdf/1802.01561.pdf
Interfaces:
__init__, forward.
__init__(in_channnel, nblock, out_channel, scale=1, pool=True, **kwargs)
¶
Overview
Initialize every impala cnn block of the Impala Cnn Encoder.
Arguments:
- in_channnel (:obj:int): Channel number of input features.
- nblock (:obj:int): Residual Block number in each block.
- out_channel (:obj:int): Channel number of output features.
- scale (:obj:float): Scale of the module.
- pool (:obj:bool): Whether to use maxing pooling after first conv layer.
forward(x)
¶
Overview
Return output tensor of the downsampling stack. The output shape is different from input shape. And you can refer to the output_shape method to get the output shape.
Arguments:
- x (:obj:torch.Tensor): Input tensor.
Returns:
- output (:obj:torch.Tensor): Output tensor.
Examples:
>>> stack = IMPALACnnDownStack(16, 2, 32)
>>> x = torch.randn(1, 16, 84, 84)
>>> output = stack(x)
output_shape(inshape)
¶
Overview
Calculate the output shape of the downsampling stack according to input shape and related arguments.
Arguments:
- inshape (:obj:tuple): Input shape.
Returns:
- output_shape (:obj:tuple): Output shape.
Shapes:
- inshape (:obj:tuple): :math:(C, H, W), where C is channel number, H is height and W is width.
- output_shape (:obj:tuple): :math:(C, H, W), where C is channel number, H is height and W is width.
Examples:
>>> stack = IMPALACnnDownStack(16, 2, 32)
>>> inshape = (16, 84, 84)
>>> output_shape = stack.output_shape(inshape)
IMPALAConvEncoder
¶
Bases: Module
Overview
IMPALA CNN encoder, which is used in IMPALA algorithm. IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures, https://arxiv.org/pdf/1802.01561.pdf,
Interface:
__init__, forward, output_shape.
__init__(obs_shape, channels=(16, 32, 32), outsize=256, scale_ob=255.0, nblock=2, final_relu=True, **kwargs)
¶
Overview
Initialize the IMPALA CNN encoder according to arguments.
Arguments:
- obs_shape (:obj:SequenceType): 2D image observation shape.
- channels (:obj:SequenceType): The channel number of a series of impala cnn blocks. Each element of the sequence is the output channel number of a impala cnn block.
- outsize (:obj:int): The output size the final linear layer, which means the dimension of the 1D embedding vector.
- scale_ob (:obj:float): The scale of the input observation, which is used to normalize the input observation, such as dividing 255.0 for the raw image observation.
- nblock (:obj:int): The number of Residual Block in each block.
- final_relu (:obj:bool): Whether to use ReLU activation in the final output of encoder.
- kwargs (:obj:Dict[str, Any]): Other arguments for IMPALACnnDownStack.
forward(x)
¶
Overview
Return the 1D embedding vector of the input 2D observation.
Arguments:
- x (:obj:torch.Tensor): Input 2D observation tensor.
Returns:
- output (:obj:torch.Tensor): Output 1D embedding vector.
Shapes:
- x (:obj:torch.Tensor): :math:(B, C, H, W), where B is batch size, C is channel number, H is height and W is width.
- output (:obj:torch.Tensor): :math:(B, outsize), where B is batch size.
Examples:
>>> encoder = IMPALAConvEncoder(
>>> obs_shape=(4, 84, 84),
>>> channels=(16, 32, 32),
>>> outsize=256,
>>> scale_ob=255.0,
>>> nblock=2,
>>> final_relu=True,
>>> )
>>> x = torch.randn(1, 4, 84, 84)
>>> output = encoder(x)
GaussianFourierProjectionTimeEncoder
¶
Bases: Module
Overview
Gaussian random features for encoding time steps. This module is used as the encoder of time in generative models such as diffusion model.
Interfaces:
__init__, forward.
__init__(embed_dim, scale=30.0)
¶
Overview
Initialize the Gaussian Fourier Projection Time Encoder according to arguments.
Arguments:
- embed_dim (:obj:int): The dimension of the output embedding vector.
- scale (:obj:float): The scale of the Gaussian random features.
forward(x)
¶
Overview
Return the output embedding vector of the input time step.
Arguments:
- x (:obj:torch.Tensor): Input time step tensor.
Returns:
- output (:obj:torch.Tensor): Output embedding vector.
Shapes:
- x (:obj:torch.Tensor): :math:(B,), where B is batch size.
- output (:obj:torch.Tensor): :math:(B, embed_dim), where B is batch size, embed_dim is the dimension of the output embedding vector.
Examples:
>>> encoder = GaussianFourierProjectionTimeEncoder(128)
>>> x = torch.randn(100)
>>> output = encoder(x)
prod(iterable)
¶
Overview
Product of all elements.(To be deprecated soon.) This function denifition is for supporting python version that under 3.8. In Python3.8 and larger, 'math.prod()' is recommended.
Full Source Code
../ding/model/common/encoder.py