Caffe2 - C++ API
A deep learning, cross platform ML framework
flatten_op.cc
1 #include "caffe2/operators/flatten_op.h"
2 
3 namespace caffe2 {
4 
5 REGISTER_CPU_OPERATOR(Flatten, FlattenOp<CPUContext>);
6 
7 OPERATOR_SCHEMA(Flatten)
8  .NumInputs(1)
9  .NumOutputs(1)
10  .TensorInferenceFunction([](const OperatorDef& def,
11  const vector<TensorShape>& in) {
12  ArgumentHelper helper(def);
13  const int axis = helper.GetSingleArgument<int>("axis", 1);
14  vector<TensorShape> out(1);
15  TIndex outer = 1;
16  TIndex inner = 1;
17  std::size_t index = 0;
18  for (auto d : in[0].dims()) {
19  if (index < axis) {
20  outer *= d;
21  } else {
22  inner *= d;
23  }
24  ++index;
25  }
26  out[0].set_data_type(in[0].data_type());
27  out[0].add_dims(outer);
28  out[0].add_dims(inner);
29  return out;
30  })
31  .SetDoc(R"DOC(
32 Flattens the input tensor into a 2D matrix. If input tensor has shape
33 (d_0, d_1, ... d_n) then the output will have shape
34 (d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn)
35 )DOC")
36  .Input(0, "input", "A tensor of rank >= axis.")
37  .Output(
38  0,
39  "output",
40  "A 2D tensor with the contents of the input tensor, "
41  "with input dimensions up to axis flattened to the outer dimension "
42  "of the output and remaining input dimensions flattened into the inner "
43  "dimension of the output.")
44  .Arg(
45  "axis",
46  "(Default to 1) Indicate up to which input dimensions "
47  "(exclusive) should be flattened to the outer dimension of the output")
48  .InheritOnnxSchema("Flatten");
49 
51  using GradientMakerBase::GradientMakerBase;
52  vector<OperatorDef> GetGradientDefs() override {
53  return SingleGradientDef(
54  "ResizeLike", "", vector<string>{GO(0), I(0)}, vector<string>{GI(0)});
55  }
56 };
57 
58 REGISTER_GRADIENT(Flatten, GetFlattenGradient);
59 
60 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
static vector< OperatorDef > SingleGradientDef(const Args &...args)
a helper function to allow one to create one single operator def, which is usually the case for many ...