blob: d459820dde57dd5d3f284590ca681e7e345a2478 [file] [log] [blame]
Matteo Martincigh747ef822018-12-18 09:26:39 +00001//
Teresa Charlin7db70892024-04-23 13:43:03 +01002// Copyright © 2017-2024 Arm Ltd. All rights reserved.
Matteo Martincigh747ef822018-12-18 09:26:39 +00003// SPDX-License-Identifier: MIT
4//
5
Matteo Martincighe5b8eb92019-11-28 15:45:42 +00006#include <backendsCommon/WorkloadUtils.hpp>
Matteo Martincigh747ef822018-12-18 09:26:39 +00007
Derek Lambertid466a542020-01-22 15:37:29 +00008#include <armnn/Utils.hpp>
Matthew Sloyan171214c2020-09-09 09:07:37 +01009#include <armnn/utility/NumericCast.hpp>
Jan Eilers53ef7952021-06-02 12:01:25 +010010#include <armnnUtils/DataLayoutIndexed.hpp>
Teresa Charlin7db70892024-04-23 13:43:03 +010011#include <armnnUtils/TensorUtils.hpp>
Jan Eilers53ef7952021-06-02 12:01:25 +010012
13#include <fmt/format.h>
Teresa Charlinb2d3ec52022-04-12 22:07:09 +010014#include <numeric>
Jan Eilersbb446e52020-04-02 13:56:54 +010015
Matteo Martincigh747ef822018-12-18 09:26:39 +000016namespace armnn
17{
18
James Conroy1f58f032021-04-27 17:13:27 +010019armnn::ConstTensor PermuteTensor(const ConstTensorHandle* tensor,
Kevin May665a964a2019-08-21 16:53:50 +010020 const PermutationVector& permutationVector, void* permuteBuffer)
Matteo Martincigh747ef822018-12-18 09:26:39 +000021{
David Monahan6a1d5062023-08-29 09:10:50 +010022 if (tensor == nullptr)
23 {
24 throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null input tensor pointer");
25 }
26 if (permuteBuffer == nullptr)
27 {
28 throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null permute buffer pointer");
29 }
Matteo Martincigh747ef822018-12-18 09:26:39 +000030
31 TensorInfo tensorInfo = tensor->GetTensorInfo();
32
33 if (permutationVector.GetSize() > 0)
34 {
35 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector);
36 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector,
37 tensor->GetConstTensor<void>(), permuteBuffer,
38 GetDataTypeSize(tensorInfo.GetDataType()));
39 }
40 else
41 {
42 ::memcpy(permuteBuffer, tensor->GetConstTensor<void>(), tensorInfo.GetNumBytes());
43 }
Cathal Corbett5b8093c2021-10-22 11:12:07 +010044 tensorInfo.SetConstant(true);
Matteo Martincigh747ef822018-12-18 09:26:39 +000045 return ConstTensor(tensorInfo, permuteBuffer);
46}
47
48void ReshapeWeightsForAcl(TensorInfo& weightInfo, DataLayout dataLayout)
49{
50 // Reshape the weights in-place
51 const TensorShape& weightShape = weightInfo.GetShape();
52 switch (dataLayout)
53 {
54 case DataLayout::NHWC:
55 // The data layout is NHWC, reshape from [ H, W, I, M ] to [ 1, H, W, I * M ]
56 weightInfo.SetShape({ 1,
57 weightShape[0],
58 weightShape[1],
59 weightShape[2] * weightShape[3] });
Matteo Martincigh747ef822018-12-18 09:26:39 +000060 weightInfo.SetShape({ 1,
61 weightShape[0] * weightShape[1],
62 weightShape[2],
63 weightShape[3] });
64 break;
Kevin May665a964a2019-08-21 16:53:50 +010065 case DataLayout::NCHW:
66 default:
67 // The data layout is NCHW, reshape from [ M, I, H, W ] to [ 1, I * M, H, W, ]
68 weightInfo.SetShape({ 1, weightShape[0] * weightShape[1], weightShape[2], weightShape[3] });
69 break;
Matteo Martincigh747ef822018-12-18 09:26:39 +000070 }
71}
72
Kevin May665a964a2019-08-21 16:53:50 +010073template <typename DataType>
74ConstTensor ReorderWeightChannelsForAcl(const ConstTensor& weightHandle, DataLayout dataLayout, void* permuteBuffer)
75{
76 DataType* weight = static_cast<DataType*>(permuteBuffer);
77 const TensorShape& weightShape = weightHandle.GetShape();
78 unsigned int multiplier;
79 unsigned int height;
80 unsigned int width;
81 unsigned int inputChannels;
82 switch (dataLayout)
83 {
84 case DataLayout::NHWC: //It actually is [ H, W, I, M ]
85 height = weightShape[0];
86 width = weightShape[1];
87 inputChannels = weightShape[2];
88 multiplier = weightShape[3];
89 break;
90 case DataLayout::NCHW: //It actually is [ M, I, H, W ]
91 default:
92 height = weightShape[2];
93 width = weightShape[3];
94 inputChannels = weightShape[1];
95 multiplier = weightShape[0];
96 break;
97 }
98
Rob Hughes93667b12019-09-23 16:24:05 +010099 std::vector<DataType> weightAclOrder(height*width*inputChannels*multiplier);
Kevin May665a964a2019-08-21 16:53:50 +0100100 unsigned int destinationWeightsChannel;
101 unsigned int totalChannels = inputChannels * multiplier;
102 unsigned int channelSize = height * width;
Teresa Charlin93cbbcc2019-12-18 22:10:47 +0000103 unsigned int inputChannel = 0;
Kevin May665a964a2019-08-21 16:53:50 +0100104
105 for (unsigned int originWeightsChannel = 0; originWeightsChannel < totalChannels; originWeightsChannel++)
106 {
Teresa Charlin93cbbcc2019-12-18 22:10:47 +0000107 inputChannel = originWeightsChannel % inputChannels;
108 destinationWeightsChannel = (originWeightsChannel - inputChannel) / inputChannels + multiplier * inputChannel;
Kevin May665a964a2019-08-21 16:53:50 +0100109
110 for (unsigned int i = 0; i < channelSize; i++)
111 {
112 weightAclOrder[i + destinationWeightsChannel * channelSize] =
113 weight[i + originWeightsChannel * channelSize];
114 }
115 }
116
Rob Hughes93667b12019-09-23 16:24:05 +0100117 ::memcpy(permuteBuffer, weightAclOrder.data(), weightHandle.GetInfo().GetNumBytes());
Kevin May665a964a2019-08-21 16:53:50 +0100118 return ConstTensor(weightHandle.GetInfo(), permuteBuffer);
119}
120
Jan Eilers53ef7952021-06-02 12:01:25 +0100121
Matteo Martincigh747ef822018-12-18 09:26:39 +0000122TensorInfo ConvertWeightTensorInfoFromArmnnToAcl(const TensorInfo& weightInfo, DataLayout dataLayout)
123{
124 // Convert the weight format from ArmNN's [ M, I, H, W ] (does NOT depend on the data layout) to either
125 // [ 1, H, W, I * M ] (if NHWC) or [ 1, I * M, H, W ] (if NCHW), as required by the compute library
126
127 // 1. Permute the weights if necessary
128 // If the data layout is NCHW no permutation is necessary, as a reshape to [ 1, I * M, H, W ] can be better done
129 // starting from the current shape of [ M, I, H, W ]
130 TensorInfo weightPermutedInfo(weightInfo);
131 if (dataLayout == DataLayout::NHWC)
132 {
133 // The data layout is NHWC, then permute the weights from [ M, I, H, W ] to [ H, W, I, M ]
134 PermutationVector permutationVector{ 3, 2, 0, 1 };
135 weightPermutedInfo = armnnUtils::Permuted(weightInfo, permutationVector);
136 }
137
138 // 2. Reshape the weights
139 ReshapeWeightsForAcl(weightPermutedInfo, dataLayout);
140
141 // 3. Return the permuted weight info
142 return weightPermutedInfo;
143}
144
Jan Eilers53ef7952021-06-02 12:01:25 +0100145
146std::tuple<ConstTensor, unsigned int> Convert1HWOTensorToAcl(const ConstTensorHandle* weightTensor,
147 const TensorInfo& inputInfo,
148 const DataLayout dataLayout,
149 void* permuteBuffer)
150{
151 TensorInfo weightsInfo = weightTensor->GetTensorInfo();
152 unsigned int depthMultiplier = 1;
153 PermutationVector permutationVector{};
154 if (dataLayout == armnn::DataLayout::NHWC)
155 {
156 // No permutation required. Data layouts are the same.
157
158 depthMultiplier = weightsInfo.GetShape()[3] / inputInfo.GetShape()[3];
159 }
160 else if (dataLayout == armnn::DataLayout::NCHW)
161 {
162 // [ 1, H, W, I*M] --> [ 1, I * M, H, W ]
163 depthMultiplier = weightsInfo.GetShape()[3] / inputInfo.GetShape()[1];
164 permutationVector = { 0, 2, 3, 1 };
165 }
166 else
167 {
168 throw InvalidArgumentException(fmt::format("Unknown data layout for tensor conversion: {}",
169 GetDataLayoutName(dataLayout)));
170 }
171
172 ConstTensor weightsPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
173
174 return std::make_tuple(weightsPermuted, depthMultiplier);
175}
176
177std::tuple<TensorInfo, unsigned int> Convert1HWOTensorInfoToAcl(const TensorInfo& weightInfo,
178 const TensorInfo& inputInfo,
179 const DataLayout dataLayout)
180{
181 unsigned int aclDepthMultiplier = 1;
182 TensorInfo weightsPermuted;
183 if (dataLayout == armnn::DataLayout::NHWC)
184 {
Cathal Corbett4b19d222022-05-11 20:12:17 +0100185 // No permutation required. Input and weights data layouts are the same.
Jan Eilers53ef7952021-06-02 12:01:25 +0100186 aclDepthMultiplier = weightInfo.GetShape()[3] / inputInfo.GetShape()[3];
187 weightsPermuted = weightInfo;
188 }
Cathal Corbett4b19d222022-05-11 20:12:17 +0100189
Jan Eilers53ef7952021-06-02 12:01:25 +0100190 else if (dataLayout == armnn::DataLayout::NCHW)
191 {
Cathal Corbett4b19d222022-05-11 20:12:17 +0100192 // Weights permutation required. Weights [N,H,W,C] and input [N,C,H,W] data layouts are different.
Jan Eilers53ef7952021-06-02 12:01:25 +0100193 // [ 1, H, W, I*M] --> [ 1, I * M, H, W ]
194 aclDepthMultiplier = weightInfo.GetShape()[3] / inputInfo.GetShape()[1];
195 PermutationVector permutationVector{ 0, 2, 3, 1 };
196 weightsPermuted = armnnUtils::Permuted(weightInfo, permutationVector);
197 }
198 else
199 {
200 throw InvalidArgumentException(fmt::format("Unknown data layout for tensor info conversion: {}",
201 GetDataLayoutName(dataLayout)));
202 }
203
204 return std::make_tuple(weightsPermuted, aclDepthMultiplier);
205}
206
207
208std::tuple<ConstTensor, unsigned int> Convert1HWOtoMIHW(const ConstTensorHandle* weightTensor,
209 const TensorInfo& inputInfo,
210 const DataLayout& dataLayout,
211 void* permuteBuffer)
212{
213 TensorInfo weightsInfo = weightTensor->GetTensorInfo();
214
215 if (weightsInfo.HasPerAxisQuantization())
216 {
217 throw InvalidArgumentException("Can't convert tensor from [1,H,W,Cout] to [M,Cin,H,W] when per channel "
218 "quantization is applied.");
219 }
220
221 // Reshape weights [ 1, H, W, I*M ] --> [ H, W, I, M ]
222 auto weightsShape = weightsInfo.GetShape();
223 auto channelIndex = armnnUtils::DataLayoutIndexed(dataLayout).GetChannelsIndex();
224 unsigned int depthMultiplier = weightsShape[3] / inputInfo.GetShape()[channelIndex];
225 weightsInfo.SetShape({ weightsShape[1],
226 weightsShape[2],
227 inputInfo.GetShape()[channelIndex],
228 depthMultiplier});
229
230 // Permute [ H, W, I, M ] --> [ M, I, H, W ]
231 PermutationVector permutationVector = { 2, 3, 1, 0 };
232 ConstTensor weightsPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
233
234 return std::make_tuple(weightsPermuted, depthMultiplier);
235}
236
James Conroy1f58f032021-04-27 17:13:27 +0100237armnn::ConstTensor ConvertWeightTensorFromArmnnToAcl(const ConstTensorHandle* weightTensor,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000238 DataLayout dataLayout,
239 void* permuteBuffer)
240{
David Monahan6a1d5062023-08-29 09:10:50 +0100241 if (weightTensor == nullptr)
242 {
243 throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null input tensor pointer");
244 }
245 if (permuteBuffer == nullptr)
246 {
247 throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null permute buffer pointer");
248 }
Matteo Martincigh747ef822018-12-18 09:26:39 +0000249
Kevin May665a964a2019-08-21 16:53:50 +0100250 auto multiplier = weightTensor->GetTensorInfo().GetShape()[0];
251 auto inputChannels = weightTensor->GetTensorInfo().GetShape()[1];
252
Matteo Martincigh747ef822018-12-18 09:26:39 +0000253 // Convert the weight format from ArmNN's [ M, I, H, W ] (does NOT depend on the data layout) to either
254 // [ 1, H, W, I * M ] (if NHWC) or [ 1, I * M, H, W ] (if NCHW), as required by the compute library
255
256 // 1. Permute the weights if necessary
257 // If the data layout is NCHW no permutation is necessary, as a reshape to [ 1, I * M, H, W ] can be better done
258 // starting from the current shape of [ M, I, H, W ]
259 // If no permutation is necessary, leave the permutation vector empty
260 PermutationVector permutationVector{};
261 if (dataLayout == DataLayout::NHWC)
262 {
263 // The data layout is NHWC, then permute the weights from [ M, I, H, W ] to [ H, W, I, M ]
264 permutationVector = { 3, 2, 0, 1 };
265 }
266 ConstTensor weightPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
267
Kevin May665a964a2019-08-21 16:53:50 +0100268 // Shuffle the weights data to obtain the channel order needed used by Acl
Rob Hughes93667b12019-09-23 16:24:05 +0100269 if (multiplier > 1 && inputChannels > 1 && dataLayout == DataLayout::NCHW)
Kevin May665a964a2019-08-21 16:53:50 +0100270 {
271 switch (weightPermuted.GetDataType())
272 {
273 case DataType::Float32:
274 weightPermuted = ReorderWeightChannelsForAcl<float>(weightPermuted, dataLayout, permuteBuffer);
275 break;
276 case DataType::Float16:
277 weightPermuted =
278 ReorderWeightChannelsForAcl<half_float::half>(weightPermuted, dataLayout, permuteBuffer);
279 break;
Keith Davisa8565012020-02-14 12:22:40 +0000280 case DataType::QAsymmS8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000281 case DataType::QAsymmU8:
Kevin May665a964a2019-08-21 16:53:50 +0100282 weightPermuted = ReorderWeightChannelsForAcl<uint8_t>(weightPermuted, dataLayout, permuteBuffer);
283 break;
Derek Lambertid466a542020-01-22 15:37:29 +0000284 case DataType::QSymmS8:
Teresa Charlina68d8532019-11-29 13:59:18 +0000285 weightPermuted = ReorderWeightChannelsForAcl<int8_t>(weightPermuted, dataLayout, permuteBuffer);
286 break;
Kevin May665a964a2019-08-21 16:53:50 +0100287 default:
288 break;
289 }
290 }
291
Matteo Martincigh747ef822018-12-18 09:26:39 +0000292 // 2. Reshape the weights
293 ReshapeWeightsForAcl(weightPermuted.GetInfo(), dataLayout);
294
295 // 3. Return both the tensor and the allocated storage to ensure that the data stays alive
296 return weightPermuted;
297}
298
Francis Murtaghec33a912019-11-05 14:26:23 +0000299int32_t ConvertMaskToACLFormat(int32_t mask, int32_t numDim)
300{
301 int32_t reversedMask = 0;
Matthew Sloyan171214c2020-09-09 09:07:37 +0100302 for (unsigned int i = 0; i < armnn::numeric_cast<unsigned int>(numDim); ++i)
Francis Murtaghec33a912019-11-05 14:26:23 +0000303 {
304 // Check if bit set in mask for each dimension
305 int32_t bit = (mask & 1 << i) != 0;
306 // Increment the new mask with the bits reversed
Matthew Sloyan171214c2020-09-09 09:07:37 +0100307 reversedMask += (bit << std::max(numDim-(armnn::numeric_cast<int>(i)+1), 0));
Francis Murtaghec33a912019-11-05 14:26:23 +0000308 }
309
310 return reversedMask;
311}
312
Teresa Charlinb2d3ec52022-04-12 22:07:09 +0100313std::map<std::string, unsigned int> CalculateGatherNdKeyIndices(TensorInfo inputInfo0, TensorInfo inputInfo1)
314{
315 std::vector<unsigned int> paramsShape;
316 for (unsigned int i = 0; i < inputInfo0.GetNumDimensions(); ++i)
317 {
318 paramsShape.push_back(inputInfo0.GetShape()[i]);
319 }
320
321 std::vector<unsigned int> indicesShape;
322 for (unsigned int i = 0; i < inputInfo1.GetNumDimensions(); ++i)
323 {
324 indicesShape.push_back(inputInfo1.GetShape()[i]);
325 }
326
327 std::map<std::string, unsigned int> keyIndices;
328
329 // N: number of batches
330 keyIndices["N"] = 1;
331
332 // ND: number of dimensions that are sliced from params
333 keyIndices["ND"] = indicesShape.back();
334
335 // W: number of indices in each batch (all but the last dimension)
336 keyIndices["W"] =
337 static_cast<unsigned int>(std::accumulate(std::begin(indicesShape),
338 std::end(indicesShape) - 1,
339 1,
340 std::multiplies<>() ));
341 // K: range of each index
342 keyIndices["K"] =
343 static_cast<unsigned int>(std::accumulate(std::begin(paramsShape),
344 std::begin(paramsShape) + static_cast<int>(keyIndices["ND"]),
345 1,
346 std::multiplies<>() ));
347 // C: number of channels for each index
348 keyIndices["C"] =
349 static_cast<unsigned int>(std::accumulate(std::begin(paramsShape) + static_cast<int>(keyIndices["ND"]),
350 std::end(paramsShape),
351 1,
352 std::multiplies<>() ));
353
354 return keyIndices;
355}
356
Teresa Charlin0f86ecf2022-10-13 15:47:08 +0100357armnn::PermutationVector GeneratePermutationVectorOnLastTwoDimensions(unsigned int rank)
358{
359 armnn::PermutationVector permutationVector{};
360 switch (rank)
361 {
362 case 2:
363 permutationVector = {1U, 0U};
364 break;
365 case 3:
366 permutationVector = {0U, 2U, 1U};
367 break;
368 case 4:
369 permutationVector = {0U, 1U, 3U, 2U};
370 break;
371 default:
372 throw Exception("Invalid number of dimensions.");
373 }
374 return permutationVector;
375}
376
Teresa Charlin7db70892024-04-23 13:43:03 +0100377std::set<unsigned int> ComputeSplitAxis(const armnn::SplitterDescriptor& desc, const TensorShape& input)
378{
379 unsigned int numSplit = desc.GetNumViews();
380 unsigned int numDimensions = desc.GetNumDimensions();
381 std::set<unsigned int> splitAxis;
382 if (desc.HasAxis())
383 {
384 splitAxis.insert(armnnUtils::GetUnsignedAxis(desc.GetNumDimensions(), desc.GetAxis()));
385 }
386 else
387 {
388 for (unsigned int i = 0; i < numSplit; ++i)
389 {
390 for (unsigned int dimIdx = 0; dimIdx < numDimensions; ++dimIdx)
391 {
392 if (desc.GetViewSizes(i)[dimIdx] != input[dimIdx])
393 {
394 splitAxis.insert(dimIdx);
395 }
396 }
397 }
398 }
399 return splitAxis;
400}
401
Matteo Martincigh747ef822018-12-18 09:26:39 +0000402} // namespace armnn