blob: d2ae16af0c9fbfc252fe61dcb2d1706ce4714c60 [file] [log] [blame]
Matteo Martincigh747ef822018-12-18 09:26:39 +00001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// 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>
11
12#include <fmt/format.h>
Teresa Charlinb2d3ec52022-04-12 22:07:09 +010013#include <numeric>
Jan Eilersbb446e52020-04-02 13:56:54 +010014
Matteo Martincigh747ef822018-12-18 09:26:39 +000015namespace armnn
16{
17
James Conroy1f58f032021-04-27 17:13:27 +010018armnn::ConstTensor PermuteTensor(const ConstTensorHandle* tensor,
Kevin May665a964a2019-08-21 16:53:50 +010019 const PermutationVector& permutationVector, void* permuteBuffer)
Matteo Martincigh747ef822018-12-18 09:26:39 +000020{
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010021 ARMNN_ASSERT_MSG(tensor, "Invalid input tensor");
22 ARMNN_ASSERT_MSG(permuteBuffer, "Invalid permute buffer");
Matteo Martincigh747ef822018-12-18 09:26:39 +000023
24 TensorInfo tensorInfo = tensor->GetTensorInfo();
25
26 if (permutationVector.GetSize() > 0)
27 {
28 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector);
29 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector,
30 tensor->GetConstTensor<void>(), permuteBuffer,
31 GetDataTypeSize(tensorInfo.GetDataType()));
32 }
33 else
34 {
35 ::memcpy(permuteBuffer, tensor->GetConstTensor<void>(), tensorInfo.GetNumBytes());
36 }
Cathal Corbett5b8093c2021-10-22 11:12:07 +010037 tensorInfo.SetConstant(true);
Matteo Martincigh747ef822018-12-18 09:26:39 +000038 return ConstTensor(tensorInfo, permuteBuffer);
39}
40
41void ReshapeWeightsForAcl(TensorInfo& weightInfo, DataLayout dataLayout)
42{
43 // Reshape the weights in-place
44 const TensorShape& weightShape = weightInfo.GetShape();
45 switch (dataLayout)
46 {
47 case DataLayout::NHWC:
48 // The data layout is NHWC, reshape from [ H, W, I, M ] to [ 1, H, W, I * M ]
49 weightInfo.SetShape({ 1,
50 weightShape[0],
51 weightShape[1],
52 weightShape[2] * weightShape[3] });
Matteo Martincigh747ef822018-12-18 09:26:39 +000053 weightInfo.SetShape({ 1,
54 weightShape[0] * weightShape[1],
55 weightShape[2],
56 weightShape[3] });
57 break;
Kevin May665a964a2019-08-21 16:53:50 +010058 case DataLayout::NCHW:
59 default:
60 // The data layout is NCHW, reshape from [ M, I, H, W ] to [ 1, I * M, H, W, ]
61 weightInfo.SetShape({ 1, weightShape[0] * weightShape[1], weightShape[2], weightShape[3] });
62 break;
Matteo Martincigh747ef822018-12-18 09:26:39 +000063 }
64}
65
Kevin May665a964a2019-08-21 16:53:50 +010066template <typename DataType>
67ConstTensor ReorderWeightChannelsForAcl(const ConstTensor& weightHandle, DataLayout dataLayout, void* permuteBuffer)
68{
69 DataType* weight = static_cast<DataType*>(permuteBuffer);
70 const TensorShape& weightShape = weightHandle.GetShape();
71 unsigned int multiplier;
72 unsigned int height;
73 unsigned int width;
74 unsigned int inputChannels;
75 switch (dataLayout)
76 {
77 case DataLayout::NHWC: //It actually is [ H, W, I, M ]
78 height = weightShape[0];
79 width = weightShape[1];
80 inputChannels = weightShape[2];
81 multiplier = weightShape[3];
82 break;
83 case DataLayout::NCHW: //It actually is [ M, I, H, W ]
84 default:
85 height = weightShape[2];
86 width = weightShape[3];
87 inputChannels = weightShape[1];
88 multiplier = weightShape[0];
89 break;
90 }
91
Rob Hughes93667b12019-09-23 16:24:05 +010092 std::vector<DataType> weightAclOrder(height*width*inputChannels*multiplier);
Kevin May665a964a2019-08-21 16:53:50 +010093 unsigned int destinationWeightsChannel;
94 unsigned int totalChannels = inputChannels * multiplier;
95 unsigned int channelSize = height * width;
Teresa Charlin93cbbcc2019-12-18 22:10:47 +000096 unsigned int inputChannel = 0;
Kevin May665a964a2019-08-21 16:53:50 +010097
98 for (unsigned int originWeightsChannel = 0; originWeightsChannel < totalChannels; originWeightsChannel++)
99 {
Teresa Charlin93cbbcc2019-12-18 22:10:47 +0000100 inputChannel = originWeightsChannel % inputChannels;
101 destinationWeightsChannel = (originWeightsChannel - inputChannel) / inputChannels + multiplier * inputChannel;
Kevin May665a964a2019-08-21 16:53:50 +0100102
103 for (unsigned int i = 0; i < channelSize; i++)
104 {
105 weightAclOrder[i + destinationWeightsChannel * channelSize] =
106 weight[i + originWeightsChannel * channelSize];
107 }
108 }
109
Rob Hughes93667b12019-09-23 16:24:05 +0100110 ::memcpy(permuteBuffer, weightAclOrder.data(), weightHandle.GetInfo().GetNumBytes());
Kevin May665a964a2019-08-21 16:53:50 +0100111 return ConstTensor(weightHandle.GetInfo(), permuteBuffer);
112}
113
Jan Eilers53ef7952021-06-02 12:01:25 +0100114
Matteo Martincigh747ef822018-12-18 09:26:39 +0000115TensorInfo ConvertWeightTensorInfoFromArmnnToAcl(const TensorInfo& weightInfo, DataLayout dataLayout)
116{
117 // Convert the weight format from ArmNN's [ M, I, H, W ] (does NOT depend on the data layout) to either
118 // [ 1, H, W, I * M ] (if NHWC) or [ 1, I * M, H, W ] (if NCHW), as required by the compute library
119
120 // 1. Permute the weights if necessary
121 // If the data layout is NCHW no permutation is necessary, as a reshape to [ 1, I * M, H, W ] can be better done
122 // starting from the current shape of [ M, I, H, W ]
123 TensorInfo weightPermutedInfo(weightInfo);
124 if (dataLayout == DataLayout::NHWC)
125 {
126 // The data layout is NHWC, then permute the weights from [ M, I, H, W ] to [ H, W, I, M ]
127 PermutationVector permutationVector{ 3, 2, 0, 1 };
128 weightPermutedInfo = armnnUtils::Permuted(weightInfo, permutationVector);
129 }
130
131 // 2. Reshape the weights
132 ReshapeWeightsForAcl(weightPermutedInfo, dataLayout);
133
134 // 3. Return the permuted weight info
135 return weightPermutedInfo;
136}
137
Jan Eilers53ef7952021-06-02 12:01:25 +0100138
139std::tuple<ConstTensor, unsigned int> Convert1HWOTensorToAcl(const ConstTensorHandle* weightTensor,
140 const TensorInfo& inputInfo,
141 const DataLayout dataLayout,
142 void* permuteBuffer)
143{
144 TensorInfo weightsInfo = weightTensor->GetTensorInfo();
145 unsigned int depthMultiplier = 1;
146 PermutationVector permutationVector{};
147 if (dataLayout == armnn::DataLayout::NHWC)
148 {
149 // No permutation required. Data layouts are the same.
150
151 depthMultiplier = weightsInfo.GetShape()[3] / inputInfo.GetShape()[3];
152 }
153 else if (dataLayout == armnn::DataLayout::NCHW)
154 {
155 // [ 1, H, W, I*M] --> [ 1, I * M, H, W ]
156 depthMultiplier = weightsInfo.GetShape()[3] / inputInfo.GetShape()[1];
157 permutationVector = { 0, 2, 3, 1 };
158 }
159 else
160 {
161 throw InvalidArgumentException(fmt::format("Unknown data layout for tensor conversion: {}",
162 GetDataLayoutName(dataLayout)));
163 }
164
165 ConstTensor weightsPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
166
167 return std::make_tuple(weightsPermuted, depthMultiplier);
168}
169
170std::tuple<TensorInfo, unsigned int> Convert1HWOTensorInfoToAcl(const TensorInfo& weightInfo,
171 const TensorInfo& inputInfo,
172 const DataLayout dataLayout)
173{
174 unsigned int aclDepthMultiplier = 1;
175 TensorInfo weightsPermuted;
176 if (dataLayout == armnn::DataLayout::NHWC)
177 {
178 // No permutation required. Data layouts are the same.
179 aclDepthMultiplier = weightInfo.GetShape()[3] / inputInfo.GetShape()[3];
180 weightsPermuted = weightInfo;
181 }
182 else if (dataLayout == armnn::DataLayout::NCHW)
183 {
184 // [ 1, H, W, I*M] --> [ 1, I * M, H, W ]
185 aclDepthMultiplier = weightInfo.GetShape()[3] / inputInfo.GetShape()[1];
186 PermutationVector permutationVector{ 0, 2, 3, 1 };
187 weightsPermuted = armnnUtils::Permuted(weightInfo, permutationVector);
188 }
189 else
190 {
191 throw InvalidArgumentException(fmt::format("Unknown data layout for tensor info conversion: {}",
192 GetDataLayoutName(dataLayout)));
193 }
194
195 return std::make_tuple(weightsPermuted, aclDepthMultiplier);
196}
197
198
199std::tuple<ConstTensor, unsigned int> Convert1HWOtoMIHW(const ConstTensorHandle* weightTensor,
200 const TensorInfo& inputInfo,
201 const DataLayout& dataLayout,
202 void* permuteBuffer)
203{
204 TensorInfo weightsInfo = weightTensor->GetTensorInfo();
205
206 if (weightsInfo.HasPerAxisQuantization())
207 {
208 throw InvalidArgumentException("Can't convert tensor from [1,H,W,Cout] to [M,Cin,H,W] when per channel "
209 "quantization is applied.");
210 }
211
212 // Reshape weights [ 1, H, W, I*M ] --> [ H, W, I, M ]
213 auto weightsShape = weightsInfo.GetShape();
214 auto channelIndex = armnnUtils::DataLayoutIndexed(dataLayout).GetChannelsIndex();
215 unsigned int depthMultiplier = weightsShape[3] / inputInfo.GetShape()[channelIndex];
216 weightsInfo.SetShape({ weightsShape[1],
217 weightsShape[2],
218 inputInfo.GetShape()[channelIndex],
219 depthMultiplier});
220
221 // Permute [ H, W, I, M ] --> [ M, I, H, W ]
222 PermutationVector permutationVector = { 2, 3, 1, 0 };
223 ConstTensor weightsPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
224
225 return std::make_tuple(weightsPermuted, depthMultiplier);
226}
227
James Conroy1f58f032021-04-27 17:13:27 +0100228armnn::ConstTensor ConvertWeightTensorFromArmnnToAcl(const ConstTensorHandle* weightTensor,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000229 DataLayout dataLayout,
230 void* permuteBuffer)
231{
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100232 ARMNN_ASSERT_MSG(weightTensor, "Invalid input tensor");
233 ARMNN_ASSERT_MSG(permuteBuffer, "Invalid permute buffer");
Matteo Martincigh747ef822018-12-18 09:26:39 +0000234
Kevin May665a964a2019-08-21 16:53:50 +0100235 auto multiplier = weightTensor->GetTensorInfo().GetShape()[0];
236 auto inputChannels = weightTensor->GetTensorInfo().GetShape()[1];
237
Matteo Martincigh747ef822018-12-18 09:26:39 +0000238 // Convert the weight format from ArmNN's [ M, I, H, W ] (does NOT depend on the data layout) to either
239 // [ 1, H, W, I * M ] (if NHWC) or [ 1, I * M, H, W ] (if NCHW), as required by the compute library
240
241 // 1. Permute the weights if necessary
242 // If the data layout is NCHW no permutation is necessary, as a reshape to [ 1, I * M, H, W ] can be better done
243 // starting from the current shape of [ M, I, H, W ]
244 // If no permutation is necessary, leave the permutation vector empty
245 PermutationVector permutationVector{};
246 if (dataLayout == DataLayout::NHWC)
247 {
248 // The data layout is NHWC, then permute the weights from [ M, I, H, W ] to [ H, W, I, M ]
249 permutationVector = { 3, 2, 0, 1 };
250 }
251 ConstTensor weightPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
252
Kevin May665a964a2019-08-21 16:53:50 +0100253 // Shuffle the weights data to obtain the channel order needed used by Acl
Rob Hughes93667b12019-09-23 16:24:05 +0100254 if (multiplier > 1 && inputChannels > 1 && dataLayout == DataLayout::NCHW)
Kevin May665a964a2019-08-21 16:53:50 +0100255 {
256 switch (weightPermuted.GetDataType())
257 {
258 case DataType::Float32:
259 weightPermuted = ReorderWeightChannelsForAcl<float>(weightPermuted, dataLayout, permuteBuffer);
260 break;
261 case DataType::Float16:
262 weightPermuted =
263 ReorderWeightChannelsForAcl<half_float::half>(weightPermuted, dataLayout, permuteBuffer);
264 break;
Keith Davisa8565012020-02-14 12:22:40 +0000265 case DataType::QAsymmS8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000266 case DataType::QAsymmU8:
Kevin May665a964a2019-08-21 16:53:50 +0100267 weightPermuted = ReorderWeightChannelsForAcl<uint8_t>(weightPermuted, dataLayout, permuteBuffer);
268 break;
Derek Lambertid466a542020-01-22 15:37:29 +0000269 case DataType::QSymmS8:
Teresa Charlina68d8532019-11-29 13:59:18 +0000270 weightPermuted = ReorderWeightChannelsForAcl<int8_t>(weightPermuted, dataLayout, permuteBuffer);
271 break;
Kevin May665a964a2019-08-21 16:53:50 +0100272 default:
273 break;
274 }
275 }
276
Matteo Martincigh747ef822018-12-18 09:26:39 +0000277 // 2. Reshape the weights
278 ReshapeWeightsForAcl(weightPermuted.GetInfo(), dataLayout);
279
280 // 3. Return both the tensor and the allocated storage to ensure that the data stays alive
281 return weightPermuted;
282}
283
Francis Murtaghec33a912019-11-05 14:26:23 +0000284int32_t ConvertMaskToACLFormat(int32_t mask, int32_t numDim)
285{
286 int32_t reversedMask = 0;
Matthew Sloyan171214c2020-09-09 09:07:37 +0100287 for (unsigned int i = 0; i < armnn::numeric_cast<unsigned int>(numDim); ++i)
Francis Murtaghec33a912019-11-05 14:26:23 +0000288 {
289 // Check if bit set in mask for each dimension
290 int32_t bit = (mask & 1 << i) != 0;
291 // Increment the new mask with the bits reversed
Matthew Sloyan171214c2020-09-09 09:07:37 +0100292 reversedMask += (bit << std::max(numDim-(armnn::numeric_cast<int>(i)+1), 0));
Francis Murtaghec33a912019-11-05 14:26:23 +0000293 }
294
295 return reversedMask;
296}
297
Teresa Charlinb2d3ec52022-04-12 22:07:09 +0100298std::map<std::string, unsigned int> CalculateGatherNdKeyIndices(TensorInfo inputInfo0, TensorInfo inputInfo1)
299{
300 std::vector<unsigned int> paramsShape;
301 for (unsigned int i = 0; i < inputInfo0.GetNumDimensions(); ++i)
302 {
303 paramsShape.push_back(inputInfo0.GetShape()[i]);
304 }
305
306 std::vector<unsigned int> indicesShape;
307 for (unsigned int i = 0; i < inputInfo1.GetNumDimensions(); ++i)
308 {
309 indicesShape.push_back(inputInfo1.GetShape()[i]);
310 }
311
312 std::map<std::string, unsigned int> keyIndices;
313
314 // N: number of batches
315 keyIndices["N"] = 1;
316
317 // ND: number of dimensions that are sliced from params
318 keyIndices["ND"] = indicesShape.back();
319
320 // W: number of indices in each batch (all but the last dimension)
321 keyIndices["W"] =
322 static_cast<unsigned int>(std::accumulate(std::begin(indicesShape),
323 std::end(indicesShape) - 1,
324 1,
325 std::multiplies<>() ));
326 // K: range of each index
327 keyIndices["K"] =
328 static_cast<unsigned int>(std::accumulate(std::begin(paramsShape),
329 std::begin(paramsShape) + static_cast<int>(keyIndices["ND"]),
330 1,
331 std::multiplies<>() ));
332 // C: number of channels for each index
333 keyIndices["C"] =
334 static_cast<unsigned int>(std::accumulate(std::begin(paramsShape) + static_cast<int>(keyIndices["ND"]),
335 std::end(paramsShape),
336 1,
337 std::multiplies<>() ));
338
339 return keyIndices;
340}
341
Matteo Martincigh747ef822018-12-18 09:26:39 +0000342} // namespace armnn