forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_sparse_to_dense_op.cc
243 lines (211 loc) · 7.43 KB
/
batch_sparse_to_dense_op.cc
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#include "batch_sparse_to_dense_op.h"
#include "caffe2/core/context.h"
namespace caffe2 {
template <typename T, class Context>
bool BatchSparseToDenseOp<T, Context>::RunOnDevice() {
auto& lengths = Input(LENGTHS);
auto& indices = Input(INDICES);
auto& values = Input(VALUES);
auto* output = Output(0);
CAFFE_ENFORCE_EQ(indices.size(), values.size());
CAFFE_ENFORCE_EQ(lengths.ndim(), 1);
CAFFE_ENFORCE_EQ(indices.ndim(), 1);
const int64_t* lengths_data = lengths.template data<int64_t>();
const int64_t* indices_data = indices.template data<int64_t>();
const T* values_data = values.template data<T>();
int64_t batch_size = lengths.size();
int64_t lengths_sum = 0;
math::Sum<int64_t, Context>(batch_size, lengths_data, &lengths_sum, &context_);
CAFFE_ENFORCE_EQ(lengths_sum, indices.size());
vector<int64_t> output_shape = {batch_size};
if (InputSize() == 4) {
auto& shaper = Input(3);
CAFFE_ENFORCE_EQ(shaper.ndim(), 2);
if (dense_last_dim_ == -1) {
dense_last_dim_ = shaper.dim(1);
} else {
CAFFE_ENFORCE(
dense_last_dim_ == shaper.dim(1),
"The last dim argument is not aligned with the shape input last dim");
}
} else {
CAFFE_ENFORCE(dense_last_dim_ >= 1, "The last dim of dense must be >= 1");
}
output_shape.push_back(dense_last_dim_);
output->Resize(output_shape);
T* output_data = output->template mutable_data<T>();
math::Set(
output->size(), static_cast<T>(default_value_), output_data, &context_);
int64_t k = 0;
for (int64_t i = 0; i < batch_size; ++i) {
for (int64_t j = 0; j < lengths_data[i]; ++j) {
CAFFE_ENFORCE(
indices_data[k] < dense_last_dim_,
"An indice (",
indices_data[k],
") is larger then last dim of dense (",
dense_last_dim_,
").");
output_data[i * dense_last_dim_ + indices_data[k]] = values_data[k];
k += 1;
}
}
return true;
}
template <typename T, class Context>
bool BatchDenseToSparseOp<T, Context>::RunOnDevice() {
auto& lengths = Input(LENGTHS);
auto& indices = Input(INDICES);
auto& dense = Input(DENSE);
auto* output = Output(0);
CAFFE_ENFORCE_EQ(lengths.ndim(), 1);
CAFFE_ENFORCE_EQ(indices.ndim(), 1);
CAFFE_ENFORCE_EQ(dense.ndim(), 2);
const int64_t* lengths_data = lengths.template data<int64_t>();
const int64_t* indices_data = indices.template data<int64_t>();
const T* dense_data = dense.template data<T>();
int64_t batch_size = lengths.size();
int64_t lengths_sum = 0;
math::Sum<int64_t, Context>(batch_size, lengths_data, &lengths_sum, &context_);
CAFFE_ENFORCE_EQ(lengths_sum, indices.size());
CAFFE_ENFORCE_EQ(batch_size, dense.dim(0));
dense_last_dim_ = dense.dim(1);
vector<int64_t> output_shape = indices.sizes().vec();
output->Resize(output_shape);
T* output_data = output->template mutable_data<T>();
int64_t k = 0;
for (int64_t i = 0; i < batch_size; ++i) {
for (int64_t j = 0; j < lengths_data[i]; ++j) {
CAFFE_ENFORCE(
indices_data[k] < dense.dim(1),
"An indice (",
indices_data[k],
") is larger then last dim of dense (",
dense.dim(1),
").");
output_data[k] = dense_data[i * dense.dim(1) + indices_data[k]];
k += 1;
}
}
return true;
}
REGISTER_CPU_OPERATOR(
BatchSparseToDense,
BatchSparseToDenseOp<float, CPUContext>);
OPERATOR_SCHEMA(BatchSparseToDense)
.NumInputs(3, 4)
.NumOutputs(1)
.DisallowInputFillers() // TODO: enable the filler
.SetDoc(R"DOC(
Convert sparse matrix representation into dense matrix.
A sparse matrix is represented by `lengths` vector, `indices` vector,
and `values` vector. Each element in `lengths` vector (lengths[`i`]) represents
the number of indices in this batch (batch `i`).
With in each batch, `indices` should not have duplicate number.
For example, with input:
lengths = [2, 3, 1]
indices = [0, 1, 2, 3, 4, 5]
values = [6, 7, 8, 9, 10, 11]
dense_dim = 6
default_value = 0
The output is:
output = [[6, 7, 0, 0, 0, 0],
[0, 0, 8, 9, 10, 0],
[0, 0, 0, 0, 0, 11]]
after running this operator.
)DOC")
.Input(
0,
"lengths",
"Flatten tensor, used to break down indices and values into per batch indices and values.")
.Input(
1,
"indices",
"Flatten tensor of total size = \\sum lengths, containing the indices ")
.Input(2, "values", "Data tensor, dimension has to match `indices`")
.Input(
3,
"output_shape_inference",
"Optional, a dense tensor whose shape define the output shape")
.Output(
0,
"dense",
"2-D dense tensor, with 1st dim = len(lengths), 2nd dim = dense_last_dim"
"in the arg list, the tensor is of the same data type as `values`."
"Missing values are filled with default_value")
.Arg(
"dense_last_dim",
"Optional, output dense last dimension. "
"If both this argument and output_shape_inference are set, "
"it should be consistent with output_shape_inference's last dim")
.Arg(
"default_value",
"Optional, missing values are filled with this value."
"default_value = 0 when not set");
REGISTER_CPU_OPERATOR(
BatchDenseToSparse,
BatchDenseToSparseOp<float, CPUContext>);
OPERATOR_SCHEMA(BatchDenseToSparse)
.NumInputs(3)
.NumOutputs(1)
.SetDoc(R"DOC(
This Op is a inverse of BatchSparseToDenseOp.
Basically, given a `lengths` vector, a `indices` vector,
and a dense matrix `dense`, output `value` vector so that, along with
`lengths` vector and `indices` vector, forms a sparse representation
of the dense matrix.
A sparse matrix is represented by `lengths` vector, `indices` vector,
and `values` vector. Each element in `lengths` vector (lengths[`i`]) represents
the number of indices in this batch (batch `i`).
With in each batch, `indices` should not have duplicate number.
For example, with input:
lengths = [2, 3, 1]
indices = [0, 1, 2, 3, 4, 5]
output = [[6, 7, 0, 0, 0, 0],
[0, 0, 8, 9, 10, 0],
[0, 0, 0, 0, 0, 11]]
The output is:
values = [6, 7, 8, 9, 10, 11]
after running this operator.
)DOC")
.Input(
0,
"lengths",
"Flatten lengths, Used to break down indices into per batch indices")
.Input(
1,
"indices",
"Flatten indices, tensor of total size = \\sum lengths, containing the indices ")
.Input(
2,
"dense",
"dense 2-D tensor, first dim = len(lengths), last dim > Any(indices)")
.Output(
0,
"values",
"Values, tensor of the same size as `indices` and same data type as dense tensor.");
namespace {
class GetBatchSparseToDenseGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"BatchDenseToSparse",
"",
vector<string>{I(0), I(1), GO(0)},
vector<string>{GI(2)});
}
};
class GetBatchDenseToSparseGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"BatchSparseToDense",
"",
vector<string>{I(0), I(1), GO(0), I(2)},
vector<string>{GI(2)});
}
};
REGISTER_GRADIENT(BatchSparseToDense, GetBatchSparseToDenseGradient);
REGISTER_GRADIENT(BatchDenseToSparse, GetBatchDenseToSparseGradient);
} // namespace
} // namespace caffe2