快捷方式

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 (strcallable) – 檢查此名稱模組(例如 “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+ 版本。

static get_class_that_defined_method(f)[來源]

如果方法已定義,則返回其類;否則返回 None。

classmethod import_module(module_name: Union[Callable, str]) str[來源]

匯入模組並返回其版本。

module_set()[來源]

如果在其模組中已存在該函式,則設定該函式。

classmethod reset(setters_dict: Optional[Dict[str, implement_for]] = None)[來源]

重置 setter_dict 中的設定器。

setter_dict 是 implementations 的副本。我們只需遍歷其值併為每個值呼叫 module_set()

文件

訪問全面的 PyTorch 開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得解答

檢視資源