implement_for¶
- class torchrl._utils.implement_for(module_name: Union[str, Callable], from_version: Optional[str] = None, to_version: Optional[str] = None, *, class_method: bool = False, compilable: bool = False)[來源]¶
一個版本裝飾器,用於檢查環境中的版本並使用匹配的版本實現函式。
如果指定的模組缺失或沒有匹配的實現,呼叫被裝飾的函式將導致顯式錯誤。如果版本範圍相交,則使用最後一個匹配的實現。
此包裝器也適用於為同一函式實現不同的後端(例如 gym vs gymnasium, numpy vs jax-numpy 等)。
- 引數:
module_name (str 或 callable) – 檢查此名稱模組(例如 “gym”)的版本。如果提供了 callable,它應返回該模組。
from_version – 實現相容的起始版本。可以是開放的 (None)。
to_version – 實現不再相容的終止版本。可以是開放的 (None)。
- 關鍵字引數:
class_method (bool, 可選) – 如果為
True,該函式將作為類方法編寫。預設為False。compilable (bool, 可選) – 如果為
False,模組僅在第一次呼叫被包裝的函式時匯入。如果為True,模組在被包裝的函式初始化時匯入。這使得被包裝的函式能夠很好地與torch.compile配合使用。預設為False。
示例
>>> @implement_for("gym", "0.13", "0.14") >>> def fun(self, x): ... # Older gym versions will return x + 1 ... return x + 1 ... >>> @implement_for("gym", "0.14", "0.23") >>> def fun(self, x): ... # More recent gym versions will return x + 2 ... return x + 2 ... >>> @implement_for(lambda: import_module("gym"), "0.23", None) >>> def fun(self, x): ... # More recent gym versions will return x + 2 ... return x + 2 ... >>> @implement_for("gymnasium", None, "1.0.0") >>> def fun(self, x): ... # If gymnasium is to be used instead of gym, x+3 will be returned ... return x + 3 ...
這表明該函式相容 gym 0.13+ 版本,但不相容 gym 0.14+ 版本。
- classmethod reset(setters_dict: Optional[Dict[str, implement_for]] = None)[來源]¶
重置 setter_dict 中的設定器。
setter_dict是 implementations 的副本。我們只需遍歷其值併為每個值呼叫module_set()。