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)