/
vuron
/
adept
Обзор
Документация
Войти
/
vuron
/
adept
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
python/cpp_bindings/module_py.cpp
51 строка
2 KB
kolkir
Fix tensor filling and module registration
06 мар 2025, 09:54
06 мар 2025, 09:54
cea0aaa
Код
Авторство
О чём код?
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <adept/nn/module.hpp> namespace py = pybind11; using namespace adept; void bind_module(py::module& m) { py::class_<Module, std::shared_ptr<Module>>(m, "Module") .def(py::init<std::string>()) .def("parameters", &Module::parameters) .def("save", [](const Module& self, OutputSerializer& output) { self.save(output); }) .def("load", [](Module& self, InputSerializer& input) { self.load(input); }) .def("train", &Module::train) .def("eval", &Module::eval) .def("register_module", [](Module& self, const std::string_view name, py::object value) -> void { try { auto m = value.cast<std::shared_ptr<Module>>(); if (m) // ignore None values self.register_module(std::string(name), m); } catch (const py::cast_error&) { // ignore } }) .def("__repr__", [](const Module& v) { std::stringstream buf; buf << v; return buf.str(); }) .def("__setattr__", [](Module& instance, const std::string_view name, py::object value) -> void { try { auto m = value.cast<std::shared_ptr<Module>>(); if (m) // ignore None values instance.register_module(std::string(name), m); } catch (const py::cast_error&) { // ignore } // fall back on parent class's __setattr__ ... py::type selfType = py::type::of<Module>(); py::object selfObj = py::cast(instance); py::module::import("builtins") .attr("super")(selfType, selfObj) .attr("__setattr__")(name, value); }); }