AddStateIndependentNormalScale#
- class tensordict.nn.distributions.AddStateIndependentNormalScale(scale_shape: Size | int | tuple = None, *, scale_mapping: str = 'exp', scale_lb: Number = 0.0001, device: device | None = None, make_param: bool = True, init_value: float = 0.0)#
Bases:
ModuleA module that returns its input as a location, with a learned scale that does not depend on the input.
The module holds one tensor,
state_independent_scale, of shapescale_shape.module(loc, *others)returns(loc, scale, *others), wherescaleis that tensor expanded to the shape ofloc, mapped byscale_mappingand clamped to at leastscale_lb. UnlikeNormalParamExtractor, the input is not split: all of it is the location.- Parameters:
scale_shape (Size, int or tuple of int, optional) – the shape of the scale tensor. It must match the trailing dimensions of
loc, or the call raises aRuntimeError. Defaults totorch.Size(()): one scale for all the elements.- Keyword Arguments:
scale_mapping (str, optional) – the function that maps the scale tensor to positive values, by name, for example
"softplus","exp"or"biased_softplus_1.0". Seemappings(). Defaults to"exp".scale_lb (Number, optional) – the minimum value of the scale (the standard deviation). Defaults to
1e-4.device (device, optional) – the device of the scale tensor. Defaults to
None, the default device.make_param (bool, optional) – if
True, the scale tensor is a trainableParameter. IfFalse, it is a buffer. Defaults toTrue.init_value (float, optional) – the initial value of the scale tensor, before
scale_mapping. With the default"exp"mapping,0.0gives a scale of1. Defaults to0.0.
Examples
>>> from torch import nn >>> import torch >>> from tensordict.nn.distributions import AddStateIndependentNormalScale >>> num_outputs = 4 >>> module = nn.Linear(3, num_outputs) >>> module_normal = AddStateIndependentNormalScale(num_outputs) >>> tensor = torch.randn(3) >>> loc, scale = module_normal(module(tensor)) >>> print(loc.shape, scale.shape) torch.Size([4]) torch.Size([4]) >>> assert (scale > 0).all() >>> # with modules that return more than one tensor >>> module = nn.LSTM(3, num_outputs) >>> module_normal = AddStateIndependentNormalScale(num_outputs) >>> tensor = torch.randn(4, 2, 3) >>> loc, scale, others = module_normal(*module(tensor)) >>> print(loc.shape, scale.shape) torch.Size([4, 2, 4]) torch.Size([4, 2, 4]) >>> assert (scale > 0).all()
- forward(loc: Tensor, *others: Tensor) tuple[Tensor, ...]#
Returns
loc, the scale expanded to the shape ofloc, andothers.- Parameters:
loc (Tensor) – the location. Its trailing dimensions must match
scale_shape.*others – other values, returned unchanged.
- Returns:
The tuple
(loc, scale, *others).- Raises:
RuntimeError – if the trailing dimensions of
locdo not matchscale_shape.