Caffe2 - C++ API
A deep learning, cross platform ML framework
python_cpp_function.h
1 #pragma once
2 
3 #include <torch/csrc/python_headers.h>
4 #include <memory>
5 #include <typeinfo>
6 
7 #include <torch/csrc/autograd/function.h>
8 #include <torch/csrc/utils/object_ptr.h>
9 #include <torch/csrc/Exceptions.h>
10 
11 namespace torch { namespace autograd {
12 
14  PyObject_HEAD
15  std::shared_ptr<Function> cdata;
16 };
17 
18 template<typename Ctor>
19 PyObject* CppFunction_pynew(PyTypeObject *type, PyObject *args, PyObject *kwds)
20 {
21  THPObjectPtr obj(type->tp_alloc(type, 0));
22  if (!obj) return nullptr;
23  THPCppFunction* f = (THPCppFunction*)obj.get();
24  HANDLE_TH_ERRORS
25  new (&f->cdata) std::shared_ptr<Function>(Ctor()(args));
26  END_HANDLE_TH_ERRORS
27  if (!f->cdata) {
28  return nullptr;
29  }
30  return obj.release();
31 }
32 
33 #define THP_FUNCTION_DEFAULT_METHODS \
34  {(char*)"_register_hook_dict", (PyCFunction)THPCppFunction_register_hook_dict, METH_O, nullptr}, \
35  {(char*)"register_hook", (PyCFunction)THPCppFunction_register_hook, METH_O, nullptr}, \
36  {(char*)"name", (PyCFunction)THPCppFunction_name, METH_NOARGS, nullptr}
37 
38 #define THP_FUNCTION_DEFAULT_PROPERTIES \
39  {(char*)"next_functions", (getter)THPCppFunction_next_functions, nullptr, nullptr, nullptr}, \
40  {(char*)"requires_grad", (getter)THPCppFunction_requires_grad, nullptr, nullptr, nullptr}, \
41  {(char*)"metadata", (getter)THPCppFunction_metadata, nullptr, nullptr, nullptr}
42 
43 PyObject* THPCppFunction_next_functions(THPCppFunction* self, PyObject* hook);
44 PyObject* THPCppFunction_metadata(THPCppFunction *self, void *_unused);
45 PyObject* THPCppFunction_requires_grad(THPCppFunction* self);
46 PyObject* THPCppFunction_register_hook_dict(PyObject* self, PyObject* _var);
47 PyObject* THPCppFunction_register_hook(PyObject* self, PyObject* hook);
48 PyObject* THPCppFunction_name(PyObject* self);
49 
50 PyTypeObject* _initFunctionPyTypeObject(PyTypeObject& type, const char* name,
51  PyGetSetDef* function_properties, PyMethodDef* function_methods);
52 
53 PyObject* registerFunctionHook(Function& fn, PyObject* hook);
54 
55 template<typename Ctor>
56 PyTypeObject* createForwardFunctionPyTypeObject(PyTypeObject& type, const char* name,
57  PyGetSetDef* function_properties=nullptr, PyMethodDef* function_methods=nullptr)
58 {
59  type.tp_new = &CppFunction_pynew<Ctor>;
60  return _initFunctionPyTypeObject(type, name, function_properties, function_methods);
61 }
62 
63 void registerCppFunction(const std::type_info& type, PyTypeObject* pytype);
64 PyObject* functionToPyObject(const std::shared_ptr<Function>& cdata);
65 
66 }} // namespace torch::autograd
Definition: jit_type.h:17