ArmNN
 23.02
TensorUtils.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 
11 
12 #include <fmt/format.h>
13 
14 using namespace armnn;
15 
16 namespace armnnUtils
17 {
18 
19 TensorShape GetTensorShape(unsigned int numberOfBatches,
20  unsigned int numberOfChannels,
21  unsigned int height,
22  unsigned int width,
23  const DataLayout dataLayout)
24 {
25  switch (dataLayout)
26  {
27  case DataLayout::NCHW:
28  return TensorShape({numberOfBatches, numberOfChannels, height, width});
29  case DataLayout::NHWC:
30  return TensorShape({numberOfBatches, height, width, numberOfChannels});
31  default:
32  throw InvalidArgumentException("Unknown data layout ["
33  + std::to_string(static_cast<int>(dataLayout)) +
34  "]", CHECK_LOCATION());
35  }
36 }
37 
38 TensorInfo GetTensorInfo(unsigned int numberOfBatches,
39  unsigned int numberOfChannels,
40  unsigned int height,
41  unsigned int width,
42  const DataLayout dataLayout,
43  const DataType dataType)
44 {
45  switch (dataLayout)
46  {
47  case DataLayout::NCHW:
48  return TensorInfo({numberOfBatches, numberOfChannels, height, width}, dataType);
49  case DataLayout::NHWC:
50  return TensorInfo({numberOfBatches, height, width, numberOfChannels}, dataType);
51  default:
52  throw InvalidArgumentException("Unknown data layout ["
53  + std::to_string(static_cast<int>(dataLayout)) +
54  "]", CHECK_LOCATION());
55  }
56 }
57 
58 TensorInfo GetTensorInfo(unsigned int numberOfBatches,
59  unsigned int numberOfChannels,
60  unsigned int depth,
61  unsigned int height,
62  unsigned int width,
63  const DataLayout dataLayout,
64  const DataType dataType)
65 {
66  switch (dataLayout)
67  {
68  case DataLayout::NDHWC:
69  return TensorInfo({numberOfBatches, depth, height, width, numberOfChannels}, dataType);
70  case DataLayout::NCDHW:
71  return TensorInfo({numberOfBatches, numberOfChannels, depth, height, width}, dataType);
72  default:
73  throw InvalidArgumentException("Unknown data layout ["
74  + std::to_string(static_cast<int>(dataLayout)) +
75  "]", CHECK_LOCATION());
76  }
77 }
78 
79 std::pair<float, float> FindMinMax(ITensorHandle* tensorHandle)
80 {
81  auto tensor_data = static_cast<const float *>(tensorHandle->Map(true));
82  auto tensor_size = tensorHandle->GetShape().GetNumElements();
83 
84  // Set min/max initially to first value in tensor
85  float min = tensor_data[0];
86  float max = tensor_data[0];
87 
88  // Loop over rest of tensor and update min/max if necessary
89  for (unsigned int val = 1; val < tensor_size; val++)
90  {
91  if (tensor_data[val] < min)
92  {
93  min = tensor_data[val];
94  }
95  else if (tensor_data[val] > max)
96  {
97  max = tensor_data[val];
98  }
99  }
100 
101  tensorHandle->Unmap();
102 
103  return std::make_pair(min, max);
104 }
105 
106 TensorShape ReduceDims(const TensorShape& tensorShape, unsigned int dimensions)
107 {
108  if (tensorShape.GetNumDimensions() <= dimensions)
109  {
110  return tensorShape;
111  }
112  std::vector<unsigned int> newShape;
113 
114  unsigned int dimsToSkip = tensorShape.GetNumDimensions() - dimensions;
115  unsigned int dimsSkipped = 0;
116  bool insertRemainder = false;
117 
118  for (unsigned int i = 0; i < tensorShape.GetNumDimensions(); ++i)
119  {
120  if (tensorShape[i] == 1 && dimsSkipped < dimsToSkip && !insertRemainder)
121  {
122  ++dimsSkipped;
123  continue;
124  }
125  newShape.push_back(tensorShape[i]);
126  // Once we insert the first dimension we can't skip any more
127  insertRemainder = true;
128  }
129  return TensorShape(static_cast<unsigned int>(newShape.size()), newShape.data());
130 }
131 
132 TensorInfo ReduceDims(const TensorInfo& tensorInfo, unsigned int dimensions)
133 {
134  TensorInfo strippedTensor(tensorInfo);
135  TensorShape strippedShape = ReduceDims(tensorInfo.GetShape(), dimensions);
136  strippedTensor.SetShape(strippedShape);
137  return strippedTensor;
138 }
139 
140 TensorShape ExpandDims(const TensorShape& tensorShape, int axis)
141 {
142  unsigned int outputDim = tensorShape.GetNumDimensions() + 1;
143 
144  if (axis < -armnn::numeric_cast<int>(outputDim) || axis > armnn::numeric_cast<int>(tensorShape.GetNumDimensions()))
145  {
146  throw InvalidArgumentException(fmt::format("Invalid expansion axis {} for {}D input tensor. {}",
147  axis,
148  tensorShape.GetNumDimensions(),
149  CHECK_LOCATION().AsString()));
150  }
151 
152  if (axis < 0)
153  {
154  axis = armnn::numeric_cast<int>(outputDim) + axis;
155  }
156 
157  std::vector<unsigned int> outputShape;
158  outputShape.reserve(tensorShape.GetNumDimensions());
159  for (unsigned int i = 0; i < tensorShape.GetNumDimensions(); ++i)
160  {
161  outputShape.push_back(tensorShape[i]);
162  }
163  outputShape.insert(outputShape.begin() + axis, 1);
164 
165  return { outputDim, outputShape.data() };
166 }
167 
168 std::vector<unsigned int> SqueezeDims(const TensorShape& tensorShape)
169 {
170  std::vector<unsigned int> squeezedDims;
171 
172  for (unsigned int i = 0; i < tensorShape.GetNumDimensions(); ++i)
173  {
174  if (tensorShape[i] != 1)
175  {
176  squeezedDims.push_back(tensorShape[i]);
177  }
178  }
179  return squeezedDims;
180 }
181 
182 unsigned int GetNumElementsBetween(const TensorShape& shape,
183  const unsigned int firstAxisInclusive,
184  const unsigned int lastAxisExclusive)
185 {
186  ARMNN_ASSERT(firstAxisInclusive <= lastAxisExclusive);
187  ARMNN_ASSERT(lastAxisExclusive <= shape.GetNumDimensions());
188  unsigned int count = 1;
189  for (unsigned int i = firstAxisInclusive; i < lastAxisExclusive; i++)
190  {
191  count *= shape[i];
192  }
193  return count;
194 }
195 
196 unsigned int GetUnsignedAxis(const unsigned int inputDimension, const int axis)
197 {
198  ARMNN_ASSERT_MSG(axis < armnn::numeric_cast<int>(inputDimension),
199  "Required axis index greater than number of dimensions.");
200  ARMNN_ASSERT_MSG(axis >= -armnn::numeric_cast<int>(inputDimension),
201  "Required axis index lower than negative of the number of dimensions");
202 
203  unsigned int uAxis = axis < 0 ?
204  inputDimension - armnn::numeric_cast<unsigned int>(abs(axis))
205  : armnn::numeric_cast<unsigned int>(axis);
206  return uAxis;
207 }
208 
209 unsigned int GetNumElementsAfter(const armnn::TensorShape& shape, unsigned int axis)
210 {
211  unsigned int numDim = shape.GetNumDimensions();
212  ARMNN_ASSERT(axis <= numDim - 1);
213  unsigned int count = 1;
214  for (unsigned int i = axis+1; i < numDim; i++)
215  {
216  count *= shape[i];
217  }
218  return count;
219 }
220 
221 std::pair<unsigned int, std::vector<float>> GetPerAxisParams(const armnn::TensorInfo& info)
222 {
223  const std::vector<float>& scales = info.GetQuantizationScales();
224  armnn::Optional<unsigned int> quantizationDim = info.GetQuantizationDim();
225  if (!info.HasPerAxisQuantization())
226  {
228  std::string("Per-axis quantization params not set for tensor of type ") +
229  armnn::GetDataTypeName(info.GetDataType()), CHECK_LOCATION());
230  }
231  unsigned int axisFactor = GetNumElementsAfter(info.GetShape(), quantizationDim.value()) ;
232 
233  return { axisFactor, scales };
234 }
235 
236 template<typename PrimitiveType>
237 void CheckSizes(const std::vector<PrimitiveType>& data, const armnn::TensorInfo& tensorInfo, unsigned int size = 1)
238 {
239  if (data.size() / size != tensorInfo.GetNumElements())
240  {
242  fmt::format("The data does not contain the expected number of elements {} != {}. {}",
243  data.size(), tensorInfo.GetNumElements(), CHECK_LOCATION().AsString()));
244  }
245 }
246 
247 template<typename PrimitiveType>
248 std::unique_ptr<float[]> ToFloatArray(const std::vector<PrimitiveType>& data, const armnn::TensorInfo& tensorInfo)
249 {
250  CheckSizes(data, tensorInfo);
251 
252  std::unique_ptr<float[]> returnBuffer(new float[tensorInfo.GetNumElements()]);
253 
254  if (tensorInfo.HasPerAxisQuantization())
255  {
256  unsigned int axis = tensorInfo.GetQuantizationDim().value();
257  auto axisDimensionality = tensorInfo.GetShape()[axis];
258  auto axisFactor = armnnUtils::GetNumElementsAfter(tensorInfo.GetShape(), axis);
259 
260  for (unsigned int i = 0; i < tensorInfo.GetNumElements(); ++i)
261  {
262  unsigned int axisIndex;
263 
264  if (i < axisFactor)
265  {
266  axisIndex = 0;
267  }
268  else
269  {
270  axisIndex = (i / axisFactor) % axisDimensionality;
271  }
272  returnBuffer[i] = Dequantize<PrimitiveType>(data[i],
273  tensorInfo.GetQuantizationScales()[axisIndex],
274  tensorInfo.GetQuantizationOffset());
275  }
276  }
277  else
278  {
279  for (unsigned int i = 0; i < tensorInfo.GetNumElements(); ++i)
280  {
281  returnBuffer[i] = Dequantize<PrimitiveType>(data[i],
282  tensorInfo.GetQuantizationScale(),
283  tensorInfo.GetQuantizationOffset());
284  }
285  }
286  return returnBuffer;
287 }
288 
289 std::unique_ptr<float[]> ToFloatArray(const std::vector<uint8_t>& data, const armnn::TensorInfo& tensorInfo)
290 {
291  if (tensorInfo.GetDataType() == DataType::QAsymmS8 || tensorInfo.GetDataType() == DataType::QSymmS8)
292  {
293  CheckSizes(data, tensorInfo);
294  std::vector<int8_t> buffer(tensorInfo.GetNumElements());
295  ::memcpy(buffer.data(), data.data(), data.size());
296  return ToFloatArray<int8_t>(buffer, tensorInfo);
297  }
298  else if (tensorInfo.GetDataType() == DataType::QAsymmU8)
299  {
300  CheckSizes(data, tensorInfo);
301  return ToFloatArray<uint8_t>(data, tensorInfo);
302  }
303  else if (tensorInfo.GetDataType() == DataType::Signed32)
304  {
305  CheckSizes(data, tensorInfo, 4);
306  std::vector<int32_t> buffer(tensorInfo.GetNumElements());
307  ::memcpy(buffer.data(), data.data(), data.size());
308  return ToFloatArray<int32_t>(buffer, tensorInfo);
309  }
310  else if (tensorInfo.GetDataType() == DataType::Signed64)
311  {
312  CheckSizes(data, tensorInfo, 8);
313  std::vector<int64_t> buffer(tensorInfo.GetNumElements());
314  ::memcpy(buffer.data(), data.data(), data.size());
315  return ToFloatArray<int64_t>(buffer, tensorInfo);
316  }
318  fmt::format("Unsupported datatype {}. {}",
319  GetDataTypeName(tensorInfo.GetDataType()),
320  CHECK_LOCATION().AsString()));
321 }
322 
323 } // namespace armnnUtils
armnn::GetTensorInfo
const TensorInfo & GetTensorInfo(const ITensorHandle *tensorHandle)
float32 helpers
Definition: RefWorkloadUtils.hpp:27
armnnUtils::ExpandDims
armnn::TensorShape ExpandDims(const armnn::TensorShape &tensorShape, int axis)
Definition: TensorUtils.cpp:140
armnn::TensorInfo::GetQuantizationOffset
int32_t GetQuantizationOffset() const
Definition: Tensor.cpp:478
armnn::TensorInfo::GetQuantizationScale
float GetQuantizationScale() const
Definition: Tensor.cpp:461
armnn::DataType::QAsymmU8
@ QAsymmU8
armnn::DataLayout
DataLayout
Definition: Types.hpp:62
armnnUtils::FindMinMax
std::pair< float, float > FindMinMax(armnn::ITensorHandle *tensorHandle)
Definition: TensorUtils.cpp:79
armnnUtils::GetTensorShape
armnn::TensorShape GetTensorShape(unsigned int numberOfBatches, unsigned int numberOfChannels, unsigned int height, unsigned int width, const armnn::DataLayout dataLayout)
Definition: TensorUtils.cpp:19
CHECK_LOCATION
#define CHECK_LOCATION()
Definition: Exceptions.hpp:203
armnnUtils::CheckSizes
void CheckSizes(const std::vector< PrimitiveType > &data, const armnn::TensorInfo &tensorInfo, unsigned int size=1)
Definition: TensorUtils.cpp:237
armnn::TensorShape::GetNumElements
unsigned int GetNumElements() const
Function that calculates the tensor elements by multiplying all dimension size which are Specified.
Definition: Tensor.cpp:181
armnn::ITensorHandle::GetShape
virtual TensorShape GetShape() const =0
Get the number of elements for each dimension ordered from slowest iterating dimension to fastest ite...
armnnUtils::ToFloatArray
std::unique_ptr< float[]> ToFloatArray(const std::vector< PrimitiveType > &data, const armnn::TensorInfo &tensorInfo)
Definition: TensorUtils.cpp:248
TensorUtils.hpp
armnn::DataType::Signed32
@ Signed32
Assert.hpp
armnn::DataType::QAsymmS8
@ QAsymmS8
armnn
Copyright (c) 2021 ARM Limited and Contributors.
Definition: 01_00_quick_start.dox:6
armnn::OptionalReferenceSwitch::value
const T & value() const
Definition: Optional.hpp:146
armnn::ITensorHandle
Definition: ITensorHandle.hpp:15
armnnUtils
Definition: CompatibleTypes.hpp:10
armnnUtils::GetNumElementsAfter
unsigned int GetNumElementsAfter(const armnn::TensorShape &shape, unsigned int axis)
Definition: TensorUtils.cpp:209
armnn::TensorShape
Definition: Tensor.hpp:20
armnn::ITensorHandle::Map
virtual const void * Map(bool blocking=true) const =0
Map the tensor data for access.
armnn::DataLayout::NCHW
@ NCHW
armnn::DataLayout::NCDHW
@ NCDHW
armnn::TensorInfo::GetNumElements
unsigned int GetNumElements() const
Definition: Tensor.hpp:196
armnn::TensorInfo
Definition: Tensor.hpp:152
armnn::DataType::Signed64
@ Signed64
armnnUtils::SqueezeDims
std::vector< unsigned int > SqueezeDims(const armnn::TensorShape &tensorShape)
Definition: TensorUtils.cpp:168
armnn::TensorInfo::HasPerAxisQuantization
bool HasPerAxisQuantization() const
Definition: Tensor.cpp:446
armnnUtils::ReduceDims
armnn::TensorShape ReduceDims(const armnn::TensorShape &tensorInfo, unsigned int dimensions)
Definition: TensorUtils.cpp:106
armnnUtils::GetNumElementsBetween
unsigned int GetNumElementsBetween(const armnn::TensorShape &shape, unsigned int firstAxisInclusive, unsigned int lastAxisExclusive)
Definition: TensorUtils.cpp:182
armnn::TensorInfo::GetShape
const TensorShape & GetShape() const
Definition: Tensor.hpp:191
armnn::DataLayout::NHWC
@ NHWC
ARMNN_ASSERT_MSG
#define ARMNN_ASSERT_MSG(COND, MSG)
Definition: Assert.hpp:15
armnn::abs
Definition: Abs.hpp:13
armnn::TensorShape::GetNumDimensions
unsigned int GetNumDimensions() const
Function that returns the tensor rank.
Definition: Tensor.cpp:174
armnn::DataType
DataType
Definition: Types.hpp:48
armnn::TensorInfo::GetQuantizationDim
Optional< unsigned int > GetQuantizationDim() const
Definition: Tensor.cpp:494
ARMNN_ASSERT
#define ARMNN_ASSERT(COND)
Definition: Assert.hpp:14
ITensorHandle.hpp
armnn::Optional< unsigned int >
armnn::DataType::QSymmS8
@ QSymmS8
armnnUtils::GetPerAxisParams
std::pair< unsigned int, std::vector< float > > GetPerAxisParams(const armnn::TensorInfo &info)
Definition: TensorUtils.cpp:221
NumericCast.hpp
armnn::TensorInfo::SetShape
void SetShape(const TensorShape &newShape)
Definition: Tensor.hpp:193
armnn::TensorInfo::GetQuantizationScales
std::vector< float > GetQuantizationScales() const
Definition: Tensor.cpp:451
armnn::DataLayout::NDHWC
@ NDHWC
armnn::GetDataTypeName
constexpr const char * GetDataTypeName(DataType dataType)
Definition: TypesUtils.hpp:206
armnn::InvalidArgumentException
Definition: Exceptions.hpp:80
armnn::ITensorHandle::Unmap
virtual void Unmap() const =0
Unmap the tensor data.
armnn::TensorInfo::GetDataType
DataType GetDataType() const
Definition: Tensor.hpp:198
armnn::BoostLogSeverityMapping::info
@ info
armnnUtils::GetUnsignedAxis
unsigned int GetUnsignedAxis(const unsigned int inputDimension, const int axis)
Definition: TensorUtils.cpp:196