-
Notifications
You must be signed in to change notification settings - Fork 8
/
TorchModel.cpp
193 lines (159 loc) · 4.73 KB
/
TorchModel.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#include "TorchModel.h"
TorchModel::TorchModel()
{
if(torch::cuda::device_count() > 0)
{
torch::Device defaultDevice(torch::kCUDA,0);
this->device = defaultDevice;
}
else
{
torch::Device defaultCpu = torch::kCPU;
this->device = defaultCpu;
}
}
TorchModel::~TorchModel()
{
}
bool TorchModel::loadModel(const std::string &modelPath)
{
bool success = false;
try
{
//auto startModel = chrono::steady_clock::now();
this->model = torch::jit::load(modelPath.c_str());
this->model.to(this->device);
//auto endModel = chrono::steady_clock::now();
//auto diff = endModel - startModel;
//std::cout <<"MODEL TIME "<< chrono::duration <double, milli> (diff).count() << " ms"<<std::endl;
this->model.eval();
success = true;
}
catch (std::exception &e)
{
std::cout << "ERRORS";
std::cout << e.what();
}
return success;
}
torch::Tensor TorchModel::predict(const std::vector<torch::Tensor> &input)
{
torch::Tensor result = torch::empty({ 0 }).to(this->device);
std::vector<torch::jit::IValue> testInputs;
for(auto &x:input)
testInputs.push_back(x.to(this->device));
try
{
auto res = this->model.forward(testInputs).toTensor();
return res;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
// Clears growing cuda cache and frees memory if process is interupted.
//c10::cuda::CUDACachingAllocator::emptyCache();
return result;
}
torch::Tensor TorchModel::predictTuple(const std::vector<torch::Tensor>& input)
{
torch::Tensor result = torch::empty({ 0 }).to(this->device);
std::vector<torch::jit::IValue> testInputs;
for (auto& x : input)
testInputs.push_back(x.to(this->device));
try
{
auto res = this->model.forward(testInputs).toTuple()->elements()[0].toTensor();
return res;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
// Clears growing cuda cache and frees memory if process is interupted.
//c10::cuda::CUDACachingAllocator::emptyCache();
return result;
}
void TorchModel::changeDevice(const torch::DeviceType &deviceSet, const int &index)
{
int deviceCount = torch::cuda::device_count();
//MOVE model and all tensors created from now on to desired device
if(deviceCount > 0 && deviceSet == torch::kCUDA)
{
if(index < deviceCount)
{
torch::Device dev(deviceSet,index);
this->device = dev;
this->model.to(this->device);
}
else
{
//Trying to use a device thats not there, set to next available GPU
torch::Device dev(deviceSet,deviceCount-1);
this->device = dev;
this->model.to(this->device);
}
}
else
//Set to CPU if there are no CUDA devices
{
torch::Device dev = torch::kCPU;
this->device = dev;
this->model.to(this->device);
}
}
torch::Tensor TorchModel::convertToTensor(const cv::Mat& img, bool normalize,bool color)
{
cv::Mat c = img.clone();
if (color)
{
cv::cvtColor(c, c, cv::COLOR_BGR2RGB);
}
float scale = (normalize) ? 1.0 / 255.0 : 1.0;
int channels = c.channels();
auto colorRead = (channels == 3) ? CV_32FC3 : CV_32FC1;
c.convertTo(c,colorRead , scale);
torch::Tensor converted = torch::zeros({ c.rows, c.cols,channels }, torch::kF32);
std::memcpy(converted.data_ptr(), c.data, sizeof(float) * converted.numel());
// add color dimension if it is greyscale 1
converted = converted.permute({ 2, 0, 1 });
//Add batch dimension
converted = converted.unsqueeze(0).to(this->device);
return converted;
}
cv::Mat TorchModel::loadMat(const std::string file, bool grey, bool rgb)
{
auto readMode = (grey) ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR;
cv::Mat returnMat = cv::imread(file, readMode);
return returnMat;
}
torch::Tensor TorchModel::convertListToTensor(std::list<cv::Mat>& imgs)
{
//Initalize tensor with first image and pop it from list
cv::Mat first = imgs.front();
torch::Tensor converted = this->convertToTensor(first);
imgs.pop_front();
//Concat all images to a single tensor
for (auto& img : imgs)
{
torch::Tensor next = this->convertToTensor(img);
converted = torch::cat({ next,converted });
}
return converted.to(this->device);
}
cv::Mat TorchModel::convertToMat(const torch::Tensor& output, bool isFloat, bool permute, bool bgr, bool color)
{
torch::Tensor tensor = output.clone();
tensor = tensor.permute({ 1, 2, 0 }).contiguous();
// if float, image is range of 0 -> 1
tensor = (isFloat) ? tensor.mul(255).clamp(0, 255).to(torch::kU8): tensor.to(torch::kU8);
tensor = tensor.to(torch::kCPU);
int64_t height = tensor.size(0);
int64_t width = tensor.size(1);
int channels = tensor.size(2);
auto dataType = (channels == 3) ? CV_8UC3 : CV_8UC1;
cv::Mat outputMat = cv::Mat(cv::Size(width, height), dataType, tensor.data_ptr());
if(bgr)
cv::cvtColor(outputMat, outputMat, cv::COLOR_RGB2BGR);
return outputMat.clone();
}