pytorch-inference
inference_engine.hpp
Go to the documentation of this file.
1 //
2 // Created by Aman LaChapelle on 5/18/17.
3 //
4 // pytorch_inference
5 // Copyright (c) 2017 Aman LaChapelle
6 // Full license at pytorch_inference/LICENSE.txt
7 //
8 
9 #ifndef PYTORCH_INFERENCE_INFERENCE_ENGINE_HPP
10 #define PYTORCH_INFERENCE_INFERENCE_ENGINE_HPP
11 
12 #include <algorithm>
13 #include <functional>
14 
15 #include <arrayfire.h>
16 
17 #include "utils.hpp"
18 #include "layers.hpp"
19 #include "layers.hpp"
20 
21 namespace pytorch {
22 
29  private:
30  std::vector<std::vector<pytorch::Layer *>> layers; // how to speed this up to avoid vtable lookup?
31  const int device;
32 
33  public:
34  inference_engine(const int &device = 0,
35  af::Backend backend = AF_BACKEND_CUDA,
36  bool quiet = true) : device(device) {
37  af::setBackend(backend);
38  af::setDevice(this->device);
39  if (!quiet){
40  af::info();
41  }
42  }
43 
44  virtual ~inference_engine() {
45  af::deviceGC();
46  }
47 
48  inline void add_layer(Layer *l){
49  layers.push_back({l});
50  }
51 
52  inline void add_layer(std::vector<Layer *>l){
53  layers.push_back(l);
54  }
55 
56  inline Layer *get_layer_ptr(const int &depth, const int &width = 0){
57  return layers[depth][width];
58  }
59 
60  inline tensor forward(const std::vector<tensor> &input){
61  std::vector<tensor> out = input;
62  for (auto &layer : layers){
63  if (layer.size() == 1) {
64  out = layer[0]->forward(out);
65  }
66  else{
67  internal::check_size(out.size(), layer.size(), __func__); // make sure there are enough inputs
68  int wid = layer.size();
69  for (int i = 0; i < wid; i++){
70  out[i] = layer[i]->forward({out[i]})[0];
71  }
72  }
73  }
74 
75 
76  return out[0]; // must be a single tensor by the end
77  }
78 
79  };
80 } // pytorch
81 
82 
83 
84 
85 #endif //PYTORCH_INFERENCE_INFERENCE_ENGINE_HPP
Layer * get_layer_ptr(const int &depth, const int &width=0)
Definition: inference_engine.hpp:56
Definition: inference_engine.hpp:28
inference_engine(const int &device=0, af::Backend backend=AF_BACKEND_CUDA, bool quiet=true)
Definition: inference_engine.hpp:34
void add_layer(std::vector< Layer *>l)
Definition: inference_engine.hpp:52
tensor forward(const std::vector< tensor > &input)
Definition: inference_engine.hpp:60
void check_size(const int &size1, const int &size2, const std::string &func)
Definition: include/utils.hpp:62
Definition: inference_engine.hpp:21
virtual ~inference_engine()
Definition: inference_engine.hpp:44
Equivalent to Conv2d in pytorch.
Definition: Layer.hpp:31
std::vector< std::vector< pytorch::Layer * > > layers
Definition: inference_engine.hpp:30
void add_layer(Layer *l)
Definition: inference_engine.hpp:48
const int device
Definition: inference_engine.hpp:31