ONE - On-device Neural Engine
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
FullyConnectedLayer.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "FullyConnectedLayer.h"
18
19#include "GGMLHelper.h"
20
21#include "../Tensor.h"
23#include <cker/TensorUtils.h>
25
27{
28
30 : _input(nullptr), _weights(nullptr), _bias(nullptr), _output(nullptr),
31 _activation(ir::Activation::NONE), _temp_arena(new nnfw::cker::FCTempArena()),
32 _external_context(nullptr), _is_hybrid(false), _is_shuffled16x1float32(false)
33{
34 // DO NOTHING
35}
36
38
40{
42 float output_activation_min = 0;
43 float output_activation_max = 0;
44 CalculateActivationRange(_activation, &output_activation_min, &output_activation_max);
45
47 op_params.float_activation_min = output_activation_min;
48 op_params.float_activation_max = output_activation_max;
49 // TODO Set both cachables as false when training
50 op_params.lhs_cacheable = _weights->is_constant();
51 op_params.rhs_cacheable = _input->is_constant();
52
53 nnfw::cker::FullyConnected(op_params, getShape(_input), getBuffer<float>(_input),
54 getShape(_weights), getBuffer<float>(_weights), getShape(_bias),
55 _bias ? getBuffer<float>(_bias) : nullptr, getShape(_output),
56 getBuffer<float>(_output));
57}
58
59// executionMutex is used to protect concurrent access of non-threadsafe resources
60// like gemmlowp::GemmContext.
62{
63 double real_multiplier = 0.0;
64 int32_t output_multiplier = 0;
65 int32_t output_shift = 0;
66 int32_t output_activation_min = 0;
67 int32_t output_activation_max = 0;
69 QuantizeMultiplier(real_multiplier, &output_multiplier, &output_shift);
71 &output_activation_max);
72
74 op_params.input_offset = -_input->data_zero_point();
77 op_params.output_multiplier = output_multiplier;
78 op_params.output_shift = output_shift;
79 op_params.quantized_activation_min = output_activation_min;
80 op_params.quantized_activation_max = output_activation_max;
81
82 nnfw::cker::FullyConnected(op_params, getShape(_input), getBuffer<uint8_t>(_input),
83 getShape(_weights), getBuffer<uint8_t>(_weights), getShape(_bias),
84 _bias ? getBuffer<int32_t>(_bias) : nullptr, getShape(_output),
85 getBuffer<uint8_t>(_output));
86}
87
89{
91 if (!temp_arena.prepared)
92 {
94 }
95
98 op_params.weights_scale = _weights->data_scale();
99
100#ifndef USE_RUY_GEMV
102 op_params, getShape(_input), getBuffer<float>(_input), getShape(_weights),
103 getBuffer<int8_t>(_weights), getShape(_bias), _bias ? getBuffer<float>(_bias) : nullptr,
104 getShape(_output), getBuffer<float>(_output), temp_arena, _external_context->ruy_context());
105#else
107 op_params, getShape(_input), getBuffer<float>(_input), getShape(_weights),
108 (_cached_weights) ? reinterpret_cast<const int8_t *>(_cached_weights)
109 : getBuffer<int8_t>(_weights),
110 getShape(_bias), _bias ? getBuffer<float>(_bias) : nullptr, getShape(_output),
111 getBuffer<float>(_output), temp_arena, _external_context->ruy_context());
112
113 if (_cached_weights == nullptr || _is_weights_freed)
114 return;
115
116 // '_cached_weights is not nullptr and _is_weights_freed is false' means
117 // this weight shape is satisfied with the ruy kernel's prepack cache's condition.
118 // After entering here, it will not enter again except below the case - input is zero-vector
119
120 // if input's elements are filled with zero, it by-passes(does not enter ruy-kernel path)
121 // so that handle this case
122 const int input_size = getShape(_input).FlatSize();
123 if (nnfw::cker::IsZeroVector(getBuffer<float>(_input), input_size))
124 return;
125
126 auto weight_tensor = nnfw::misc::polymorphic_downcast<const Tensor *>(_weights);
127
128 // This weight tensor could be other ops' const tensor.
129 // Therefore, below reference should be checked like following
130 auto tensor = const_cast<Tensor *>(weight_tensor);
131 if (tensor->buffer() == nullptr) // ref is already 0?
132 {
133 _is_weights_freed = true;
134 return;
135 }
136
137 tensor->decrease_ref();
138 if (tensor->buffer() == nullptr) // ref == 0?
139 {
140#if defined(__ANDROID__) && (__ANDROID_API__ >= 26)
141 // NOTE This line forces OS to release any unused memory immediately
142 mallopt(M_PURGE, 0);
143#endif
144 _is_weights_freed = true;
145 }
146#endif
147}
148
150{
153
154 const uint16_t *w1_segments = _weights->sparsity()->w1_segments();
155 const uint16_t *w1_indices = _weights->sparsity()->w1_indices();
156
157 auto block_size = _weights->sparsity()->block_size();
158 if (block_size.size() == 0)
159 {
161 op_params, getShape(_input), getBuffer<float>(_input), getShape(_weights),
162 getBuffer<float>(_weights), getShape(_bias), _bias ? getBuffer<float>(_bias) : nullptr,
163 getShape(_output), getBuffer<float>(_output), w1_segments, w1_indices);
164 }
165 else if (block_size.size() == 2 && block_size[0] == 16 && block_size[1] == 1)
166 {
168 op_params, getShape(_input), getBuffer<float>(_input), getShape(_weights),
169 getBuffer<float>(_weights), getShape(_bias), _bias ? getBuffer<float>(_bias) : nullptr,
170 getShape(_output), getBuffer<float>(_output), w1_segments, w1_indices);
171 }
172 else
173 throw std::runtime_error{"FullyConnected: unsupported sparsity"};
174}
175
177{
178 if (_bias)
179 throw std::runtime_error{"FullyConnected: GGML weights format does not support bias yet."};
180
181 // convert tensor
182 auto input = getGGMLTensor(_input);
183 auto weights = getGGMLTensor(_weights);
184 auto output = getGGMLTensor(_output);
185 {
186 output.op = GGML_OP_MUL_MAT;
187 output.src[0] = &weights;
188 output.src[1] = &input;
189 }
190 auto *nodes = &output;
191
192 // create graph
193 struct ggml_cgraph graph;
194 {
195 memset(&graph, 0, sizeof(graph));
196 graph.n_nodes = 1;
197 graph.nodes = &nodes;
198 }
199
200 // get cplan
201 auto cplan = ggml_graph_plan(&graph, _external_context->maxNumThreads());
202 std::vector<uint8_t> buf(cplan.work_size);
203 cplan.work_data = buf.data();
204
205 // compute
206 ggml_graph_compute(&graph, &cplan);
207}
208
210{
211#if defined(__aarch64__) && defined(USE_NEON)
212 float output_activation_min = 0, output_activation_max = 0;
213 CalculateActivationRange(_activation, &output_activation_min, &output_activation_max);
214
217
218 nnfw::cker::FullyConnected16x1Float32(op_params, getShape(_input), getBuffer<float>(_input),
219 getShape(_weights), getBuffer<float>(_weights),
220 getShape(_bias), _bias ? getBuffer<float>(_bias) : nullptr,
221 getShape(_output), getBuffer<float>(_output));
222#else
223 throw std::runtime_error{"FullyConnected: Shuffled16x1Float32 weights_format is not supported."};
224#endif
225}
226
228 const IPortableTensor *bias, ir::Activation activation,
229 ir::FullyConnectedWeightsFormat weights_format,
230 IPortableTensor *output,
231 const std::shared_ptr<ExternalContext> &external_context)
232{
233 _input = input;
234 _weights = weights;
235 _bias = bias;
236 _activation = activation;
237 _output = output;
238 _is_hybrid = input->data_type() == OperandType::FLOAT32 &&
239 weights->data_type() == OperandType::QUANT_INT8_SYMM;
241#if !defined(__aarch64__) || !defined(USE_NEON)
243 {
244 throw std::runtime_error{
245 "FullyConnected: Shuffled16x1Float32 weights_format is not supported."};
246 }
247#endif
248 _external_context = external_context;
249
250 if (_weights->data_type() == OperandType::QUANT_GGML_Q4_0 ||
251 _weights->data_type() == OperandType::QUANT_GGML_Q8_0)
252 _external_context->initGgmlContext();
253}
254
256{
257 if (_is_hybrid)
258 {
260 }
261 else if (_weights->sparsity())
262 {
264 }
265 else if (_weights->data_type() == OperandType::QUANT_GGML_Q4_0 ||
266 _weights->data_type() == OperandType::QUANT_GGML_Q8_0)
267 {
269 }
270 else if (_input->data_type() == OperandType::FLOAT32)
271 {
273 }
274 else if (_input->data_type() == OperandType::QUANT_UINT8_ASYMM)
275 {
277 }
278 else
279 {
280 throw std::runtime_error{"FullyConnected: unsupported data type"};
281 }
282}
283
285{
286 if (_bias && _bias->is_constant())
287 {
288 const int bias_size = getShape(_bias).FlatSize();
289 if (nnfw::cker::IsZeroVector(getBuffer<float>(_bias), bias_size))
290 {
291 _bias = nullptr;
292 }
293 }
294
295#if (defined(__ARM_NEON__) || defined(__ARM_NEON)) && defined(USE_RUY_GEMV)
296 // TODO This is workaround
297 // The only fc hybrid will use ruy kernel
298 if (_input->data_type() != OperandType::FLOAT32 ||
299 _weights->data_type() != OperandType::QUANT_INT8_SYMM)
300 {
301 return;
302 }
303
304 // NOTE. The condition to enable caching on ruy kernel can be changed according to ruy's version
305
306 // If input is dynamic, it changes total size of input
307 // If weights is not constant, weights cannot be cached
309 return;
310
311 const int rows = getShape(_weights).Dims(0);
312 if (rows % 4 == 0)
313 {
314 // TODO If it's possible to extract precaching from ruy kernel,
315 // place this instead of below code
316
317 // buffer will be used by ruy kernel as a cache key
318 _cached_weights = _weights->buffer();
319 }
320#endif
321}
322
323} // namespace onert::backend::cpu::ops
void prepare(const Shape &input_shape, const Shape &weights_shape)
int32_t Dims(int i) const
Definition Shape.h:110
int FlatSize() const
Definition Shape.h:249
A tensor class that is portable for other backends.
const ir::Sparsity * sparsity() const
float data_scale() const override final
int32_t data_zero_point() const override final
ir::DataType data_type() const override final
bool is_dynamic() const override final
Return true if the tensor needs dynamic allocation, meaning that during compile-time the outpus shape...
bool is_constant() const override final
Return true if the tensor is constant.
virtual uint8_t * buffer() const =0
std::unique_ptr< nnfw::cker::FCTempArena > _temp_arena
std::shared_ptr< ExternalContext > _external_context
void configure(const IPortableTensor *input, const IPortableTensor *weights, const IPortableTensor *bias, ir::Activation activation, ir::FullyConnectedWeightsFormat weights_format, IPortableTensor *output, const std::shared_ptr< ExternalContext > &external_context)
void FullyConnectedSparseWeightRandom(const FullyConnectedParams &params, const Shape &input_shape, const float *input_data, const Shape &weights_shape, const float *weights_data, const Shape &bias_shape, const float *bias_data, const Shape &output_shape, float *output_data, const uint16_t *w1_segments, const uint16_t *w1_indices)
void FullyConnectedSparseWeight16x1(const FullyConnectedParams &params, const Shape &input_shape, const float *input_data, const Shape &weights_shape, const float *weights_data, const Shape &bias_shape, const float *bias_data, const Shape &output_shape, float *output_data, const uint16_t *w1_segments, const uint16_t *w1_indices)
void FullyConnectedHybrid(const FullyConnectedParams &params, const Shape &input_shape, const float *input_data, const Shape &filter_shape, const int8_t *filter_data, const Shape &, const float *bias_data, const Shape &output_shape, float *output_data, FCTempArena &temp_arena, ruy::Context *ruy_context)
void FullyConnected(const FullyConnectedParams &params, const Shape &input_shape, const float *input_data, const Shape &weights_shape, const float *weights_data, const Shape &, const float *bias_data, const Shape &, float *output_data)
bool IsZeroVector(const float *vector, int v_size)
Definition topk_v2.h:30
nnfw::cker::FusedActivationFunctionType convertActivationType(const ir::Activation activation)
nnfw::cker::Shape getShape(const IPortableTensor *tensor)
struct ggml_tensor getGGMLTensor(const IPortableTensor *tensor)
Definition GGMLHelper.cc:41
void QuantizeMultiplier(double double_multiplier, int32_t *quantized_multiplier, int *shift)
void CalculateActivationRangeQuantized(ir::Activation activation, const IPortableTensor *output, int32_t *act_min, int32_t *act_max)
void GetQuantizedConvolutionMultiplier(const IPortableTensor *input, const IPortableTensor *filter, const IPortableTensor *bias, const IPortableTensor *output, double *multiplier)
FullyConnectedWeightsFormat
void CalculateActivationRange(ir::Activation activation, T *activation_min, T *activation_max)
FusedActivationFunctionType activation
Definition Types.h:257
const std::vector< int32_t > & block_size() const
Returns block size which is used for block sparsity.
Definition Sparsity.h:51
const uint16_t * w1_segments() const
Returns segments array. See compressed sparse row format.
Definition Sparsity.h:43
const uint16_t * w1_indices() const
Returns indices array. See compressed sparse row format.
Definition Sparsity.h:47