TensorDictPrimer¶
- class torchrl.envs.transforms.TensorDictPrimer(primers: dict | Composite | None = None, random: bool | None = None, default_value: float | Callable | dict[NestedKey, float] | dict[NestedKey, Callable] | None = None, reset_key: NestedKey | None = None, expand_specs: bool | None = None, single_default_value: bool = False, call_before_env_reset: bool = False, **kwargs)[source]¶
一個用於在重置時進行 TensorDict 初始化的 primer。
此轉換將在重置時使用初始化時提供的相對張量規範(tensordicts)中的值填充 tensordict。如果轉換在 env 上下文之外使用(例如,作為 nn.Module 或附加到 replay buffer),呼叫 forward 也會使用所需特徵填充 tensordict。
- 引數:
primers (dict 或 Composite, 可選) – 包含鍵-規範對的字典,將用於填充輸入 tensordict。也支援
Composite例項。random (bool, 可選) – 如果為
True,則值將從 TensorSpec 域(或無界的單位高斯)中隨機抽取。否則,將假定一個固定值。預設為 False。default_value (
float, Callable, Dict[NestedKey, float], Dict[NestedKey, Callable], optional) –如果選擇了非隨機填充,default_value 將用於填充張量。
如果 default_value 是一個浮點數或任何其他標量,則張量的所有元素都將被設定為該值。
如果它是一個可呼叫物件且 single_default_value=False(預設),則此可呼叫物件應返回一個符合規範的張量(即,
default_value()將為每個葉子規範獨立呼叫)。如果它是一個可呼叫物件且
single_default_value=True,則可呼叫物件將只調用一次,並且預期其返回的 TensorDict 例項或等效物件的結構將與提供的規範匹配。default_value必須接受一個可選的 reset 關鍵字引數,指示要重置哪些環境。返回的 TensorDict 必須具有與要重置的環境數量相同數量的元素。另請參閱
DataLoadingPrimer最後,如果 default_value 是一個張量字典或可呼叫物件字典,且鍵與規範的鍵匹配,則它們將用於生成相應的張量。預設為 0.0。
reset_key (NestedKey, 可選) – 要用作部分重置指示器的重置鍵。必須是唯一的。如果未提供,則預設為父環境的唯一重置鍵(如果只有一個),否則引發異常。
single_default_value (bool, optional) – 如果為
True且 default_value 是一個可呼叫物件,則預期default_value返回一個與規範匹配的單個 tensordict。如果為 False,default_value() 將為每個葉子獨立呼叫。預設為False。call_before_env_reset (bool, optional) – 如果為
True,則在呼叫 env.reset 之前填充 tensordict。預設為False。**kwargs – 每個關鍵字引數對應 tensordict 中的一個鍵。相應的值必須是 TensorSpec 例項,指示值必須是什麼。
當在 TransformedEnv 中使用時,如果父環境是批次鎖定的(env.batch_locked=True),則規範形狀必須與環境的形狀匹配。如果規範形狀和父形狀不匹配,則會就地修改規範形狀以匹配父批次大小的前導維度。此調整適用於父批次大小維度在例項化期間未知的情況。
示例
>>> 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.]])
示例
>>> from torchrl.envs.libs.gym import GymEnv >>> from torchrl.envs import SerialEnv, TransformedEnv >>> from torchrl.modules.utils import get_primers_from_module >>> from torchrl.modules import GRUModule >>> base_env = SerialEnv(2, lambda: GymEnv("Pendulum-v1")) >>> env = TransformedEnv(base_env) >>> model = GRUModule(input_size=2, hidden_size=2, in_key="observation", out_key="action") >>> primers = get_primers_from_module(model) >>> print(primers) # Primers shape is independent of the env batch size TensorDictPrimer(primers=Composite( recurrent_state: UnboundedContinuous( shape=torch.Size([1, 2]), space=ContinuousBox( low=Tensor(shape=torch.Size([1, 2]), device=cpu, dtype=torch.float32, contiguous=True), high=Tensor(shape=torch.Size([1, 2]), device=cpu, dtype=torch.float32, contiguous=True)), device=cpu, dtype=torch.float32, domain=continuous), device=None, shape=torch.Size([])), default_value={'recurrent_state': 0.0}, random=None) >>> env.append_transform(primers) >>> print(env.reset()) # The primers are automatically expanded to match the env batch size TensorDict( fields={ done: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False), observation: Tensor(shape=torch.Size([2, 3]), device=cpu, dtype=torch.float32, is_shared=False), recurrent_state: Tensor(shape=torch.Size([2, 1, 2]), device=cpu, dtype=torch.float32, is_shared=False), terminated: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False), truncated: Tensor(shape=torch.Size([2, 1]), device=cpu, dtype=torch.bool, is_shared=False)}, batch_size=torch.Size([2]), device=None, is_shared=False)
注意
某些 TorchRL 模組依賴於在環境 TensorDicts 中存在特定的鍵,例如
LSTM或GRU。為了方便此過程,方法get_primers_from_module()會自動檢查模組及其子模組中必需的 primer 轉換並生成它們。- forward(tensordict: TensorDictBase) TensorDictBase[source]¶
讀取輸入 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.
- 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(如果已給出),但 dtypes 不變。當設定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)
- transform_input_spec(input_spec: TensorSpec) TensorSpec[source]¶
轉換輸入規範,使結果規範與轉換對映匹配。
- 引數:
input_spec (TensorSpec) – 轉換前的規範
- 返回:
轉換後的預期規範
- transform_observation_spec(observation_spec: Composite) Composite[source]¶
轉換觀察規範,使結果規範與轉換對映匹配。
- 引數:
observation_spec (TensorSpec) – 轉換前的規範
- 返回:
轉換後的預期規範