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 "../op_cuda.hpp"
45 #include "../op_inf_engine.hpp"
46 #include "../ie_ngraph.hpp"
48 #include "layers_common.hpp"
49 #include <opencv2/dnn/shape_utils.hpp>
51 #include <opencv2/core/utils/logger.hpp>
54 #include "opencl_kernels_dnn.hpp"
58 #include "../cuda4dnn/primitives/slice.hpp"
59 using namespace cv::dnn::cuda4dnn;
67 class SliceLayerImpl : public SliceLayer
70 SliceLayerImpl(const LayerParams& params)
72 setParamsFrom(params);
73 axis = params.get<int>("axis", 1);
74 num_split = params.get<int>("num_split", 0);
75 hasDynamicShapes = params.get<bool>("has_dynamic_shapes", false);
76 shapesInitialized = !hasDynamicShapes;
77 if (params.has("slice_point"))
79 CV_Assert(!params.has("begin") && !params.has("size") && !params.has("end"));
80 const DictValue &indicesValue = params.get("slice_point");
81 sliceRanges.resize(indicesValue.size() + 1,
82 std::vector<Range>(axis + 1, Range::all()));
84 for (int i = 0; i < indicesValue.size(); ++i)
86 sliceRanges[i][axis].start = prevSlice;
87 sliceRanges[i][axis].end = indicesValue.get<int>(i);
88 prevSlice = sliceRanges[i][axis].end;
90 sliceRanges.back()[axis].start = prevSlice;
92 else if (params.has("begin"))
94 CV_Assert(params.has("size") ^ params.has("end"));
95 const DictValue &begins = params.get("begin");
96 const DictValue &sizesOrEnds = params.has("size") ? params.get("size") : params.get("end");
97 CV_Assert(begins.size() == sizesOrEnds.size());
99 sliceRanges.resize(1);
100 sliceRanges[0].resize(begins.size(), Range::all());
101 for (int i = 0; i < begins.size(); ++i)
103 int start = begins.get<int>(i);
104 int sizeOrEnd = sizesOrEnds.get<int>(i); // It may be negative to reverse indexation.
105 CV_Assert(start >= 0);
107 sliceRanges[0][i].start = start;
108 if (params.has("size"))
110 int size = sizeOrEnd;
111 CV_Assert(size == -1 || size > 0); // -1 value means range [start, axis_size).
112 sliceRanges[0][i].end = size > 0 ? (start + size) : -1; // We'll finalize a negative value later.
117 CV_Assert(end < 0 || end > start); // End index is excluded.
118 sliceRanges[0][i].end = end; // We'll finalize a negative value later.
124 virtual bool supportBackend(int backendId) CV_OVERRIDE
126 #ifdef HAVE_DNN_IE_NN_BUILDER_2019
127 if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
128 return INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2019R1) &&
129 sliceRanges.size() == 1 && sliceRanges[0].size() == 4;
131 #ifdef HAVE_DNN_NGRAPH
132 if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
133 return sliceRanges.size() == 1;
135 return backendId == DNN_BACKEND_OPENCV ||
136 backendId == DNN_BACKEND_CUDA;
139 bool getMemoryShapes(const std::vector<MatShape> &inputs,
140 const int requiredOutputs,
141 std::vector<MatShape> &outputs,
142 std::vector<MatShape> &internals) const CV_OVERRIDE
144 CV_Assert(inputs.size() == 1);
145 MatShape inpShape = inputs[0];
147 if (!sliceRanges.empty())
149 outputs.resize(sliceRanges.size(), inpShape);
150 for (int i = 0; i < outputs.size(); ++i)
152 CV_Assert(sliceRanges[i].size() <= inpShape.size());
153 for (int j = 0; j < sliceRanges[i].size(); ++j)
155 if (shapesInitialized || inpShape[j] > 0)
156 outputs[i][j] = clamp(sliceRanges[i][j], inpShape[j]).size();
160 else // Divide input blob on equal parts by axis.
162 CV_Assert(0 <= axis && axis < inpShape.size());
163 int splits = num_split ? num_split : requiredOutputs;
164 CV_Assert(splits > 0 && inpShape[axis] % splits == 0);
165 inpShape[axis] /= splits;
166 outputs.resize(splits, inpShape);
171 bool updateMemoryShapes(const std::vector<MatShape> &inputs) CV_OVERRIDE
173 shapesInitialized = true;
177 void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
180 ocl_exec_cache.clear();
183 std::vector<Mat> inputs, outputs;
184 inputs_arr.getMatVector(inputs);
185 outputs_arr.getMatVector(outputs);
187 CV_Assert(inputs.size() == 1);
188 const MatSize& inpShape = inputs[0].size;
190 finalSliceRanges = sliceRanges;
191 if (sliceRanges.empty())
193 // Divide input blob on equal parts by axis.
194 int outAxisSize = inpShape[axis] / outputs.size();
195 finalSliceRanges.resize(outputs.size(),
196 std::vector<Range>(axis + 1, Range::all()));
198 for (int i = 0; i < outputs.size(); ++i)
200 finalSliceRanges[i][axis].start = prevSlice;
201 finalSliceRanges[i][axis].end = finalSliceRanges[i][axis].start + outAxisSize;
202 prevSlice = finalSliceRanges[i][axis].end;
206 CV_Assert(outputs.size() == sliceRanges.size());
208 for (int i = 0; i < outputs.size(); ++i)
210 CV_Assert(finalSliceRanges[i].size() <= inpShape.dims());
211 // Fill the rest of ranges.
212 for (int j = finalSliceRanges[i].size(); j < inpShape.dims(); ++j)
214 finalSliceRanges[i].push_back(Range::all());
217 for (int j = 0; j < finalSliceRanges[i].size(); ++j)
219 finalSliceRanges[i][j] = clamp(finalSliceRanges[i][j], inpShape[j]);
224 std::cout << "DEBUG: DNN/Slice: " << outputs.size() << " inpShape=" << inpShape << std::endl;
225 for (int i = 0; i < outputs.size(); ++i)
227 for (int j = 0; j < finalSliceRanges[i].size(); ++j)
229 std::cout << finalSliceRanges[i][j];
231 std::cout << std::endl;
237 struct OpenCLExecInfo
239 std::string kernel_name;
240 std::string build_opts;
241 size_t local_size[2];
242 size_t global_size[2];
246 local_size[0] = local_size[1] = 0;
247 global_size[0] = global_size[1] = 0;
250 std::vector<OpenCLExecInfo> ocl_exec_cache;
252 void ocl_prepare(const std::vector<UMat>& inputs, const std::vector<UMat>& outputs)
256 CV_Assert(outputs.size() == finalSliceRanges.size());
257 ocl_exec_cache.resize(outputs.size());
259 const UMat& input = inputs[0];
260 const int dims = input.dims;
264 const int elemSize = (int)input.elemSize();
265 String opts0 = cv::format(
266 "-DDIMS=%d -DELEMSIZE=%d",
269 for (int d = 0; d < dims; d++)
271 opts0 += cv::format(" -DSRC_STEP_%d=%d", d, (int)input.step[dims - 1 - d]);
273 for (size_t i = 0; i < outputs.size(); i++)
275 OpenCLExecInfo& ocl = ocl_exec_cache[i];
277 const UMat& output = outputs[i];
278 const std::vector<Range>& range = finalSliceRanges[i];
282 CV_CheckEQ(output.dims, dims, "");
283 for (int d = 0; d < dims; d++)
285 opts += cv::format(" -DDST_STEP_%d=%d -DDST_SZ_%d=%d -DSRC_START_%d=%d",
286 d, (int)output.step[dims - 1 - d],
287 d, (int)output.size[dims - 1 - d],
288 d, (int)range[dims - 1 - d].start
290 CV_CheckEQ(range[d].size(), (int)output.size[d], "");
293 const size_t param_LIMIT_BLOCK_SIZE_PER_WG = WSZ * 64;
296 size_t block_size = elemSize;
297 for (int i = dims - 1; i >= 0; --i)
299 if (input.step[i] != output.step[i])
301 block_size *= output.size[i];
303 if (block_size >= param_LIMIT_BLOCK_SIZE_PER_WG)
307 const size_t total = output.total() * elemSize;
308 size_t num_blocks = total / block_size;
310 if ((num_blocks <= 8 && block_size >= WSZ * 4) || (block_size >= param_LIMIT_BLOCK_SIZE_PER_WG))
313 opts += cv::format(" -DUSE_COPY_1D=1");
315 opts += cv::format(" -DBLOCK_DIMS=%d", block_dims);
316 opts += cv::format(" -DBLOCK_DIMS_CONTIGUOUS=%d", block_dims);
317 opts += cv::format(" -DBLOCK_SIZE=%d", (int)block_size);
319 opts += cv::format(" -DBLOCK_COLS=%d", (int)block_size);
324 int block_cols = block_size;
325 int block_dims_contiguous = block_dims;
326 size_t input_base_step = input.step[dims - 1 - block_dims_contiguous];
327 size_t output_base_step = output.step[dims - 1 - block_dims_contiguous];
329 size_t block_rows = 1;
330 for (int i = dims - 1 - block_dims_contiguous; i >= 0; --i)
332 if (input.step[i] * output_base_step != output.step[i] * input_base_step)
334 block_rows *= output.size[i];
338 block_size *= block_rows;
340 num_blocks = total / block_size;
344 opts += cv::format(" -DBLOCK_DIMS=%d", block_dims);
345 opts += cv::format(" -DBLOCK_DIMS_CONTIGUOUS=%d", block_dims_contiguous);
346 opts += cv::format(" -DBLOCK_SIZE=%d", (int)block_size);
348 opts += cv::format(" -DBLOCK_COLS=%d", (int)block_cols);
350 opts += cv::format(" -DBLOCK_ROWS=%d", (int)block_rows);
351 opts += cv::format(" -DBLOCK_SRC_STRIDE=%d", (int)input_base_step);
356 opts += cv::format(" -DUSE_COPY_1D=1");
358 opts += cv::format(" -DBLOCK_DIMS=%d", block_dims_contiguous);
359 opts += cv::format(" -DBLOCK_DIMS_CONTIGUOUS=%d", block_dims_contiguous);
360 opts += cv::format(" -DBLOCK_SIZE=%d", (int)block_size);
362 opts += cv::format(" -DBLOCK_COLS=%d", (int)block_size);
366 const size_t MIN_WORK_ITEMS = 16;
367 if (block_size <= 4 * MIN_WORK_ITEMS)
369 else if (block_size <= 8 * MIN_WORK_ITEMS)
371 else if (block_size <= 16 * MIN_WORK_ITEMS)
373 else if (block_size <= 32 * MIN_WORK_ITEMS)
375 else if (block_size <= 64 * MIN_WORK_ITEMS)
378 opts += cv::format(" -DWSZ=%d", (int)WSZ);
380 std::ostringstream kernel_suffix;
381 kernel_suffix << dims << 'x' << elemSize << "_bsz" << block_size;
382 kernel_suffix << "__src_";
383 for (int d = 0; d < dims; d++)
385 kernel_suffix << input.size[dims - 1 - d] << '_';
387 kernel_suffix << '_';
388 /*for (int d = 0; d < dims; d++)
390 kernel_suffix << input.step[dims - 1 - d] << '_';
392 kernel_suffix << '_';*/
394 kernel_suffix << "dst_";
395 for (int d = 0; d < dims; d++)
397 kernel_suffix << output.size[dims - 1 - d] << '_';
399 /*kernel_suffix << '_';
400 for (int d = 0; d < dims; d++)
402 kernel_suffix << output.step[dims - 1 - d] << '_';
404 kernel_suffix << "_slice_";
405 for (int d = 0; d < dims; d++)
407 kernel_suffix << range[dims - 1 - d].start << '_';
409 for (int d = 0; d < dims; d++)
411 kernel_suffix << '_' << range[dims - 1 - d].end;
414 std::string kernel_suffix_str = kernel_suffix.str();
415 opts += cv::format(" -DSLICE_KERNEL_SUFFIX=%s", kernel_suffix_str.c_str());
417 ocl.kernel_name = cv::format("slice_%s", kernel_suffix_str.c_str());
418 ocl.build_opts = opts;
419 ocl.local_size[0] = WSZ;
420 ocl.local_size[1] = 1;
421 ocl.global_size[0] = WSZ;
422 ocl.global_size[1] = num_blocks;
423 } // for outputs.size()
426 bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
430 std::vector<UMat> inputs;
431 std::vector<UMat> outputs;
433 inputs_.getUMatVector(inputs);
434 outputs_.getUMatVector(outputs);
436 CV_Assert(outputs.size() == finalSliceRanges.size());
438 const UMat& input = inputs[0];
439 const int dims = input.dims;
442 CV_LOG_INFO(NULL, "DNN/OpenCL/Slice: implementation doesn't support dims=" << dims << ". Fallback to CPU");
446 if (ocl_exec_cache.empty())
448 ocl_prepare(inputs, outputs);
450 CV_CheckEQ(ocl_exec_cache.size(), outputs.size(), "");
452 for (size_t i = 0; i < outputs.size(); i++)
454 const OpenCLExecInfo& ocl = ocl_exec_cache[i];
456 UMat& output = outputs[i];
458 ocl::Kernel kernel(ocl.kernel_name.c_str(), ocl::dnn::slice_oclsrc, ocl.build_opts);
461 bool ret = kernel.args(
462 ocl::KernelArg::PtrReadOnly(input),
463 ocl::KernelArg::PtrWriteOnly(output)
465 .run(2, (size_t*)ocl.global_size, (size_t*)ocl.local_size, false);
468 } // for outputs.size()
474 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
477 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
479 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
480 forward_ocl(inputs_arr, outputs_arr, internals_arr))
482 std::vector<Mat> inputs, outputs;
483 inputs_arr.getMatVector(inputs);
484 outputs_arr.getMatVector(outputs);
486 const Mat& inpMat = inputs[0];
487 CV_Assert(outputs.size() == finalSliceRanges.size());
488 for (size_t i = 0; i < outputs.size(); i++)
490 inpMat(finalSliceRanges[i]).copyTo(outputs[i]);
495 #ifdef HAVE_DNN_IE_NN_BUILDER_2019
496 #if INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2019R1)
497 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >& inputs) CV_OVERRIDE
499 CV_Assert_N(finalSliceRanges.size() == 1, inputs.size() <= 2);
501 std::vector<size_t> axes, offsets, dims;
503 int numDims = finalSliceRanges[0].size();
504 if (preferableTarget == DNN_TARGET_MYRIAD || preferableTarget == DNN_TARGET_HDDL)
516 for (int i = from; i != to; i += step)
519 offsets.push_back(finalSliceRanges[0][i].start);
520 dims.push_back(finalSliceRanges[0][i].size());
523 InferenceEngine::Builder::Layer ieLayer(name);
524 ieLayer.setName(name);
525 ieLayer.setType("Crop");
526 ieLayer.getParameters()["axis"] = axes;
527 ieLayer.getParameters()["dim"] = dims;
528 ieLayer.getParameters()["offset"] = offsets;
529 ieLayer.setInputPorts(std::vector<InferenceEngine::Port>(2));
530 ieLayer.setOutputPorts(std::vector<InferenceEngine::Port>(1));
532 if (inputs.size() != 2)
534 std::vector<size_t> outShape(numDims);
535 for (int i = 0; i < numDims; ++i)
536 outShape[i] = finalSliceRanges[0][i].size();
538 ieLayer.getInputPorts()[1].setParameter("type", "weights");
540 auto shapeSource = InferenceEngine::make_shared_blob<float>({
541 InferenceEngine::Precision::FP32, outShape,
542 InferenceEngine::Layout::ANY
544 shapeSource->allocate();
545 addConstantData("weights", shapeSource, ieLayer);
547 return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
553 #ifdef HAVE_DNN_NGRAPH
554 virtual Ptr<BackendNode> initNgraph(const std::vector<Ptr<BackendWrapper> >& inputs,
555 const std::vector<Ptr<BackendNode> >& nodes) CV_OVERRIDE
557 CV_Assert_N(nodes.size() <= 2);
558 auto& ieInpNode = nodes[0].dynamicCast<InfEngineNgraphNode>()->node;
559 CV_Assert(finalSliceRanges[0].size() == ieInpNode->get_shape().size());
561 std::vector<int64_t> offsets, dims;
562 for (int i = 0; i < finalSliceRanges[0].size(); ++i)
564 offsets.push_back(finalSliceRanges[0][i].start);
565 dims.push_back(finalSliceRanges[0][i].end);
568 auto lower_bounds = std::make_shared<ngraph::op::Constant>(ngraph::element::i64,
569 ngraph::Shape{offsets.size()}, offsets.data());
570 auto upper_bounds = std::make_shared<ngraph::op::Constant>(ngraph::element::i64,
571 ngraph::Shape{dims.size()}, dims.data());
572 auto strides = std::make_shared<ngraph::op::Constant>(ngraph::element::i64,
573 ngraph::Shape{dims.size()}, std::vector<int64_t>((int64_t)dims.size(), 1));
575 auto slice = std::make_shared<ngraph::op::v1::StridedSlice>(ieInpNode,
576 lower_bounds, upper_bounds, strides, std::vector<int64_t>{}, std::vector<int64_t>{});
578 return Ptr<BackendNode>(new InfEngineNgraphNode(slice));
580 #endif // HAVE_DNN_NGRAPH
584 Ptr<BackendNode> initCUDA(
586 const std::vector<Ptr<BackendWrapper>>& inputs,
587 const std::vector<Ptr<BackendWrapper>>& outputs
590 auto context = reinterpret_cast<csl::CSLContext*>(context_);
592 std::vector<std::vector<std::size_t>> offsets;
593 for (const auto& ranges : finalSliceRanges)
595 std::vector<std::size_t> offsets_i;
596 for (const auto& range : ranges)
597 offsets_i.push_back(range.start);
598 offsets.push_back(std::move(offsets_i));
601 return make_cuda_node<cuda4dnn::SliceOp>(preferableTarget, std::move(context->stream), std::move(offsets));
607 // The actual non-negative values determined from @p sliceRanges depends on input size.
608 std::vector<std::vector<Range> > finalSliceRanges;
609 bool hasDynamicShapes;
610 bool shapesInitialized;
613 class CropLayerImpl CV_FINAL : public SliceLayerImpl
616 CropLayerImpl(const LayerParams& params) : SliceLayerImpl(LayerParams())
618 setParamsFrom(params);
619 axis = params.get<int>("axis", 2);
620 const DictValue *paramOffset = params.ptr("offset");
624 for (int i = 0; i < paramOffset->size(); i++)
625 offset.push_back(paramOffset->get<int>(i));
629 bool getMemoryShapes(const std::vector<MatShape> &inputs,
630 const int requiredOutputs,
631 std::vector<MatShape> &outputs,
632 std::vector<MatShape> &internals) const CV_OVERRIDE
634 CV_Assert(inputs.size() == 2);
636 MatShape dstShape = inputs[0];
637 int start = clamp(axis, dstShape);
638 for (int i = start; i < dstShape.size(); i++)
640 dstShape[i] = inputs[1][i];
642 outputs.resize(1, dstShape);
646 void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays) CV_OVERRIDE
648 std::vector<Mat> inputs;
649 inputs_arr.getMatVector(inputs);
650 CV_Assert(2 == inputs.size());
652 const Mat &inpBlob = inputs[0];
653 const Mat &inpSzBlob = inputs[1];
655 int dims = inpBlob.dims;
656 int start_axis = clamp(axis, dims);
658 std::vector<int> offset_final(dims, 0);
659 if (offset.size() == 1)
661 for (int i = start_axis; i < dims; i++)
662 offset_final[i] = offset[0];
664 else if (offset.size() > 1)
666 if ((int)offset.size() != dims - start_axis)
667 CV_Error(Error::StsBadArg, "number of offset values specified must be "
668 "equal to the number of dimensions following axis.");
670 for (int i = start_axis; i < dims; i++)
671 offset_final[i] = offset[i - start_axis];
674 finalSliceRanges.resize(1);
675 finalSliceRanges[0].resize(dims);
676 for (int i = 0; i < start_axis; i++)
678 finalSliceRanges[0][i] = Range(0, inpBlob.size[i]);
680 for (int i = start_axis; i < dims; i++)
682 if (offset_final[i] < 0 || offset_final[i] + inpSzBlob.size[i] > inpBlob.size[i])
683 CV_Error(Error::StsBadArg, "invalid crop parameters or blob sizes");
685 finalSliceRanges[0][i] = Range(offset_final[i], offset_final[i] + inpSzBlob.size[i]);
690 std::vector<int> offset;
693 Ptr<SliceLayer> SliceLayer::create(const LayerParams& params)
695 return Ptr<SliceLayer>(new SliceLayerImpl(params));
698 Ptr<Layer> CropLayer::create(const LayerParams& params)
700 return Ptr<Layer>(new CropLayerImpl(params));