COMPMID-1844: Implement CLCrop

Change-Id: I8822c37adc45960705dc3f32a53214795ba3cf39
Signed-off-by: George Wort <george.wort@arm.com>
Reviewed-on: https://review.mlplatform.org/c/789
Reviewed-by: Manuel Bottini <manuel.bottini@arm.com>
Tested-by: Arm Jenkins <bsgcomp@arm.com>
Reviewed-by: Pablo Marquez <pablo.tello@arm.com>
diff --git a/src/core/CL/kernels/CLCopyKernel.cpp b/src/core/CL/kernels/CLCopyKernel.cpp
index e14e5da..30a0b8f 100644
--- a/src/core/CL/kernels/CLCopyKernel.cpp
+++ b/src/core/CL/kernels/CLCopyKernel.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018 ARM Limited.
+ * Copyright (c) 2018-2019 ARM Limited.
  *
  * SPDX-License-Identifier: MIT
  *
@@ -37,38 +37,58 @@
 {
 namespace
 {
-Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, const PaddingList &padding = PaddingList())
+Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, const PaddingList &padding = PaddingList(), Window *output_window = nullptr)
 {
     ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, output);
+    ARM_COMPUTE_ERROR_ON(!padding.empty() && output_window != nullptr);
     ARM_COMPUTE_RETURN_ERROR_ON(padding.size() > 4);
 
     // Validate output if initialized
     if(output->total_size() != 0)
     {
-        ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(misc::shape_calculator::compute_padded_shape(input->tensor_shape(), padding), output->tensor_shape());
+        if(output_window == nullptr)
+        {
+            ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(misc::shape_calculator::compute_padded_shape(input->tensor_shape(), padding), output->tensor_shape());
+        }
+        else
+        {
+            ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
+            ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input, output);
+            ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(input, output);
+            ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(input->tensor_shape(), output_window->shape());
+        }
         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
     }
 
     return Status{};
 }
 
-std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output)
+std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, Window *output_window)
 {
     // Output auto inizialitation if not yet initialized
     auto_init_if_empty(*output, *input);
 
     // Configure window
-    const unsigned int num_elems_processed_per_iteration = 16 / input->element_size();
+    const unsigned int vec_size_x = 16 / input->element_size();
 
-    Window win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration));
+    if(output_window == nullptr)
+    {
+        // Create and update the window (if needed)
+        Window win = calculate_max_window(*input, Steps(vec_size_x));
 
-    AccessWindowHorizontal input_access(input, 0, num_elems_processed_per_iteration);
-    AccessWindowHorizontal output_access(output, 0, num_elems_processed_per_iteration);
+        AccessWindowHorizontal input_access(input, 0, vec_size_x);
+        AccessWindowHorizontal output_access(output, 0, vec_size_x);
 
-    bool window_changed = update_window_and_padding(win, input_access, output_access);
+        bool window_changed = update_window_and_padding(win, input_access, output_access);
 
-    Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
-    return std::make_pair(err, win);
+        Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
+        return std::make_pair(err, win);
+    }
+    else
+    {
+        Window win = calculate_max_window(*input);
+        return std::make_pair(Status{}, win);
+    }
 }
 
 std::pair<Status, Window> validate_and_configure_window_with_padding(ITensorInfo *input, ITensorInfo *output, const PaddingList &padding)
@@ -131,14 +151,14 @@
 } // namespace
 
 CLCopyKernel::CLCopyKernel()
-    : _input(nullptr), _output(nullptr)
+    : _input(nullptr), _output(nullptr), _output_window(), _has_output_window(false)
 {
 }
 
-void CLCopyKernel::configure(const ICLTensor *input, ICLTensor *output, const PaddingList &padding)
+void CLCopyKernel::configure(const ICLTensor *input, ICLTensor *output, const PaddingList &padding, Window *output_window)
 {
     ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
-    ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), padding));
+    ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), padding, output_window));
 
     _input  = input;
     _output = output;
@@ -147,21 +167,44 @@
     CLBuildOptions build_opts;
     build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
 
-    const unsigned int num_elems_processed_per_iteration = 16 / input->info()->element_size();
-    build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration));
-
     std::pair<Status, Window> win_config;
 
