快捷方式

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 开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得解答

查看资源