weixin_43978681头像

PyTorch 算子注册机制深度解析

作者​:昇腾实战派

​知识地图​:https://blog.csdn.net/Lumos_Lovegood/article/details/161489952

背景概述

在PyTorch的扩展开发中,算子注册是连接C++实现与Python调用的核心桥梁。无论是为自定义后端添加算子支持,还是扩展新的算子功能,理解torch::Library的注册机制都至关重要。本文将深入剖析PyTorch算子注册的完整流程,从宏定义入口到Dispatcher分发机制,帮助开发者全面掌握这一关键技术。

一、注册入口宏定义

PyTorch通过torch/library.h中的一系列宏提供了不同场景下的算子注册入口,主要包括以下三种形式:

1.1 TORCH_LIBRARY:定义算子命名空间

TORCH_LIBRARY用于在唯一的命名空间块中定义算子schema,是整个注册流程的起点:

#define TORCH_LIBRARY(ns, m)                                                   \
  static void TORCH_LIBRARY_init_##ns(torch::Library&);                        \
  static const torch::detail::TorchLibraryInit TORCH_LIBRARY_static_init_##ns( \
      torch::Library::DEF,                                                     \
      &TORCH_LIBRARY_init_##ns,                                                \
      #ns,                                                                     \
      c10::nullopt,                                                            \
      __FILE__,                                                                \
      __LINE__);                                                               \
  void TORCH_LIBRARY_init_##ns(torch::Library& m)

1.2 TORCH_LIBRARY_FRAGMENT:补充算子定义

TORCH_LIBRARY_FRAGMENT允许在多个文件中分散定义同一命名空间的算子,通过C10_UID确保静态变量名的唯一性:

#define TORCH_LIBRARY_FRAGMENT(ns, m) _TORCH_LIBRARY_FRAGMENT(ns, m, C10_UID)