+    const unsigned int vec_size_x = 16 / input->info()->element_size();
+
     if(padding.empty())
     {
+        // Configure window
+        win_config = validate_and_configure_window(input->info(), output->info(), output_window);
+
+        if(output_window != nullptr)
+        {
+            _has_output_window        = true;
+            _output_window            = Window(*output_window);
+            const int  width_x        = output_window->num_iterations(0);
+            const bool multi_access_x = width_x >= static_cast<int32_t>(vec_size_x);
+            const bool remainder_x    = width_x % vec_size_x > 0;
+
+            if(multi_access_x)
+            {
+                _output_window.set(Window::DimX, Window::Dimension(output_window->x().start(), ceil_to_multiple(output_window->x().end(), vec_size_x), vec_size_x));
+                win_config.second.set(Window::DimX, Window::Dimension(win_config.second.x().start(), ceil_to_multiple(win_config.second.x().end(), vec_size_x), vec_size_x));
+            }
+
+            build_opts.add_option_if(multi_access_x, "-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
+            build_opts.add_option_if(multi_access_x && remainder_x, "-DLAST_ACCESSED_X=" + support::cpp11::to_string(std::max<int>(width_x - vec_size_x, 0)));
+        }
+        else
+        {
+            build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
+        }
+
         // Build kernel
         _kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel("copy_tensor", build_opts.options()));
-
-        // Configure window
-        win_config = validate_and_configure_window(input->info(), output->info());
     }
     else
     {
+        build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
+
         // Add compile time options
         add_padding_as_build_options(padding, build_opts);
 
@@ -185,13 +228,13 @@
     ICLKernel::configure_internal(win_config.second);
 }
 
-Status CLCopyKernel::validate(const arm_compute::ITensorInfo *input, const arm_compute::ITensorInfo *output, const PaddingList &padding)
+Status CLCopyKernel::validate(const arm_compute::ITensorInfo *input, const arm_compute::ITensorInfo *output, const PaddingList &padding, Window *output_window)
 {
-    ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, padding));
+    ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, padding, output_window));
 
     if(padding.empty())
     {
-        ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get()).first);
+        ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), output_window).first);
     }
     else
     {
@@ -206,16 +249,33 @@
     ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
     ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
 
-    Window collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ);
-    Window slice     = collapsed.first_slice_window_3D();
+    Window slice;
 
-    do
+    if(_has_output_window)
     {
-        unsigned int idx = 0;
-        add_3D_tensor_argument(idx, _input, slice);
-        add_3D_tensor_argument(idx, _output, slice);
-        enqueue(queue, *this, slice);
+        slice            = window.first_slice_window_3D();
+        Window out_slice = _output_window.first_slice_window_3D();
+        do
+        {
+            unsigned int idx = 0;
+            add_3D_tensor_argument(idx, _input, slice);
+            add_3D_tensor_argument(idx, _output, out_slice);
+            enqueue(queue, *this, slice);
+        }
+        while(window.slide_window_slice_3D(slice) && _output_window.slide_window_slice_3D(out_slice));
     }
-    while(collapsed.slide_window_slice_3D(slice));
+    else
+    {
+        Window collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ);
+        slice            = collapsed.first_slice_window_3D();
+        do
+        {
+            unsigned int idx = 0;
+            add_3D_tensor_argument(idx, _input, slice);
+            add_3D_tensor_argument(idx, _output, slice);
+            enqueue(queue, *this, slice);
+        }
+        while(collapsed.slide_window_slice_3D(slice));
+    }
 }
 } // namespace arm_compute
