MLX
Loading...
Searching...
No Matches
array.h
Go to the documentation of this file.
1// Copyright © 2023 Apple Inc.
2#pragma once
3
4#include <algorithm>
5#include <cstdint>
6#include <functional>
7#include <memory>
8#include <vector>
9
10#include "mlx/allocator.h"
11#include "mlx/dtype.h"
12#include "mlx/event.h"
13
14namespace mlx::core {
15
16// Forward declaration
17class Primitive;
18using deleter_t = std::function<void(allocator::Buffer)>;
19
20class array {
21 /* An array is really a node in a graph. It contains a shared ArrayDesc
22 * object */
23
24 public:
26 template <typename T>
27 explicit array(T val, Dtype dtype = TypeToDtype<T>());
28
29 /* Special case since std::complex can't be implicitly converted to other
30 * types. */
31 explicit array(const std::complex<float>& val, Dtype dtype = complex64);
32
33 template <typename It>
34 array(
35 It data,
36 std::vector<int> shape,
37 Dtype dtype =
38 TypeToDtype<typename std::iterator_traits<It>::value_type>());
39
40 template <typename T>
41 array(std::initializer_list<T> data, Dtype dtype = TypeToDtype<T>());
42
43 /* Special case so empty lists default to float32. */
44 array(std::initializer_list<float> data);
45
46 /* Special case so array({}, type) is an empty array. */
47 array(std::initializer_list<int> data, Dtype dtype);
48
49 template <typename T>
50 array(
51 std::initializer_list<T> data,
52 std::vector<int> shape,
54
55 /* Build an array from a buffer */
58 std::vector<int> shape,
60 deleter_t deleter = allocator::free);
61
63 array& operator=(const array& other) && = delete;
64 array& operator=(array&& other) && = delete;
65
67 array& operator=(array&& other) & = default;
68 array(const array& other) = default;
69 array(array&& other) = default;
70
71 array& operator=(const array& other) & {
72 if (this->id() != other.id()) {
73 this->array_desc_ = other.array_desc_;
74 }
75 return *this;
76 }
77
79 size_t itemsize() const {
80 return size_of(dtype());
81 }
82
84 size_t size() const {
85 return array_desc_->size;
86 }
87
89 size_t nbytes() const {
90 return size() * itemsize();
91 }
92
94 size_t ndim() const {
95 return array_desc_->shape.size();
96 }
97
99 const std::vector<int>& shape() const {
100 return array_desc_->shape;
101 }
102
108 int shape(int dim) const {
109 return shape().at(dim < 0 ? dim + ndim() : dim);
110 }
111
113 const std::vector<size_t>& strides() const {
114 return array_desc_->strides;
115 }
116
122 size_t strides(int dim) const {
123 return strides().at(dim < 0 ? dim + ndim() : dim);
124 }
125
127 Dtype dtype() const {
128 return array_desc_->dtype;
129 }
130
132 void eval();
133
135 template <typename T>
136 T item();
137
138 template <typename T>
139 T item() const;
140
142 using iterator_category = std::random_access_iterator_tag;
143 using difference_type = size_t;
144 using value_type = const array;
146
147 explicit ArrayIterator(const array& arr, int idx = 0);
148
150
152 idx += diff;
153 return *this;
154 }
155
157 idx++;
158 return *this;
159 }
160
161 friend bool operator==(const ArrayIterator& a, const ArrayIterator& b) {
162 return a.arr.id() == b.arr.id() && a.idx == b.idx;
163 }
164 friend bool operator!=(const ArrayIterator& a, const ArrayIterator& b) {
165 return !(a == b);
166 }
167
168 private:
169 const array& arr;
170 int idx;
171 };
172
174 return ArrayIterator(*this);
175 }
177 return ArrayIterator(*this, shape(0));
178 }
179
187 std::vector<int> shape,
188 Dtype dtype,
189 std::shared_ptr<Primitive> primitive,
190 std::vector<array> inputs);
191
192 static std::vector<array> make_arrays(
193 std::vector<std::vector<int>> shapes,
194 const std::vector<Dtype>& dtypes,
195 const std::shared_ptr<Primitive>& primitive,
196 const std::vector<array>& inputs);
197
199 std::uintptr_t id() const {
200 return reinterpret_cast<std::uintptr_t>(array_desc_.get());
201 }
202
204 std::uintptr_t primitive_id() const {
205 return reinterpret_cast<std::uintptr_t>(array_desc_->primitive.get());
206 }
207
208 struct Data {
213 // Not copyable
214 Data(const Data& d) = delete;
215 Data& operator=(const Data& d) = delete;
217 d(buffer);
218 }
219 };
220
221 struct Flags {
222 // True if there are no gaps in the underlying data. Each item
223 // in the underlying data buffer belongs to at least one index.
224 bool contiguous : 1;
225
228 };
229
232 return *(array_desc_->primitive);
233 }
234
236 std::shared_ptr<Primitive>& primitive_ptr() const {
237 return array_desc_->primitive;
238 }
239
241 bool has_primitive() const {
242 return array_desc_->primitive != nullptr;
243 }
244
246 const std::vector<array>& inputs() const {
247 return array_desc_->inputs;
248 }
249
250 std::vector<array>& inputs() {
251 return array_desc_->inputs;
252 }
253
255 bool is_donatable() const {
256 return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1);
257 }
258
260 const std::vector<array>& siblings() const {
261 return array_desc_->siblings;
262 }
263
265 std::vector<array>& siblings() {
266 return array_desc_->siblings;
267 }
268
269 void set_siblings(std::vector<array> siblings, uint16_t position) {
270 array_desc_->siblings = std::move(siblings);
271 array_desc_->position = position;
272 }
273
276 std::vector<array> outputs() const {
277 auto idx = array_desc_->position;
278 std::vector<array> outputs;
279 outputs.reserve(siblings().size() + 1);
280 outputs.insert(outputs.end(), siblings().begin(), siblings().begin() + idx);
281 outputs.push_back(*this);
282 outputs.insert(outputs.end(), siblings().begin() + idx, siblings().end());
283 return outputs;
284 }
285
287 void detach();
288
290 const Flags& flags() const {
291 return array_desc_->flags;
292 }
293
295 size_t data_size() const {
296 return array_desc_->data_size;
297 }
298
300 return array_desc_->data->buffer;
301 }
302 const allocator::Buffer& buffer() const {
303 return array_desc_->data->buffer;
304 }
305
306 // Return a copy of the shared pointer
307 // to the array::Data struct
308 std::shared_ptr<Data> data_shared_ptr() const {
309 return array_desc_->data;
310 }
311 // Return a raw pointer to the arrays data
312 template <typename T>
313 T* data() {
314 return static_cast<T*>(array_desc_->data_ptr);
315 }
316
317 template <typename T>
318 const T* data() const {
319 return static_cast<T*>(array_desc_->data_ptr);
320 }
321
323
324 bool is_available() const {
325 return status() == Status::available;
326 }
327
328 Status status() const {
329 return array_desc_->status;
330 }
331
332 void set_status(Status s) const {
333 array_desc_->status = s;
334 }
335
336 // Get the array's shared event
337 Event& event() const {
338 return array_desc_->event;
339 }
340
341 // Attach an event to a not yet evaluated array
342 void attach_event(Event e) const {
343 array_desc_->event = std::move(e);
344 }
345
346 // Mark the array as a tracer array (true) or not.
348 array_desc_->is_tracer = is_tracer;
349 }
350 // Check if the array is a tracer array
351 bool is_tracer() const;
352
354
357 size_t data_size,
358 std::vector<size_t> strides,
359 Flags flags,
361
363 const array& other,
364 const std::vector<size_t>& strides,
365 Flags flags,
366 size_t data_size,
367 size_t offset = 0);
368
369 void copy_shared_buffer(const array& other);
370
372 array other,
373 const std::vector<size_t>& strides,
374 Flags flags,
375 size_t data_size,
376 size_t offset = 0);
377
379
380 void overwrite_descriptor(const array& other) {
381 array_desc_ = other.array_desc_;
382 }
383
385
386 private:
387 // Initialize the arrays data
388 template <typename It>
389 void init(const It src);
390
391 struct ArrayDesc {
392 std::vector<int> shape;
393 std::vector<size_t> strides;
394 size_t size;
395 Dtype dtype;
396 std::shared_ptr<Primitive> primitive;
397
398 Status status;
399
400 // An event on the array used for synchronization
401 Event event;
402
403 // Indicates an array is being used in a graph transform
404 // and should not be detached from the graph
405 bool is_tracer{false};
406
407 // This is a shared pointer so that *different* arrays
408 // can share the underlying data buffer.
409 std::shared_ptr<Data> data;
410
411 // Properly offset data pointer
412 void* data_ptr{nullptr};
413
414 // The size in elements of the data buffer the array accesses
415 // This can be different than the actual size of the array if it
416 // has been broadcast or irregularly strided.
417 size_t data_size;
418
419 // Contains useful meta data about the array
420 Flags flags;
421
422 std::vector<array> inputs;
423 // An array to keep track of the siblings from a multi-output
424 // primitive.
425 std::vector<array> siblings;
426 // The arrays position in the output list
427 uint32_t position{0};
428
429 explicit ArrayDesc(std::vector<int> shape, Dtype dtype);
430
431 explicit ArrayDesc(
432 std::vector<int> shape,
433 Dtype dtype,
434 std::shared_ptr<Primitive> primitive,
435 std::vector<array> inputs);
436
437 ~ArrayDesc();
438
439 private:
440 // Initialize size, strides, and other metadata
441 void init();
442 };
443
444 // The ArrayDesc contains the details of the materialized array including the
445 // shape, strides, the data type. It also includes
446 // the primitive which knows how to compute the array's data from its inputs
447 // and the list of array's inputs for the primitive.
448 std::shared_ptr<ArrayDesc> array_desc_;
449};
450
451template <typename T>
452array::array(T val, Dtype dtype /* = TypeToDtype<T>() */)
453 : array_desc_(std::make_shared<ArrayDesc>(std::vector<int>{}, dtype)) {
454 init(&val);
455}
456
457template <typename It>
459 It data,
460 std::vector<int> shape,
461 Dtype dtype /* = TypeToDtype<typename std::iterator_traits<It>::value_type>() */) :
462 array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
463 init(data);
464}
465
466template <typename T>
468 std::initializer_list<T> data,
469 Dtype dtype /* = TypeToDtype<T>() */)
470 : array_desc_(std::make_shared<ArrayDesc>(
471 std::vector<int>{static_cast<int>(data.size())},
472 dtype)) {
473 init(data.begin());
474}
475
476template <typename T>
478 std::initializer_list<T> data,
479 std::vector<int> shape,
480 Dtype dtype /* = TypeToDtype<T>() */)
481 : array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
482 if (data.size() != size()) {
483 throw std::invalid_argument(
484 "Data size and provided shape mismatch in array construction.");
485 }
486 init(data.begin());
487}
488
489template <typename T>
491 if (size() != 1) {
492 throw std::invalid_argument("item can only be called on arrays of size 1.");
493 }
494 eval();
495 return *data<T>();
496}
497
498template <typename T>
499T array::item() const {
500 if (size() != 1) {
501 throw std::invalid_argument("item can only be called on arrays of size 1.");
502 }
503 if (status() == Status::unscheduled) {
504 throw std::invalid_argument(
505 "item() const can only be called on evaled arrays");
506 }
507 const_cast<array*>(this)->eval();
508 return *data<T>();
509}
510
511template <typename It>
512void array::init(It src) {
514 switch (dtype()) {
515 case bool_:
516 std::copy(src, src + size(), data<bool>());
517 break;
518 case uint8:
519 std::copy(src, src + size(), data<uint8_t>());
520 break;
521 case uint16:
522 std::copy(src, src + size(), data<uint16_t>());
523 break;
524 case uint32:
525 std::copy(src, src + size(), data<uint32_t>());
526 break;
527 case uint64:
528 std::copy(src, src + size(), data<uint64_t>());
529 break;
530 case int8:
531 std::copy(src, src + size(), data<int8_t>());
532 break;
533 case int16:
534 std::copy(src, src + size(), data<int16_t>());
535 break;
536 case int32:
537 std::copy(src, src + size(), data<int32_t>());
538 break;
539 case int64:
540 std::copy(src, src + size(), data<int64_t>());
541 break;
542 case float16:
543 std::copy(src, src + size(), data<float16_t>());
544 break;
545 case float32:
546 std::copy(src, src + size(), data<float>());
547 break;
548 case bfloat16:
549 std::copy(src, src + size(), data<bfloat16_t>());
550 break;
551 case complex64:
552 std::copy(src, src + size(), data<complex64_t>());
553 break;
554 }
555}
556
557/* Utilities for determining whether a template parameter is array. */
558template <typename T>
559inline constexpr bool is_array_v =
560 std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, array>;
561
562template <typename... T>
563inline constexpr bool is_arrays_v = (is_array_v<T> && ...);
564
565template <typename... T>
566using enable_for_arrays_t = typename std::enable_if_t<is_arrays_v<T...>>;
567
568} // namespace mlx::core
Definition event.h:11
Definition primitives.h:48
Definition allocator.h:12
Definition array.h:20
void attach_event(Event e) const
Definition array.h:342
const Flags & flags() const
Get the Flags bit-field.
Definition array.h:290
Event & event() const
Definition array.h:337
static std::vector< array > make_arrays(std::vector< std::vector< int > > shapes, const std::vector< Dtype > &dtypes, const std::shared_ptr< Primitive > &primitive, const std::vector< array > &inputs)
const std::vector< size_t > & strides() const
The strides of the array.
Definition array.h:113
Status
Definition array.h:322
@ available
Definition array.h:322
@ unscheduled
Definition array.h:322
@ scheduled
Definition array.h:322
void set_data(allocator::Buffer buffer, size_t data_size, std::vector< size_t > strides, Flags flags, deleter_t d=allocator::free)
void eval()
Evaluate the array.
void copy_shared_buffer(const array &other, const std::vector< size_t > &strides, Flags flags, size_t data_size, size_t offset=0)
const std::vector< array > & inputs() const
The array's inputs.
Definition array.h:246
array(const array &other)=default
std::vector< array > outputs() const
The outputs of the array's primitive (i.e.
Definition array.h:276
size_t nbytes() const
The number of bytes in the array.
Definition array.h:89
void move_shared_buffer(array other)
array(std::initializer_list< float > data)
bool is_donatable() const
True indicates the arrays buffer is safe to reuse.
Definition array.h:255
const std::vector< int > & shape() const
The shape of the array as a vector of integers.
Definition array.h:99
std::shared_ptr< Primitive > & primitive_ptr() const
A shared pointer to the array's primitive.
Definition array.h:236
int shape(int dim) const
Get the size of the corresponding dimension.
Definition array.h:108
size_t ndim() const
The number of dimensions of the array.
Definition array.h:94
size_t size() const
The number of elements in the array.
Definition array.h:84
array(allocator::Buffer data, std::vector< int > shape, Dtype dtype, deleter_t deleter=allocator::free)
array & operator=(array &&other) &&=delete
array & operator=(const array &other) &
Definition array.h:71
ArrayIterator end() const
Definition array.h:176
array(std::initializer_list< int > data, Dtype dtype)
void set_data(allocator::Buffer buffer, deleter_t d=allocator::free)
const allocator::Buffer & buffer() const
Definition array.h:302
void set_status(Status s) const
Definition array.h:332
array(const std::complex< float > &val, Dtype dtype=complex64)
Status status() const
Definition array.h:328
std::vector< array > & siblings()
The array's siblings.
Definition array.h:265
T * data()
Definition array.h:313
array(T val, Dtype dtype=TypeToDtype< T >())
Construct a scalar array with zero dimensions.
Definition array.h:452
ArrayIterator begin() const
Definition array.h:173
Primitive & primitive() const
The array's primitive.
Definition array.h:231
void detach()
Detach the array from the graph.
array & operator=(const array &other) &&=delete
Assignment to rvalue does not compile.
void set_siblings(std::vector< array > siblings, uint16_t position)
Definition array.h:269
T item()
Get the value from a scalar array.
Definition array.h:490
size_t strides(int dim) const
Get the stride of the corresponding dimension.
Definition array.h:122
void copy_shared_buffer(const array &other)
void overwrite_descriptor(const array &other)
Definition array.h:380
const T * data() const
Definition array.h:318
bool has_primitive() const
Check if the array has an attached primitive or is a leaf node.
Definition array.h:241
allocator::Buffer & buffer()
Definition array.h:299
array(array &&other)=default
std::shared_ptr< Data > data_shared_ptr() const
Definition array.h:308
void move_shared_buffer(array other, const std::vector< size_t > &strides, Flags flags, size_t data_size, size_t offset=0)
const std::vector< array > & siblings() const
The array's siblings.
Definition array.h:260
std::vector< array > & inputs()
Definition array.h:250
array & operator=(array &&other) &=default
Default copy and move constructors otherwise.
array(std::vector< int > shape, Dtype dtype, std::shared_ptr< Primitive > primitive, std::vector< array > inputs)
The following methods should be used with caution.
std::uintptr_t id() const
A unique identifier for an array.
Definition array.h:199
Dtype dtype() const
Get the arrays data type.
Definition array.h:127
bool is_available() const
Definition array.h:324
void set_tracer(bool is_tracer)
Definition array.h:347
size_t itemsize() const
The size of the array's datatype in bytes.
Definition array.h:79
std::uintptr_t primitive_id() const
A unique identifier for an arrays primitive.
Definition array.h:204
bool is_tracer() const
size_t data_size() const
The size (in elements) of the underlying buffer the array points to.
Definition array.h:295
array std(const array &a, bool keepdims, int ddof=0, StreamOrDevice s={})
Computes the standard deviation of the elements of an array.
Buffer malloc(size_t size)
void free(Buffer buffer)
Definition allocator.h:7
constexpr bool is_array_v
Definition array.h:559
constexpr Dtype bool_
Definition dtype.h:58
std::function< void(allocator::Buffer)> deleter_t
Definition array.h:18
constexpr Dtype uint64
Definition dtype.h:63
constexpr Dtype uint16
Definition dtype.h:61
constexpr Dtype bfloat16
Definition dtype.h:72
constexpr Dtype int32
Definition dtype.h:67
constexpr Dtype float32
Definition dtype.h:71
constexpr Dtype int16
Definition dtype.h:66
constexpr Dtype int8
Definition dtype.h:65
constexpr Dtype int64
Definition dtype.h:68
constexpr bool is_arrays_v
Definition array.h:563
constexpr Dtype uint8
Definition dtype.h:60
constexpr Dtype float16
Definition dtype.h:70
constexpr Dtype uint32
Definition dtype.h:62
uint8_t size_of(const Dtype &t)
Definition dtype.h:93
typename std::enable_if_t< is_arrays_v< T... > > enable_for_arrays_t
Definition array.h:566
constexpr Dtype complex64
Definition dtype.h:73
Definition dtype.h:13
Definition dtype.h:100
Definition array.h:141
friend bool operator==(const ArrayIterator &a, const ArrayIterator &b)
Definition array.h:161
std::random_access_iterator_tag iterator_category
Definition array.h:142
ArrayIterator & operator++()
Definition array.h:156
friend bool operator!=(const ArrayIterator &a, const ArrayIterator &b)
Definition array.h:164
ArrayIterator(const array &arr, int idx=0)
size_t difference_type
Definition array.h:143
const array value_type
Definition array.h:144
ArrayIterator & operator+(difference_type diff)
Definition array.h:151
Definition array.h:208
~Data()
Definition array.h:216
deleter_t d
Definition array.h:210
Data(const Data &d)=delete
Data & operator=(const Data &d)=delete
Data(allocator::Buffer buffer, deleter_t d=allocator::free)
Definition array.h:211
allocator::Buffer buffer
Definition array.h:209
Definition array.h:221
bool row_contiguous
Definition array.h:226
bool col_contiguous
Definition array.h:227
bool contiguous
Definition array.h:224