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,則對照輸入規格檢查輸出值。由於探索策略或數值下溢/上溢問題,可能會發生超出域的取樣。如果此值超出範圍,則使用TensorSpec.project方法將其投影回期望的空間。預設值為False。
- 將神經網路嵌入 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: Union[dtype, device, str, int]) 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 張量移動到 CUDA 裝置。參見下面的示例。
注意
此方法會就地修改模組。
- 引數:
device (
torch.device) – 此模組中引數和緩衝區的目標裝置dtype (
torch.dtype) – 此模組中引數和緩衝區的目標浮點或複數 dtypetensor (torch.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)