forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dense_vector_to_id_list_op.h
65 lines (52 loc) · 1.75 KB
/
dense_vector_to_id_list_op.h
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
#ifndef CAFFE2_OPERATORS_DENSE_VECTOR_TO_ID_LIST_OP_H_
#define CAFFE2_OPERATORS_DENSE_VECTOR_TO_ID_LIST_OP_H_
#include <set>
#include <vector>
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
namespace caffe2 {
template <class Context>
class DenseVectorToIdListOp : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
USE_SIMPLE_CTOR_DTOR(DenseVectorToIdListOp)
template <typename T, typename M>
bool DoRunWithType() {
auto& input = Input(0);
const auto* input_data = input.template data<T>();
CAFFE_ENFORCE_EQ(input.dim(), 2, "Sample should be 2-D");
const auto batch_size = input.size(0);
const auto col_num = input.size(1);
auto* out_lengths = Output(0, {batch_size}, at::dtype<int32_t>());
auto* out_lengths_data = out_lengths->template mutable_data<int32_t>();
auto* out_values = Output(1, {batch_size * col_num}, at::dtype<M>());
auto* out_values_data = out_values->template mutable_data<M>();
auto v_pos = 0;
auto l_pos = 0;
for (auto i = 0; i < batch_size; i++) {
auto length = 0;
for (int j = 0; j < col_num; j++) {
if ((int)(input_data[i * col_num + j] + 0.5) != 0) {
out_values_data[v_pos++] = j;
length++;
}
}
out_lengths_data[l_pos++] = length;
}
out_values->Resize(v_pos);
out_lengths->Resize(l_pos);
return true;
}
bool RunOnDevice() override {
if (Input(0).template IsType<float>()) {
return DoRunWithType<float, int>();
} else {
CAFFE_THROW(
"DenseVectorToIdList operator only supports 32-bit float, but",
" input was of type ",
Input(0).dtype().name());
}
}
};
} // namespace caffe2
#endif // CAFFE2_OPERATORS_DENSE_VECTOR_TO_ID_LIST_OP_H_