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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
|
#include "caffe2/operators/index_ops.h"
#include <atomic>
#include <limits>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <vector>
#include "caffe2/core/blob_serialization.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/tensor.h"
namespace caffe2 {
// TODO(azzolini): support sizes larger than int32
template <class T>
class IndexCreateOp : public Operator<CPUContext> {
public:
IndexCreateOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws),
maxElements_(OperatorBase::GetSingleArgument<int>(
"max_elements",
std::numeric_limits<int>::max())) {}
bool RunOnDevice() override {
*OperatorBase::Output<std::unique_ptr<IndexBase>>(0) =
std::unique_ptr<IndexBase>(new Index<T>(maxElements_));
return true;
}
private:
int64_tValue maxElements_;
};
class IndexGetOp : public Operator<CPUContext> {
public:
IndexGetOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
return DispatchHelper<IndexKeyTypes>::call(this, Input(1));
}
template <typename T>
bool DoRunWithType() {
auto& base = OperatorBase::Input<std::unique_ptr<IndexBase>>(0);
auto* dict = dynamic_cast_if_rtti<Index<T>*>(base.get());
CAFFE_ENFORCE(dict, "Wrong dictionary type given input keys.");
const auto& keys = Input(1);
auto* values = Output(0, keys.sizes(), at::dtype<int64_tValue>());
dict->Get(
keys.data<T>(),
values->template mutable_data<int64_tValue>(),
keys.numel());
return true;
}
};
class IndexLoadOp : public Operator<CPUContext> {
public:
IndexLoadOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws),
skipFirstEntry_(
OperatorBase::GetSingleArgument<int>("skip_first_entry", 0)) {}
bool RunOnDevice() override {
return DispatchHelper<IndexKeyTypes>::call(this, Input(1));
}
template <typename T>
bool DoRunWithType() {
auto& base = OperatorBase::Input<std::unique_ptr<IndexBase>>(0);
auto* dict = dynamic_cast_if_rtti<Index<T>*>(base.get());
CAFFE_ENFORCE(dict, "Wrong dictionary type given input keys.");
const auto& keys = Input(1);
const auto* keys_data = keys.data<T>();
auto keys_size = keys.numel();
if (skipFirstEntry_) {
CAFFE_ENFORCE(keys.numel() > 0);
++keys_data;
--keys_size;
}
return dict->Load(keys_data, keys_size);
}
private:
bool skipFirstEntry_;
};
class IndexStoreOp : public Operator<CPUContext> {
public:
IndexStoreOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
auto& base = OperatorBase::Input<std::unique_ptr<IndexBase>>(0);
return DispatchHelper<IndexKeyTypes>::call(this, base->Type());
}
template <typename T>
bool DoRunWithType() {
auto& base = OperatorBase::Input<std::unique_ptr<IndexBase>>(0);
auto* dict = dynamic_cast_if_rtti<Index<T>*>(base.get());
CAFFE_ENFORCE(dict);
return dict->Store(Output(0));
}
};
class IndexFreezeOp : public Operator<CPUContext> {
public:
IndexFreezeOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
auto& base = OperatorBase::Input<std::unique_ptr<IndexBase>>(0);
base->Freeze();
return true;
}
};
class IndexSizeOp : public Operator<CPUContext> {
public:
IndexSizeOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
auto& base = OperatorBase::Input<std::unique_ptr<IndexBase>>(0);
auto* out = Output(0, std::vector<int64_t>{}, at::dtype<int64_tValue>());
*out->template mutable_data<int64_tValue>() = base->Size();
return true;
}
};
REGISTER_CPU_OPERATOR(IntIndexCreate, IndexCreateOp<int32_t>);
REGISTER_CPU_OPERATOR(LongIndexCreate, IndexCreateOp<int64_t>);
REGISTER_CPU_OPERATOR(StringIndexCreate, IndexCreateOp<std::string>);
REGISTER_CPU_OPERATOR(IndexGet, IndexGetOp);
REGISTER_CPU_OPERATOR(IndexLoad, IndexLoadOp);
REGISTER_CPU_OPERATOR(IndexStore, IndexStoreOp);
REGISTER_CPU_OPERATOR(IndexFreeze, IndexFreezeOp);
REGISTER_CPU_OPERATOR(IndexSize, IndexSizeOp);
OPERATOR_SCHEMA(IntIndexCreate)
.NumInputs(0)
.NumOutputs(1)
.SetDoc(R"DOC(
Creates a dictionary that maps int32 keys to consecutive integers
from 1 to max_elements. Zero is reserved for unknown keys.
)DOC")
.Arg("max_elements", "Max number of elements, including the zero entry.")
.Output(0, "handler", "Pointer to an Index instance.")
.ScalarType(TensorProto_DataType_UNDEFINED);
OPERATOR_SCHEMA(LongIndexCreate)
.NumInputs(0)
.NumOutputs(1)
.SetDoc(R"DOC(
Creates a dictionary that maps int64 keys to consecutive integers
from 1 to max_elements. Zero is reserved for unknown keys.
)DOC")
.Arg("max_elements", "Max number of elements, including the zero entry.")
.Output(0, "handler", "Pointer to an Index instance.")
.ScalarType(TensorProto_DataType_UNDEFINED);
OPERATOR_SCHEMA(StringIndexCreate)
.NumInputs(0)
.NumOutputs(1)
.SetDoc(R"DOC(
Creates a dictionary that maps string keys to consecutive integers
from 1 to max_elements. Zero is reserved for unknown keys.
)DOC")
.Arg("max_elements", "Max number of elements, including the zero entry.")
.Output(0, "handle", "Pointer to an Index instance.")
.ScalarType(TensorProto_DataType_UNDEFINED);
OPERATOR_SCHEMA(IndexGet)
.NumInputs(2)
.NumOutputs(1)
.SetDoc(R"DOC(
Given an index handle and a tensor of keys, return an Int tensor of same shape
containing the indices for each of the keys. If the index is frozen, unknown
entries are given index 0. Otherwise, new entries are added into the index.
If an insert is necessary but max_elements has been reached, fail.
)DOC")
.Input(0, "handle", "Pointer to an Index instance.")
.Input(1, "keys", "Tensor of keys to be looked up.")
.Output(0, "indices", "Indices for each of the keys.")
.ScalarType(TensorProto::INT64);
OPERATOR_SCHEMA(IndexFreeze)
.NumInputs(1)
.NumOutputs(1)
.SetDoc(R"DOC(
Freezes the given index, disallowing creation of new index entries.
Should not be called concurrently with IndexGet.
)DOC")
.Input(0, "handle", "Pointer to an Index instance.")
.Output(0, "handle", "The input handle.")
.EnforceInplace({{0, 0}})
.ScalarType(TensorProto_DataType_UNDEFINED);
OPERATOR_SCHEMA(IndexLoad)
.NumInputs(2)
.NumOutputs(1)
.SetDoc(R"DOC(
Loads the index from the given 1-D tensor. Elements in the tensor will be given
consecutive indexes starting at 1. Fails if tensor contains repeated elements.
)DOC")
.Input(0, "handle", "Pointer to an Index instance.")
.Input(1, "items", "1-D tensor with elements starting with index 1.")
.Output(0, "handle", "The input handle.")
.EnforceInplace({{0, 0}})
.Arg(
"skip_first_entry",
"If set, skips the first entry of the tensor. This allows "
"to load tensors that are aligned with an embedding, where the first "
"entry corresponds to the default 0 index entry.")
.ScalarType(TensorProto_DataType_UNDEFINED);
OPERATOR_SCHEMA(IndexStore)
.NumInputs(1)
.NumOutputs(1)
.SetDoc(R"DOC(
Stores the keys of this index in a 1-D tensor. Since element 0 is reserved
for unknowns, the first element of the output tensor will be element of index 1.
)DOC")
.Input(0, "handle", "Pointer to an Index instance.")
.Output(0, "items", "1-D tensor with elements starting with index 1.");
OPERATOR_SCHEMA(IndexSize)
.NumInputs(1)
.NumOutputs(1)
.SetDoc(R"DOC(
Returns the number of entries currently present in the index.
)DOC")
.Input(0, "handle", "Pointer to an Index instance.")
.Output(0, "items", "Scalar int64 tensor with number of entries.");
NO_GRADIENT(IndexGetOp);
NO_GRADIENT(IntIndexCreate);
NO_GRADIENT(LongIndexCreate);
NO_GRADIENT(StringIndexCreate);
SHOULD_NOT_DO_GRADIENT(IndexFreeze);
SHOULD_NOT_DO_GRADIENT(IndexLoad);
SHOULD_NOT_DO_GRADIENT(IndexStore);
SHOULD_NOT_DO_GRADIENT(IndexSize);
class IndexSerializer : public BlobSerializerBase {
public:
IndexSerializer() {}
~IndexSerializer() {}
void Serialize(
const void* pointer,
TypeMeta typeMeta,
const string& name,
SerializationAcceptor acceptor) override {
CAFFE_ENFORCE(typeMeta.Match<std::unique_ptr<IndexBase>>());
const auto& base = *static_cast<const std::unique_ptr<IndexBase>*>(pointer);
Blob tensor_blob;
auto* tensor_out = BlobGetMutableTensor(&tensor_blob, CPU);
if (base->Type().Match<std::string>()) {
doStore<std::string>(base, tensor_out);
} else if (base->Type().Match<int32_t>()) {
doStore<int32_t>(base, tensor_out);
} else if (base->Type().Match<int64_t>()) {
doStore<int64_t>(base, tensor_out);
} else {
CAFFE_THROW("Index of this type can't be serialized.");
}
CAFFE_ENFORCE(
tensor_out->numel() <= std::numeric_limits<int32_t>::max(),
"Index too large to be serialized.");
BlobProto blob_proto;
TensorSerializer ser;
ser.Serialize(
*tensor_out, name, blob_proto.mutable_tensor(), 0, tensor_out->numel());
blob_proto.set_name(name);
blob_proto.set_type("std::unique_ptr<caffe2::IndexBase>");
std::ostringstream os;
os << base->maxElements() << " " << base->isFrozen();
blob_proto.set_content(os.str());
acceptor(name, SerializeBlobProtoAsString_EnforceCheck(blob_proto));
}
private:
template <typename T>
void doStore(const std::unique_ptr<IndexBase>& base, Tensor* tensor_out) {
auto* dict = dynamic_cast_if_rtti<Index<T>*>(base.get());
CAFFE_ENFORCE(dict, "Wrong dictionary type.");
dict->Store(tensor_out);
}
};
class IndexDeserializer : public BlobDeserializerBase {
public:
void Deserialize(const BlobProto& proto, Blob* blob) override {
TensorDeserializer deser;
Blob tensor_blob;
deser.Deserialize(proto, &tensor_blob);
std::istringstream is(proto.content());
int64_t maxElements{std::numeric_limits<int64_t>::max()};
bool isFrozen{false};
is >> maxElements >> isFrozen;
auto& tensor_in = tensor_blob.template Get<Tensor>();
auto* base = blob->template GetMutable<std::unique_ptr<IndexBase>>();
if (tensor_in.IsType<std::string>()) {
doLoad<std::string>(base, maxElements, tensor_in);
} else if (tensor_in.IsType<int32_t>()) {
doLoad<int32_t>(base, maxElements, tensor_in);
} else if (tensor_in.IsType<int64_t>()) {
doLoad<int64_t>(base, maxElements, tensor_in);
} else {
CAFFE_THROW("Index of this type cannot be deserialized.");
}
if (isFrozen) {
(*base)->Freeze();
}
}
private:
template <typename T>
void doLoad(
std::unique_ptr<IndexBase>* base,
int64_t maxElements,
const Tensor& tensor_in) {
base->reset(new Index<T>(maxElements));
auto* dict = dynamic_cast_if_rtti<Index<T>*>(base->get());
dict->Load(tensor_in.data<T>(), tensor_in.numel());
}
};
CAFFE_KNOWN_TYPE(std::unique_ptr<caffe2::IndexBase>);
REGISTER_BLOB_SERIALIZER(
(TypeMeta::Id<std::unique_ptr<caffe2::IndexBase>>()),
IndexSerializer);
REGISTER_BLOB_DESERIALIZER(
std::unique_ptr<caffe2::IndexBase>,
IndexDeserializer);
} // namespace caffe2
|