Skip to content

Commit beccd99

Browse files
authored
Optimize tensor copies on inference path (#245)
1 parent e6daf49 commit beccd99

1 file changed

Lines changed: 20 additions & 10 deletions

File tree

include/graph/graph.hpp

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,13 @@ class Graph {
248248
if (it != branch_list_.rend()) {
249249
for (size_t f = 0; f < it->distribution.size(); ++f) {
250250
if (it->distribution[f].first == current_layer) {
251-
inten_.push_back(it->give_for_all[it->distribution[f].second]);
251+
bool last_use = (it->count_used_ten == 1);
252+
auto& src = it->give_for_all[it->distribution[f].second];
253+
if (last_use) {
254+
inten_.push_back(std::move(src));
255+
} else {
256+
inten_.push_back(src);
257+
}
252258
}
253259
}
254260
}
@@ -263,6 +269,9 @@ class Graph {
263269
}
264270
}
265271
}
272+
if (outten_.empty()) {
273+
outten_.resize(1);
274+
}
266275
layers_[current_layer]->run(inten_, outten_, options);
267276

268277
#ifdef ENABLE_STATISTIC_TENSORS
@@ -273,19 +282,19 @@ class Graph {
273282
weights_.push_back(layers_[current_layer]->get_weights());
274283
#endif
275284

276-
inten_ = outten_;
285+
inten_.swap(outten_);
277286

278287
if (layers_[current_layer]->postops.count > 0) {
279288
for (unsigned int j = 0; j < layers_[current_layer]->postops.count;
280289
j++) {
281290
layers_[current_layer]->postops.layers[j]->run(inten_, outten_,
282291
options);
283292
}
284-
inten_ = outten_;
293+
inten_.swap(outten_);
285294
}
286295

287296
BranchState new_branch;
288-
new_branch.give_for_all = inten_;
297+
new_branch.give_for_all = std::move(inten_);
289298
new_branch.count_used_ten = countinout[current_layer].second;
290299
new_branch.ind_layer = current_layer;
291300
new_branch.split = layers_[current_layer]->getName() == kSplit;
@@ -310,7 +319,12 @@ class Graph {
310319
}
311320
new_branch.distribution = dis;
312321
}
313-
branch_list_.push_back(new_branch);
322+
branch_list_.push_back(std::move(new_branch));
323+
if (outtenres_ && current_layer == end_ &&
324+
!branch_list_.back().give_for_all.empty() &&
325+
countinout[current_layer].second == 0) {
326+
*outtenres_ = std::move(branch_list_.back().give_for_all[0]);
327+
}
314328

315329
#ifdef ENABLE_STATISTIC_TIME
316330
auto end = std::chrono::high_resolution_clock::now();
@@ -320,10 +334,6 @@ class Graph {
320334
time_layer_.push_back(layers_[current_layer]->getName());
321335
#endif
322336
}
323-
324-
if (outtenres_ && !outten_.empty()) {
325-
*outtenres_ = outten_[0];
326-
}
327337
}
328338

329339
void setOutput(Layer* layer, Tensor& vec) {
@@ -439,4 +449,4 @@ class Graph {
439449
return traversal;
440450
}
441451
};
442-
} // namespace it_lab_ai
452+
} // namespace it_lab_ai

0 commit comments

Comments
 (0)