diff --git a/src/core/CL/kernels/CLCropKernel.cpp b/src/core/CL/kernels/CLCropKernel.cpp
new file mode 100644
index 0000000..f8a2456
--- /dev/null
+++ b/src/core/CL/kernels/CLCropKernel.cpp
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2019 ARM Limited.
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#include "arm_compute/core/CL/kernels/CLCropKernel.h"
+
+#include "arm_compute/core/CL/CLHelpers.h"
+#include "arm_compute/core/CL/CLKernelLibrary.h"
+#include "arm_compute/core/CL/ICLTensor.h"
+#include "arm_compute/core/CPP/Validate.h"
+#include "arm_compute/core/IAccessWindow.h"
+#include "arm_compute/core/TensorInfo.h"
+#include "arm_compute/core/Window.h"
+
+#include "arm_compute/core/Helpers.h"
+#include "arm_compute/core/Types.h"
+#include "arm_compute/core/utils/helpers/bit_ops.h"
+#include "arm_compute/core/utils/helpers/tensor_transform.h"
+#include "arm_compute/core/utils/misc/ShapeCalculator.h"
+
+#include <map>
+
+namespace arm_compute
+{
+CLCropKernel::CLCropKernel()
+    : _input(nullptr), _output(nullptr), _start(), _batch_index(0), _extrapolation_value(0)
+{
+}
+
+void CLCropKernel::configure(const ICLTensor *input, ICLTensor *output, Coordinates2D start, Coordinates2D end, uint32_t batch_index, float extrapolation_value, Window *output_window)
+{
+    ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);
+    ARM_COMPUTE_ERROR_THROW_ON(validate(input->info(), output->info(), start, end, batch_index, extrapolation_value, output_window));
+
+    _input               = input;
+    _output              = output;
+    _start               = start;
+    _batch_index         = batch_index;
+    _extrapolation_value = extrapolation_value;
+
+    const int vec_size_x = 4;
+    // Create and update the window (if needed)
+    Window win = calculate_max_window(*output->info());
+
+    if(output_window != nullptr)
+    {
+        ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(win, *output_window);
+        win = *output_window;
+    }
+
+    const int  output_width_x = win.num_iterations(0);
+    const bool multi_access_x = output_width_x >= vec_size_x;
+    const bool remainder_x    = output_width_x % vec_size_x > 0;
+
+    if(multi_access_x)
+    {
+        win.set(Window::DimX,
+                Window::Dimension(win.x().start(), ceil_to_multiple(win.x().end(), vec_size_x), vec_size_x));
+    }
+    ICLKernel::configure_internal(win);
+
+    // Create kernel
+    CLBuildOptions build_opts;
+    build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
+    build_opts.add_option_if(multi_access_x, "-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
+    build_opts.add_option_if(multi_access_x && remainder_x, "-DLAST_ACCESSED_X=" + support::cpp11::to_string(std::max<int>(output_width_x - vec_size_x, 0)));
+    build_opts.add_option_if(start.x > end.x, "-DWIDTH_FLIPPED=");
+    build_opts.add_option_if(start.y > end.y, "-DHEIGHT_FLIPPED=");
+    _kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel("crop_tensor", build_opts.options()));
+}
+
+Status CLCropKernel::validate(const ITensorInfo *input, const ITensorInfo *output, Coordinates2D start, Coordinates2D end, uint32_t batch_index, float extrapolation_value, Window *output_window)
+{
+    ARM_COMPUTE_UNUSED(extrapolation_value, output_window);
+    ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(input);
+    ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::U16, DataType::S16, DataType::F16, DataType::U32, DataType::S32, DataType::F32);
+    ARM_COMPUTE_RETURN_ERROR_ON_DATA_LAYOUT_NOT_IN(input, DataLayout::NHWC);
+    ARM_COMPUTE_RETURN_ERROR_ON(input->tensor_shape().num_dimensions() > 4);
+    ARM_COMPUTE_RETURN_ERROR_ON(start.x < 0 || start.y < 0 || end.x < 0 || end.y < 0);
+    ARM_COMPUTE_RETURN_ERROR_ON(start.x >= static_cast<int32_t>(input->dimension(1)) || start.y >= static_cast<int32_t>(input->dimension(2))
+                                || end.x >= static_cast<int32_t>(input->dimension(1)) || end.y >= static_cast<int32_t>(input->dimension(2)));
+    ARM_COMPUTE_RETURN_ERROR_ON(batch_index >= input->dimension(3));
+    if(output_window != nullptr)
+    {
+        ARM_COMPUTE_RETURN_ERROR_ON(output_window->x().step() != 1);
+    }
+    if(output->total_size() > 0)
+    {
+        ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(output, DataType::F32);
+        ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input, output);
+        ARM_COMPUTE_RETURN_ERROR_ON(output->num_dimensions() > 3);
+    }
+    return Status{};
+}
+
+void CLCropKernel::run(const Window &window, cl::CommandQueue &queue)
+{
+    ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
+    ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
+
+    Window in_slice = Window();
+    in_slice.use_tensor_dimensions(_input->info()->tensor_shape());
+    in_slice.set(Window::DimX, Window::Dimension(in_slice.x().start(), ceil_to_multiple(in_slice.x().end(), window.x().step()), window.x().step()));
+    in_slice.set(3, Window::Dimension(_batch_index, _batch_index + 1, 1));
+
+    unsigned int idx = 0;
+    add_3D_tensor_argument(idx, _input, in_slice);
+    add_3D_tensor_argument(idx, _output, window);
+    add_argument(idx, _start.x);
+    add_argument(idx, _start.y);
+    enqueue(queue, *this, window);
+}
+} // namespace arm_compute
diff --git a/src/core/CL/kernels/CLMemsetKernel.cpp b/src/core/CL/kernels/CLMemsetKernel.cpp
index ab53897..80caf94 100644
--- a/src/core/CL/kernels/CLMemsetKernel.cpp
+++ b/src/core/CL/kernels/CLMemsetKernel.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018 ARM Limited.
+ * Copyright (c) 2018-2019 ARM Limited.
  *
  * SPDX-License-Identifier: MIT
  *
