TensorDictPrimer¶
- 类 torchrl.envs.transforms.TensorDictPrimer(primers: dict | Composite = None, random: bool | None = None, default_value: float | Callable | Dict[NestedKey, float] | Dict[NestedKey, Callable] = None, reset_key: NestedKey | None = None, expand_specs: bool = None, **kwargs)[源]¶
用于在重置时初始化 TensorDict 的 primer。
此转换将在重置时使用初始化时提供的相对 tensorspec 中的值填充 tensordict。如果在环境上下文之外使用此转换(例如作为 nn.Module 或附加到经验回放缓冲区),调用 forward 也会使用所需特征填充 tensordict。
- 参数:
primers (dict 或 Composite, 可选) – 一个包含键-spec 对的字典,将用于填充输入 tensordict。
Composite
实例也受支持。random (bool, 可选) – 如果为
True
,将从 TensorSpec 域中随机抽取值(如果无界,则从标准高斯分布中抽取)。否则将使用固定值。默认为 False。default_value (
float
, Callable, Dict[NestedKey, float], Dict[NestedKey, Callable], 可选) – 如果选择非随机填充,将使用 default_value 填充张量。如果 default_value 是一个 float,张量的所有元素都将设置为该值。如果它是一个 callable,则预期该 callable 返回一个符合 specs 的张量,并将用于生成张量。最后,如果 default_value 是一个张量字典或一个 callable 字典,且键与 specs 的键匹配,这些将用于生成相应的张量。默认为 0.0。reset_key (NestedKey, 可选) – 用作部分重置指示器的重置键。必须唯一。如果未提供,则默认为父环境的唯一重置键(如果只有一个),否则抛出异常。
**kwargs – 每个关键字参数对应 tensordict 中的一个键。相应的值必须是一个 TensorSpec 实例,指示该值必须是什么。
在 TransformedEnv 中使用时,如果父环境是 batch-locked (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 模块依赖于环境 TensorDict 中存在特定的键,例如
LSTM
或GRU
。为了简化此过程,方法get_primers_from_module()
会自动检查模块及其子模块中所需的 primer 转换并生成它们。- to(*args, **kwargs)[源]¶
移动和/或转换参数和缓冲区。
可以按如下方式调用
- to(device=None, dtype=None, non_blocking=False)[源]
- to(dtype, non_blocking=False)[源]
- to(tensor, non_blocking=False)[源]
- to(memory_format=torch.channels_last)[源]
其签名类似于
torch.Tensor.to()
,但只接受浮点型或复数型dtype
。此外,此方法仅将浮点型或复数型参数和缓冲区转换为指定的dtype
(如果给定)。如果给定了device
,整数型参数和缓冲区将被移动到该设备,但 dtype 保持不变。当设置了non_blocking
时,如果可能,它会尝试相对于主机异步转换/移动,例如将带有固定内存的 CPU 张量移动到 CUDA 设备。请参见下面的示例。
注意
此方法会原地修改模块。
- 参数:
device (
torch.device
) – 此模块中参数和缓冲区的目标设备dtype (
torch.dtype
) – 此模块中参数和缓冲区的目标浮点型或复数型 dtypetensor (torch.Tensor) – 一个 Tensor,其 dtype 和 device 是此模块中所有参数和缓冲区的目标 dtype 和 device
memory_format (
torch.memory_format
) – 此模块中 4D 参数和缓冲区的目标内存格式(仅关键字参数)
- 返回:
self
- 返回类型:
Module
示例
>>> # 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 [源]¶
转换输入 spec,使结果 spec 与转换映射匹配。
- 参数:
input_spec (TensorSpec) – 转换前的 spec
- 返回:
转换后预期的 spec
- transform_observation_spec(observation_spec: Composite) Composite [源]¶
转换观察 spec,使结果 spec 与转换映射匹配。
- 参数:
observation_spec (TensorSpec) – 转换前的 spec
- 返回:
转换后预期的 spec