快捷方式

implement_for

class torchrl.implement_for(module_name: str | Callable, from_version: str = None, to_version: str = None, *, class_method: bool = False, compilable: bool = False)[源代码]

一个版本装饰器,用于检查环境中的版本并实现具有匹配功能的功能。

如果指定的模块丢失或没有匹配的实现,调用装饰后的函数将导致明确的错误。在范围重叠的情况下,将使用最后匹配的实现。

此包装器还可以用于为同一函数实现不同的后端(例如 gym vs gymnasium,numpy vs jax-numpy 等)。

参数:
  • module_name (strcallable) – 检查具有此名称的模块的版本(例如,“gym”)。如果提供了可调用对象,它应返回模块。

  • from_version – 实现兼容的版本。可以是开放的(None)。

  • to_version – 实现不再兼容的版本。可以是开放的(None)。

关键字参数:
  • class_method (bool, optional) – 如果为 True,则函数将作为类方法编写。默认为 False

  • compilable (bool, optional) – 如果为 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: Callable | str) str[源代码]

导入模块并返回其版本。

module_set()[源代码]

如果函数已存在于其模块中,则将其设置到模块中。

classmethod reset(setters_dict: Optional[dict[str, torchrl._utils.implement_for]] = None)[源代码]

重置 setters_dict 中的设置器。

setter_dict 是实现的副本。我们只需要迭代其值并通过 module_set() 为每个值调用。

文档

访问全面的 PyTorch 开发者文档

查看文档

教程

为初学者和高级开发者提供深入的教程

查看教程

资源

查找开发资源并让您的问题得到解答

查看资源