@@ -35,27 +35,38 @@
 namespace arm_compute
 {
 CLMemsetKernel::CLMemsetKernel()
-    : ICLKernel(), _tensor(nullptr)
+    : ICLKernel(), _tensor(nullptr), _full_window()
 {
 }
 
 void CLMemsetKernel::configure(ICLTensor        *tensor,
-                               const PixelValue &constant_value)
+                               const PixelValue &constant_value,
+                               Window           *window)
 {
     ARM_COMPUTE_ERROR_ON_NULLPTR(tensor);
+    ARM_COMPUTE_ERROR_THROW_ON(validate(tensor->info(), constant_value, window));
+
     _tensor = tensor;
 
-    const DataType data_type      = tensor->info()->data_type();
-    const int      vec_size_x     = 16 / tensor->info()->element_size();
-    const int      output_width_x = tensor->info()->tensor_shape().x();
-    const bool     multi_access_x = (output_width_x / vec_size_x > 0);
+    const DataType data_type  = tensor->info()->data_type();
+    const int      vec_size_x = 16 / tensor->info()->element_size();
 
     // Create and update the window (if needed)
-    Window win = calculate_max_window(*tensor->info());
+    _full_window = calculate_max_window(*tensor->info());
+    Window win   = _full_window;
+    if(window != nullptr)
+    {
+        ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(win, *window);
+        win = *window;
+    }
+
+    const int  output_width_x = win.num_iterations(0);
+    const bool multi_access_x = output_width_x >= vec_size_x;
+    const bool remainder_x    = output_width_x % vec_size_x > 0;
+
     if(multi_access_x)
     {
-        win.set(Window::DimX,
-                Window::Dimension(win.x().start(), ceil_to_multiple(win.x().end(), vec_size_x), vec_size_x));
+        win.set(Window::DimX, Window::Dimension(win.x().start(), ceil_to_multiple(win.x().end(), vec_size_x), vec_size_x));
     }
     ICLKernel::configure_internal(win);
 
@@ -64,14 +75,18 @@
     build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type));
     build_opts.add_option("-DCONSTANT_VALUE=" + string_from_pixel_value(constant_value, data_type));
     build_opts.add_option_if(multi_access_x, "-DVEC_SIZE=" + support::cpp11::to_string(vec_size_x));
-    build_opts.add_option_if(multi_access_x, "-DLAST_ACCESSED_X=" + support::cpp11::to_string(std::max<int>(output_width_x - vec_size_x, 0)));
+    build_opts.add_option_if(multi_access_x && remainder_x, "-DLAST_ACCESSED_X=" + support::cpp11::to_string(std::max<int>(output_width_x - vec_size_x, 0)));
     _kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel("memset", build_opts.options()));
 }
 
-Status CLMemsetKernel::validate(const ITensorInfo *tensor, const PixelValue &constant_value)
+Status CLMemsetKernel::validate(const ITensorInfo *tensor, const PixelValue &constant_value, Window *window)
 {
     ARM_COMPUTE_UNUSED(tensor);
     ARM_COMPUTE_UNUSED(constant_value);
+    if(window != nullptr)
+    {
+        ARM_COMPUTE_RETURN_ERROR_ON(window->x().step() != 1);
+    }
     return Status{};
 }
 
@@ -81,15 +96,15 @@
     ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
 
     // Collapse all the batches on the third
-    Window collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimY);
-    Window slice     = collapsed.first_slice_window_2D();
+    Window collapsed = window.collapse_if_possible(_full_window, Window::DimZ);
+    Window slice     = collapsed.first_slice_window_3D();
 
     do
     {
         unsigned int idx = 0;
-        add_2D_tensor_argument(idx, _tensor, slice);
+        add_3D_tensor_argument(idx, _tensor, slice);
         enqueue(queue, *this, slice);
     }
-    while(collapsed.slide_window_slice_2D(slice));
+    while(collapsed.slide_window_slice_3D(slice));
 }
 } // namespace arm_compute