Caffe2 - C++ API
A deep learning, cross platform ML framework
channel_stats_op.cc
1 #include "caffe2/operators/channel_stats_op.h"
2 
3 #include "caffe2/utils/eigen_utils.h"
4 
5 namespace caffe2 {
6 
7 template <>
8 template <>
9 bool ChannelStatsOp<CPUContext>::ComputeChannelStatsNCHW<float>(
10  const int N,
11  const int C,
12  const int HxW,
13  const float* X,
14  float* sum,
15  float* sumsq) {
16  ConstEigenArrayMap<float> X_arr(X, HxW, N * C);
17  for (int i = 0; i < C; ++i) {
18  sum[i] = X_arr.col(i).sum();
19  sumsq[i] = X_arr.col(i).square().sum();
20  }
21  for (int i = 1; i < N; ++i) {
22  for (int j = 0; j < C; ++j) {
23  const int c = i * C + j;
24  sum[j] += X_arr.col(c).sum();
25  sumsq[j] += X_arr.col(c).square().sum();
26  }
27  }
28  return true;
29 }
30 
31 template <>
32 template <>
33 bool ChannelStatsOp<CPUContext>::ComputeChannelStatsNHWC<float>(
34  const int N,
35  const int C,
36  const int HxW,
37  const float* X,
38  float* sum,
39  float* sumsq) {
40  ConstEigenArrayMap<float> X_arr(X, C, N * HxW);
41  EigenVectorArrayMap<float> sum_arr(sum, C);
42  EigenVectorArrayMap<float> sumsq_arr(sumsq, C);
43  sum_arr = X_arr.col(0);
44  sumsq_arr = X_arr.col(0).square();
45  for (int i = 1; i < N * HxW; ++i) {
46  sum_arr += X_arr.col(i);
47  sumsq_arr += X_arr.col(i).square();
48  }
49  return true;
50 }
51 
52 REGISTER_CPU_OPERATOR(ChannelStats, ChannelStatsOp<CPUContext>);
53 
54 OPERATOR_SCHEMA(ChannelStats)
55  .NumInputs(1)
56  .NumOutputs(2)
57  .SetDoc(R"DOC(
58 Given an input tensor in NCHW format, computes the sum of all elements per
59 channel and the sum of all elements squared per channel. These values can be
60 reduced across multiple batches and used to obtain the mean and variance across
61 the full set of batches. Using the new mean and variance as input to SpatialBN
62 has the effect of changing the batch size over which SpatialBN is applied.
63 )DOC")
64  .Input(0, "X", "The input 4-dimensional tensor of shape NCHW")
65  .Output(
66  0,
67  "sum",
68  "The output 1-dimensional tensor of size C containing the sum of "
69  "elements of X per channel.")
70  .Output(
71  1,
72  "sumsq",
73  "The output 1-dimensional tensor of size C containing the sum of "
74  "elements squared per channel.");
75 
76 SHOULD_NOT_DO_GRADIENT(ChannelStats);
77 
78 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13
Definition: static.cpp:64