Caffe2 - C++ API
A deep learning, cross platform ML framework
conditional_op.cc
1 
17 #include "caffe2/operators/conditional_op.h"
18 #include "caffe2/core/operator.h"
19 #include "caffe2/core/tensor.h"
20 
21 namespace caffe2 {
22 
23 template <>
24 bool ConditionalOp<CPUContext>::RunOnDevice() {
25  auto& condition = Input(0);
26  auto& dataT = Input(1);
27  auto& dataF = Input(2);
28 
29  // verify the inputs shape
30  CAFFE_ENFORCE_EQ(condition.ndim(), 1);
31  CAFFE_ENFORCE(dataT.ndim() >= 1);
32  CAFFE_ENFORCE(dataT.dims()[0] == condition.dims()[0]);
33  CAFFE_ENFORCE_EQ(dataT.ndim(), dataF.ndim());
34  for (size_t i = 0; i < dataT.dims().size(); i++) {
35  CAFFE_ENFORCE(dataT.dims().at(i) == dataF.dims().at(i));
36  }
37  const auto innerSize = dataT.size_from_dim(1);
38  const auto innerSizeBytes = innerSize * dataT.meta().itemsize();
39  CAFFE_ENFORCE(innerSize * dataF.meta().itemsize() == innerSizeBytes);
40 
41  // initialize output shape
42  auto* dataOut = Output(0);
43  const auto* condPtr = condition.template data<bool>();
44  dataOut->ResizeLike(dataT);
45  auto* outPtr = (char*)dataOut->raw_mutable_data(dataT.meta());
46 
47  // perform conditional op along first dimension
48  const auto* ptrT = (char*)dataT.raw_data();
49  const auto* ptrF = (char*)dataF.raw_data();
50  for (TIndex i = 0; i < condition.size(); i++) {
51  auto* dst = outPtr + i * innerSizeBytes;
52  if (condPtr[i]) {
53  context_.template CopyItems<CPUContext, CPUContext>(
54  dataT.meta(), innerSize, ptrT + i * innerSizeBytes, dst);
55  } else {
56  context_.template CopyItems<CPUContext, CPUContext>(
57  dataF.meta(), innerSize, ptrF + i * innerSizeBytes, dst);
58  }
59  }
60  return true;
61 }
62 
63 REGISTER_CPU_OPERATOR(Conditional, ConditionalOp<CPUContext>);
64 
65 OPERATOR_SCHEMA(Conditional)
66  .NumInputs(3)
67  .NumOutputs(1)
68  .SetDoc(R"DOC(
69 Given a 1-D tensor of boolean values, apply conditional operator along the first
70 dimension of DataT and DataF and return DataO. Note, DataT and DataF must
71 have the exact same shape and type.
72 )DOC")
73  .Input(0, "Condition", "Boolean tensor to select DataT or DataF")
74  .Input(1, "DataT", "Data to use when True")
75  .Input(2, "DataF", "Data to use when False")
76  .Output(0, "DataO", "Output data after applying ConditionalOp");
77 
78 NO_GRADIENT(Conditional);
79 
80 } // caffe2
Copyright (c) 2016-present, Facebook, Inc.