MU Library
ndarray.hpp
Go to the documentation of this file.
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright 2024 XCENA Inc.
3 
4 #pragma once
5 
6 #include <algorithm>
7 #include <array>
8 #include <cstddef>
9 #include <cstdint>
10 #include <initializer_list>
11 #include <type_traits>
12 
13 namespace mu
14 {
15 
21 template <typename T>
22 class NDArray
23 {
24 public:
25  static constexpr std::int64_t MAX_DIMS = 10;
26  using ShapeArray = std::array<std::int64_t, MAX_DIMS>;
27  using StridesArray = std::array<std::int64_t, MAX_DIMS>;
28 
29  NDArray() = default;
30  NDArray(T* data, std::initializer_list<int64_t> shape)
31  : data_(const_cast<void*>(reinterpret_cast<const void*>(data))),
32  dims_(std::min<std::int64_t>(static_cast<std::int64_t>(shape.size()), MAX_DIMS)),
33  elemSize_(sizeof(T))
34  {
35  std::fill(shape_.begin(), shape_.end(), 0);
36  std::fill(strides_.begin(), strides_.end(), 0);
37  // Entries past MAX_DIMS are dropped, since device code cannot throw.
38  auto last = shape.size() > static_cast<std::size_t>(MAX_DIMS) ? shape.begin() + MAX_DIMS : shape.end();
39  std::copy(shape.begin(), last, shape_.begin());
40  calculateSizeAndStrides();
41  }
42 
43  // A ShapeArray has no length, so dims ends at the last nonzero entry; zeros
44  // before it are zero-length dimensions. A trailing zero-length dimension
45  // cannot be expressed this way, and an all-zero shape is a scalar (dims 0):
46  // use the constructor that takes dims.
48  : NDArray(const_cast<void*>(static_cast<const void*>(data)), shape, sizeof(T), dimsOf(shape))
49  {
50  }
51 
52  NDArray(void* data, const ShapeArray& shape, std::int64_t elemSize)
53  : NDArray(data, shape, elemSize, dimsOf(shape))
54  {
55  }
56 
57  // Uses shape[0..dims) as given, zeros included; entries past dims are ignored.
58  // dims outside [0, MAX_DIMS] is clamped, since device code cannot throw; a
59  // negative dims gives a scalar.
60  NDArray(void* data, const ShapeArray& shape, std::int64_t elemSize, std::int64_t dims)
61  : data_(data),
62  dims_(std::clamp<std::int64_t>(dims, 0, MAX_DIMS)),
63  elemSize_(elemSize)
64  {
65  std::fill(shape_.begin(), shape_.end(), 0);
66  std::fill(strides_.begin(), strides_.end(), 0);
67  std::copy(shape.begin(), shape.begin() + dims_, shape_.begin());
68  calculateSizeAndStrides();
69  }
70 
71  ~NDArray() = default;
72 
73  T* data()
74  {
75  return reinterpret_cast<T*>(data_);
76  }
77  const T* data() const
78  {
79  return reinterpret_cast<const T*>(data_);
80  }
81 
82  void setData(void* data)
83  {
84  data_ = data;
85  }
86 
87  const ShapeArray& shape() const
88  {
89  return shape_;
90  }
91  const StridesArray& strides() const
92  {
93  return strides_;
94  }
95  std::int64_t dims() const
96  {
97  return dims_;
98  }
99  std::int64_t elemSize() const
100  {
101  return elemSize_;
102  }
103  std::int64_t size() const
104  {
105  return size_;
106  }
107  std::int64_t numElements() const
108  {
109  return numElements_;
110  }
111 
112  template <typename... Idxs>
113  T& operator()(Idxs... idxs)
114  {
115  return const_cast<T&>(static_cast<const NDArray&>(*this)(idxs...));
116  }
117 
118  template <typename... Idxs>
119  const T& operator()(Idxs... idxs) const
120  {
121  return reinterpret_cast<const T*>(data_)[computeOffset({idxs...})];
122  }
123 
124  // Subndarray access with operator[] - always returns a NDArray
125  // Like operator(), it steps in units of T, so it assumes elemSize() == sizeof(T).
126  NDArray<T> operator[](std::int64_t idx)
127  {
128  auto const_result = static_cast<const NDArray&>(*this)[idx];
129  return NDArray<T>(
130  const_cast<void*>(static_cast<const void*>(const_result.data())),
131  const_result.shape(),
132  const_result.elemSize(),
133  const_result.dims());
134  }
135 
136  NDArray<const T> operator[](std::int64_t idx) const
137  {
138  ShapeArray new_shape;
139  std::fill(new_shape.begin(), new_shape.end(), 0);
140  std::copy(shape_.begin() + 1, shape_.end(), new_shape.begin());
141 
142  const T* subData = reinterpret_cast<const T*>(data_) + idx * strides_[0];
143  return NDArray<const T>(
144  const_cast<void*>(static_cast<const void*>(subData)),
145  new_shape,
146  sizeof(T),
147  dims_ > 0 ? dims_ - 1 : 0);
148  }
149 
150  // Implicit conversion to scalar for 0-dimensional ndarrays
151  template <typename U = T>
152  operator typename std::enable_if_t<std::is_same_v<U, std::remove_const_t<T>>, T&>()
153  {
154  if (dims_ != 0)
155  {
156  // Return reference to first element as fallback
157  return *reinterpret_cast<T*>(data_);
158  }
159  return *reinterpret_cast<T*>(data_);
160  }
161 
162  operator const T&() const
163  {
164  if (dims_ != 0)
165  {
166  // Return reference to first element as fallback
167  return *reinterpret_cast<const T*>(data_);
168  }
169  return *reinterpret_cast<const T*>(data_);
170  }
171 
172  // Explicit scalar() method for clearer intent
173  T& scalar()
174  {
175  return const_cast<T&>(static_cast<const NDArray&>(*this).scalar());
176  }
177 
178  const T& scalar() const
179  {
180  if (dims_ != 0)
181  {
182  // Return reference to first element as fallback
183  return *reinterpret_cast<const T*>(data_);
184  }
185  return *reinterpret_cast<const T*>(data_);
186  }
187 
188  // Multi-dimensional access with bounds checking
189  template <typename... Idxs>
190  T& at(Idxs... idxs)
191  {
192  return const_cast<T&>(static_cast<const NDArray&>(*this).at(idxs...));
193  }
194 
195  template <typename... Idxs>
196  const T& at(Idxs... idxs) const
197  {
198  std::array<std::int64_t, MAX_DIMS> indices = {idxs...};
199  if (sizeof...(Idxs) != static_cast<std::size_t>(dims_))
200  {
201  // Return reference to first element as fallback
202  return *reinterpret_cast<const T*>(data_);
203  }
204  for (std::size_t i = 0; i < indices.size(); ++i)
205  {
206  if (indices[i] < 0 || indices[i] >= shape_[i])
207  {
208  // Return reference to first element as fallback
209  return *reinterpret_cast<const T*>(data_);
210  }
211  }
212  return operator()(idxs...);
213  }
214 
215 private:
216  void* data_;
217  ShapeArray shape_;
218  StridesArray strides_;
219  std::int64_t dims_;
220  std::int64_t size_;
221  std::int64_t elemSize_;
222  std::int64_t numElements_;
223 
224  static std::int64_t dimsOf(const ShapeArray& shape)
225  {
226  std::int64_t dims = 0;
227  for (std::int64_t i = 0; i < MAX_DIMS; ++i)
228  {
229  if (shape[i] != 0)
230  {
231  dims = i + 1;
232  }
233  }
234  return dims;
235  }
236 
237  void calculateSizeAndStrides()
238  {
239  // Calculate size
240  size_ = elemSize_;
241  for (std::int64_t i = 0; i < dims_; ++i)
242  {
243  size_ *= shape_[i];
244  }
245  numElements_ = size_ / elemSize_;
246 
247  // Calculate strides
248  std::int64_t stride = 1;
249  for (std::int64_t i = dims_ - 1; i >= 0; --i)
250  {
251  strides_[i] = stride;
252  stride *= shape_[i];
253  }
254  }
255 
256  std::int64_t computeOffset(const std::array<std::int64_t, MAX_DIMS>& idxs) const
257  {
258  std::int64_t offset = 0;
259  for (std::int64_t i = 0; i < dims_; ++i)
260  {
261  offset += idxs[i] * strides_[i];
262  }
263  return offset;
264  }
265 };
266 
267 } // namespace mu
NDArray is a class that can be used in both host and device code. NDArray is automatically divided in...
Definition: ndarray.hpp:23
const T & operator()(Idxs... idxs) const
Definition: ndarray.hpp:119
std::int64_t elemSize() const
Definition: ndarray.hpp:99
const T & scalar() const
Definition: ndarray.hpp:178
NDArray(T *data, std::initializer_list< int64_t > shape)
Definition: ndarray.hpp:30
const StridesArray & strides() const
Definition: ndarray.hpp:91
NDArray(void *data, const ShapeArray &shape, std::int64_t elemSize)
Definition: ndarray.hpp:52
T * data()
Definition: ndarray.hpp:73
const T * data() const
Definition: ndarray.hpp:77
T & operator()(Idxs... idxs)
Definition: ndarray.hpp:113
NDArray()=default
std::array< std::int64_t, MAX_DIMS > ShapeArray
Definition: ndarray.hpp:26
std::int64_t numElements() const
Definition: ndarray.hpp:107
~NDArray()=default
const ShapeArray & shape() const
Definition: ndarray.hpp:87
T & scalar()
Definition: ndarray.hpp:173
const T & at(Idxs... idxs) const
Definition: ndarray.hpp:196
void setData(void *data)
Definition: ndarray.hpp:82
NDArray(void *data, const ShapeArray &shape, std::int64_t elemSize, std::int64_t dims)
Definition: ndarray.hpp:60
std::int64_t dims() const
Definition: ndarray.hpp:95
NDArray< const T > operator[](std::int64_t idx) const
Definition: ndarray.hpp:136
NDArray< T > operator[](std::int64_t idx)
Definition: ndarray.hpp:126
std::int64_t size() const
Definition: ndarray.hpp:103
NDArray(T *data, const ShapeArray &shape)
Definition: ndarray.hpp:47
T & at(Idxs... idxs)
Definition: ndarray.hpp:190
std::array< std::int64_t, MAX_DIMS > StridesArray
Definition: ndarray.hpp:27
static constexpr std::int64_t MAX_DIMS
Definition: ndarray.hpp:25
Definition: access.hpp:10
Extensions to the C++ standard library.
Definition: half.hpp:5447