Timer¶
- class torchrl.envs.transforms.Timer(out_keys: Optional[Sequence[NestedKey]] = None, time_key: str = 'time')[source]¶
一個用於測量環境中 inv 和 call 操作之間時間間隔的變換。
Timer 變換用於跟蹤 inv 呼叫和 call 呼叫之間,以及 call 呼叫和 inv 呼叫之間經過的時間。這對於環境中的效能監控和除錯很有用。時間以秒為單位測量,並以 PyTorch 的預設 dtype 儲存為張量。如果 tensordict 具有批處理大小(例如,在批處理環境中),則時間將被擴充套件到輸入 tensordict 的大小。
- 變數:
out_keys – 反向變換的輸出 tensordict 的鍵。預設為 out_keys = [f”{time_key}_step”, f”{time_key}_policy”, f”{time_key}_reset”],其中第一個鍵表示在環境中執行一步所需的時間,第二個鍵表示執行策略所需的時間,第三個鍵表示 reset 呼叫所需的時間。
time_key – 用於儲存時間間隔在 tensordict 中的鍵的字首。預設為 “time”。
注意
在連續的 rollouts 中,reset 的時間標記將寫入根目錄(“time_reset” 條目或等效鍵在 “next” tensordict 中始終為 0)。在根目錄,當存在 reset 時,“time_policy” 和 “time_step” 條目將為 0。它們在 “next” 中永遠不會是 0。
示例
>>> from torchrl.envs import Timer, GymEnv >>> >>> env = GymEnv("Pendulum-v1").append_transform(Timer()) >>> r = env.rollout(10) >>> print("time for policy", r["time_policy"]) time for policy tensor([0.0000, 0.0882, 0.0004, 0.0002, 0.0002, 0.0002, 0.0002, 0.0002, 0.0002, 0.0002]) >>> print("time for step", r["time_step"]) time for step tensor([9.5797e-04, 1.6289e-03, 9.7990e-05, 8.0824e-05, 9.0837e-05, 7.6056e-05, 8.2016e-05, 7.6056e-05, 8.1062e-05, 7.7009e-05])
- 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.
- transform_observation_spec(observation_spec: TensorSpec) TensorSpec[source]¶
轉換觀察規範,使結果規範與轉換對映匹配。
- 引數:
observation_spec (TensorSpec) – 轉換前的規範
- 返回:
轉換後的預期規範