SafeModule¶
- class torchrl.modules.tensordict_module.SafeModule(*args, **kwargs)[源代码]¶
tensordict.nn.TensorDictModule
的子类,它接受一个TensorSpec
作为参数来控制输出域。- 参数:
module (nn.Module) – 用于将输入映射到输出参数空间的 nn.Module。可以是一个函数式模块 (FunctionalModule 或 FunctionalModuleWithBuffers),在这种情况下,
forward
方法将期望 params (以及可能) buffers 关键字参数。in_keys (str 可迭代对象) – 要从输入 tensordict 读取并传递给模块的键。如果包含多个元素,将按照 in_keys 可迭代对象给出的顺序传递值。
out_keys (str 可迭代对象) – 要写入输入 tensordict 的键。out_keys 的长度必须与嵌入模块返回的张量数量匹配。使用“_”作为键可以避免将张量写入输出。
spec (TensorSpec, 可选) – 输出张量的规格。如果模块输出多个输出张量,spec 将表征第一个输出张量的空间。
safe (bool) – 如果为
True
,则输出值将根据输入 spec 进行检查。由于探索策略或数值下溢/溢出问题,可能会发生域外采样。如果此值超出界限,它将使用TensorSpec.project
方法投影回所需空间。默认为False
。inplace (bool 或 str, 可选) – 如果为 True,则原地修改输入 tensordict。如果为 False,则会创建一个新的空
TensorDict
实例。如果为 “empty”,则使用 input.empty()(即输出保留类型、设备和批次大小)。默认为 True。
- 只需指定输入和输出键即可将神经网络嵌入 TensorDictModule。域规格可以
根据需要传递。TensorDictModule 支持函数式和常规的
nn.Module
对象。在函数式情况下,必须指定 'params'(以及 'buffers')关键字参数。
示例
>>> import torch >>> from tensordict import TensorDict >>> from torchrl.data import Unbounded >>> from torchrl.modules import TensorDictModule >>> td = TensorDict({"input": torch.randn(3, 4), "hidden": torch.randn(3, 8)}, [3,]) >>> spec = Unbounded(8) >>> module = torch.nn.GRUCell(4, 8) >>> td_fmodule = TensorDictModule( ... module=module, ... spec=spec, ... in_keys=["input", "hidden"], ... out_keys=["output"], ... ) >>> params = TensorDict.from_module(td_fmodule) >>> with params.to_module(td_module): ... td_functional = td_fmodule(td.clone()) >>> print(td_functional) TensorDict( fields={ hidden: Tensor(torch.Size([3, 8]), dtype=torch.float32), input: Tensor(torch.Size([3, 4]), dtype=torch.float32), output: Tensor(torch.Size([3, 8]), dtype=torch.float32)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- 在有状态情况下
>>> td_module = TensorDictModule( ... module=torch.nn.GRUCell(4, 8), ... spec=spec, ... in_keys=["input", "hidden"], ... out_keys=["output"], ... ) >>> td_stateful = td_module(td.clone()) >>> print(td_stateful) TensorDict( fields={ hidden: Tensor(torch.Size([3, 8]), dtype=torch.float32), input: Tensor(torch.Size([3, 4]), dtype=torch.float32), output: Tensor(torch.Size([3, 8]), dtype=torch.float32)}, batch_size=torch.Size([3]), device=None, is_shared=False)
可以使用 vmap 运算符来调用函数式模块。在这种情况下,tensordict 会扩展以匹配批次大小(即 tensordict 不再原地修改)。
>>> # Model ensemble using vmap >>> from torch import vmap >>> params_repeat = params.expand(4, *params.shape) >>> td_vmap = vmap(td_fmodule, (None, 0))(td.clone(), params_repeat) >>> print(td_vmap) TensorDict( fields={ hidden: Tensor(torch.Size([4, 3, 8]), dtype=torch.float32), input: Tensor(torch.Size([4, 3, 4]), dtype=torch.float32), output: Tensor(torch.Size([4, 3, 8]), dtype=torch.float32)}, batch_size=torch.Size([4, 3]), device=None, is_shared=False)
- random(tensordict: TensorDictBase) TensorDictBase [源代码]¶
在目标空间中随机采样一个元素,与任何输入无关。
如果存在多个输出键,只有第一个会被写入输入的
tensordict
。- 参数:
tensordict (TensorDictBase) – 应将输出值写入的 tensordict。
- 返回:
具有新/更新的输出键值的原始 tensordict。
- to(dest: torch.dtype | DEVICE_TYPING) TensorDictModule [源代码]¶
移动和/或转换参数和缓冲区。
这可以这样调用
- 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 Tensor 移动到 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)