#define _TORCH_LIBRARY_FRAGMENT(ns, m, uid)                       \
  static void C10_CONCATENATE(                                    \
      TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid)(torch::Library&); \
  static const torch::detail::TorchLibraryInit C10_CONCATENATE(   \
      TORCH_LIBRARY_FRAGMENT_static_init_##ns##_, uid)(           \
      torch::Library::FRAGMENT,                                   \
      &C10_CONCATENATE(TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid), \
      #ns,                                                        \
      c10::nullopt,                                               \
      __FILE__,                                                   \
      __LINE__);                                                  \
  void C10_CONCATENATE(                                           \
      TORCH_LIBRARY_FRAGMENT_init_##ns##_, uid)(torch::Library & m)

1.3 TORCH_LIBRARY_IMPL:注册后端实现

TORCH_LIBRARY_IMPL用于为特定DispatchKey(如CPU、自定义后端)注册算子实现:

#define TORCH_LIBRARY_IMPL(ns, k, m) _TORCH_LIBRARY_IMPL(ns, k, m, C10_UID)

#define _TORCH_LIBRARY_IMPL(ns, k, m, uid)                                \
  static void C10_CONCATENATE(                                            \
      TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid)(torch::Library&);       \
  static const torch::detail::TorchLibraryInit C10_CONCATENATE(           \
      TORCH_LIBRARY_IMPL_static_init_##ns##_##k##_, uid)(                 \
      torch::Library::IMPL,                                               \
      (c10::impl::dispatch_key_allowlist_check(c10::DispatchKey::k)       \
           ? &C10_CONCATENATE(TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid) \
           : [](torch::Library&) -> void {}),                             \
      #ns,                                                                \
      c10::make_optional(c10::DispatchKey::k),                            \
      __FILE__,                                                           \
      __LINE__);                                                          \
  void C10_CONCATENATE(                                                   \
      TORCH_LIBRARY_IMPL_init_##ns##_##k##_, uid)(torch::Library & m)

二、初始化机制

所有宏最终都会构造一个TorchLibraryInit对象,该对象在静态初始化阶段自动执行注册函数:

class TorchLibraryInit final {
 private:
  using InitFn = void(Library&);
  Library lib_;

public:
  TorchLibraryInit(
      Library::Kind kind,
      InitFn* fn,
      const char* ns,
      c10::optional k,
      const char* file,
      uint32_t line)
      : lib_(kind, ns, k, file, line) {
    fn(lib_);
  }
};

三、算子定义与实现注册

3.1 def:定义算子Schema

Library::def方法负责注册算子的schema定义,支持两种形式:

形式一:仅定义schema

template 
  Library& def(
      Schema&& raw_schema,
      const std::vector& tags = {},
      _RegisterOrVerify rv = _RegisterOrVerify::REGISTER) & {
    c10::FunctionSchema s = schema(std::forward(raw_schema));
    return _def(std::move(s), nullptr, tags, rv);
  }

形式二:同时定义schema和实现

template 
  Library& def(NameOrSchema&& raw_name_or_schema, Func&& raw_f) & {
    CppFunction f(std::forward(raw_f));
    auto name_or_schema = detail::constructSchemaOrName(
        std::forward(raw_name_or_schema));
    return _def(std::move(name_or_schema), std::move(f));
  }

3.2 _def:核心注册逻辑

_def方法执行完整的注册流程,包括schema校验、命名空间处理和Dispatcher调用:

Library& Library::_def(c10::FunctionSchema&& schema, c10::OperatorName* out_name, const std::vector& tags, _RegisterOrVerify rv) & {
  TORCH_CHECK(kind_ == DEF || kind_ == FRAGMENT,
    DEF_PRELUDE,
    "Cannot define an operator inside of a ", toString(kind_), " block.  "
    "All def()s should be placed in the (unique) TORCH_LIBRARY block for their namespace.  ",
    ERROR_CONTEXT
  );
  TORCH_INTERNAL_ASSERT(ns_.has_value(), ERROR_CONTEXT);
  TORCH_INTERNAL_ASSERT(!dispatch_key_.has_value(), ERROR_CONTEXT);
  auto ns_opt = schema.getNamespace();
  if (ns_opt.has_value()) {
    // 校验显式指定的命名空间与当前块一致
    TORCH_CHECK(*ns_opt == *ns_,
      "Explicitly provided namespace (", *ns_opt, ") in schema string "
      "does not match namespace of enclosing ", toString(kind_), " block (", *ns_, ").  "
      "Move this definition to the (unique) TORCH_LIBRARY block corresponding to this namespace "
      "(and consider deleting the namespace from your schema string.)  ",
      ERROR_CONTEXT
    );
  } else {
    // 自动设置命名空间
    bool b = schema.setNamespaceIfNotSet(ns_->c_str());
    TORCH_INTERNAL_ASSERT(b, ERROR_CONTEXT);
  }
  if (out_name) {
    *out_name = schema.operator_name(); // copy!
  }
  switch (rv) {
    case _RegisterOrVerify::REGISTER:
      registrars_.emplace_back(
        c10::Dispatcher::singleton().registerDef(
          std::move(schema),
          debugString(file_, line_),
          tags
        )
      );
      break;
    case _RegisterOrVerify::VERIFY:
      c10::Dispatcher::singleton().waitForDef(schema);
      break;
  }
  return *this;
}

3.3 impl:注册算子实现

当同时提供schema和实现时,_def会先注册schema,再通过registerImpl注册具体的kernel实现:

Library& Library::_def(c10::either&& name_or_schema, CppFunction&& f) & {
  c10::FunctionSchema schema = [&] {
    if (name_or_schema.is_right()) {
      return std::move(name_or_schema).right();
    } else {
      // 根据函数签名推断schema
      c10::OperatorName name = std::move(name_or_schema).left();
      TORCH_CHECK(f.schema_,
        "def(\"", name, "\"): "
        "Full schema string was not specified, and we couldn't infer schema either.  ",
        "Please explicitly provide a schema string.  ",
        ERROR_CONTEXT
      );
      c10::FunctionSchema s = f.schema_->cloneWithName(std::move(name.name), std::move(name.overload_name));
      s.setAliasAnalysis(c10::AliasAnalysisKind::CONSERVATIVE);
      return s;
    }
  }();
  c10::OperatorName name("", "");  // 获取命名空间后的名称
  // 先注册schema
  _def(std::move(schema), &name);
  // 再注册实现
  auto dispatch_key = f.dispatch_key_.has_value() ? f.dispatch_key_ : dispatch_key_;
  registrars_.emplace_back(
    c10::Dispatcher::singleton().registerImpl(
      std::move(name),
      dispatch_key,
      std::move(f.func_),
      std::move(f.cpp_signature_),
      std::move(f.schema_),
      debugString(std::move(f.debug_), file_, line_)
    )
  );
  return *this;
}

四、Dispatcher分发机制

4.1 算子注册

Dispatcher::registerDef负责将算子schema注册到全局调度器中:

RegistrationHandleRAII Dispatcher::registerDef(FunctionSchema schema, std::string debug, std::vector tags) {
  std::lock_guard lock(guard_->mutex);

  OperatorName op_name = schema.operator_name();
  auto op = findOrRegisterName_(op_name);

  TORCH_CHECK(op.operatorDef_->def_count == 0, "Tried to register an operator (", schema, ") with the same name and overload name multiple times.",
                                                    " Each overload's schema should only be registered with a single call to def().",
                                                    " Duplicate registration: ", debug, ". Original registration: ", op.operatorDef_->op.debug());
  op.operatorDef_->op.registerSchema(std::move(schema), std::move(debug), std::move(tags));
  listeners_->callOnOperatorRegistered(op);

  ++op.operatorDef_->def_count;
  ++op.operatorDef_->def_and_impl_count;

  cond_var_.notify_all();

  return RegistrationHandleRAII([guard = this->guard_, this, op, op_name] {
    std::lock_guard lock(guard->mutex);
    if (!guard->alive.load()) {
      return;
    }
    deregisterDef_(op, op_name);
  });
}

4.2 Kernel注册

Dispatcher::registerImpl负责将具体的kernel实现绑定到对应的DispatchKey:

RegistrationHandleRAII Dispatcher::registerImpl(
  OperatorName op_name,
  c10::optional dispatch_key,
  KernelFunction kernel,
  c10::optional cpp_signature,
  std::unique_ptr inferred_function_schema,
  std::string debug
) {
  std::lock_guard lock(guard_->mutex);

  auto op = findOrRegisterName_(op_name);

  auto handle = op.operatorDef_->op.registerKernel(
    *this,
    dispatch_key,
    std::move(kernel),
    std::move(cpp_signature),
    std::move(inferred_function_schema),
    std::move(debug)
  );

  ++op.operatorDef_->def_and_impl_count;

  cond_var_.notify_all();

  return RegistrationHandleRAII([guard = this->guard_, this, op, op_name, dispatch_key, handle] {
    std::lock_guard lock(guard->mutex);
    if (!guard->alive.load()) {
      return;
    }
    deregisterImpl_(op, op_name, dispatch_key, handle);
  });
}

4.3 算子查找与注册

findOrRegisterName_实现了算子的查找或创建逻辑:

OperatorHandle Dispatcher::findOrRegisterName_(const OperatorName& op_name) {
  const auto found = findOp(op_name);
  if (found != c10::nullopt) {
    return *found;
  }

  operators_.emplace_back(OperatorName(op_name));
  OperatorHandle handle(--operators_.end());
  operatorLookupTable_.write([&] (ska::flat_hash_map& operatorLookupTable) {
    operatorLookupTable.emplace(op_name, handle);
  });

  return handle;
}

4.4 Kernel注册细节

OperatorEntry::registerKernel负责将kernel实现插入到对应的分发键列表中:

OperatorEntry::AnnotatedKernelContainerIterator OperatorEntry::registerKernel(
  const c10::Dispatcher& dispatcher,
  c10::optional dispatch_key,
  KernelFunction kernel,
  c10::optional cpp_signature,
  std::unique_ptr inferred_function_schema,
  std::string debug
) {
  // 校验C++签名一致性
  if (cpp_signature.has_value()) {
    auto& local_cpp_signature = kernel.isValidSymUnboxed() ? sym_cpp_signature_ : cpp_signature_;
    if (local_cpp_signature.has_value()) {
      TORCH_CHECK(*cpp_signature == local_cpp_signature->signature,
        "\nMismatch in kernel C++ signatures\n",
        "  operator: ", (this->schema_.has_value() ? toString(this->schema_->schema) : toString(name_)), "\n",
        "    ", (this->schema_.has_value() ? this->schema_->debug : "no debug info"), "\n",
        "  kernel 1: ", local_cpp_signature->signature.name(), "\n",
        "    dispatch key: ", toString(local_cpp_signature->dispatch_key), "\n",
        "    ", local_cpp_signature->debug, "\n",
        "  kernel 2: ", cpp_signature->name(), "\n",
        "    dispatch key: ", toString(dispatch_key), "\n",
        "    ", debug, "\n"
      );
    } else {
      local_cpp_signature = CppSignatureWithDebug { *cpp_signature, debug, dispatch_key };
    }
  }

  // 校验推断的schema与已注册的schema一致
  if (schema_ && inferred_function_schema) {
    checkSchema(name_, schema_->schema, schema_->debug, kernel, *inferred_function_schema, debug);
  }

  // 将kernel添加到对应的分发键列表
  auto& k = dispatch_key.has_value() ? kernels_[*dispatch_key] : kernels_[DispatchKey::CompositeImplicitAutograd];

#ifdef C10_DISPATCHER_ONE_KERNEL_PER_DISPATCH_KEY
  if (k[0].kernel.isValid()) {
#else
  if (!k.empty()) {
#endif
    // 处理重复注册的情况
    if (dispatch_key != DispatchKey::Meta) {
      TORCH_WARN_ONCE("Warning only once for all operators,  other operators may also be overrided.\n",
            "  Overriding a previously registered kernel for the same operator and the same dispatch key\n",
            "  operator: ", (schema_.has_value() ? toString(schema_->schema) : toString(name_)), "\n",
            "    ", (this->schema_.has_value() ? this->schema_->debug : "no debug info"), "\n",
            "  dispatch key: ", toString(dispatch_key), "\n",
            "  previous kernel: ", (cpp_signature_.has_value() ? cpp_signature_->debug : (sym_cpp_signature_.has_value() ? sym_cpp_signature_->debug : "no debug info")), "\n",
            "       new kernel: ", debug
      );
    }
  }

#ifdef C10_DISPATCHER_ONE_KERNEL_PER_DISPATCH_KEY
  k[0].kernel = std::move(kernel);
  k[0].inferred_function_schema = std::move(inferred_function_schema);
  k[0].debug = std::move(debug);
#else
  k.emplace_front(std::move(kernel), std::move(inferred_function_schema), std::move(debug));
#endif
  AnnotatedKernelContainerIterator inserted = k.begin();

  // 更新分发表
  if (dispatch_key.has_value()) {
    updateDispatchTable_(dispatcher, *dispatch_key);
  } else {
    updateDispatchTableFull_(dispatcher);
  }
  return inserted;
}

五、JIT集成机制

PyTorch的JIT通过注册监听器实现与Dispatcher的联动,确保新注册的算子能够自动同步到JIT中:

class RegistrationListener final : public c10::OpRegistrationListener {
 public:
  void onOperatorRegistered(const c10::OperatorHandle& op) override {
    if (op.schema().name() == "aten::backward") {
      // aten::backward有手动包装器,需要特殊处理
      return;
    }
    torch::jit::registerOperator(createOperatorFromC10(op));
  }

  void onOperatorDeregistered(const c10::OperatorHandle& op) override {
    if (op.schema().name() == "aten::backward") {
      return;
    }
    torch::jit::deregisterOperator(op.schema());
  }
};

struct Registerer final {
  Registerer()
      : listenerRAII(c10::Dispatcher::singleton().addRegistrationListener(
            std::make_unique())) {}
  c10::RegistrationHandleRAII listenerRAII;
};

Registerer& registerer() {
  static Registerer registerer;
  return registerer;
}

// 全局实例,在启动时执行构造函数
C10_UNUSED Registerer& dummy = registerer();

六、总结

PyTorch的算子注册机制是一个精心设计的多层架构:

  1. 宏定义层:提供TORCH_LIBRARY、TORCH_LIBRARY_FRAGMENT、TORCH_LIBRARY_IMPL三种注册入口,分别对应schema定义、补充定义和实现注册场景。
  2. Library层:通过Library类封装注册逻辑,提供def和impl方法,处理命名空间校验、schema推断等细节。
  3. Dispatcher层:作为全局调度中心,维护算子注册表,管理schema和kernel的注册、查找和分发。
  4. JIT集成层:通过监听器机制,实现算子注册的自动同步,确保JIT能够识别新注册的算子。

理解这一机制对于开发自定义算子、适配新硬件后端以及调试算子注册问题都具有重要的指导意义。开发者可以根据实际需求选择合适的注册方式,构建高效、可维护的算子扩展。

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/weixin_43978681/article/details/171433598

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--