Pytorch 自定义算子的实现 - 1part: test_torch_library_expand.cpp 中, 一个同时存在 TORCH_LIBRARY 下同时存在 define 和 impl; PyTorch 的设计允许: 简单情况:直接在 TORCH_LIBRARY 中同时完成定义和默认实现 复杂情况:使用 TORCH_LIBRARY_IMPL 为不同设备(CPU/CUDA)或后端提供专门的实现 - 2part: > TORCH_LIBRARY 和 TORCH_LIBRARY_IMPL 的在多个CPP实现; test_torch_library_expand.cpp 包含 PyInit_test_ops 的初始化以及创建; 支持2种编译方法: 1. `bash build.sh` 2. pip 安装: ```bash pip install --no-build-isolation . python3 test_torch_library_expand.py ``` - 3part: PyInit 的模块名字发生变化; build.sh 方式编译的导入到python需要使用 test_torch_library_expand_build_sh.py - 4part: test_torch_library_expand.cpp 没有包含 ```c++ // // Python模块初始化函数 // extern "C" { // PyObject *PyInit_test_ops(void) { // static struct PyModuleDef module_def = { // PyModuleDef_HEAD_INIT, // "test_ops", // 模块名 // "Test operations module", // 文档 // -1, // NULL // 方法定义 // }; // return PyModule_Create(&module_def); // } // } ``` 报错: ``` 加载扩展失败: dynamic module does not define module export function (PyInit_test_ops) 请先编译 C++ 扩展 ```