Caffe2 - C++ API
A deep learning, cross platform ML framework
sparse_to_dense_op.cc
1 
17 #include "sparse_to_dense_op.h"
18 
19 #include "caffe2/core/context.h"
20 
21 namespace caffe2 {
22 
23 REGISTER_CPU_OPERATOR(SparseToDense, SparseToDenseOp<CPUContext>);
24 
25 OPERATOR_SCHEMA(SparseToDense)
26  .NumInputs(2, 3)
27  .NumOutputs(1)
28  .SetDoc(R"DOC(
29 Convert sparse representations to dense with given indices.
30 
31 Transforms a sparse representation of map<id, value> represented as `indices`
32 vector and `values` tensor into a compacted tensor where the first dimension
33 is determined by the first dimension of the 3rd input if it is given or the
34 max index. Missing values are filled with zeros.
35 
36 The op supports duplicated indices and performs summation over corresponding
37 values. This behavior is useful for converting GradientSlices into dense
38 representation.
39 
40 After running this op:
41 
42  output[indices[i], :] += values[i] # sum over all indices[i] equal to the index
43  output[j, ...] = 0 if j not in indices
44 )DOC")
45  .Input(0, "indices", "1-D int32/int64 tensor of concatenated ids of data")
46  .Input(
47  1,
48  "values",
49  "Data tensor, first dimension has to match `indices`, "
50  "basic numeric types are supported")
51  .Input(
52  2,
53  "data_to_infer_dim",
54  "Optional: if provided, the first dimension of output is the first "
55  "dimension of this tensor.")
56  .Output(
57  0,
58  "output",
59  "Output tensor of the same type as `values` of shape `[len(lengths), "
60  "len(mask)] + shape(default_value)` (if `lengths` is not provided the "
61  "first dimension is omitted)");
62 
63 
64 namespace {
65 class GetSparseToDenseGradient : public GradientMakerBase {
66  using GradientMakerBase::GradientMakerBase;
67  vector<OperatorDef> GetGradientDefs() override {
68  return SingleGradientDef(
69  "Gather", "", vector<string>{GO(0), I(0)}, vector<string>{GI(1)});
70  }
71 };
72 
73 REGISTER_GRADIENT(SparseToDense, GetSparseToDenseGradient);
74 }
75 } // namespace caffe2
Copyright (c) 2016-present, Facebook, Inc.