46ffcc5238af903c54b15aa38b74c7c64f3f0def
[platform/upstream/opencv.git] / modules / dnn / src / layers / mvn_layer.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14 // Copyright (C) 2017, Intel Corporation, all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42
43 #include "../precomp.hpp"
44 #include "layers_common.hpp"
45 #include <opencv2/dnn/shape_utils.hpp>
46 #include "math_functions.hpp"
47 #include "opencl_kernels_dnn.hpp"
48
49 namespace cv
50 {
51 namespace dnn
52 {
53
54 class MVNLayerImpl : public MVNLayer
55 {
56 public:
57     MVNLayerImpl(const LayerParams& params)
58     {
59         setParamsFrom(params);
60         normVariance = params.get<bool>("normalize_variance", true);
61         acrossChannels = params.get<bool>("across_channels", false);
62         eps = params.get<double>("eps", 1e-9);
63     }
64
65 #ifdef HAVE_OPENCL
66     bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
67     {
68         std::vector<UMat> inputs;
69         std::vector<UMat> outputs;
70
71         inputs_.getUMatVector(inputs);
72         outputs_.getUMatVector(outputs);
73
74         for (size_t inpIdx = 0; inpIdx < inputs.size(); inpIdx++)
75         {
76             UMat &inpBlob = inputs[inpIdx];
77             UMat &outBlob = outputs[inpIdx];
78
79             int splitDim = (acrossChannels) ? 1 : 2;
80             int i, newRows = 1;
81             for( i = 0; i < splitDim; i++ )
82                 newRows *= inpBlob.size[i];
83
84             MatShape s = shape(newRows, inpBlob.total() / newRows);
85             UMat& inpMat = inpBlob;
86             UMat& outMat = outBlob;
87             UMat oneMat = UMat::ones(s[1], 1, CV_32F);
88             UMat meanMat = UMat(s[0], 1, CV_32F);
89             UMat devMat  = UMat(s[0], 1, CV_32F);
90             UMat tmpMat  = UMat(s[0], s[1], CV_32F);
91             float alpha = 1.0f / s[1];
92
93             bool ret = ocl4dnn::ocl4dnnGEMV<float>(ocl4dnn::CblasNoTrans, s[0], s[1], alpha,
94                                                    inpMat, 0, oneMat, 0, 0.0f, meanMat, 0);
95             if (!ret)
96                 return false;
97
98             int number = (s[1] % 8 == 0) ? 8 : ((s[1] % 4 == 0) ? 4 : 1);
99             String buildopt = format("-DNUM=%d ", number);
100             String kname = format("calc_mean%d", number);
101             ocl::Kernel kernel(kname.c_str(), ocl::dnn::mvn_oclsrc, buildopt);
102             if (kernel.empty())
103                 return false;
104             size_t global[] = { (size_t)s[0], (size_t)(s[1] / number) };
105             kernel.set(0, ocl::KernelArg::PtrReadOnly(inpMat));
106             kernel.set(1, (int)s[0]);
107             kernel.set(2, (int)s[1]);
108             kernel.set(3, ocl::KernelArg::PtrReadOnly(meanMat));
109             kernel.set(4, ocl::KernelArg::PtrWriteOnly(tmpMat));
110             ret = kernel.run(2, global, NULL, false);
111             if (!ret)
112                 return false;
113
114             if (normVariance)
115             {
116                 ret = ocl4dnn::ocl4dnnGEMV<float>(ocl4dnn::CblasNoTrans, s[0], s[1], alpha,
117                                                   tmpMat, 0, oneMat, 0, 0.0f, devMat, 0);
118                 if (!ret)
119                     return false;
120             }
121
122             kname = format("mvn%d", number);
123             if (normVariance)
124                 buildopt += "-DNORM_VARIANCE";
125             ocl::Kernel kernel1(kname.c_str(), ocl::dnn::mvn_oclsrc, buildopt);
126             if (kernel1.empty())
127                 return false;
128             kernel1.set(0, ocl::KernelArg::PtrReadOnly(inpMat));
129             kernel1.set(1, (int)s[0]);
130             kernel1.set(2, (int)s[1]);
131             kernel1.set(3, (float)eps);
132             kernel1.set(4, ocl::KernelArg::PtrReadOnly(meanMat));
133             kernel1.set(5, ocl::KernelArg::PtrReadOnly(devMat));
134             kernel1.set(6, ocl::KernelArg::PtrWriteOnly(outMat));
135             ret = kernel1.run(2, global, NULL, false);
136             if (!ret)
137                 return false;
138         }
139         return true;
140     }
141 #endif
142
143     void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
144     {
145         CV_TRACE_FUNCTION();
146         CV_TRACE_ARG_VALUE(name, "name", name.c_str());
147
148         CV_OCL_RUN((preferableTarget == DNN_TARGET_OPENCL) &&
149                    OCL_PERFORMANCE_CHECK(ocl::Device::getDefault().isIntel()),
150                    forward_ocl(inputs_arr, outputs_arr, internals_arr))
151
152         Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr);
153     }
154
155     void forward(std::vector<Mat *> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
156     {
157         CV_TRACE_FUNCTION();
158         CV_TRACE_ARG_VALUE(name, "name", name.c_str());
159
160         for (size_t inpIdx = 0; inpIdx < inputs.size(); inpIdx++)
161         {
162             Mat &inpBlob = *inputs[inpIdx];
163             Mat &outBlob = outputs[inpIdx];
164
165             int splitDim = (acrossChannels) ? 1 : 2;
166             int i, newRows = 1;
167             for( i = 0; i < splitDim; i++ )
168                 newRows *= inpBlob.size[i];
169             Mat inpMat = inpBlob.reshape(1, newRows);
170             Mat outMat = outBlob.reshape(1, newRows);
171
172             Scalar mean, dev;
173             for ( i = 0; i < newRows; i++)
174             {
175                 Mat inpRow = inpMat.row(i);
176                 Mat outRow = outMat.row(i);
177
178                 cv::meanStdDev(inpRow, mean, (normVariance) ? dev : noArray());
179                 double alpha = (normVariance) ? 1/(eps + dev[0]) : 1;
180                 inpRow.convertTo(outRow, outRow.type(), alpha, -mean[0] * alpha);
181             }
182         }
183     }
184
185     virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
186                            const std::vector<MatShape> &outputs) const
187     {
188         (void)outputs; // suppress unused variable warning
189         long flops = 0;
190         for(int i = 0; i < inputs.size(); i++)
191         {
192             flops += 6*total(inputs[i]) + 3*total(inputs[i], 0, normVariance ? 2 : 1);
193         }
194         return flops;
195     }
196 };
197
198 Ptr<MVNLayer> MVNLayer::create(const LayerParams& params)
199 {
200     return Ptr<MVNLayer>(new MVNLayerImpl(params));
201 }
202
203 }
204 }