1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
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.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
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.
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.
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.
43 #include "../precomp.hpp"
44 #include "layers_common.hpp"
45 #include "op_halide.hpp"
46 #include "opencl_kernels_dnn.hpp"
53 class EltwiseLayerImpl : public EltwiseLayer
62 std::vector<float> coeffs;
64 EltwiseLayerImpl(const LayerParams& params)
66 setParamsFrom(params);
68 if (params.has("operation"))
70 String operation = params.get<String>("operation").toLowerCase();
71 if (operation == "prod")
73 else if (operation == "sum")
75 else if (operation == "max")
78 CV_Error(cv::Error::StsBadArg, "Unknown operaticon type \"" + operation + "\"");
81 if (params.has("coeff"))
83 DictValue paramCoeff = params.get("coeff");
84 int i, n = paramCoeff.size();
86 for (i = 0; i < n; i++)
88 coeffs[i] = paramCoeff.get<float>(i);
93 virtual bool supportBackend(int backendId)
95 return backendId == DNN_BACKEND_DEFAULT ||
96 backendId == DNN_BACKEND_HALIDE && haveHalide();
99 bool getMemoryShapes(const std::vector<MatShape> &inputs,
100 const int requiredOutputs,
101 std::vector<MatShape> &outputs,
102 std::vector<MatShape> &internals) const
104 CV_Assert(inputs.size() >= 2);
105 CV_Assert(coeffs.size() == 0 || coeffs.size() == inputs.size());
106 CV_Assert(op == SUM || coeffs.size() == 0);
108 for (int i = 1; i < inputs.size(); i++)
110 CV_Assert(inputs[0] == inputs[i]);
113 outputs.assign(1, inputs[0]);
118 class EltwiseInvoker : public ParallelLoopBody
124 const std::vector<float>* coeffs;
127 const ActivationLayer* activ;
131 EltwiseInvoker() : srcs(0), nsrcs(0), dst(0), coeffs(0), op(PROD), nstripes(0), activ(0), channels(0), planeSize(0) {}
133 static void run(const Mat** srcs, int nsrcs, Mat& dst,
134 const std::vector<float>& coeffs, EltwiseOp op,
135 const ActivationLayer* activ, int nstripes)
137 CV_Assert(1 < dst.dims && dst.dims <= 4, dst.type() == CV_32F, dst.isContinuous());
138 CV_Assert(coeffs.empty() || coeffs.size() == (size_t)nsrcs);
140 for( int i = 0; i > nsrcs; i++ )
142 CV_Assert(srcs[i]->size == dst.size &&
143 srcs[i]->type() == dst.type() &&
144 srcs[i]->isContinuous());
152 p.nstripes = nstripes;
153 p.channels = (dst.dims == 4 ? dst.size[1] : 1);
154 p.planeSize = (dst.dims >= 3 ? dst.size[dst.dims - 1] * dst.size[dst.dims - 2] :
155 dst.size[dst.dims - 1]);
156 CV_Assert(dst.total() == dst.size[0] * p.channels * p.planeSize);
158 bool simpleCoeffs = true;
159 if( op == SUM && !coeffs.empty() )
161 CV_Assert( coeffs.size() == (size_t)nsrcs );
163 for( size_t i = 0; i < coeffs.size(); i++ )
166 simpleCoeffs = false;
170 p.coeffs = simpleCoeffs ? 0 : &coeffs;
173 parallel_for_(Range(0, nstripes), p, nstripes);
176 void operator()(const Range& r) const
178 size_t total = dst->size[0]*planeSize;
179 size_t stripeSize = (total + nstripes - 1)/nstripes;
180 size_t stripeStart = r.start*stripeSize;
181 size_t stripeEnd = std::min(r.end*stripeSize, total);
182 int c, j, k, n = nsrcs;
183 const float* coeffsptr = coeffs && !coeffs->empty() ? &coeffs->at(0) : 0;
184 float* dstptr0 = dst->ptr<float>();
185 int blockSize0 = 1 << 12, blockSize = blockSize0;
187 for( size_t ofs = stripeStart; ofs < stripeEnd; ofs += blockSize )
189 int sampleIdx = (int)(ofs / planeSize);
190 int delta = (int)ofs - sampleIdx * planeSize;
191 blockSize = std::min(blockSize0, std::min((int)(stripeEnd - ofs), (int)planeSize - delta));
195 for( c = 0; c < channels; c++ )
197 size_t globalDelta = delta + (sampleIdx*channels + c)*planeSize;
198 const float* srcptr0 = srcs[0]->ptr<float>() + globalDelta;
199 float* dstptr = dstptr0 + globalDelta;
203 for( k = 1; k < n; k++ )
205 const float* srcptr1 = srcs[k]->ptr<float>() + globalDelta;
206 for( j = 0; j < blockSize; j++ )
208 dstptr[j] = srcptr0[j]*srcptr1[j];
210 srcptr0 = (const float*)dstptr;
215 for( k = 1; k < n; k++ )
217 const float* srcptr1 = srcs[k]->ptr<float>() + globalDelta;
218 for( j = 0; j < blockSize; j++ )
220 dstptr[j] = std::max(srcptr0[j], srcptr1[j]);
222 srcptr0 = (const float*)dstptr;
225 else if( !coeffsptr )
227 for( k = 1; k < n; k++ )
229 const float* srcptr1 = srcs[k]->ptr<float>() + globalDelta;
230 for( j = 0; j < blockSize; j++ )
232 dstptr[j] = srcptr0[j] + srcptr1[j];
234 srcptr0 = (const float*)dstptr;
239 float c0 = coeffsptr[0];
240 for( k = 1; k < n; k++ )
242 const float* srcptr1 = srcs[k]->ptr<float>() + globalDelta;
243 float c1 = coeffsptr[k];
244 for( j = 0; j < blockSize; j++ )
246 dstptr[j] = c0*srcptr0[j] + c1*srcptr1[j];
248 srcptr0 = (const float*)dstptr;
256 float* ptr = dstptr0 + delta + sampleIdx*channels*planeSize;
257 activ->forwardSlice(ptr, ptr, blockSize, planeSize, 0, channels);
264 bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
266 std::vector<UMat> inputs;
267 std::vector<UMat> outputs;
269 inputs_.getUMatVector(inputs);
270 outputs_.getUMatVector(outputs);
276 int channels = total(shape(outputs[0]), 0, 2);
277 int plane_size = total(shape(outputs[0]), 2);
278 if (channels % 4 == 0 && plane_size % 4 == 0)
280 size_t localsize[] = { 128 };
281 size_t globalsize[] = { (size_t)channels / 4 * localsize[0] };
283 for (int i = 0; i < (inputs.size() - 1); ++i)
285 String buildopt = format("-DLOOP=%d", i);
286 ocl::Kernel kernel("op_sum4", ocl::dnn::eltwise_oclsrc, buildopt);
288 UMat inpMat = (i == 0) ? inputs[0] : UMat();
289 float coeff1 = (coeffs.empty() || i > 0) ? 1.0f : coeffs[i];
290 float coeff2 = coeffs.empty() ? 1.0f : coeffs[i + 1];
291 kernel.set(idx++, ocl::KernelArg::PtrReadOnly(inputs[0]));
292 kernel.set(idx++, ocl::KernelArg::PtrReadOnly(inputs[1]));
293 kernel.set(idx++, (int)plane_size);
294 kernel.set(idx++, (float)coeff1);
295 kernel.set(idx++, (float)coeff2);
296 kernel.set(idx++, ocl::KernelArg::PtrReadWrite(outputs[0]));
297 bool ret = kernel.run(1, globalsize, localsize, false);
304 float coeff1 = coeffs.empty() ? 1.f : coeffs[0];
305 float coeff2 = coeffs.empty() ? 1.f : coeffs[1];
307 multiply(coeff1, inputs[0], mul0);
308 multiply(coeff2, inputs[1], mul1);
309 add(mul0, mul1, outputs[0]);
310 for (int i = 2; i < inputs.size(); ++i)
312 float coeff = coeffs.empty() ? 1.f : coeffs[i];
313 multiply(coeff, inputs[i], mul0);
314 add(mul0, outputs[0], outputs[0]);
320 multiply(inputs[0], inputs[1], outputs[0]);
321 for (int i = 2; i < inputs.size(); ++i)
322 multiply(inputs[i], outputs[0], outputs[0]);
325 max(inputs[0], inputs[1], outputs[0]);
326 for (int i = 2; i < inputs.size(); ++i)
327 max(inputs[i], outputs[0], outputs[0]);
336 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
339 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
341 CV_OCL_RUN((preferableTarget == DNN_TARGET_OPENCL) &&
342 OCL_PERFORMANCE_CHECK(ocl::Device::getDefault().isIntel()),
343 forward_ocl(inputs_arr, outputs_arr, internals_arr))
345 Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr);
348 void forward(std::vector<Mat *> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
351 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
353 CV_Assert(outputs.size() == 1);
354 const int nstripes = getNumThreads();
355 EltwiseInvoker::run((const Mat**)&inputs[0], (int)inputs.size(), outputs[0],
356 coeffs, op, activ.get(), nstripes);
359 virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &input)
362 Halide::Var x("x"), y("y"), c("c"), n("n");
363 Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
364 Halide::Expr topExpr;
365 std::vector<Halide::Buffer<> > inputBuffers = halideBuffers(input);
371 topExpr = inputBuffers[0](x, y, c, n) +
372 inputBuffers[1](x, y, c, n);
373 for (int i = 2; i < inputBuffers.size(); ++i)
374 topExpr += inputBuffers[i](x, y, c, n);
378 topExpr = coeffs[0] * inputBuffers[0](x, y, c, n) +
379 coeffs[1] * inputBuffers[1](x, y, c, n);
380 for (int i = 2; i < inputBuffers.size(); ++i)
381 topExpr += coeffs[i] * inputBuffers[i](x, y, c, n);
385 topExpr = inputBuffers[0](x, y, c, n) *
386 inputBuffers[1](x, y, c, n);
387 for (int i = 2; i < inputBuffers.size(); ++i)
388 topExpr *= inputBuffers[i](x, y, c, n);
391 topExpr = max(inputBuffers[0](x, y, c, n),
392 inputBuffers[1](x, y, c, n));
393 for (int i = 2; i < inputBuffers.size(); ++i)
394 topExpr = max(topExpr, inputBuffers[i](x, y, c, n));
397 return Ptr<BackendNode>();
399 top(x, y, c, n) = topExpr;
400 return Ptr<BackendNode>(new HalideBackendNode(top));
401 #endif // HAVE_HALIDE
402 return Ptr<BackendNode>();
405 virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
406 const std::vector<MatShape> &outputs) const
408 (void)outputs; // suppress unused variable warning
409 CV_Assert(inputs.size());
411 long flops = inputs.size() * total(inputs[0]);
416 bool setActivation(const Ptr<ActivationLayer>& layer)
419 return !activ.empty();
422 Ptr<ActivationLayer> activ;
425 Ptr<EltwiseLayer> EltwiseLayer::create(const LayerParams& params)
427 return Ptr<EltwiseLayer>(new EltwiseLayerImpl(params));