评价此页

Torch 库 API#

PyTorch C++ API 提供了能力,允许用户通过自定义算子和数据类型来扩展 PyTorch 的核心算子库。使用 Torch Library API 实现的扩展可以在 PyTorch eager API 和 TorchScript 中使用。

有关库 API 的教程式介绍,请参阅 使用自定义 C++ 算子扩展 TorchScript 教程。

#

TORCH_LIBRARY(ns, m)

定义一个函数宏,该函数在静态初始化时运行,用于在命名空间 ns(必须是有效的 C++ 标识符,不带引号)中定义算子库。

当您想定义一组 PyTorch 中尚不存在的新自定义算子时,请使用此宏。

使用示例

TORCH_LIBRARY(myops, m) {
  // m is a torch::Library; methods on it will define
  // operators in the myops namespace
  m.def("add", add_impl);
}

m 参数绑定到一个 torch::Library 对象,该对象用于注册算子。任何给定的命名空间只能有一个 TORCH_LIBRARY()

TORCH_LIBRARY_IMPL(ns, k, m)

定义一个函数宏,该函数在静态初始化时运行,用于在命名空间 ns(必须是有效的 C++ 标识符,不带引号)中定义用于派发键 k(必须是 c10::DispatchKey 的未限定枚举成员)的算子重载。

当您想在新派发键上实现预先存在的自定义算子集时(例如,您想为已存在的算子提供 CUDA 实现),请使用此宏。一种常见的用法模式是使用 TORCH_LIBRARY() 来定义您想定义的所有新算子的 schema,然后使用多个 TORCH_LIBRARY_IMPL() 块为 CPU、CUDA 和 Autograd 提供算子实现。

在某些情况下,您需要定义适用于所有命名空间(而不仅仅是一个命名空间)的内容(通常是回退)。在这种情况下,请使用保留的命名空间 _,例如:

TORCH_LIBRARY_IMPL(_, XLA, m) {
   m.fallback(xla_fallback);
}

使用示例

TORCH_LIBRARY_IMPL(myops, CPU, m) {
  // m is a torch::Library; methods on it will define
  // CPU implementations of operators in the myops namespace.
  // It is NOT valid to call torch::Library::def()
  // in this context.
  m.impl("add", add_cpu_impl);
}

如果 add_cpu_impl 是一个重载函数,请使用 static_cast 来指定您想要的重载(通过提供完整类型)。

#

class Library

此对象提供了用于定义算子和在派发键上提供实现的 API。

通常,torch::Library 不会被直接分配;相反,它由 TORCH_LIBRARY()TORCH_LIBRARY_IMPL() 宏创建。

torch::Library 上的大多数方法都返回其自身的引用,支持方法链式调用。

// Examples:

TORCH_LIBRARY(torchvision, m) {
   // m is a torch::Library
   m.def("roi_align", ...);
   ...
}

TORCH_LIBRARY_IMPL(aten, XLA, m) {
   // m is a torch::Library
   m.impl("add", ...);
   ...
}

公共函数

inline Library &def(c10::FunctionSchema &&s, const std::vector<at::Tag> &tags = {}, _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) &

声明一个具有 schema 的算子,但不对其提供任何实现。

您应该随后使用 impl() 方法提供实现。所有模板参数都将推断出来。

// Example:
TORCH_LIBRARY(myops, m) {
  m.def("add(Tensor self, Tensor other) -> Tensor");
}

参数

raw_schema – 要定义的算子的 schema。通常,这是一个 const char* 字符串字面量,但这里接受 torch::schema() 可接受的任何类型。

inline Library &set_python_module(const char *pymodule, const char *context = "")

声明对于之后所有定义的算子,它们的伪实现可以在给定的 Python 模块 (pymodule) 中找到。

这会注册一些帮助文本,当找不到伪实现时会使用。

参数 (Args)

  • pymodule:python 模块

  • context:我们可能会将其包含在错误消息中。

inline Library &impl_abstract_pystub(const char *pymodule, const char *context = "")

已弃用;请改用 set_python_module。

template<typename NameOrSchema, typename Func>
inline Library &def(NameOrSchema &&raw_name_or_schema, Func &&raw_f, const std::vector<at::Tag> &tags = {}) &

定义一个算子的 schema,然后为其注册一个实现。

如果您不打算利用调度器来构建您的算子实现,通常会使用此方法。它大致等同于调用 def() 然后调用 impl(),但如果您省略算子的 schema,我们将从您的 C++ 函数类型中推断出它。所有模板参数都将推断出来。

// Example:
TORCH_LIBRARY(myops, m) {
  m.def("add", add_fn);
}

参数
  • raw_name_or_schema – 要定义的算子的 schema,或者如果 schema 将从 raw_f 推断出来,则只是算子的名称。通常是 const char* 字面量。

  • raw_f – 实现此算子的 C++ 函数。这里接受 torch::CppFunction 的任何有效构造函数;通常您提供一个函数指针或 lambda。

template<typename Name, typename Func>
inline Library &impl(Name name, Func &&raw_f, _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) &

注册一个算子的实现。

您可以在不同的派发键上为单个算子注册多个实现(参见 torch::dispatch())。实现必须具有相应的声明(来自 def()),否则它们无效。如果您打算注册多个实现,请在 def() 算子时不要提供函数实现。

// Example:
TORCH_LIBRARY_IMPL(myops, CUDA, m) {
  m.impl("add", add_cuda);
}

参数
  • name – 要实现的算子名称。此处不要提供 schema。

  • raw_f – 实现此算子的 C++ 函数。这里接受 torch::CppFunction 的任何有效构造函数;通常您提供一个函数指针或 lambda。

