File: cpp_frontend_extension.cpp

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (54 lines) | stat: -rw-r--r-- 1,360 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <torch/extension.h>

#include <cstddef>
#include <string>

struct Net : torch::nn::Cloneable<Net> {
  Net(int64_t in, int64_t out) : in_(in), out_(out) {
    reset();
  }

  void reset() override {
    fc = register_module("fc", torch::nn::Linear(in_, out_));
    buffer = register_buffer("buf", torch::eye(5));
  }

  torch::Tensor forward(torch::Tensor x) {
    return fc->forward(x);
  }

  void set_bias(torch::Tensor bias) {
    torch::NoGradGuard guard;
    fc->bias.set_(bias);
  }

  torch::Tensor get_bias() const {
    return fc->bias;
  }

  void add_new_parameter(const std::string& name, torch::Tensor tensor) {
    register_parameter(name, tensor);
  }

  void add_new_buffer(const std::string& name, torch::Tensor tensor) {
    register_buffer(name, tensor);
  }

  void add_new_submodule(const std::string& name) {
    register_module(name, torch::nn::Linear(fc->options));
  }

  int64_t in_, out_;
  torch::nn::Linear fc{nullptr};
  torch::Tensor buffer;
};

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  torch::python::bind_module<Net>(m, "Net")
      .def(py::init<int64_t, int64_t>())
      .def("set_bias", &Net::set_bias)
      .def("get_bias", &Net::get_bias)
      .def("add_new_parameter", &Net::add_new_parameter)
      .def("add_new_buffer", &Net::add_new_buffer)
      .def("add_new_submodule", &Net::add_new_submodule);
}