Caffe2 - C++ API
A deep learning, cross platform ML framework
conditional_op.cc
1 #include "caffe2/operators/conditional_op.h"
2 #include "caffe2/core/operator.h"
3 #include "caffe2/core/tensor.h"
4 
5 namespace caffe2 {
6 
7 template <>
8 bool ConditionalOp<CPUContext>::RunOnDevice() {
9  auto& condition = Input(0);
10  auto& dataT = Input(1);
11  auto& dataF = Input(2);
12 
13  // verify the inputs shape
14  CAFFE_ENFORCE_EQ(condition.dim(), 1);
15  CAFFE_ENFORCE(dataT.dim() >= 1);
16  CAFFE_ENFORCE(dataT.sizes()[0] == condition.sizes()[0]);
17  CAFFE_ENFORCE_EQ(dataT.dim(), dataF.dim());
18  for (size_t i = 0; i < dataT.sizes().size(); i++) {
19  CAFFE_ENFORCE(dataT.sizes().at(i) == dataF.sizes().at(i));
20  }
21  const auto innerSize = dataT.size_from_dim(1);
22  const auto innerSizeBytes = innerSize * dataT.dtype().itemsize();
23  CAFFE_ENFORCE(innerSize * dataF.dtype().itemsize() == innerSizeBytes);
24 
25  // initialize output shape
26  auto* dataOut = Output(0);
27  const auto* condPtr = condition.template data<bool>();
28  dataOut->ResizeLike(dataT);
29  auto* outPtr = (char*)dataOut->raw_mutable_data(dataT.dtype());
30 
31  // perform conditional op along first dimension
32  const auto* ptrT = (char*)dataT.raw_data();
33  const auto* ptrF = (char*)dataF.raw_data();
34  for (int64_t i = 0; i < condition.numel(); i++) {
35  auto* dst = outPtr + i * innerSizeBytes;
36  if (condPtr[i]) {
37  context_.CopyItemsSameDevice(
38  dataT.dtype(), innerSize, ptrT + i * innerSizeBytes, dst);
39  } else {
40  context_.CopyItemsSameDevice(
41  dataF.dtype(), innerSize, ptrF + i * innerSizeBytes, dst);
42  }
43  }
44  return true;
45 }
46 
47 REGISTER_CPU_OPERATOR(Conditional, ConditionalOp<CPUContext>);
48 
49 OPERATOR_SCHEMA(Conditional)
50  .NumInputs(3)
51  .NumOutputs(1)
52  .SetDoc(R"DOC(
53 Given a 1-D tensor of boolean values, apply conditional operator along the first
54 dimension of DataT and DataF and return DataO. Note, DataT and DataF must
55 have the exact same shape and type.
56 )DOC")
57  .Input(0, "Condition", "Boolean tensor to select DataT or DataF")
58  .Input(1, "DataT", "Data to use when True")
59  .Input(2, "DataF", "Data to use when False")
60  .Output(0, "DataO", "Output data after applying ConditionalOp")
61  .IdenticalTypeAndShapeOfInput(1);
62 
63 NO_GRADIENT(Conditional);
64 
65 } // caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13