快捷方式

Transform

class torchrl.envs.transforms.Transform(in_keys: Sequence[NestedKey] = None, out_keys: Sequence[NestedKey] | None = None, in_keys_inv: Sequence[NestedKey] | None = None, out_keys_inv: Sequence[NestedKey] | None = None)[源代码]

用于修改或创建 tensordict 中新数据的环境转换器的基类。

转换器用于操作环境的输入和输出数据。它们可用于预处理观察值、修改奖励或转换动作。转换器可以组合在一起,创建更复杂的转换。

转换器接收一个 tensordict 作为输入,并返回(相同或另一个)tensordict 作为输出,其中一系列值已被修改或创建了新键。

变量:
  • parent – 转换器的父环境。

  • container – 包含转换器的容器。

  • in_keys – 转换器将从中读取的输入 tensordict 的键。

  • out_keys – 转换器将写入的输出 tensordict 的键。

另请参阅

TorchRL 转换器.

继承 Transform

有多种继承转换器的方法。需要考虑的事项是

  • 对于要转换的每个张量/项,转换器是否相同?使用 _apply_transform()_inv_apply_transform()

  • 转换器需要访问 env.step 的输入数据以及输出吗?重写 _step()。否则,重写 _call()(或 _inv_call())。

  • 转换器要在回放缓冲区内使用吗?重写 forward()inv()_apply_transform()_inv_apply_transform()

  • 在转换器内,您可以通过 parent(基础环境 + 直到该转换的所有转换)或 container()(封装转换器的对象)来访问(并调用)父环境。

  • 不要忘记根据需要编辑 spec:顶层:transform_output_spec()transform_input_spec()。叶子层:transform_observation_spec()transform_action_spec()transform_state_spec()transform_reward_spec()transform_reward_spec()

有关实际示例,请参阅上面列出的方法。

clone()[源代码]

创建 tensordict 的副本,不带父项(一个转换器对象只能有一个父项)。

set_container()[源代码]

设置转换器的容器,并顺带设置父项(如果容器是或包含环境)。

reset_parent()[源代码]

重置父项和容器缓存。

close()[源代码]

关闭转换。

property collector: DataCollectorBase | None

返回与容器关联的收集器(如果存在)。

每当变换需要了解收集器或与之关联的策略时,都可以使用此属性。请确保仅在未嵌套在子进程中的变换上调用此属性。收集器引用不会传递给 ParallelEnv 或类似的批处理环境的 worker。

请确保仅在未嵌套在子进程中的转换上调用此属性。 Collector 引用不会传递给 ParallelEnv 或类似批量环境的 worker。

property container: EnvBase | None

返回包含该变换的环境。

示例

>>> from torchrl.envs import TransformedEnv, Compose, RewardSum, StepCounter
>>> from torchrl.envs.libs.gym import GymEnv
>>> env = TransformedEnv(GymEnv("Pendulum-v1"), Compose(RewardSum(), StepCounter()))
>>> env.transform[0].container is env
True
forward(tensordict: TensorDictBase = None) TensorDictBase[源代码]

读取输入 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.
init(tensordict) None[源代码]

运行转换的初始化步骤。

inv(tensordict: TensorDictBase = None) TensorDictBase[源代码]

读取输入 tensordict,并对选定的键应用逆变换。

默认情况下,此方法

  • 直接调用 _inv_apply_transform()

  • 不调用 _inv_call()

注意

inv 也通过使用 dispatch 将参数名称强制转换为键来处理常规关键字参数。

注意

invextend() 调用。

property parent: TransformedEnv | None

返回变换的父环境。

父环境是包含直到当前变换的所有变换的环境。

示例

>>> from torchrl.envs import TransformedEnv, Compose, RewardSum, StepCounter
>>> from torchrl.envs.libs.gym import GymEnv
>>> env = TransformedEnv(GymEnv("Pendulum-v1"), Compose(RewardSum(), StepCounter()))
>>> env.transform[1].parent
TransformedEnv(
    env=GymEnv(env=Pendulum-v1, batch_size=torch.Size([]), device=cpu),
    transform=Compose(
            RewardSum(keys=['reward'])))
to(*args, **kwargs) Transform[源代码]

移动和/或转换参数和缓冲区。

这可以这样调用

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 设置为 True 时,它会尝试异步(相对于主机)转换/移动,如果可能的话,例如将具有固定内存的 CPU 张量移动到 CUDA 设备。

有关示例,请参阅下文。

注意

此方法就地修改模块。

参数:
  • device (torch.device) – the desired device of the parameters and buffers in this module – 此模块中参数和缓冲区的目标设备。

  • dtype (torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this module – 此模块中参数和缓冲区的目标浮点数或复数 dtype。

  • tensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module – 其 dtype 和 device 是此模块中所有参数和缓冲区的目标 dtype 和 device 的 Tensor。

  • memory_format (torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument) – 此模块中 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_action_spec(action_spec: TensorSpec) TensorSpec[源代码]

转换动作规范,使结果规范与变换映射匹配。

参数:

action_spec (TensorSpec) – 变换前的规范

返回:

转换后的预期规范

transform_done_spec(done_spec: TensorSpec) TensorSpec[源代码]

变换 done spec,使结果 spec 与变换映射匹配。

参数:

done_spec (TensorSpec) – 变换前的 spec

返回:

转换后的预期规范

transform_env_batch_size(batch_size: Size) Size[源代码]

转换父环境的 batch-size。

transform_env_device(device: device) device[源代码]

转换父环境的 device。

transform_input_spec(input_spec: TensorSpec) TensorSpec[源代码]

转换输入规范,使结果规范与转换映射匹配。

参数:

input_spec (TensorSpec) – 转换前的规范

返回:

转换后的预期规范

transform_observation_spec(observation_spec: TensorSpec) TensorSpec[源代码]

转换观察规范,使结果规范与转换映射匹配。

参数:

observation_spec (TensorSpec) – 转换前的规范

返回:

转换后的预期规范

transform_output_spec(output_spec: Composite) Composite[源代码]

转换输出规范,使结果规范与转换映射匹配。

此方法通常应保持不变。更改应通过 transform_observation_spec()transform_reward_spec()transform_full_done_spec() 来实现。 :param output_spec: 转换之前的 spec :type output_spec: TensorSpec

返回:

转换后的预期规范

transform_reward_spec(reward_spec: TensorSpec) TensorSpec[源代码]

转换奖励的 spec,使其与变换映射匹配。

参数:

reward_spec (TensorSpec) – 变换前的 spec

返回:

转换后的预期规范

transform_state_spec(state_spec: TensorSpec) TensorSpec[源代码]

转换状态规范,使结果规范与变换映射匹配。

参数:

state_spec (TensorSpec) – 变换前的规范

返回:

转换后的预期规范

文档

访问全面的 PyTorch 开发者文档

查看文档

教程

为初学者和高级开发者提供深入的教程

查看教程

资源

查找开发资源并让您的问题得到解答

查看资源