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 的鍵。
另請參閱
繼承 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()。
有關實際示例,請參閱上面列出的方法。
- 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.
- inv(tensordict: TensorDictBase = None) TensorDictBase[原始碼]¶
讀取輸入 tensordict,並對選定的鍵應用逆變換。
預設情況下,此方法
直接呼叫
_inv_apply_transform()。不呼叫
_inv_call()。
注意
inv也透過使用dispatch將引數名稱強制轉換為鍵來處理常規關鍵字引數。注意
inv由extend()呼叫。
- 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_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) – 變換前的規範
- 返回:
轉換後的預期規範