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;
18
19using Deleter = std::function<void(allocator::Buffer)>;
20using ShapeElem = int32_t;
21using Shape = std::vector<ShapeElem>;
22using Strides = std::vector<int64_t>;
23
24class array {
25 /* An array is really a node in a graph. It contains a shared ArrayDesc
26 * object */
27
28 public:
30 template <typename T>
31 explicit array(T val, Dtype dtype = TypeToDtype<T>());
32
33 /* Special case since std::complex can't be implicitly converted to other
34 * types. */
35 explicit array(const std::complex<float>& val, Dtype dtype = complex64);
36
37 template <typename It>
38 explicit array(
39 It data,
41 Dtype dtype =
42 TypeToDtype<typename std::iterator_traits<It>::value_type>());
43
44 template <typename T>
45 explicit array(std::initializer_list<T> data, Dtype dtype = TypeToDtype<T>());
46
47 /* Special case so empty lists default to float32. */
48 explicit array(std::initializer_list<float> data);
49
50 /* Special case so array({}, type) is an empty array. */
51 explicit array(std::initializer_list<int> data, Dtype dtype);
52
53 template <typename T>
54 explicit array(
55 std::initializer_list<T> data,
58
59 /* Build an array from a buffer */
60 explicit array(
64 Deleter deleter = allocator::free);
65
67 array& operator=(const array& other) && = delete;
68 array& operator=(array&& other) && = delete;
69
71 array& operator=(array&& other) & = default;
72 array(const array& other) = default;
73 array(array&& other) = default;
74
75 array& operator=(const array& other) & {
76 if (this->id() != other.id()) {
77 this->array_desc_ = other.array_desc_;
78 }
79 return *this;
80 }
81
83 size_t itemsize() const {
84 return size_of(dtype());
85 }
86
88 size_t size() const {
89 return array_desc_->size;
90 }
91
93 size_t nbytes() const {
94 return size() * itemsize();
95 }
96
98 size_t ndim() const {
99 return array_desc_->shape.size();
100 }
101
103 const Shape& shape() const {
104 return array_desc_->shape;
105 }
106
112 auto shape(int dim) const {
113 return shape().at(dim < 0 ? dim + ndim() : dim);
114 }
115
117 const Strides& strides() const {
118 return array_desc_->strides;
119 }
120
126 auto strides(int dim) const {
127 return strides().at(dim < 0 ? dim + ndim() : dim);
128 }
129
131 Dtype dtype() const {
132 return array_desc_->dtype;
133 }
134
136 void eval();
137
139 template <typename T>
140 T item();
141
142 template <typename T>
143 T item() const;
144
146 using iterator_category = std::random_access_iterator_tag;
147 using difference_type = size_t;
148 using value_type = const array;
150
151 explicit ArrayIterator(const array& arr, int idx = 0);
152
154
156 idx += diff;
157 return *this;
158 }
159
161 idx++;
162 return *this;
163 }
164
165 friend bool operator==(const ArrayIterator& a, const ArrayIterator& b) {
166 return a.arr.id() == b.arr.id() && a.idx == b.idx;
167 }
168 friend bool operator!=(const ArrayIterator& a, const ArrayIterator& b) {
169 return !(a == b);
170 }
171
172 private:
173 const array& arr;
174 int idx;
175 };
176
178 return ArrayIterator(*this);
179 }
181 return ArrayIterator(*this, shape(0));
182 }
183
189
191 Shape shape,
192 Dtype dtype,
193 std::shared_ptr<Primitive> primitive,
194 std::vector<array> inputs);
195
196 static std::vector<array> make_arrays(
197 std::vector<Shape> shapes,
198 const std::vector<Dtype>& dtypes,
199 const std::shared_ptr<Primitive>& primitive,
200 const std::vector<array>& inputs);
201
203 std::uintptr_t id() const {
204 return reinterpret_cast<std::uintptr_t>(array_desc_.get());
205 }
206
208 std::uintptr_t primitive_id() const {
209 return reinterpret_cast<std::uintptr_t>(array_desc_->primitive.get());
210 }
211
212 struct Data {
217 // Not copyable
218 Data(const Data& d) = delete;
219 Data& operator=(const Data& d) = delete;
221 d(buffer);
222 }
223 };
224
225 struct Flags {
226 // True iff there are no gaps in the underlying data. Each item
227 // in the underlying data buffer belongs to at least one index.
228 //
229 // True iff:
230 // prod(shape[i] for i in range(ndim) if strides[i] > 0) == data_size()
231 bool contiguous : 1;
232
233 // True iff:
234 // strides[-1] == 1 and
235 // all(strides[i] == (shape[i+1]*strides[i+1]) or shape[i] == 1 for i in
236 // range(ndim - 1))
238
239 // True iff:
240 // strides[0] == 1 and
241 // all(strides[i] == (shape[i-1]*strides[i-1]) or shape[i] == 1 for i in
242 // range(1, ndim))
244 };
245
248 return *(array_desc_->primitive);
249 }
250
252 std::shared_ptr<Primitive>& primitive_ptr() const {
253 return array_desc_->primitive;
254 }
255
257 bool has_primitive() const {
258 return array_desc_->primitive != nullptr;
259 }
260
262 const std::vector<array>& inputs() const {
263 return array_desc_->inputs;
264 }
265
266 std::vector<array>& inputs() {
267 return array_desc_->inputs;
268 }
269
271 bool is_donatable() const {
272 return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1);
273 }
274
276 const std::vector<array>& siblings() const {
277 return array_desc_->siblings;
278 }
279
281 std::vector<array>& siblings() {
282 return array_desc_->siblings;
283 }
284
285 void set_siblings(std::vector<array> siblings, uint16_t position) {
286 array_desc_->siblings = std::move(siblings);
287 array_desc_->position = position;
288 }
289
292 std::vector<array> outputs() const {
293 auto idx = array_desc_->position;
294 std::vector<array> outputs;
295 outputs.reserve(siblings().size() + 1);
296 outputs.insert(outputs.end(), siblings().begin(), siblings().begin() + idx);
297 outputs.push_back(*this);
298 outputs.insert(outputs.end(), siblings().begin() + idx, siblings().end());
299 return outputs;
300 }
301
303 void detach();
304
306 const Flags& flags() const {
307 return array_desc_->flags;
308 }
309
320 size_t data_size() const {
321 return array_desc_->data_size;
322 }
323
325 return array_desc_->data->buffer;
326 }
327 const allocator::Buffer& buffer() const {
328 return array_desc_->data->buffer;
329 }
330
331 size_t buffer_size() const {
332 return allocator::allocator().size(buffer());
333 }
334
335 // Return a copy of the shared pointer
336 // to the array::Data struct
337 std::shared_ptr<Data> data_shared_ptr() const {
338 return array_desc_->data;
339 }
340 // Return a raw pointer to the arrays data
341 template <typename T>
342 T* data() {
343 return static_cast<T*>(array_desc_->data_ptr);
344 }
345
346 template <typename T>
347 const T* data() const {
348 return static_cast<T*>(array_desc_->data_ptr);
349 }
350
351 enum Status {
352 // The ouptut of a computation which has not been scheduled.
353 // For example, the status of `x` in `auto x = a + b`.
355
356 // The ouptut of a computation which has been scheduled but `eval_*` has
357 // not yet been called on the array's primitive. A possible
358 // status of `x` in `auto x = a + b; eval(x);`
360
361 // The array's `eval_*` function has been run, but the computation is not
362 // necessarily complete. The array will have memory allocated and if it is
363 // not a tracer then it will be detached from the graph.
365
366 // If the array is the output of a computation then the computation
367 // is complete. Constant arrays are always available (e.g. `array({1, 2,
368 // 3})`)
370 };
371
372 // Check if the array is safe to read.
373 bool is_available() const;
374
375 // Wait on the array to be available. After this `is_available` returns
376 // `true`.
377 void wait();
378
379 Status status() const {
380 return array_desc_->status;
381 }
382
383 void set_status(Status s) const {
384 array_desc_->status = s;
385 }
386
387 // Get the array's shared event
388 Event& event() const {
389 return array_desc_->event;
390 }
391
392 // Attach an event to a not yet evaluated array
393 void attach_event(Event e) const {
394 array_desc_->event = std::move(e);
395 }
396
397 // Mark the array as a tracer array (true) or not.
399 array_desc_->is_tracer = is_tracer;
400 }
401 // Check if the array is a tracer array
402 bool is_tracer() const;
403
405
408 size_t data_size,
410 Flags flags,
412
414 const array& other,
415 const Strides& strides,
416 Flags flags,
417 size_t data_size,
418 size_t offset = 0);
419
420 void copy_shared_buffer(const array& other);
421
423 array other,
424 const Strides& strides,
425 Flags flags,
426 size_t data_size,
427 size_t offset = 0);
428
430
431 void overwrite_descriptor(const array& other) {
432 array_desc_ = other.array_desc_;
433 }
434
436
437 private:
438 // Initialize the arrays data
439 template <typename It>
440 void init(const It src);
441
442 struct ArrayDesc {
443 Shape shape;
445 size_t size;
446 Dtype dtype;
447 std::shared_ptr<Primitive> primitive;
448
450
451 // An event on the array used for synchronization
452 Event event;
453
454 // Indicates an array is being used in a graph transform
455 // and should not be detached from the graph
456 bool is_tracer{false};
457
458 // This is a shared pointer so that *different* arrays
459 // can share the underlying data buffer.
460 std::shared_ptr<Data> data;
461
462 // Properly offset data pointer
463 void* data_ptr{nullptr};
464
465 // The size in elements of the data buffer the array accesses
466 size_t data_size;
467
468 // Contains useful meta data about the array
469 Flags flags;
470
471 std::vector<array> inputs;
472 // An array to keep track of the siblings from a multi-output
473 // primitive.
474 std::vector<array> siblings;
475 // The arrays position in the output list
476 uint32_t position{0};
477
478 explicit ArrayDesc(Shape shape, Dtype dtype);
479
480 explicit ArrayDesc(
481 Shape shape,
482 Dtype dtype,
483 std::shared_ptr<Primitive> primitive,
484 std::vector<array> inputs);
485
486 ~ArrayDesc();
487
488 private:
489 // Initialize size, strides, and other metadata
490 void init();
491 };
492
493 // The ArrayDesc contains the details of the materialized array including the
494 // shape, strides, the data type. It also includes
495 // the primitive which knows how to compute the array's data from its inputs
496 // and the list of array's inputs for the primitive.
497 std::shared_ptr<ArrayDesc> array_desc_;
498};
499
500template <typename T>
501array::array(T val, Dtype dtype /* = TypeToDtype<T>() */)
502 : array_desc_(std::make_shared<ArrayDesc>(Shape{}, dtype)) {
503 init(&val);
504}
505
506template <typename It>
508 It data,
509 Shape shape,
510 Dtype dtype /* = TypeToDtype<typename std::iterator_traits<It>::value_type>() */) :
511 array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
512 init(data);
513}
514
515template <typename T>
517 std::initializer_list<T> data,
518 Dtype dtype /* = TypeToDtype<T>() */)
519 : array_desc_(std::make_shared<ArrayDesc>(
520 Shape{static_cast<ShapeElem>(data.size())},
521 dtype)) {
522 init(data.begin());
523}
524
525template <typename T>
527 std::initializer_list<T> data,
528 Shape shape,
529 Dtype dtype /* = TypeToDtype<T>() */)
530 : array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
531 if (data.size() != size()) {
532 throw std::invalid_argument(
533 "Data size and provided shape mismatch in array construction.");
534 }
535 init(data.begin());
536}
537
538template <typename T>
540 if (size() != 1) {
541 throw std::invalid_argument("item can only be called on arrays of size 1.");
542 }
543 eval();
544 return *data<T>();
545}
546
547template <typename T>
548T array::item() const {
549 if (size() != 1) {
550 throw std::invalid_argument("item can only be called on arrays of size 1.");
551 }
552 if (status() == Status::unscheduled) {
553 throw std::invalid_argument(
554 "item() const can only be called on evaled arrays");
555 }
556 const_cast<array*>(this)->eval();
557 return *data<T>();
558}
559
560template <typename It>
561void array::init(It src) {
563 switch (dtype()) {
564 case bool_:
565 std::copy(src, src + size(), data<bool>());
566 break;
567 case uint8:
568 std::copy(src, src + size(), data<uint8_t>());
569 break;
570 case uint16:
571 std::copy(src, src + size(), data<uint16_t>());
572 break;
573 case uint32:
574 std::copy(src, src + size(), data<uint32_t>());
575 break;
576 case uint64:
577 std::copy(src, src + size(), data<uint64_t>());
578 break;
579 case int8:
580 std::copy(src, src + size(), data<int8_t>());
581 break;
582 case int16:
583 std::copy(src, src + size(), data<int16_t>());
584 break;
585 case int32:
586 std::copy(src, src + size(), data<int32_t>());
587 break;
588 case int64:
589 std::copy(src, src + size(), data<int64_t>());
590 break;
591 case float16:
592 std::copy(src, src + size(), data<float16_t>());
593 break;
594 case float32:
595 std::copy(src, src + size(), data<float>());
596 break;
597 case bfloat16:
598 std::copy(src, src + size(), data<bfloat16_t>());
599 break;
600 case complex64:
601 std::copy(src, src + size(), data<complex64_t>());
602 break;
603 }
604}
605
606/* Utilities for determining whether a template parameter is array. */
607template <typename T>
608inline constexpr bool is_array_v =
609 std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, array>;
610
611template <typename... T>
612inline constexpr bool is_arrays_v = (is_array_v<T> && ...);
613
614template <typename... T>
615using enable_for_arrays_t = typename std::enable_if_t<is_arrays_v<T...>>;
616
617} // namespace mlx::core
Definition event.h:11
Definition primitives.h:48
virtual size_t size(Buffer buffer) const =0
Definition allocator.h:12
Definition array.h:24
void attach_event(Event e) const
Definition array.h:393
const Flags & flags() const
Get the Flags bit-field.
Definition array.h:306
Event & event() const
Definition array.h:388
Status
Definition array.h:351
@ available
Definition array.h:369
@ evaluated
Definition array.h:364
@ unscheduled
Definition array.h:354
@ scheduled
Definition array.h:359
const Shape & shape() const
The shape of the array as a vector of integers.
Definition array.h:103
void eval()
Evaluate the array.
const Strides & strides() const
The strides of the array.
Definition array.h:117
const std::vector< array > & inputs() const
The array's inputs.
Definition array.h:262
array(const array &other)=default
std::vector< array > outputs() const
The outputs of the array's primitive (i.e.
Definition array.h:292
size_t nbytes() const
The number of bytes in the array.
Definition array.h:93
void move_shared_buffer(array other)
static std::vector< array > make_arrays(std::vector< Shape > shapes, const std::vector< Dtype > &dtypes, const std::shared_ptr< Primitive > &primitive, const std::vector< array > &inputs)
array(std::initializer_list< float > data)
bool is_donatable() const
True indicates the arrays buffer is safe to reuse.
Definition array.h:271
array(allocator::Buffer data, Shape shape, Dtype dtype, Deleter deleter=allocator::free)
std::shared_ptr< Primitive > & primitive_ptr() const
A shared pointer to the array's primitive.
Definition array.h:252
size_t ndim() const
The number of dimensions of the array.
Definition array.h:98
size_t size() const
The number of elements in the array.
Definition array.h:88
array & operator=(array &&other) &&=delete
array & operator=(const array &other) &
Definition array.h:75
ArrayIterator end() const
Definition array.h:180
array(std::initializer_list< int > data, Dtype dtype)
void set_data(allocator::Buffer buffer, size_t data_size, Strides strides, Flags flags, Deleter d=allocator::free)
const allocator::Buffer & buffer() const
Definition array.h:327
void set_status(Status s) const
Definition array.h:383
array(const std::complex< float > &val, Dtype dtype=complex64)
Status status() const
Definition array.h:379
std::vector< array > & siblings()
The array's siblings.
Definition array.h:281
T * data()
Definition array.h:342
array(T val, Dtype dtype=TypeToDtype< T >())
Construct a scalar array with zero dimensions.
Definition array.h:501
ArrayIterator begin() const
Definition array.h:177
Primitive & primitive() const
The array's primitive.
Definition array.h:247
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:285
T item()
Get the value from a scalar array.
Definition array.h:539
size_t buffer_size() const
Definition array.h:331
void copy_shared_buffer(const array &other)
void overwrite_descriptor(const array &other)
Definition array.h:431
const T * data() const
Definition array.h:347
bool has_primitive() const
Check if the array has an attached primitive or is a leaf node.
Definition array.h:257
allocator::Buffer & buffer()
Definition array.h:324
array(array &&other)=default
std::shared_ptr< Data > data_shared_ptr() const
Definition array.h:337
array(Shape shape, Dtype dtype, std::shared_ptr< Primitive > primitive, std::vector< array > inputs)
The following methods should be used with caution.
auto shape(int dim) const
Get the size of the corresponding dimension.
Definition array.h:112
auto strides(int dim) const
Get the stride of the corresponding dimension.
Definition array.h:126
const std::vector< array > & siblings() const
The array's siblings.
Definition array.h:276
std::vector< array > & inputs()
Definition array.h:266
void copy_shared_buffer(const array &other, const Strides &strides, Flags flags, size_t data_size, size_t offset=0)
array & operator=(array &&other) &=default
Default copy and move constructors otherwise.
void move_shared_buffer(array other, const Strides &strides, Flags flags, size_t data_size, size_t offset=0)
std::uintptr_t id() const
A unique identifier for an array.
Definition array.h:203
Dtype dtype() const
Get the arrays data type.
Definition array.h:131
bool is_available() const
void set_tracer(bool is_tracer)
Definition array.h:398
size_t itemsize() const
The size of the array's datatype in bytes.
Definition array.h:83
std::uintptr_t primitive_id() const
A unique identifier for an arrays primitive.
Definition array.h:208
bool is_tracer() const
void set_data(allocator::Buffer buffer, Deleter d=allocator::free)
size_t data_size() const
The size (in elements) of the underlying buffer the array points to.
Definition array.h:320
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)
Allocator & allocator()
Definition allocator.h:7
constexpr bool is_array_v
Definition array.h:608
constexpr Dtype bool_
Definition dtype.h:67
int32_t ShapeElem
Definition array.h:20
constexpr Dtype uint64
Definition dtype.h:72
constexpr Dtype uint16
Definition dtype.h:70
constexpr Dtype bfloat16
Definition dtype.h:81
constexpr Dtype int32
Definition dtype.h:76
constexpr Dtype float32
Definition dtype.h:80
std::vector< ShapeElem > Shape
Definition array.h:21
constexpr Dtype int16
Definition dtype.h:75
std::vector< int64_t > Strides
Definition array.h:22
constexpr Dtype int8
Definition dtype.h:74
constexpr Dtype int64
Definition dtype.h:77
constexpr bool is_arrays_v
Definition array.h:612
constexpr Dtype uint8
Definition dtype.h:69
constexpr Dtype float16
Definition dtype.h:79
constexpr Dtype uint32
Definition dtype.h:71
uint8_t size_of(const Dtype &t)
Definition dtype.h:102
std::function< void(allocator::Buffer)> Deleter
Definition array.h:19
typename std::enable_if_t< is_arrays_v< T... > > enable_for_arrays_t
Definition array.h:615
constexpr Dtype complex64
Definition dtype.h:82
Definition dtype.h:13
Definition dtype.h:109
Definition array.h:145
friend bool operator==(const ArrayIterator &a, const ArrayIterator &b)
Definition array.h:165
std::random_access_iterator_tag iterator_category
Definition array.h:146
ArrayIterator & operator++()
Definition array.h:160
value_type reference
Definition array.h:149
friend bool operator!=(const ArrayIterator &a, const ArrayIterator &b)
Definition array.h:168
ArrayIterator(const array &arr, int idx=0)
size_t difference_type
Definition array.h:147
const array value_type
Definition array.h:148
ArrayIterator & operator+(difference_type diff)
Definition array.h:155
Deleter d
Definition array.h:214
Data(allocator::Buffer buffer, Deleter d=allocator::free)
Definition array.h:215
~Data()
Definition array.h:220
Data(const Data &d)=delete
Data & operator=(const Data &d)=delete
allocator::Buffer buffer
Definition array.h:213
Definition array.h:225
bool row_contiguous
Definition array.h:237
bool col_contiguous
Definition array.h:243
bool contiguous
Definition array.h:231