ArmNN
 24.02
WorkloadUtils.cpp
Go to the documentation of this file.
1 //
2 // Copyright © 2017-2023 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 
7 
8 #include <armnn/Utils.hpp>
11 
12 #include <fmt/format.h>
13 #include <numeric>
14 
15 namespace armnn
16 {
17 
19  const PermutationVector& permutationVector, void* permuteBuffer)
20 {
21  if (tensor == nullptr)
22  {
23  throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null input tensor pointer");
24  }
25  if (permuteBuffer == nullptr)
26  {
27  throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null permute buffer pointer");
28  }
29 
30  TensorInfo tensorInfo = tensor->GetTensorInfo();
31 
32  if (permutationVector.GetSize() > 0)
33  {
34  tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector);
35  armnnUtils::Permute(tensorInfo.GetShape(), permutationVector,
36  tensor->GetConstTensor<void>(), permuteBuffer,
37  GetDataTypeSize(tensorInfo.GetDataType()));
38  }
39  else
40  {
41  ::memcpy(permuteBuffer, tensor->GetConstTensor<void>(), tensorInfo.GetNumBytes());
42  }
43  tensorInfo.SetConstant(true);
44  return ConstTensor(tensorInfo, permuteBuffer);
45 }
46 
47 void ReshapeWeightsForAcl(TensorInfo& weightInfo, DataLayout dataLayout)
48 {
49  // Reshape the weights in-place
50  const TensorShape& weightShape = weightInfo.GetShape();
51  switch (dataLayout)
52  {
53  case DataLayout::NHWC:
54  // The data layout is NHWC, reshape from [ H, W, I, M ] to [ 1, H, W, I * M ]
55  weightInfo.SetShape({ 1,
56  weightShape[0],
57  weightShape[1],
58  weightShape[2] * weightShape[3] });
59  weightInfo.SetShape({ 1,
60  weightShape[0] * weightShape[1],
61  weightShape[2],
62  weightShape[3] });
63  break;
64  case DataLayout::NCHW:
65  default:
66  // The data layout is NCHW, reshape from [ M, I, H, W ] to [ 1, I * M, H, W, ]
67  weightInfo.SetShape({ 1, weightShape[0] * weightShape[1], weightShape[2], weightShape[3] });
68  break;
69  }
70 }
71 
72 template <typename DataType>
73 ConstTensor ReorderWeightChannelsForAcl(const ConstTensor& weightHandle, DataLayout dataLayout, void* permuteBuffer)
74 {
75  DataType* weight = static_cast<DataType*>(permuteBuffer);
76  const TensorShape& weightShape = weightHandle.GetShape();
77  unsigned int multiplier;
78  unsigned int height;
79  unsigned int width;
80  unsigned int inputChannels;
81  switch (dataLayout)
82  {
83  case DataLayout::NHWC: //It actually is [ H, W, I, M ]
84  height = weightShape[0];
85  width = weightShape[1];
86  inputChannels = weightShape[2];
87  multiplier = weightShape[3];
88  break;
89  case DataLayout::NCHW: //It actually is [ M, I, H, W ]
90  default:
91  height = weightShape[2];
92  width = weightShape[3];
93  inputChannels = weightShape[1];
94  multiplier = weightShape[0];
95  break;
96  }
97 
98  std::vector<DataType> weightAclOrder(height*width*inputChannels*multiplier);
99  unsigned int destinationWeightsChannel;
100  unsigned int totalChannels = inputChannels * multiplier;
101  unsigned int channelSize = height * width;
102  unsigned int inputChannel = 0;
103 
104  for (unsigned int originWeightsChannel = 0; originWeightsChannel < totalChannels; originWeightsChannel++)
105  {
106  inputChannel = originWeightsChannel % inputChannels;
107  destinationWeightsChannel = (originWeightsChannel - inputChannel) / inputChannels + multiplier * inputChannel;
108 
109  for (unsigned int i = 0; i < channelSize; i++)
110  {
111  weightAclOrder[i + destinationWeightsChannel * channelSize] =
112  weight[i + originWeightsChannel * channelSize];
113  }
114  }
115 
116  ::memcpy(permuteBuffer, weightAclOrder.data(), weightHandle.GetInfo().GetNumBytes());
117  return ConstTensor(weightHandle.GetInfo(), permuteBuffer);
118 }
119 
120 
122 {
123  // Convert the weight format from ArmNN's [ M, I, H, W ] (does NOT depend on the data layout) to either
124  // [ 1, H, W, I * M ] (if NHWC) or [ 1, I * M, H, W ] (if NCHW), as required by the compute library
125 
126  // 1. Permute the weights if necessary
127  // If the data layout is NCHW no permutation is necessary, as a reshape to [ 1, I * M, H, W ] can be better done
128  // starting from the current shape of [ M, I, H, W ]
129  TensorInfo weightPermutedInfo(weightInfo);
130  if (dataLayout == DataLayout::NHWC)
131  {
132  // The data layout is NHWC, then permute the weights from [ M, I, H, W ] to [ H, W, I, M ]
133  PermutationVector permutationVector{ 3, 2, 0, 1 };
134  weightPermutedInfo = armnnUtils::Permuted(weightInfo, permutationVector);
135  }
136 
137  // 2. Reshape the weights
138  ReshapeWeightsForAcl(weightPermutedInfo, dataLayout);
139 
140  // 3. Return the permuted weight info
141  return weightPermutedInfo;
142 }
143 
144 
145 std::tuple<ConstTensor, unsigned int> Convert1HWOTensorToAcl(const ConstTensorHandle* weightTensor,
146  const TensorInfo& inputInfo,
147  const DataLayout dataLayout,
148  void* permuteBuffer)
149 {
150  TensorInfo weightsInfo = weightTensor->GetTensorInfo();
151  unsigned int depthMultiplier = 1;
152  PermutationVector permutationVector{};
153  if (dataLayout == armnn::DataLayout::NHWC)
154  {
155  // No permutation required. Data layouts are the same.
156 
157  depthMultiplier = weightsInfo.GetShape()[3] / inputInfo.GetShape()[3];
158  }
159  else if (dataLayout == armnn::DataLayout::NCHW)
160  {
161  // [ 1, H, W, I*M] --> [ 1, I * M, H, W ]
162  depthMultiplier = weightsInfo.GetShape()[3] / inputInfo.GetShape()[1];
163  permutationVector = { 0, 2, 3, 1 };
164  }
165  else
166  {
167  throw InvalidArgumentException(fmt::format("Unknown data layout for tensor conversion: {}",
168  GetDataLayoutName(dataLayout)));
169  }
170 
171  ConstTensor weightsPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
172 
173  return std::make_tuple(weightsPermuted, depthMultiplier);
174 }
175 
176 std::tuple<TensorInfo, unsigned int> Convert1HWOTensorInfoToAcl(const TensorInfo& weightInfo,
177  const TensorInfo& inputInfo,
178  const DataLayout dataLayout)
179 {
180  unsigned int aclDepthMultiplier = 1;
181  TensorInfo weightsPermuted;
182  if (dataLayout == armnn::DataLayout::NHWC)
183  {
184  // No permutation required. Input and weights data layouts are the same.
185  aclDepthMultiplier = weightInfo.GetShape()[3] / inputInfo.GetShape()[3];
186  weightsPermuted = weightInfo;
187  }
188 
189  else if (dataLayout == armnn::DataLayout::NCHW)
190  {
191  // Weights permutation required. Weights [N,H,W,C] and input [N,C,H,W] data layouts are different.
192  // [ 1, H, W, I*M] --> [ 1, I * M, H, W ]
193  aclDepthMultiplier = weightInfo.GetShape()[3] / inputInfo.GetShape()[1];
194  PermutationVector permutationVector{ 0, 2, 3, 1 };
195  weightsPermuted = armnnUtils::Permuted(weightInfo, permutationVector);
196  }
197  else
198  {
199  throw InvalidArgumentException(fmt::format("Unknown data layout for tensor info conversion: {}",
200  GetDataLayoutName(dataLayout)));
201  }
202 
203  return std::make_tuple(weightsPermuted, aclDepthMultiplier);
204 }
205 
206 
207 std::tuple<ConstTensor, unsigned int> Convert1HWOtoMIHW(const ConstTensorHandle* weightTensor,
208  const TensorInfo& inputInfo,
209  const DataLayout& dataLayout,
210  void* permuteBuffer)
211 {
212  TensorInfo weightsInfo = weightTensor->GetTensorInfo();
213 
214  if (weightsInfo.HasPerAxisQuantization())
215  {
216  throw InvalidArgumentException("Can't convert tensor from [1,H,W,Cout] to [M,Cin,H,W] when per channel "
217  "quantization is applied.");
218  }
219 
220  // Reshape weights [ 1, H, W, I*M ] --> [ H, W, I, M ]
221  auto weightsShape = weightsInfo.GetShape();
222  auto channelIndex = armnnUtils::DataLayoutIndexed(dataLayout).GetChannelsIndex();
223  unsigned int depthMultiplier = weightsShape[3] / inputInfo.GetShape()[channelIndex];
224  weightsInfo.SetShape({ weightsShape[1],
225  weightsShape[2],
226  inputInfo.GetShape()[channelIndex],
227  depthMultiplier});
228 
229  // Permute [ H, W, I, M ] --> [ M, I, H, W ]
230  PermutationVector permutationVector = { 2, 3, 1, 0 };
231  ConstTensor weightsPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
232 
233  return std::make_tuple(weightsPermuted, depthMultiplier);
234 }
235 
237  DataLayout dataLayout,
238  void* permuteBuffer)
239 {
240  if (weightTensor == nullptr)
241  {
242  throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null input tensor pointer");
243  }
244  if (permuteBuffer == nullptr)
245  {
246  throw armnn::InvalidArgumentException("WorkloadUtils: PermuteTensor: Null permute buffer pointer");
247  }
248 
249  auto multiplier = weightTensor->GetTensorInfo().GetShape()[0];
250  auto inputChannels = weightTensor->GetTensorInfo().GetShape()[1];
251 
252  // Convert the weight format from ArmNN's [ M, I, H, W ] (does NOT depend on the data layout) to either
253  // [ 1, H, W, I * M ] (if NHWC) or [ 1, I * M, H, W ] (if NCHW), as required by the compute library
254 
255  // 1. Permute the weights if necessary
256  // If the data layout is NCHW no permutation is necessary, as a reshape to [ 1, I * M, H, W ] can be better done
257  // starting from the current shape of [ M, I, H, W ]
258  // If no permutation is necessary, leave the permutation vector empty
259  PermutationVector permutationVector{};
260  if (dataLayout == DataLayout::NHWC)
261  {
262  // The data layout is NHWC, then permute the weights from [ M, I, H, W ] to [ H, W, I, M ]
263  permutationVector = { 3, 2, 0, 1 };
264  }
265  ConstTensor weightPermuted = PermuteTensor(weightTensor, permutationVector, permuteBuffer);
266 
267  // Shuffle the weights data to obtain the channel order needed used by Acl
268  if (multiplier > 1 && inputChannels > 1 && dataLayout == DataLayout::NCHW)
269  {
270  switch (weightPermuted.GetDataType())
271  {
272  case DataType::Float32:
273  weightPermuted = ReorderWeightChannelsForAcl<float>(weightPermuted, dataLayout, permuteBuffer);
274  break;
275  case DataType::Float16:
276  weightPermuted =
277  ReorderWeightChannelsForAcl<half_float::half>(weightPermuted, dataLayout, permuteBuffer);
278  break;
279  case DataType::QAsymmS8:
280  case DataType::QAsymmU8:
281  weightPermuted = ReorderWeightChannelsForAcl<uint8_t>(weightPermuted, dataLayout, permuteBuffer);
282  break;
283  case DataType::QSymmS8:
284  weightPermuted = ReorderWeightChannelsForAcl<int8_t>(weightPermuted, dataLayout, permuteBuffer);
285  break;
286  default:
287  break;
288  }
289  }
290 
291  // 2. Reshape the weights
292  ReshapeWeightsForAcl(weightPermuted.GetInfo(), dataLayout);
293 
294  // 3. Return both the tensor and the allocated storage to ensure that the data stays alive
295  return weightPermuted;
296 }
297 
298 int32_t ConvertMaskToACLFormat(int32_t mask, int32_t numDim)
299 {
300  int32_t reversedMask = 0;
301  for (unsigned int i = 0; i < armnn::numeric_cast<unsigned int>(numDim); ++i)
302  {
303  // Check if bit set in mask for each dimension
304  int32_t bit = (mask & 1 << i) != 0;
305  // Increment the new mask with the bits reversed
306  reversedMask += (bit << std::max(numDim-(armnn::numeric_cast<int>(i)+1), 0));
307  }
308 
309  return reversedMask;
310 }
311 
312 std::map<std::string, unsigned int> CalculateGatherNdKeyIndices(TensorInfo inputInfo0, TensorInfo inputInfo1)
313 {
314  std::vector<unsigned int> paramsShape;
315  for (unsigned int i = 0; i < inputInfo0.GetNumDimensions(); ++i)
316  {
317  paramsShape.push_back(inputInfo0.GetShape()[i]);
318  }
319 
320  std::vector<unsigned int> indicesShape;
321  for (unsigned int i = 0; i < inputInfo1.GetNumDimensions(); ++i)
322  {
323  indicesShape.push_back(inputInfo1.GetShape()[i]);
324  }
325 
326  std::map<std::string, unsigned int> keyIndices;
327 
328  // N: number of batches
329  keyIndices["N"] = 1;
330 
331  // ND: number of dimensions that are sliced from params
332  keyIndices["ND"] = indicesShape.back();
333 
334  // W: number of indices in each batch (all but the last dimension)
335  keyIndices["W"] =
336  static_cast<unsigned int>(std::accumulate(std::begin(indicesShape),
337  std::end(indicesShape) - 1,
338  1,
339  std::multiplies<>() ));
340  // K: range of each index
341  keyIndices["K"] =
342  static_cast<unsigned int>(std::accumulate(std::begin(paramsShape),
343  std::begin(paramsShape) + static_cast<int>(keyIndices["ND"]),
344  1,
345  std::multiplies<>() ));
346  // C: number of channels for each index
347  keyIndices["C"] =
348  static_cast<unsigned int>(std::accumulate(std::begin(paramsShape) + static_cast<int>(keyIndices["ND"]),
349  std::end(paramsShape),
350  1,
351  std::multiplies<>() ));
352 
353  return keyIndices;
354 }
355 
357 {
358  armnn::PermutationVector permutationVector{};
359  switch (rank)
360  {
361  case 2:
362  permutationVector = {1U, 0U};
363  break;
364  case 3:
365  permutationVector = {0U, 2U, 1U};
366  break;
367  case 4:
368  permutationVector = {0U, 1U, 3U, 2U};
369  break;
370  default:
371  throw Exception("Invalid number of dimensions.");
372  }
373  return permutationVector;
374 }
375 
376 } // namespace armnn
armnn::Convert1HWOTensorInfoToAcl
std::tuple< TensorInfo, unsigned int > Convert1HWOTensorInfoToAcl(const TensorInfo &weightInfo, const TensorInfo &inputInfo, const DataLayout dataLayout)
Weights for depthwise have a datalayout of [1,H,W,O] = [1,H,W,I*M] This function coverts a TensorInfo...
Definition: WorkloadUtils.cpp:176
armnn::Convert1HWOTensorToAcl
std::tuple< ConstTensor, unsigned int > Convert1HWOTensorToAcl(const ConstTensorHandle *weightTensor, const TensorInfo &inputInfo, const DataLayout dataLayout, void *permuteBuffer)
Weights for depthwise have a datalayout of [1,H,W,O] = [1,H,W,I*M] This function coverts a ConstCpuTe...
Definition: WorkloadUtils.cpp:145
armnn::TensorInfo::GetNumBytes
unsigned int GetNumBytes() const
Definition: Tensor.cpp:427
armnn::DataLayout
DataLayout
Definition: Types.hpp:62
WorkloadUtils.hpp
armnn::DataLayout::NHWC
@ NHWC
armnn::ConstTensorHandle
Definition: TensorHandle.hpp:24
armnn::TensorInfo
Definition: Tensor.hpp:152
armnn::PermuteTensor
armnn::ConstTensor PermuteTensor(const ConstTensorHandle *tensor, const PermutationVector &permutationVector, void *permuteBuffer)
Definition: WorkloadUtils.cpp:18
armnn::TensorInfo::GetNumDimensions
unsigned int GetNumDimensions() const
Definition: Tensor.hpp:197
armnnUtils::DataLayoutIndexed
Provides access to the appropriate indexes for Channels, Height and Width based on DataLayout.
Definition: DataLayoutIndexed.hpp:17
armnn::DataType::Float32
@ Float32
armnn::GetDataLayoutName
constexpr const char * GetDataLayoutName(DataLayout dataLayout)
Definition: TypesUtils.hpp:253
armnn::DataType::QAsymmU8
@ QAsymmU8
armnn::ConstTensorHandle::GetTensorInfo
const TensorInfo & GetTensorInfo() const
Definition: TensorHandle.hpp:40
armnn::DataType::QSymmS8
@ QSymmS8
armnnUtils::Permute
void Permute(const armnn::TensorShape &dstShape, const armnn::PermutationVector &mappings, const void *src, void *dst, size_t dataTypeSize)
Definition: Permute.cpp:164
armnnUtils::Permuted
armnn::TensorShape Permuted(const armnn::TensorShape &srcShape, const armnn::PermutationVector &mappings)
Definition: Permute.cpp:125
armnn::TensorInfo::HasPerAxisQuantization
bool HasPerAxisQuantization() const
Definition: Tensor.cpp:446
NumericCast.hpp
armnn::BaseTensor::GetDataType
DataType GetDataType() const
Definition: Tensor.hpp:302
armnn::Convert1HWOtoMIHW
std::tuple< ConstTensor, unsigned int > Convert1HWOtoMIHW(const ConstTensorHandle *weightTensor, const TensorInfo &inputInfo, const DataLayout &dataLayout, void *permuteBuffer)
Converts a (weights) tensor from [1, H, W, I*M] = [1, H, W, O] to [M, I, H, W].
Definition: WorkloadUtils.cpp:207
armnn::ConstTensorHandle::GetConstTensor
const T * GetConstTensor() const
Definition: TensorHandle.hpp:28
armnn::TensorShape
Definition: Tensor.hpp:20
armnn::DataType::Float16
@ Float16
armnn::ConvertWeightTensorFromArmnnToAcl
armnn::ConstTensor ConvertWeightTensorFromArmnnToAcl(const ConstTensorHandle *weightTensor, DataLayout dataLayout, void *permuteBuffer)
Definition: WorkloadUtils.cpp:236
Utils.hpp
armnn::CalculateGatherNdKeyIndices
std::map< std::string, unsigned int > CalculateGatherNdKeyIndices(TensorInfo inputInfo0, TensorInfo inputInfo1)
Calculates the key index values needed for GatherNd: N, ND, K, W, C (N is always 1)
Definition: WorkloadUtils.cpp:312
armnn::DataType
DataType
Definition: Types.hpp:48
armnn::InvalidArgumentException
Definition: Exceptions.hpp:80
armnn::GetDataTypeSize
constexpr unsigned int GetDataTypeSize(DataType dataType)
Definition: TypesUtils.hpp:182
armnn::BaseTensor::GetShape
const TensorShape & GetShape() const
Definition: Tensor.hpp:299
armnn::PermutationVector
Definition: Types.hpp:314
armnn::ReorderWeightChannelsForAcl
ConstTensor ReorderWeightChannelsForAcl(const ConstTensor &weightHandle, DataLayout dataLayout, void *permuteBuffer)
Definition: WorkloadUtils.cpp:73
armnn::Exception
Base class for all ArmNN exceptions so that users can filter to just those.
Definition: Exceptions.hpp:46
armnn::BaseTensor::GetInfo
const TensorInfo & GetInfo() const
Definition: Tensor.hpp:297
armnn::TensorInfo::GetDataType
DataType GetDataType() const
Definition: Tensor.hpp:200
armnn::DataType::QAsymmS8
@ QAsymmS8
armnn::ReshapeWeightsForAcl
void ReshapeWeightsForAcl(TensorInfo &weightInfo, DataLayout dataLayout)
Definition: WorkloadUtils.cpp:47
armnn::PermutationVector::GetSize
SizeType GetSize() const
Definition: Types.hpp:357
armnn::TensorInfo::GetShape
const TensorShape & GetShape() const
Definition: Tensor.hpp:193
armnn::GeneratePermutationVectorOnLastTwoDimensions
armnn::PermutationVector GeneratePermutationVectorOnLastTwoDimensions(unsigned int rank)
Generates a permutation vector of size rank that permutes the 2 most right dimensions.
Definition: WorkloadUtils.cpp:356
armnn::ConvertMaskToACLFormat
int32_t ConvertMaskToACLFormat(int32_t mask, int32_t numDim)
Definition: WorkloadUtils.cpp:298
armnn::ConvertWeightTensorInfoFromArmnnToAcl
TensorInfo ConvertWeightTensorInfoFromArmnnToAcl(const TensorInfo &weightInfo, DataLayout dataLayout)
Definition: WorkloadUtils.cpp:121
armnn::TensorInfo::SetShape
void SetShape(const TensorShape &newShape)
Definition: Tensor.hpp:195
armnn
Copyright (c) 2021 ARM Limited and Contributors.
Definition: 01_00_quick_start.dox:6
armnnUtils::DataLayoutIndexed::GetChannelsIndex
unsigned int GetChannelsIndex() const
Definition: DataLayoutIndexed.hpp:23
armnn::ConstTensor
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
Definition: Tensor.hpp:329
armnn::TensorInfo::SetConstant
void SetConstant(const bool IsConstant=true)
Marks the data corresponding to this tensor info as constant.
Definition: Tensor.cpp:514
DataLayoutIndexed.hpp
armnn::DataLayout::NCHW
@ NCHW