TensorDictPrimer¶
- class torchrl.envs.transforms.TensorDictPrimer(primers: Optional[Union[dict, Composite]] = None, random: Optional[bool] = None, default_value: Optional[Union[float, Callable, Dict[NestedKey, float], Dict[NestedKey, Callable]]] = None, reset_key: Optional[NestedKey] = None, **kwargs)[source]¶
用于在重置时初始化 TensorDict 的 Primer。
此转换将在重置时使用初始化时提供的相关 tensorspecs 中的值填充 tensordict。如果在环境上下文之外使用转换(例如,作为 nn.Module 或附加到回放缓冲区),则调用 forward 也将使用所需的功能填充 tensordict。
- 参数:
primers (dict 或 Composite, 可选) – 包含将用于填充输入 tensordict 的键值对的字典。也支持
Composite
实例。random (bool, 可选) – 如果为
True
,则值将从 TensorSpec 域中随机抽取(如果无界,则从单位高斯分布中抽取)。否则,将假定为固定值。默认为 False。default_value (float, Callable, Dict[NestedKey, float], Dict[NestedKey, Callable], 可选) – 如果选择非随机填充,则将使用 default_value 来填充张量。如果 default_value 是浮点数,则张量的所有元素都将设置为该值。如果它是一个可调用对象,则期望此可调用对象返回适合规范的张量,并将用于生成张量。最后,如果 default_value 是张量字典或可调用对象字典,其键与规范的键匹配,则将使用这些字典来生成相应的张量。默认为 0.0。
reset_key (NestedKey, 可选) – 用作部分重置指示器的重置键。必须是唯一的。如果未提供,则默认为父环境的唯一重置键(如果只有一个),否则会引发异常。
**kwargs – 每个关键字参数对应于 tensordict 中的一个键。对应的值必须是 TensorSpec 实例,指示该值必须是什么。
当在 TransfomedEnv 中使用时,如果父环境是批次锁定的 (
env.batch_locked=True
),则规范形状必须与 envs 形状匹配。如果 env 未批次锁定(例如,基于模型的 env),则假定批次由输入 tensordict 提供。示例
>>> 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.]])
注意
一些 TorchRL 模块依赖于环境中 TensorDicts 中存在的特定键,例如
LSTM
或GRU
。为了方便此过程,方法get_primers_from_module()
会自动检查模块及其子模块中所需的 primer 转换并生成它们。- 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 和设备是此模块中所有参数和缓冲区的所需 dtype 和设备
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 [source]¶
转换输入规范,使结果规范与转换映射匹配。
- 参数:
input_spec (TensorSpec) – 转换前的规范
- 返回:
转换后预期的规范
- transform_observation_spec(observation_spec: Composite) Composite [source]¶
转换观察规范,使结果规范与转换映射匹配。
- 参数:
observation_spec (TensorSpec) – 转换前的规范
- 返回:
转换后预期的规范