Compute Library
 22.11
CpuGemmDirectConv2d.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2021-2022 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
25 
29 #include "src/common/utils/Log.h"
32 
33 #include "support/Cast.h"
34 
35 #include <set>
36 
37 namespace arm_compute
38 {
39 namespace cpu
40 {
41 using namespace arm_compute::experimental;
42 using namespace arm_compute::utils::cast;
43 
44 namespace
45 {
46 GEMMLowpOutputStageInfo calculate_output_stage_metadata(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *dst, const ActivationLayerInfo &act)
47 {
48  // Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
49  // Extract and negate input and weights offset
50  const QuantizationInfo iqinfo = src->quantization_info();
51  const QuantizationInfo wqinfo = weights->quantization_info();
52  const QuantizationInfo oqinfo = (dst->total_size() == 0) ? iqinfo : dst->quantization_info();
53  const UniformQuantizationInfo uoqinfo = oqinfo.uniform();
54  const DataType data_type = src->data_type();
55  // Merge activation with output stage
56  const std::set<ActivationLayerInfo::ActivationFunction> supported_acts = { ActivationLayerInfo::ActivationFunction::RELU,
59  };
60  PixelValue type_min{};
61  PixelValue type_max{};
62  std::tie(type_min, type_max) = get_min_max(data_type);
63  int32_t min_activation = type_min.get<int32_t>();
64  int32_t max_activation = type_max.get<int32_t>();
65  if(supported_acts.count(act.activation()) != 0)
66  {
67  std::tie(min_activation, max_activation) = get_quantized_activation_min_max(act, data_type, uoqinfo);
68  }
69  GEMMLowpOutputStageInfo os_info;
71  os_info.gemmlowp_offset = uoqinfo.offset;
72  os_info.gemmlowp_min_bound = min_activation;
73  os_info.gemmlowp_max_bound = max_activation;
74  os_info.is_quantized_per_channel = (weights->data_type() == DataType::QSYMM8_PER_CHANNEL);
75  quantization::calculate_quantized_multipliers(iqinfo, wqinfo, oqinfo, os_info);
76  return os_info;
77 }
78 cpu::AsmGemmInfo init_assembly_metadata(const Conv2dInfo &info, bool is_indirect)
79 {
80  cpu::AsmGemmInfo asm_info;
81  asm_info.method = is_indirect ? cpu::AsmConvMethod::Indirect : cpu::AsmConvMethod::Conv;
82  asm_info.ps_info = info.conv_info;
83  asm_info.activation_info = info.act_info;
84  asm_info.depth_output_gemm3d = true;
85  asm_info.reinterpret_input_as_3d = true;
86  asm_info.padding_top = info.conv_info.pad_top();
87  asm_info.padding_left = info.conv_info.pad_left();
88  asm_info.padding_value = 0.f;
89  asm_info.negated_offsets = false;
90  asm_info.fast_mode = info.enable_fast_math;
91  asm_info.fixed_format = info.weights_info.weight_format() != WeightFormat::UNSPECIFIED;
92  asm_info.weight_format = info.weights_info.weight_format();
93  return asm_info;
94 }
95 } // namespace
96 
98  : _gemm_asm_func(std::make_unique<CpuGemmAssemblyDispatch>()),
99  _activation_func(std::make_unique<CpuActivation>()),
100  _weights_permute_func(std::make_unique<CpuPermute>()),
101  _aux_mem(AuxTensorIdx::Count),
102  _perm_weights(),
103  _run_activation(false),
104  _is_prepared(false)
105 {
106 }
107 
109 
110 void CpuGemmDirectConv2d::configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const Conv2dInfo &info)
111 {
112  ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
114  weights,
115  biases != nullptr ? biases : nullptr,
116  dst,
117  info));
118  ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, info);
119 
120  _run_activation = info.act_info.enabled() && !_gemm_asm_func->is_activation_supported(info.act_info);
121  _is_prepared = false;
122 
123  _weights_permute_func->configure(weights, &_perm_weights, PermutationVector{ 3, 0, 1, 2 });
124 
125  // Configure assembly dispatch
126  cpu::AsmGemmInfo asm_info = init_assembly_metadata(info, false);
128  {
129  asm_info.output_stage = calculate_output_stage_metadata(src, weights, dst, info.act_info);
130  }
131  _gemm_asm_func->configure(src, &_perm_weights, biases, dst, asm_info);
132 
133  // Configure activation
134  if(_run_activation)
135  {
136  _activation_func->configure(dst, nullptr, info.act_info);
137  }
138 
139  // Add auxiliary memory requirements of the assembly dispatch
140  auto asm_mem_req = _gemm_asm_func->workspace();
141  _aux_mem[AsmGemmWorkspace] = asm_mem_req[AsmGemmWorkspace];
142  _aux_mem[Pretranspose] = asm_mem_req[Pretranspose];
143 
144  if(_aux_mem[Pretranspose].size > 0)
145  {
146  // Release permuted weights at the of prepare as they are further transposed by the assembly dispatch
147  _aux_mem[PermutedWeights] = MemoryInfo(offset_int_vec(PermutedWeights), MemoryLifetime::Prepare, weights->total_size());
148  }
149  else
150  {
151  // We must permute weights if they are WeightFormat::UNSPECIFIED
153  _aux_mem[PermutedWeights] = MemoryInfo(offset_int_vec(PermutedWeights), MemoryLifetime::Persistent, weights->total_size());
154  }
155 }
156 Status CpuGemmDirectConv2d::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const Conv2dInfo &info)
157 {
158  ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, weights, dst);
162  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.num_groups > 1, "Grouping (num_groups != 1) is not supported on Neon");
163  ARM_COMPUTE_RETURN_ERROR_ON_MSG(src->data_layout() != DataLayout::NHWC, "Data layout supported is NHWC");
164  const DataType data_type = src->data_type();
165  const TensorShape i_shape = src->tensor_shape();
166  const TensorShape w_shape = weights->tensor_shape();
167  ARM_COMPUTE_RETURN_ERROR_ON(w_shape[0] != i_shape[0]);
170  // Validate biases
171  if(biases != nullptr)
172  {
173  if(is_data_type_quantized_asymmetric(data_type))
174  {
176  }
177  else if(data_type == DataType::BFLOAT16)
178  {
180  }
181  else
182  {
184  }
185  ARM_COMPUTE_RETURN_ERROR_ON(biases->dimension(0) != weights->dimension(3));
187  }
188 
189  cpu::AsmGemmInfo asm_info = init_assembly_metadata(info, false);
190  ARM_COMPUTE_RETURN_ON_ERROR(cpu::CpuGemmAssemblyDispatch::validate(src, weights, biases, dst, asm_info));
191  return Status{};
192 }
194 {
195  prepare(tensors);
196 
197  _gemm_asm_func->run(tensors);
198  if(_run_activation)
199  {
200  ITensor *io = tensors.get_tensor(ACL_DST);
201  ITensorPack pack{ { ACL_SRC, io }, { ACL_DST, io } };
202  _activation_func->run(pack);
203  }
204 }
205 
207 {
208  if(!_is_prepared)
209  {
210  // If we are using fixed-format kernel the weights are already reshaped
211  if(_gemm_asm_func && _gemm_asm_func->isVarWeightsKernel())
212  {
213  _gemm_asm_func->prepare(tensors);
214  _is_prepared = true;
215  return;
216  }
217  const ITensor *weights = tensors.get_const_tensor(ACL_SRC_1);
218  ITensor *weights_aux = utils::cast::polymorphic_cast<ITensor *>(tensors.get_tensor(offset_int_vec(PermutedWeights)));
219  ARM_COMPUTE_ERROR_ON_NULLPTR(weights, weights_aux);
220 
221  CpuAuxTensorHandler permuted_weights(_perm_weights, *weights_aux);
222  ITensorPack permute_tensors{ { ACL_SRC, weights }, { ACL_DST, permuted_weights.get() } };
223  _weights_permute_func->run(permute_tensors);
224 
225  tensors.add_const_tensor(ACL_SRC_1, permuted_weights.get());
226  // Call prepare of assembly dispatch
227  _gemm_asm_func->prepare(tensors);
228 
229  _is_prepared = true;
230  }
231 }
232 
234 {
235  return _aux_mem;
236 }
237 } // namespace cpu
238 } // namespace arm_compute
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:1030
experimental::MemoryRequirements workspace() const override
Return the memory requirements required by the workspace.
virtual size_t num_dimensions() const =0
The number of dimensions of the tensor (rank)
Basic function to run kernels::CpuActivationKernel.
Definition: CpuActivation.h:34
Shape of a tensor.
Definition: TensorShape.h:39
Quantize using a fixed point multiplication.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:490
bool enabled() const
Check if initialised.
Definition: Types.h:1694
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
void add_const_tensor(int id, const ITensor *tensor)
Add const tensor to the pack.
Definition: ITensorPack.cpp:49
ActivationLayerInfo act_info
void configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const Conv2dInfo &info)
Set the input and output tensors.
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
virtual DataType data_type() const =0
Data type used for each element of the tensor.
1 channel, 1 F32 per channel
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
GEMMLowpOutputStageInfo output_stage
Status class.
Definition: Error.h:52
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Interface for CPU tensor.
Definition: ITensor.h:36
SimpleTensor< float > src
Definition: DFT.cpp:155
Copyright (c) 2017-2022 Arm Limited.
std::vector< MemoryInfo > MemoryRequirements
Definition: Types.h:134
1 channel, 1 F16 per channel
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:159
1 channel, 1 S32 per channel
16-bit brain floating-point number
const ITensor * get_const_tensor(int id) const
Get constant tensor of a given id.
Definition: ITensorPack.cpp:54
static Status validate(const ITensorInfo *a, const ITensorInfo *b, const ITensorInfo *c, const ITensorInfo *d, const AsmGemmInfo &info)
Indicates whether or not this function can be used to process the given parameters.
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
std::pair< int32_t, int32_t > get_quantized_activation_min_max(ActivationLayerInfo act_info, DataType data_type, UniformQuantizationInfo oq_info)
Returns a pair of minimum and maximum values for a quantized activation.
Definition: Utils.cpp:558
Status calculate_quantized_multipliers(const QuantizationInfo &iq_info, const QuantizationInfo &wq_info, const QuantizationInfo &oq_info, GEMMLowpOutputStageInfo &stage_info)
Calculate quantized representation of per-channel multipliers.
static Status validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const Conv2dInfo &info)
Static function to check if given info will lead to a valid configuration of CpuGemmDirectConv2d.
quantized, asymmetric fixed-point 8-bit number unsigned
Basic function to run kernels::CpuPermuteKernel.
Definition: CpuPermute.h:34
void prepare(ITensorPack &constants) override
Prepare the function for executing.
Descriptor used by the 2d Convolution function.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1052
Strides of an item in bytes.
Definition: Strides.h:37
quantized, symmetric per channel fixed-point 8-bit number
void run(ITensorPack &tensors) override
Run the kernels contained in the function.
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:64
virtual size_t total_size() const =0
Returns the total size of the tensor in bytes.
Target polymorphic_cast(Source *v)
Polymorphic cast between two types.
Definition: Cast.h:47
Class for specifying the size of an image or rectangle.
Definition: Size2D.h:34
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
Num samples, height, width, channels.
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:788
#define ARM_COMPUTE_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
arm_compute::WeightFormat weight_format() const
Definition: Types.h:2123
Tensor packing service.
Definition: ITensorPack.h:39
#define ARM_COMPUTE_LOG_PARAMS(...)
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
int offset_int_vec(int offset)
Definition: MemoryHelpers.h:38
quantized, asymmetric fixed-point 8-bit number signed
DataType
Available data types.
Definition: Types.h:79
std::tuple< PixelValue, PixelValue > get_min_max(DataType dt)
Compute the mininum and maximum values a data type can take.
Definition: Utils.h:564
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.