TensorDictPrimer¶
- class torchrl.envs.transforms.TensorDictPrimer(primers: dict | Composite | None = None, random: bool | None = None, default_value: float | Callable | dict[NestedKey, float] | dict[NestedKey, Callable] | None = None, reset_key: NestedKey | None = None, expand_specs: bool | None = None, single_default_value: bool = False, call_before_env_reset: bool = False, **kwargs)[source]¶
一个用于在重置时初始化 TensorDict 的 primer。
此转换将在重置时使用初始化时提供的相对 tensorspecs 中提取的值来填充 tensordict。如果转换在 env 上下文之外使用(例如作为 nn.Module 或附加到回放缓冲区),调用 forward 也会使用期望的特征来填充 tensordict。
- 参数:
primers (dict 或 Composite, 可选) – 包含 key-spec 对的字典,将用于填充输入 tensordict。也支持
Composite
实例。random (bool, 可选) – 如果为
True
,则值将从 TensorSpec 域(或无界情况下的单位高斯)中随机抽取。否则将假定一个固定值。默认为 False。default_value (
float
, Callable, Dict[NestedKey, float], Dict[NestedKey, Callable], 可选) –如果选择非随机填充,将使用 default_value 来填充张量。
如果 default_value 是一个浮点数或任何其他标量,张量的所有元素都将被设置为该值。
如果它是一个可调用对象且 single_default_value=False(默认),则预期此可调用对象将返回一个适合 spec 的张量(即,
default_value()
将独立地为每个叶子 spec 调用)。如果它是一个可调用对象且
single_default_value=True
,则该可调用对象将只调用一次,并且预期其返回的 TensorDict 实例或等效实例的结构将与提供的 spec 匹配。default_value
必须接受一个可选的 reset 关键字参数,指示哪些 envs 需要重置。返回的TensorDict
必须包含与需要重置的 envs 数量相同的元素。另请参阅
DataLoadingPrimer
最后,如果 default_value 是一个张量字典或一个键与 spec 匹配的可调用对象字典,它们将用于生成相应的张量。默认为 0.0。
reset_key (NestedKey, 可选) – 用作部分重置指示符的重置键。必须是唯一的。如果未提供,则默认为父环境的唯一重置键(如果它只有一个),否则会引发异常。
single_default_value (bool, 可选) – 如果为
True
且 default_value 是可调用对象,则预期default_value
返回一个与 spec 匹配的单个 tensordict。如果为False
,则default_value()
将为每个叶子独立调用。默认为False
。call_before_env_reset (bool, 可选) – 如果为
True
,则在调用 env.reset 之前填充 tensordict。默认为False
。**kwargs – 每个关键字参数对应 tensordict 中的一个键。相应的 V 值必须是一个 TensorSpec 实例,指示值必须是什么。
当在 TransformedEnv 中使用时,如果父环境是批次锁定的 (env.batch_locked=True),spec 的形状必须与环境的形状匹配。如果 spec 形状和父级形状不匹配,则会就地修改 spec 形状以匹配父级批次大小的前导维度。这种调整是为了处理父级批次大小维度在实例化期间未知的情况。
示例
>>> from torchrl.envs.libs.gym import GymEnv >>> from torchrl.envs import SerialEnv >>> base_env = SerialEnv(2, lambda: GymEnv("Pendulum-v1")) >>> env = TransformedEnv(base_env) >>> # the env is batch-locked, so the leading dims of the spec must match those of the env >>> env.append_transform(TensorDictPrimer(mykey=Unbounded([2, 3]))) >>> td = env.reset() >>> print(td) TensorDict( fields={ done: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False), mykey: Tensor(shape=torch.Size([2, 3]), device=cpu, dtype=torch.float32, is_shared=False), observation: Tensor(shape=torch.Size([2, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([2]), device=cpu, is_shared=False) >>> # the entry is populated with 0s >>> print(td.get("mykey")) tensor([[0., 0., 0.], [0., 0., 0.]])
当调用
env.step()
时,键的当前值将在"next"
tensordict 中传递,__除非它已经存在__。示例
>>> td = env.rand_step(td) >>> print(td.get(("next", "mykey"))) tensor([[0., 0., 0.], [0., 0., 0.]]) >>> # with another value for "mykey", the previous value is not carried on >>> td = env.reset() >>> td = td.set(("next", "mykey"), torch.ones(2, 3)) >>> td = env.rand_step(td) >>> print(td.get(("next", "mykey"))) tensor([[1., 1., 1.], [1., 1., 1.]])
示例
>>> from torchrl.envs.libs.gym import GymEnv >>> from torchrl.envs import SerialEnv, TransformedEnv >>> from torchrl.modules.utils import get_primers_from_module >>> from torchrl.modules import GRUModule >>> base_env = SerialEnv(2, lambda: GymEnv("Pendulum-v1")) >>> env = TransformedEnv(base_env) >>> model = GRUModule(input_size=2, hidden_size=2, in_key="observation", out_key="action") >>> primers = get_primers_from_module(model) >>> print(primers) # Primers shape is independent of the env batch size TensorDictPrimer(primers=Composite( recurrent_state: UnboundedContinuous( shape=torch.Size([1, 2]), space=ContinuousBox( low=Tensor(shape=torch.Size([1, 2]), device=cpu, dtype=torch.float32, contiguous=True), high=Tensor(shape=torch.Size([1, 2]), device=cpu, dtype=torch.float32, contiguous=True)), device=cpu, dtype=torch.float32, domain=continuous), device=None, shape=torch.Size([])), default_value={'recurrent_state': 0.0}, random=None) >>> env.append_transform(primers) >>> print(env.reset()) # The primers are automatically expanded to match the env batch size TensorDict( fields={ done: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False), observation: Tensor(shape=torch.Size([2, 3]), device=cpu, dtype=torch.float32, is_shared=False), recurrent_state: Tensor(shape=torch.Size([2, 1, 2]), device=cpu, dtype=torch.float32, is_shared=False), terminated: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False), truncated: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False)}, batch_size=torch.Size([2]), device=None, is_shared=False)
注意
某些 TorchRL 模块依赖于在环境 TensorDicts 中存在特定键,例如
LSTM
或GRU
。为了方便此过程,方法get_primers_from_module()
会自动检查模块及其子模块中所需的 primer 转换并生成它们。- forward(tensordict: TensorDictBase) TensorDictBase [source]¶
读取输入 tensordict,并对选定的键应用转换。
默认情况下,此方法
直接调用
_apply_transform()
。不调用
_step()
或_call()
。
此方法不会在任何点在 env.step 内调用。但是,它会在
sample()
中调用。注意
forward
也可以通过dispatch
使用常规关键字参数,将参数名称转换为键。示例
>>> class TransformThatMeasuresBytes(Transform): ... '''Measures the number of bytes in the tensordict, and writes it under `"bytes"`.''' ... def __init__(self): ... super().__init__(in_keys=[], out_keys=["bytes"]) ... ... def forward(self, tensordict: TensorDictBase) -> TensorDictBase: ... bytes_in_td = tensordict.bytes() ... tensordict["bytes"] = bytes ... return tensordict >>> t = TransformThatMeasuresBytes() >>> env = env.append_transform(t) # works within envs >>> t(TensorDict(a=0)) # Works offline too.
- to(*args, **kwargs)[source]¶
移动和/或转换参数和缓冲区。
这可以这样调用
- to(device=None, dtype=None, non_blocking=False)[source]
- to(dtype, non_blocking=False)[source]
- to(tensor, non_blocking=False)[source]
- to(memory_format=torch.channels_last)[source]
其签名类似于
torch.Tensor.to()
,但仅接受浮点数或复数dtype
。此外,此方法只会将浮点数或复数参数和缓冲区转换为dtype
(如果已给出)。整数参数和缓冲区将被移动到device
(如果已给出),但 dtype 不变。当设置non_blocking
时,它会尝试尽可能异步地(相对于主机)进行转换/移动,例如,将具有固定内存的 CPU 张量移动到 CUDA 设备。有关示例,请参阅下文。
注意
此方法就地修改模块。
- 参数:
device (
torch.device
) – 此模块中参数和缓冲区的期望设备dtype (
torch.dtype
) – 此模块中参数和缓冲区的期望浮点数或复数 dtypetensor (torch.Tensor) – 其 dtype 和 device 是此模块中所有参数和缓冲区的期望 dtype 和 device 的张量
memory_format (
torch.memory_format
) – 此模块中 4D 参数和缓冲区的期望内存格式(仅关键字参数)
- 返回:
self
- 返回类型:
模块
示例
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- transform_input_spec(input_spec: TensorSpec) TensorSpec [source]¶
转换输入规范,使结果规范与转换映射匹配。
- 参数:
input_spec (TensorSpec) – 转换前的规范
- 返回:
转换后的预期规范
- transform_observation_spec(observation_spec: Composite) Composite [source]¶
转换观察规范,使结果规范与转换映射匹配。
- 参数:
observation_spec (TensorSpec) – 转换前的规范
- 返回:
转换后的预期规范