Caffe2 - C++ API
A deep learning, cross platform ML framework
channel_stats_op.cc
1 
17 #include "caffe2/operators/channel_stats_op.h"
18 
19 namespace caffe2 {
20 
21 template <>
22 bool ChannelStatsOp<CPUContext>::RunOnDevice() {
23  const auto& X = Input(INPUT);
24  CAFFE_ENFORCE(X.ndim() >= 3 && X.ndim() <= 5);
25  const int N = X.dim32(0);
26  const int C = X.dim32(1);
27  const int H = X.dim32(2);
28  const int W = X.ndim() > 3 ? X.dim32(3) : 1;
29  const int D = X.ndim() > 4 ? X.dim32(4) : 1;
30 
31  const int sampleSize = H * W * D;
32 
33  Output(SUM)->Resize(C);
34  Output(SUMSQ)->Resize(C);
35  EigenVectorArrayMap<float> sum(Output(SUM)->mutable_data<float>(), C);
36  EigenVectorArrayMap<float> sumsq(Output(SUMSQ)->mutable_data<float>(), C);
37 
38  sum.setZero();
39  sumsq.setZero();
40  ConstEigenArrayMap<float> X_arr(X.data<float>(), sampleSize, N * C);
41  auto index = 0;
42  for (int n = 0; n < N; ++n) {
43  for (int c = 0; c < C; ++c) {
44  sum(c) += X_arr.col(index).sum();
45  sumsq(c) += X_arr.col(index).matrix().squaredNorm();
46  index++;
47  }
48  }
49 
50  return true;
51 }
52 
53 REGISTER_CPU_OPERATOR(ChannelStats, ChannelStatsOp<CPUContext>);
54 
55 OPERATOR_SCHEMA(ChannelStats)
56  .NumInputs(1)
57  .NumOutputs(2)
58  .SetDoc(R"DOC(
59 Given an input tensor in NCHW format, computes the sum of all elements per
60 channel and the sum of all elements squared per channel. These values can be
61 reduced across multiple batches and used to obtain the mean and variance across
62 the full set of batches. Using the new mean and variance as input to SpatialBN
63 has the effect of changing the batch size over which SpatialBN is applied.
64 )DOC")
65 
66  .Input(0, "X", "The input 4-dimensional tensor of shape NCHW")
67  .Output(
68  0,
69  "sum",
70  "The output 1-dimensional tensor of size C containing the sum of "
71  "elements of X per channel.")
72  .Output(
73  1,
74  "sumsq",
75  "The output 1-dimensional tensor of size C containing the sum of "
76  "elements squared per channel.");
77 SHOULD_NOT_DO_GRADIENT(ChannelStats);
78 } // namespace caffe2
Copyright (c) 2016-present, Facebook, Inc.