template<typename Func>
inline Library &fallback(Func &&raw_f) &

为所有算子注册一个回退实现,如果不存在特定实现,则会使用该实现。

回退必须关联一个 DispatchKey;例如,只能从命名空间为 _TORCH_LIBRARY_IMPL() 中调用此函数。

// Example:

TORCH_LIBRARY_IMPL(_, AutogradXLA, m) {
  // If there is not a kernel explicitly registered
  // for AutogradXLA, fallthrough to the next
  // available kernel
  m.fallback(torch::CppFunction::makeFallthrough());
}

// See aten/src/ATen/core/dispatch/backend_fallback_test.cpp
// for a full example of boxed fallback

参数

raw_f – 实现回退的函数。解包函数通常不能用作回退函数,因为回退函数必须适用于每个算子(尽管它们的类型签名不同)。典型参数是 CppFunction::makeFallthrough()CppFunction::makeFromBoxedFunction()

class CppFunction

表示实现算子的 C++ 函数。

大多数用户不会直接与此类交互,除了通过错误消息:此函数提供的构造函数定义了可以通过接口绑定的允许的“类函数”集合。

此类会擦除传入函数的类型,但会通过从函数推断出的 schema 来持久记录类型。

公共函数

template<typename Func>
inline explicit CppFunction(Func *f, std::enable_if_t<c10::guts::is_function_type<Func>::value, std::nullptr_t> = nullptr)

此重载接受函数指针,例如 CppFunction(&add_impl)

template<typename FuncPtr>
inline explicit CppFunction(FuncPtr f, std::enable_if_t<c10::is_compile_time_function_pointer<FuncPtr>::value, std::nullptr_t> = nullptr)

此重载接受编译时函数指针,例如 CppFunction(TORCH_FN(add_impl))

template<typename Lambda>
inline explicit CppFunction(Lambda &&f, std::enable_if_t<c10::guts::is_functor<std::decay_t<Lambda>>::value, std::nullptr_t> = nullptr)

此重载接受 lambda,例如 CppFunction([](const Tensor& self) { ...

})

公共静态函数

static inline CppFunction makeFallthrough()

这会创建一个回退函数。

回退函数会立即重新派发到下一个可用的派发键,但其实现比用同样方式手动编写的函数更有效。

template<c10::BoxedKernel::BoxedKernelFunction *func>
static inline CppFunction makeFromBoxedFunction()

从具有签名 void(const OperatorHandle&, Stack*) 的打包内核函数创建函数;也就是说,它们接收以打包调用约定表示的参数堆栈,而不是以本机 C++ 调用约定表示。

打包函数通常仅用于通过 torch::Library::fallback() 注册后端回退。

template<class KernelFunctor>
static inline CppFunction makeFromBoxedFunctor(std::unique_ptr<KernelFunctor> kernelFunctor)

创建一个从盒装内核函子(boxed kernel functor)生成的函数,该函子定义了 operator()(const OperatorHandle&, DispatchKeySet, Stack*)(从盒装调用约定接收参数)并继承自 c10::OperatorKernel

与 makeFromBoxedFunction 不同,以这种方式注册的函数还可以携带函子管理的附加状态;如果您正在为其他实现(例如,动态关联到已注册内核的 Python 可调用对象)编写适配器,这将非常有用。

template<typename FuncPtr, std::enable_if_t<c10::guts::is_function_type<FuncPtr>::value, std::nullptr_t> = nullptr>
static inline CppFunction makeFromUnboxedFunction(FuncPtr *f)

从非盒装内核函数(unboxed kernel function)创建一个函数。

这通常用于注册通用运算符。

template<typename FuncPtr, std::enable_if_t<c10::is_compile_time_function_pointer<FuncPtr>::value, std::nullptr_t> = nullptr>
static inline CppFunction makeFromUnboxedFunction(FuncPtr f)

从编译时非盒装内核函数指针(compile time unboxed kernel function pointer)创建一个函数。

这通常用于注册通用运算符。编译时函数指针可用于允许编译器优化(例如内联)对其的调用。

函数#

template<typename Func>
inline CppFunction dispatch(c10::DispatchKey k, Func &&raw_f)#

创建一个与特定 dispatch key 关联的 torch::CppFunction

带有 c10::DispatchKey 标签的 torch::CppFunctions 除非调度器确定应该调度到该特定 c10::DispatchKey,否则不会被调用。

此函数通常不直接使用,而是优先使用 TORCH_LIBRARY_IMPL(),它将隐式设置其体内的所有注册调用的 c10::DispatchKey。

template<typename Func>
inline CppFunction dispatch(c10::DeviceType type, Func &&raw_f)#

接受 c10::DeviceTypedispatch() 的便捷重载。

inline c10::FunctionSchema schema(const char *str, c10::AliasAnalysisKind k, bool allow_typevars = false)#

从字符串构造 c10::FunctionSchema,并显式指定 c10::AliasAnalysisKind。

通常,schema 直接以字符串形式传递,但如果您需要指定自定义别名分析,可以改用此函数调用。

// Default alias analysis (FROM_SCHEMA)
m.def("def3(Tensor self) -> Tensor");
// Pure function alias analysis
m.def(torch::schema("def3(Tensor self) -> Tensor",
c10::AliasAnalysisKind::PURE_FUNCTION));

inline c10::FunctionSchema schema(const char *s, bool allow_typevars = false)#

函数 schema 可以直接从字符串字面量构造。