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
207 static array unsafe_weak_copy(const array& other);
208
210 std::uintptr_t id() const {
211 return reinterpret_cast<std::uintptr_t>(array_desc_.get());
212 }
213
215 std::uintptr_t primitive_id() const {
216 return reinterpret_cast<std::uintptr_t>(array_desc_->primitive.get());
217 }
218
219 struct Data {
224 // Not copyable
225 Data(const Data& d) = delete;
226 Data& operator=(const Data& d) = delete;
228 d(buffer);
229 }
230 };
231
232 struct Flags {
233 // True iff there are no gaps in the underlying data. Each item
234 // in the underlying data buffer belongs to at least one index.
235 //
236 // True iff:
237 // prod(shape[i] for i in range(ndim) if strides[i] > 0) == data_size()
238 bool contiguous : 1;
239
240 // True iff:
241 // strides[-1] == 1 and
242 // all(strides[i] == (shape[i+1]*strides[i+1]) or shape[i] == 1 for i in
243 // range(ndim - 1))
245
246 // True iff:
247 // strides[0] == 1 and
248 // all(strides[i] == (shape[i-1]*strides[i-1]) or shape[i] == 1 for i in
249 // range(1, ndim))
251 };
252
255 return *(array_desc_->primitive);
256 }
257
259 std::shared_ptr<Primitive>& primitive_ptr() const {
260 return array_desc_->primitive;
261 }
262
264 bool has_primitive() const {
265 return array_desc_->primitive != nullptr;
266 }
267
269 const std::vector<array>& inputs() const {
270 return array_desc_->inputs;
271 }
272
273 std::vector<array>& inputs() {
274 return array_desc_->inputs;
275 }
276
278 bool is_donatable() const {
279 return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1);
280 }
281
283 const std::vector<array>& siblings() const {
284 return array_desc_->siblings;
285 }
286
288 std::vector<array>& siblings() {
289 return array_desc_->siblings;
290 }
291
292 void set_siblings(std::vector<array> siblings, uint16_t position) {
293 array_desc_->siblings = std::move(siblings);
294 array_desc_->position = position;
295 }
296
299 std::vector<array> outputs() const {
300 auto idx = array_desc_->position;
301 std::vector<array> outputs;
302 outputs.reserve(siblings().size() + 1);
303 outputs.insert(outputs.end(), siblings().begin(), siblings().begin() + idx);
304 outputs.push_back(*this);
305 outputs.insert(outputs.end(), siblings().begin() + idx, siblings().end());
306 return outputs;
307 }
308
310 void detach();
311
313 const Flags& flags() const {
314 return array_desc_->flags;
315 }
316
327 size_t data_size() const {
328 return array_desc_->data_size;
329 }
330
332 return array_desc_->data->buffer;
333 }
334 const allocator::Buffer& buffer() const {
335 return array_desc_->data->buffer;
336 }
337
338 size_t buffer_size() const {
339 return allocator::allocator().size(buffer());
340 }
341
342 // Return a copy of the shared pointer
343 // to the array::Data struct
344 std::shared_ptr<Data> data_shared_ptr() const {
345 return array_desc_->data;
346 }
347 // Return a raw pointer to the arrays data
348 template <typename T>
349 T* data() {
350 return static_cast<T*>(array_desc_->data_ptr);
351 }
352
353 template <typename T>
354 const T* data() const {
355 return static_cast<T*>(array_desc_->data_ptr);
356 }
357
358 enum Status {
359 // The ouptut of a computation which has not been scheduled.
360 // For example, the status of `x` in `auto x = a + b`.
362
363 // The array's `eval_*` function has been run, but the computation is not
364 // necessarily complete. The array will have memory allocated and if it is
365 // not a tracer then it will be detached from the graph.
367
368 // If the array is the output of a computation then the computation
369 // is complete. Constant arrays are always available (e.g. `array({1, 2,
370 // 3})`)
372 };
373
374 // Check if the array is safe to read.
375 bool is_available() const;
376
377 // Wait on the array to be available. After this `is_available` returns
378 // `true`.
379 void wait();
380
381 Status status() const {
382 return array_desc_->status;
383 }
384
385 void set_status(Status s) const {
386 array_desc_->status = s;
387 }
388
389 // Get the array's shared event
390 Event& event() const {
391 return array_desc_->event;
392 }
393
394 // Attach an event to a not yet evaluated array
395 void attach_event(Event e) const {
396 array_desc_->event = std::move(e);
397 }
398
399 void detach_event() const {
400 array_desc_->event = Event{};
401 }
402
403 // Mark the array as a tracer array (true) or not.
405 array_desc_->is_tracer = is_tracer;
406 }
407 // Check if the array is a tracer array
408 bool is_tracer() const;
409
411
414 size_t data_size,
416 Flags flags,
418
420 const array& other,
421 const Strides& strides,
422 Flags flags,
423 size_t data_size,
424 size_t offset = 0);
425
426 void copy_shared_buffer(const array& other);
427
428 void overwrite_descriptor(const array& other) {
429 array_desc_ = other.array_desc_;
430 }
431
433
434 private:
435 // Initialize the arrays data
436 template <typename It>
437 void init(const It src);
438
439 struct ArrayDesc {
440 Shape shape;
442 size_t size;
443 Dtype dtype;
444 std::shared_ptr<Primitive> primitive;
445
447
448 // An event on the array used for synchronization
449 Event event;
450
451 // Indicates an array is being used in a graph transform
452 // and should not be detached from the graph
453 bool is_tracer{false};
454
455 // This is a shared pointer so that *different* arrays
456 // can share the underlying data buffer.
457 std::shared_ptr<Data> data;
458
459 // Properly offset data pointer
460 void* data_ptr{nullptr};
461
462 // The size in elements of the data buffer the array accesses
463 size_t data_size;
464
465 // Contains useful meta data about the array
466 Flags flags;
467
468 std::vector<array> inputs;
469 // An array to keep track of the siblings from a multi-output
470 // primitive.
471 std::vector<array> siblings;
472 // The arrays position in the output list
473 uint32_t position{0};
474
475 explicit ArrayDesc(Shape shape, Dtype dtype);
476
477 explicit ArrayDesc(
478 Shape shape,
479 Dtype dtype,
480 std::shared_ptr<Primitive> primitive,
481 std::vector<array> inputs);
482
483 ~ArrayDesc();
484
485 private:
486 // Initialize size, strides, and other metadata
487 void init();
488 };
489
490 // The ArrayDesc contains the details of the materialized array including the
491 // shape, strides, the data type. It also includes
492 // the primitive which knows how to compute the array's data from its inputs
493 // and the list of array's inputs for the primitive.
494 std::shared_ptr<ArrayDesc> array_desc_;
495};
496
497template <typename T>
498array::array(T val, Dtype dtype /* = TypeToDtype<T>() */)
499 : array_desc_(std::make_shared<ArrayDesc>(Shape{}, dtype)) {
500 init(&val);
501}
502
503template <typename It>
505 It data,
506 Shape shape,
507 Dtype dtype /* = TypeToDtype<typename std::iterator_traits<It>::value_type>() */) :
508 array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
509 init(data);
510}
511
512template <typename T>
514 std::initializer_list<T> data,
515 Dtype dtype /* = TypeToDtype<T>() */)
516 : array_desc_(std::make_shared<ArrayDesc>(
517 Shape{static_cast<ShapeElem>(data.size())},
518 dtype)) {
519 init(data.begin());
520}
521
522template <typename T>
524 std::initializer_list<T> data,
525 Shape shape,
526 Dtype dtype /* = TypeToDtype<T>() */)
527 : array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
528 if (data.size() != size()) {
529 throw std::invalid_argument(
530 "Data size and provided shape mismatch in array construction.");
531 }
532 init(data.begin());
533}
534
535template <typename T>
537 if (size() != 1) {
538 throw std::invalid_argument("item can only be called on arrays of size 1.");
539 }
540 eval();
541 return *data<T>();
542}
543
544template <typename T>
545T array::item() const {
546 if (size() != 1) {
547 throw std::invalid_argument("item can only be called on arrays of size 1.");
548 }
549 if (status() == Status::unscheduled) {
550 throw std::invalid_argument(
551 "item() const can only be called on evaled arrays");
552 }
553 const_cast<array*>(this)->eval();
554 return *data<T>();
555}
556
557template <typename It>
558void array::init(It src) {
560 switch (dtype()) {
561 case bool_:
562 std::copy(src, src + size(), data<bool>());
563 break;
564 case uint8:
565 std::copy(src, src + size(), data<uint8_t>());
566 break;
567 case uint16:
568 std::copy(src, src + size(), data<uint16_t>());
569 break;
570 case uint32:
571 std::copy(src, src + size(), data<uint32_t>());
572 break;
573 case uint64:
574 std::copy(src, src + size(), data<uint64_t>());
575 break;
576 case int8:
577 std::copy(src, src + size(), data<int8_t>());
578 break;
579 case int16:
580 std::copy(src, src + size(), data<int16_t>());
581 break;
582 case int32:
583 std::copy(src, src + size(), data<int32_t>());
584 break;
585 case int64:
586 std::copy(src, src + size(), data<int64_t>());
587 break;
588 case float16:
589 std::copy(src, src + size(), data<float16_t>());
590 break;
591 case float32:
592 std::copy(src, src + size(), data<float>());
593 break;
594 case float64:
595 std::copy(src, src + size(), data<double>());
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:395
const Flags & flags() const
Get the Flags bit-field.
Definition array.h:313
Event & event() const
Definition array.h:390
Status
Definition array.h:358
@ available
Definition array.h:371
@ evaluated
Definition array.h:366
@ unscheduled
Definition array.h:361
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:269
array(const array &other)=default
std::vector< array > outputs() const
The outputs of the array's primitive (i.e.
Definition array.h:299
size_t nbytes() const
The number of bytes in the array.
Definition array.h:93
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:278
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:259
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:334
void set_status(Status s) const
Definition array.h:385
array(const std::complex< float > &val, Dtype dtype=complex64)
Status status() const
Definition array.h:381
std::vector< array > & siblings()
The array's siblings.
Definition array.h:288
T * data()
Definition array.h:349
array(T val, Dtype dtype=TypeToDtype< T >())
Construct a scalar array with zero dimensions.
Definition array.h:498
ArrayIterator begin() const
Definition array.h:177
Primitive & primitive() const
The array's primitive.
Definition array.h:254
static array unsafe_weak_copy(const array &other)
Get a new array that refers to the same data as the input but with a non-owning pointer to it.
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:292
T item()
Get the value from a scalar array.
Definition array.h:536
size_t buffer_size() const
Definition array.h:338
void copy_shared_buffer(const array &other)
void overwrite_descriptor(const array &other)
Definition array.h:428
const T * data() const
Definition array.h:354
void detach_event() const
Definition array.h:399
bool has_primitive() const
Check if the array has an attached primitive or is a leaf node.
Definition array.h:264
allocator::Buffer & buffer()
Definition array.h:331
array(array &&other)=default
std::shared_ptr< Data > data_shared_ptr() const
Definition array.h:344
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:283
std::vector< array > & inputs()
Definition array.h:273
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.
std::uintptr_t id() const
A unique identifier for an array.
Definition array.h:210
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:404
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:215
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:327
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:68
int32_t ShapeElem
Definition array.h:20
constexpr Dtype uint64
Definition dtype.h:73
constexpr Dtype uint16
Definition dtype.h:71
constexpr Dtype float64
Definition dtype.h:82
constexpr Dtype bfloat16
Definition dtype.h:83
constexpr Dtype int32
Definition dtype.h:77
constexpr Dtype float32
Definition dtype.h:81
std::vector< ShapeElem > Shape
Definition array.h:21
constexpr Dtype int16
Definition dtype.h:76
std::vector< int64_t > Strides
Definition array.h:22
constexpr Dtype int8
Definition dtype.h:75
constexpr Dtype int64
Definition dtype.h:78
constexpr bool is_arrays_v
Definition array.h:612
constexpr Dtype uint8
Definition dtype.h:70
constexpr Dtype float16
Definition dtype.h:80
constexpr Dtype uint32
Definition dtype.h:72
uint8_t size_of(const Dtype &t)
Definition dtype.h:104
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:84
Definition dtype.h:13
Definition dtype.h:111
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:221
Data(allocator::Buffer buffer, Deleter d=allocator::free)
Definition array.h:222
~Data()
Definition array.h:227
Data(const Data &d)=delete
Data & operator=(const Data &d)=delete
allocator::Buffer buffer
Definition array.h:220
Definition array.h:232
bool row_contiguous
Definition array.h:244
bool col_contiguous
Definition array.h:250
bool contiguous
Definition array.h:238