Repository navigation
Expand file tree
/
Copy pathtest_array.py
More file actions
3084 lines (2600 loc) · 106 KB
/
Copy pathtest_array.py
File metadata and controls
3084 lines (2600 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright © 2023-2024 Apple Inc.
import operator
import pickle
import platform
import sys
import unittest
import warnings
import weakref
from copy import copy, deepcopy
from itertools import permutations
import mlx.core as mx
import mlx_tests
import numpy as np
try:
import tensorflow as tf
has_tf = True
except ImportError:
has_tf = False
try:
import torch
torch_version = [int(v) for v in torch.__version__.split("+")[0].split(".")]
is_torch_212 = torch_version[0] > 2 or (
torch_version[0] == 2 and torch_version[1] >= 12
)
has_torch_mps = (
is_torch_212
and hasattr(torch.backends, "mps")
and torch.backends.mps.is_available()
)
except ImportError:
torch = None
has_torch_mps = False
class TestVersion(mlx_tests.MLXTestCase):
def test_version(self):
v = mx.__version__
vnums = v.split(".")
self.assertGreaterEqual(len(vnums), 3)
v = ".".join(str(int(vn)) for vn in vnums[:3])
self.assertEqual(v, mx.__version__[: len(v)])
class TestArrayNamespsceInfo(mlx_tests.MLXTestCase):
def test(self):
namespace = mx.__array_namespace_info__()
self.assertEqual(namespace.default_device(), mx.default_device())
self.assertEqual(
namespace.default_dtypes(),
{
"real floating": mx.float32,
"complex floating": mx.complex64,
"integral": mx.int32,
"indexing": mx.int32,
},
)
self.assertEqual(
namespace.dtypes(device=mx.Device(mx.cpu), kind="real floating"),
{"float32": mx.float32, "float64": mx.float64},
)
if mx.is_available(mx.gpu):
self.assertEqual(
namespace.dtypes(device=mx.Device(mx.gpu), kind="real floating"),
{"float32": mx.float32},
)
self.assertEqual(
namespace.dtypes(kind=("bool", "complex floating")),
{"bool": mx.bool_, "complex64": mx.complex64},
)
with self.assertRaises(ValueError):
namespace.dtypes(kind="invalid")
class TestDtypes(mlx_tests.MLXTestCase):
def test_dtypes(self):
self.assertEqual(mx.bool_.size, 1)
self.assertEqual(mx.uint8.size, 1)
self.assertEqual(mx.uint16.size, 2)
self.assertEqual(mx.uint32.size, 4)
self.assertEqual(mx.uint64.size, 8)
self.assertEqual(mx.int8.size, 1)
self.assertEqual(mx.int16.size, 2)
self.assertEqual(mx.int32.size, 4)
self.assertEqual(mx.int64.size, 8)
self.assertEqual(mx.float16.size, 2)
self.assertEqual(mx.float32.size, 4)
self.assertEqual(mx.bfloat16.size, 2)
self.assertEqual(mx.complex64.size, 8)
self.assertEqual(str(mx.bool_), "mlx.core.bool")
self.assertEqual(str(mx.uint8), "mlx.core.uint8")
self.assertEqual(str(mx.uint16), "mlx.core.uint16")
self.assertEqual(str(mx.uint32), "mlx.core.uint32")
self.assertEqual(str(mx.uint64), "mlx.core.uint64")
self.assertEqual(str(mx.int8), "mlx.core.int8")
self.assertEqual(str(mx.int16), "mlx.core.int16")
self.assertEqual(str(mx.int32), "mlx.core.int32")
self.assertEqual(str(mx.int64), "mlx.core.int64")
self.assertEqual(str(mx.float16), "mlx.core.float16")
self.assertEqual(str(mx.float32), "mlx.core.float32")
self.assertEqual(str(mx.bfloat16), "mlx.core.bfloat16")
self.assertEqual(str(mx.complex64), "mlx.core.complex64")
def test_scalar_conversion(self):
dtypes = [
"uint8",
"uint16",
"uint32",
"uint64",
"int8",
"int16",
"int32",
"int64",
"float16",
"float32",
"complex64",
]
for dtype in dtypes:
with self.subTest(dtype=dtype):
x = np.array(2, dtype=getattr(np, dtype))
y = np.min(x)
self.assertEqual(x.dtype, y.dtype)
self.assertTupleEqual(x.shape, y.shape)
z = mx.array(y)
self.assertEqual(np.array(z), x)
self.assertEqual(np.array(z), y)
self.assertEqual(z.dtype, getattr(mx, dtype))
self.assertListEqual(list(z.shape), list(x.shape))
self.assertListEqual(list(z.shape), list(y.shape))
def test_index_conversion(self):
for dtype in [
mx.uint8,
mx.uint16,
mx.uint32,
mx.uint64,
mx.int8,
mx.int16,
mx.int32,
mx.int64,
]:
with self.subTest(dtype=dtype):
self.assertEqual(operator.index(mx.array(2, dtype)), 2)
self.assertEqual(list(range(mx.array(3, dtype))), [0, 1, 2])
def test_index_conversion_invalid(self):
for dtype in [mx.float16, mx.float32, mx.bfloat16, mx.complex64, mx.bool_]:
with self.subTest(dtype=dtype):
with self.assertRaises(TypeError):
operator.index(mx.array(2, dtype))
with self.assertRaises(TypeError):
list(range(mx.array(3, dtype)))
def test_finfo(self):
with self.assertRaises(ValueError):
mx.finfo(mx.int32)
self.assertEqual(mx.finfo(mx.float32).min, np.finfo(np.float32).min)
self.assertEqual(mx.finfo(mx.float32).max, np.finfo(np.float32).max)
self.assertEqual(mx.finfo(mx.float32).eps, np.finfo(np.float32).eps)
self.assertEqual(mx.finfo(mx.float32).bits, np.finfo(np.float32).bits)
self.assertEqual(
mx.finfo(mx.float32).smallest_normal,
float(np.finfo(np.float32).smallest_normal),
)
self.assertEqual(mx.finfo(mx.float32).dtype, mx.float32)
self.assertEqual(mx.finfo(mx.float16).min, np.finfo(np.float16).min)
self.assertEqual(mx.finfo(mx.float16).max, np.finfo(np.float16).max)
self.assertEqual(mx.finfo(mx.float16).eps, np.finfo(np.float16).eps)
self.assertEqual(mx.finfo(mx.float16).bits, np.finfo(np.float16).bits)
self.assertEqual(
mx.finfo(mx.float16).smallest_normal,
float(np.finfo(np.float16).smallest_normal),
)
self.assertEqual(mx.finfo(mx.float16).dtype, mx.float16)
# bfloat16 has no numpy equivalent; check against known IEEE values.
self.assertEqual(mx.finfo(mx.bfloat16).bits, 16)
self.assertAlmostEqual(
mx.finfo(mx.bfloat16).smallest_normal, 2.0**-126, places=40
)
# finfo of a complex type reports its real component (array API).
self.assertEqual(mx.finfo(mx.complex64).dtype, mx.float32)
self.assertEqual(mx.finfo(mx.complex64).bits, 32)
def test_iinfo(self):
with self.assertRaises(ValueError):
mx.iinfo(mx.float32)
self.assertEqual(mx.iinfo(mx.int32).min, np.iinfo(np.int32).min)
self.assertEqual(mx.iinfo(mx.int32).max, np.iinfo(np.int32).max)
self.assertEqual(mx.iinfo(mx.int32).dtype, mx.int32)
self.assertEqual(mx.iinfo(mx.uint32).min, np.iinfo(np.uint32).min)
self.assertEqual(mx.iinfo(mx.uint32).max, np.iinfo(np.uint32).max)
self.assertEqual(mx.iinfo(mx.int8).dtype, mx.int8)
def test_result_type(self):
self.assertEqual(mx.result_type(mx.int8, mx.int16), mx.int16)
self.assertEqual(mx.result_type(mx.float32, mx.float64), mx.float64)
# Accepts arrays as well as dtypes, and more than two inputs.
self.assertEqual(
mx.result_type(mx.array([1], dtype=mx.int8), mx.int16, mx.int32),
mx.int32,
)
self.assertEqual(
mx.result_type(mx.array(1.0), mx.array(1, dtype=mx.int32)),
mx.float32,
)
with self.assertRaises(ValueError):
mx.result_type()
def test_can_cast(self):
self.assertTrue(mx.can_cast(mx.int8, mx.int16))
self.assertFalse(mx.can_cast(mx.int16, mx.int8))
self.assertTrue(mx.can_cast(mx.float32, mx.float64))
self.assertFalse(mx.can_cast(mx.float64, mx.float32))
self.assertTrue(mx.can_cast(mx.uint8, mx.int16))
self.assertFalse(mx.can_cast(mx.uint16, mx.int16))
# Accepts an array for the source.
self.assertTrue(mx.can_cast(mx.array([1, 2, 3], dtype=mx.int8), mx.int32))
def test_isdtype(self):
self.assertTrue(mx.isdtype(mx.int32, mx.int32))
self.assertFalse(mx.isdtype(mx.int32, mx.int16))
self.assertTrue(mx.isdtype(mx.int32, "signed integer"))
self.assertTrue(mx.isdtype(mx.uint8, "unsigned integer"))
self.assertFalse(mx.isdtype(mx.uint8, "signed integer"))
self.assertTrue(mx.isdtype(mx.int16, "integral"))
self.assertTrue(mx.isdtype(mx.float32, "real floating"))
self.assertTrue(mx.isdtype(mx.complex64, "complex floating"))
self.assertTrue(mx.isdtype(mx.bool_, "bool"))
self.assertFalse(mx.isdtype(mx.bool_, "numeric"))
self.assertTrue(mx.isdtype(mx.float32, "numeric"))
# Tuple of kinds (any match).
self.assertTrue(mx.isdtype(mx.float32, ("integral", "real floating")))
self.assertTrue(mx.isdtype(mx.int8, (mx.int8, mx.int16)))
self.assertFalse(mx.isdtype(mx.int32, ("bool", "real floating")))
with self.assertRaises(ValueError):
mx.isdtype(mx.int32, "not a kind")
# Reachable through the array API namespace.
xp = mx.array(1.0).__array_namespace__()
for name in ("result_type", "can_cast", "isdtype", "vecdot"):
self.assertTrue(hasattr(xp, name), msg=name)
class TestEquality(mlx_tests.MLXTestCase):
def test_array_eq_array(self):
a = mx.array([1, 2, 3])
b = mx.array([1, 2, 3])
c = mx.array([1, 2, 4])
self.assertTrue(mx.all(a == b))
self.assertFalse(mx.all(a == c))
def test_array_eq_scalar(self):
a = mx.array([1, 2, 3])
b = 1
c = 4
d = 2.5
e = mx.array([1, 2.5, 3.25])
self.assertTrue(mx.any(a == b))
self.assertFalse(mx.all(a == c))
self.assertFalse(mx.all(a == d))
self.assertTrue(mx.any(a == e))
def test_list_equals_array(self):
a = mx.array([1, 2, 3])
b = [1, 2, 3]
c = [1, 2, 4]
# mlx array equality returns false if is compared with any kind of
# object which is not an mlx array
self.assertFalse(a == b)
self.assertFalse(a == c)
def test_tuple_equals_array(self):
a = mx.array([1, 2, 3])
b = (1, 2, 3)
c = (1, 2, 4)
# mlx array equality returns false if is compared with any kind of
# object which is not an mlx array
self.assertFalse(a == b)
self.assertFalse(a == c)
class TestInequality(mlx_tests.MLXTestCase):
def test_array_ne_array(self):
a = mx.array([1, 2, 3])
b = mx.array([1, 2, 3])
c = mx.array([1, 2, 4])
self.assertFalse(mx.any(a != b))
self.assertTrue(mx.any(a != c))
def test_array_ne_scalar(self):
a = mx.array([1, 2, 3])
b = 1
c = 4
d = 1.5
e = 2.5
f = mx.array([1, 2.5, 3.25])
self.assertFalse(mx.all(a != b))
self.assertTrue(mx.any(a != c))
self.assertTrue(mx.any(a != d))
self.assertTrue(mx.any(a != e))
self.assertFalse(mx.all(a != f))
def test_list_not_equals_array(self):
a = mx.array([1, 2, 3])
b = [1, 2, 3]
c = [1, 2, 4]
# mlx array inequality returns true if is compared with any kind of
# object which is not an mlx array
self.assertTrue(a != b)
self.assertTrue(a != c)
def test_dlx_device_type(self):
a = mx.array([1, 2, 3])
device_type, device_id = a.__dlpack_device__()
self.assertIn(device_type, [1, 8])
self.assertEqual(device_id, 0)
if device_type == 8:
# Additional check if Metal is supposed to be available
self.assertTrue(mx.metal.is_available())
elif device_type == 1:
# Additional check if CPU is the fallback
self.assertFalse(mx.metal.is_available())
def test_tuple_not_equals_array(self):
a = mx.array([1, 2, 3])
b = (1, 2, 3)
c = (1, 2, 4)
# mlx array inequality returns true if is compared with any kind of
# object which is not an mlx array
self.assertTrue(a != b)
self.assertTrue(a != c)
def test_obj_inequality_array(self):
str_ = "hello"
a = mx.array([1, 2, 3])
lst_ = [1, 2, 3]
tpl_ = (1, 2, 3)
# check if object comparison(</>/<=/>=) with mlx array should throw an exception
# if not, the tests will fail
with self.assertRaises(ValueError):
a < str_
with self.assertRaises(ValueError):
a > str_
with self.assertRaises(ValueError):
a <= str_
with self.assertRaises(ValueError):
a >= str_
with self.assertRaises(ValueError):
a < lst_
with self.assertRaises(ValueError):
a > lst_
with self.assertRaises(ValueError):
a <= lst_
with self.assertRaises(ValueError):
a >= lst_
with self.assertRaises(ValueError):
a < tpl_
with self.assertRaises(ValueError):
a > tpl_
with self.assertRaises(ValueError):
a <= tpl_
with self.assertRaises(ValueError):
a >= tpl_
def test_invalid_op_on_array(self):
str_ = "hello"
a = mx.array([1, 2.5, 3.25])
lst_ = [1, 2.1, 3.25]
tpl_ = (1, 2.5, 3.25)
with self.assertRaises(ValueError):
a * str_
with self.assertRaises(ValueError):
a *= str_
with self.assertRaises(ValueError):
a /= lst_
with self.assertRaises(ValueError):
a // lst_
with self.assertRaises(ValueError):
a % lst_
with self.assertRaises(ValueError):
a**tpl_
with self.assertRaises(ValueError):
a & tpl_
with self.assertRaises(ValueError):
a | str_
class TestArray(mlx_tests.MLXTestCase):
def test_array_basics(self):
x = mx.array(1)
self.assertEqual(x.size, 1)
self.assertEqual(x.ndim, 0)
self.assertEqual(x.itemsize, 4)
self.assertEqual(x.nbytes, 4)
self.assertEqual(x.shape, ())
self.assertEqual(x.dtype, mx.int32)
self.assertEqual(x.item(), 1)
self.assertTrue(isinstance(x.item(), int))
with self.assertRaises(TypeError):
len(x)
x = mx.array(1, mx.uint32)
self.assertEqual(x.item(), 1)
self.assertTrue(isinstance(x.item(), int))
x = mx.array(1, mx.int64)
self.assertEqual(x.item(), 1)
self.assertTrue(isinstance(x.item(), int))
x = mx.array(1, mx.bfloat16)
self.assertEqual(x.item(), 1.0)
x = mx.array(1.0)
self.assertEqual(x.size, 1)
self.assertEqual(x.ndim, 0)
self.assertEqual(x.shape, ())
self.assertEqual(x.dtype, mx.float32)
self.assertEqual(x.item(), 1.0)
self.assertTrue(isinstance(x.item(), float))
x = mx.array(False)
self.assertEqual(x.size, 1)
self.assertEqual(x.ndim, 0)
self.assertEqual(x.shape, ())
self.assertEqual(x.dtype, mx.bool_)
self.assertEqual(x.item(), False)
self.assertTrue(isinstance(x.item(), bool))
x = mx.array(complex(1, 1))
self.assertEqual(x.ndim, 0)
self.assertEqual(x.shape, ())
self.assertEqual(x.dtype, mx.complex64)
self.assertEqual(x.item(), complex(1, 1))
self.assertTrue(isinstance(x.item(), complex))
x = mx.array([True, False, True])
self.assertEqual(x.dtype, mx.bool_)
self.assertEqual(x.ndim, 1)
self.assertEqual(x.shape, (3,))
self.assertEqual(len(x), 3)
x = mx.array([True, False, True], mx.float32)
self.assertEqual(x.dtype, mx.float32)
x = mx.array([0, 1, 2])
self.assertEqual(x.dtype, mx.int32)
self.assertEqual(x.ndim, 1)
self.assertEqual(x.shape, (3,))
x = mx.array([0, 1, 2], mx.float32)
self.assertEqual(x.dtype, mx.float32)
x = mx.array([0.0, 1.0, 2.0])
self.assertEqual(x.dtype, mx.float32)
self.assertEqual(x.ndim, 1)
self.assertEqual(x.shape, (3,))
x = mx.array([1j, 1 + 0j])
self.assertEqual(x.dtype, mx.complex64)
self.assertEqual(x.ndim, 1)
self.assertEqual(x.shape, (2,))
# From tuple
x = mx.array((1, 2, 3), mx.int32)
self.assertEqual(x.dtype, mx.int32)
self.assertEqual(x.tolist(), [1, 2, 3])
def test_matrix_transpose(self):
x = mx.array([[1, 2], [3, 4]])
self.assertEqual(x.mT.tolist(), [[1, 3], [2, 4]])
self.assertEqual(mx.matrix_transpose(x).tolist(), [[1, 3], [2, 4]])
x = mx.arange(24).reshape((2, 3, 4))
self.assertEqual(x.mT.shape, (2, 4, 3))
self.assertEqualArray(x.mT, x.transpose((0, 2, 1)))
self.assertEqualArray(x.mT.mT, x)
self.assertEqual(mx.matrix_transpose(x).shape, (2, 4, 3))
self.assertEqualArray(mx.matrix_transpose(x), x.transpose((0, 2, 1)))
x = mx.array([1, 2, 3])
with self.assertRaises(ValueError):
x.mT
with self.assertRaises(ValueError):
mx.matrix_transpose(x)
def test_bool_conversion(self):
x = mx.array(True)
self.assertTrue(x)
x = mx.array(False)
self.assertFalse(x)
x = mx.array(1.0)
self.assertTrue(x)
x = mx.array(0.0)
self.assertFalse(x)
def test_int_type(self):
x = mx.array(1)
self.assertTrue(x.dtype == mx.int32)
x = mx.array(2**32 - 1)
self.assertTrue(x.dtype == mx.int64)
x = mx.array(2**40)
self.assertTrue(x.dtype == mx.int64)
x = mx.array(2**32 - 1, dtype=mx.uint32)
self.assertTrue(x.dtype == mx.uint32)
x = mx.array([1, 2], dtype=mx.int64) + 0x80000000
self.assertTrue(x.dtype == mx.int64)
def test_construction_from_lists(self):
x = mx.array([])
self.assertEqual(x.size, 0)
self.assertEqual(x.shape, (0,))
self.assertEqual(x.dtype, mx.float32)
x = mx.array([[], [], []])
self.assertEqual(x.size, 0)
self.assertEqual(x.shape, (3, 0))
self.assertEqual(x.dtype, mx.float32)
x = mx.array([[[], []], [[], []], [[], []]])
self.assertEqual(x.size, 0)
self.assertEqual(x.shape, (3, 2, 0))
self.assertEqual(x.dtype, mx.float32)
# Check failure cases
with self.assertRaises(ValueError):
x = mx.array([[[], []], [[]], [[], []]])
with self.assertRaises(ValueError):
x = mx.array([[[], []], [[1.0, 2.0], []], [[], []]])
with self.assertRaises(ValueError):
x = mx.array([[0, 1], [[0, 1], 1]])
with self.assertRaises(ValueError):
x = mx.array([[0, 1], ["hello", 1]])
x = mx.array([True, False, 3])
self.assertEqual(x.dtype, mx.int32)
x = mx.array([True, False, 3, 4.0])
self.assertEqual(x.dtype, mx.float32)
x = mx.array([[True, False], [1, 3], [2, 4.0]])
self.assertEqual(x.dtype, mx.float32)
x = mx.array([[1.0, 2.0], [0.0, 3.9]], mx.bool_)
self.assertEqual(x.dtype, mx.bool_)
self.assertTrue(mx.array_equal(x, mx.array([[True, True], [False, True]])))
x = mx.array([[1.0, 2.0], [0.0, 3.9]], mx.int32)
self.assertTrue(mx.array_equal(x, mx.array([[1, 2], [0, 3]])))
x = mx.array([1 + 0j, 2j, True, 0], mx.complex64)
self.assertEqual(x.tolist(), [1 + 0j, 2j, 1 + 0j, 0j])
xnp = np.array([0, 4294967295], dtype=np.uint32)
x = mx.array([0, 4294967295], dtype=mx.uint32)
self.assertTrue(np.array_equal(x, xnp))
xnp = np.array([0, 4294967295], dtype=np.float32)
x = mx.array([0, 4294967295], dtype=mx.float32)
self.assertTrue(np.array_equal(x, xnp))
def test_double_keeps_precision(self):
x = 39.14223403241
out = mx.array(x, dtype=mx.float64).item()
self.assertEqual(out, x)
out = mx.array([x], dtype=mx.float64).item()
self.assertEqual(out, x)
# Integer and bool targets
v = 2**24 + 1
self.assertEqual(mx.array(float(v), dtype=mx.int32).item(), v)
self.assertEqual(mx.array([float(v)], dtype=mx.int64).tolist(), [v])
# Small non-zero values are still True
self.assertTrue(mx.array(1e-50, dtype=mx.bool_).item())
self.assertEqual(mx.array([1e-50], dtype=mx.bool_).tolist(), [True])
# Python ints to float64
out = mx.array([v], dtype=mx.float64).tolist()
self.assertEqual(out, [float(v)])
def test_construction_from_lists_wide_ints(self):
# A python int that does not fit in int32 widens to int64, the same
# rule the scalar path already uses. It used to raise std::bad_cast.
for value in (2**31, 2**40, -(2**31) - 1, -(2**40)):
for make in (
lambda v: [v],
lambda v: (v,),
lambda v: [[v]],
lambda v: [v, 1],
):
x = mx.array(make(value))
self.assertEqual(x.dtype, mx.int64, msg=f"{value} {make(value)}")
self.assertEqual(x.flatten()[0].item(), value)
self.assertEqual(mx.array(value).dtype, mx.int64)
# Values that still fit keep int32, including both boundaries.
for value in (0, 1, 2**31 - 1, -(2**31)):
x = mx.array([value])
self.assertEqual(x.dtype, mx.int32, msg=str(value))
self.assertEqual(x[0].item(), value)
# An explicit dtype still wins.
self.assertEqual(mx.array([2**40], mx.int64).dtype, mx.int64)
self.assertEqual(mx.array([1, 2], mx.int64).dtype, mx.int64)
# A float in the list still makes it float, not int64.
self.assertEqual(mx.array([2**40, 1.5]).dtype, mx.float32)
def test_construction_from_lists_of_mlx_arrays(self):
dtypes = [
mx.bool_,
mx.uint8,
mx.uint16,
mx.uint32,
mx.uint64,
mx.int8,
mx.int16,
mx.int32,
mx.int64,
mx.float16,
mx.float32,
mx.bfloat16,
mx.complex64,
]
for x_t, y_t in permutations(dtypes, 2):
# check type promotion and numeric correctness
x, y = mx.array([1.0], x_t), mx.array([2.0], y_t)
z = mx.array([x, y])
expected = mx.stack([x, y], axis=0)
self.assertEqualArray(z, expected)
# check heterogeneous construction with mlx arrays and python primitive
# types
x, y = mx.array([True], x_t), mx.array([False], y_t)
z = mx.array([[x, [2.0]], [[3.0], y]])
expected = mx.array([[[x.item()], [2.0]], [[3.0], [y.item()]]], z.dtype)
self.assertEqualArray(z, expected)
# check when create from an array which does not contain memory to the raw data
x = mx.array([1.0]).astype(mx.bfloat16) # x does not hold raw data
for y_t in dtypes:
y = mx.array([2.0], y_t)
z = mx.array([x, y])
expected = mx.stack([x, y], axis=0)
self.assertEqualArray(z, expected)
# shape check from `stack()`
with self.assertRaises(ValueError) as e:
mx.array([x, 1.0])
self.assertEqual(
str(e.exception), "Initialization encountered non-uniform length."
)
# shape check from `validate_shape`
with self.assertRaises(ValueError) as e:
mx.array([1.0, x])
self.assertEqual(
str(e.exception), "Initialization encountered non-uniform length."
)
# check that `[mx.array, ...]` retains the `mx.array` in the graph
def f(x):
y = mx.array([x, mx.array([2.0])])
return (2 * y).sum()
x = mx.array([1.0])
dfdx = mx.grad(f)
self.assertEqual(dfdx(x).item(), 2.0)
def test_init_from_array(self):
x = mx.array(3.0)
y = mx.array(x)
self.assertTrue(mx.array_equal(x, y))
y = mx.array(x, mx.int32)
self.assertEqual(y.dtype, mx.int32)
self.assertEqual(y.item(), 3)
y = mx.array(x, mx.bool_)
self.assertEqual(y.dtype, mx.bool_)
self.assertEqual(y.item(), True)
y = mx.array(x, mx.complex64)
self.assertEqual(y.dtype, mx.complex64)
self.assertEqual(y.item(), 3.0 + 0j)
def test_array_repr(self):
x = mx.array(True)
self.assertEqual(str(x), "array(True, dtype=bool)")
x = mx.array(1)
self.assertEqual(str(x), "array(1, dtype=int32)")
x = mx.array(1.0)
self.assertEqual(str(x), "array(1, dtype=float32)")
x = mx.array([1, 0, 1])
self.assertEqual(str(x), "array([1, 0, 1], dtype=int32)")
x = mx.array([1] * 6)
expected = "array([1, 1, 1, 1, 1, 1], dtype=int32)"
self.assertEqual(str(x), expected)
x = mx.array([1] * 7)
expected = "array([1, 1, 1, ..., 1, 1, 1], dtype=int32)"
self.assertEqual(str(x), expected)
x = mx.array([[1, 2], [1, 2], [1, 2]])
expected = "array([[1, 2],\n [1, 2],\n [1, 2]], dtype=int32)"
self.assertEqual(str(x), expected)
x = mx.array([[[1, 2], [1, 2]], [[1, 2], [1, 2]]])
expected = (
"array([[[1, 2],\n"
" [1, 2]],\n"
" [[1, 2],\n"
" [1, 2]]], dtype=int32)"
)
self.assertEqual(str(x), expected)
x = mx.array([[1, 2]] * 6)
expected = (
"array([[1, 2],\n"
" [1, 2],\n"
" [1, 2],\n"
" [1, 2],\n"
" [1, 2],\n"
" [1, 2]], dtype=int32)"
)
self.assertEqual(str(x), expected)
x = mx.array([[1, 2]] * 7)
expected = (
"array([[1, 2],\n"
" [1, 2],\n"
" [1, 2],\n"
" ...,\n"
" [1, 2],\n"
" [1, 2],\n"
" [1, 2]], dtype=int32)"
)
self.assertEqual(str(x), expected)
x = mx.array([1], dtype=mx.int8)
expected = "array([1], dtype=int8)"
self.assertEqual(str(x), expected)
x = mx.array([1], dtype=mx.int16)
expected = "array([1], dtype=int16)"
self.assertEqual(str(x), expected)
x = mx.array([1], dtype=mx.uint8)
expected = "array([1], dtype=uint8)"
self.assertEqual(str(x), expected)
# Fp16 is not supported in all platforms
x = mx.array([1.2], dtype=mx.float16)
expected = "array([1.2002], dtype=float16)"
self.assertEqual(str(x), expected)
x = mx.array([1 + 1j], dtype=mx.complex64)
expected = "array([1+1j], dtype=complex64)"
self.assertEqual(str(x), expected)
x = mx.array([1 - 1j], dtype=mx.complex64)
expected = "array([1-1j], dtype=complex64)"
x = mx.array([1 + 1j], dtype=mx.complex64)
expected = "array([1+1j], dtype=complex64)"
self.assertEqual(str(x), expected)
x = mx.array([1 - 1j], dtype=mx.complex64)
expected = "array([1-1j], dtype=complex64)"
def test_array_repr_precision(self):
x = mx.array([1.123456789], dtype=mx.float32)
expected = "array([1.12346], dtype=float32)"
self.assertEqual(str(x), expected)
with mx.printoptions(precision=4):
expected = "array([1.1235], dtype=float32)"
self.assertEqual(str(x), expected)
mx.set_printoptions(precision=2)
expected = "array([1.12], dtype=float32)"
self.assertEqual(str(x), expected)
x = mx.sin(x)
expected = "array([0.90], dtype=float32)"
self.assertEqual(str(x), expected)
with mx.printoptions(precision=4):
expected = "array([0.9016], dtype=float32)"
self.assertEqual(str(x), expected)
def test_array_to_list(self):
types = [mx.bool_, mx.uint32, mx.int32, mx.int64, mx.float32]
for t in types:
x = mx.array(1, t)
self.assertEqual(x.tolist(), 1)
vals = [1, 2, 3, 4]
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
vals = [[1, 2], [3, 4]]
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
vals = [[1, 0], [0, 1]]
x = mx.array(vals, mx.bool_)
self.assertEqual(x.tolist(), vals)
vals = [[1.5, 2.5], [3.5, 4.5]]
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
vals = [[[0.5, 1.5], [2.5, 3.5]], [[4.5, 5.5], [6.5, 7.5]]]
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
# Empty arrays
vals = []
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
vals = [[], []]
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
# Complex arrays
vals = [0.5 + 0j, 1.5 + 1j, 2.5 + 0j, 3.5 + 1j]
x = mx.array(vals)
self.assertEqual(x.tolist(), vals)
# Half types
vals = [1.0, 2.0, 3.0, 4.0, 5.0]
x = mx.array(vals, dtype=mx.float16)
self.assertEqual(x.tolist(), vals)
x = mx.array(vals, dtype=mx.bfloat16)
self.assertEqual(x.tolist(), vals)
def test_array_np_conversion(self):
# Shape test
a = np.array([])
x = mx.array(a)
self.assertEqual(x.size, 0)
self.assertEqual(x.shape, (0,))
self.assertEqual(x.dtype, mx.float32)
a = np.array([[], [], []])
x = mx.array(a)
self.assertEqual(x.size, 0)
self.assertEqual(x.shape, (3, 0))
self.assertEqual(x.dtype, mx.float32)
a = np.array([[[], []], [[], []], [[], []]])
x = mx.array(a)
self.assertEqual(x.size, 0)
self.assertEqual(x.shape, (3, 2, 0))
self.assertEqual(x.dtype, mx.float32)
# Content test
a = 2.0 * np.ones((3, 5, 4))
x = mx.array(a)
self.assertEqual(x.dtype, mx.float32)
self.assertEqual(x.ndim, 3)
self.assertEqual(x.shape, (3, 5, 4))
y = np.asarray(x)
self.assertTrue(np.allclose(a, y))
a = np.array(3, dtype=np.int32)
x = mx.array(a)
self.assertEqual(x.dtype, mx.int32)
self.assertEqual(x.ndim, 0)
self.assertEqual(x.shape, ())
self.assertEqual(x.item(), 3)
# mlx to numpy test
x = mx.array([True, False, True])
y = np.asarray(x)
self.assertEqual(y.dtype, np.bool_)
self.assertEqual(y.ndim, 1)
self.assertEqual(y.shape, (3,))
self.assertEqual(y[0], True)
self.assertEqual(y[1], False)
self.assertEqual(y[2], True)
# complex64 mx <-> np
cvals = [0j, 1, 1 + 1j]
x = np.array(cvals)
y = mx.array(x)
self.assertEqual(y.dtype, mx.complex64)
self.assertEqual(y.shape, (3,))
self.assertEqual(y.tolist(), cvals)
y = mx.array([0j, 1, 1 + 1j])
x = np.asarray(y)
self.assertEqual(x.dtype, np.complex64)
self.assertEqual(x.shape, (3,))
self.assertEqual(x.tolist(), cvals)
def test_array_np_dtype_conversion(self):
dtypes_list = [
(mx.bool_, np.bool_),
(mx.uint8, np.uint8),
(mx.uint16, np.uint16),
(mx.uint32, np.uint32),
(mx.uint64, np.uint64),
(mx.int8, np.int8),
(mx.int16, np.int16),
(mx.int32, np.int32),
(mx.int64, np.int64),
(mx.float16, np.float16),
(mx.float32, np.float32),
(mx.complex64, np.complex64),
]
for mlx_dtype, np_dtype in dtypes_list:
a_npy = np.random.uniform(low=0, high=100, size=(32,)).astype(np_dtype)
a_mlx = mx.array(a_npy)
self.assertEqual(a_mlx.dtype, mlx_dtype)
self.assertTrue(np.allclose(a_mlx, a_npy))
b_mlx = mx.random.uniform(
low=0,
high=10,
shape=(32,),
).astype(mlx_dtype)
b_npy = np.array(b_mlx)
self.assertEqual(b_npy.dtype, np_dtype)
def test_array_from_noncontiguous_np(self):
for t in [np.int8, np.int32, np.float16, np.float32, np.complex64]:
np_arr = np.random.uniform(size=(10, 10)).astype(np.complex64)
np_arr = np_arr.T
mx_arr = mx.array(np_arr)
self.assertTrue(mx.array_equal(np_arr, mx_arr))
def test_array_np_shape_dim_check(self):
a_npy = np.empty(2**31, dtype=np.bool_)
with self.assertRaises(OverflowError) as e:
mx.array(a_npy)
self.assertEqual(
str(e.exception),
"Shape dimension 2147483648 is outside the supported range "
"[-2147483648, 2147483647]. MLX currently uses 32-bit integers "
"for shape dimensions.",
)
def test_dtype_promotion(self):
dtypes_list = [
(mx.bool_, np.bool_),
(mx.uint8, np.uint8),
(mx.uint16, np.uint16),
(mx.uint32, np.uint32),
(mx.uint64, np.uint64),
(mx.int8, np.int8),
(mx.int16, np.int16),
(mx.int32, np.int32),
(mx.int64, np.int64),
(mx.float32, np.float32),
]
promotion_pairs = permutations(dtypes_list, 2)
for (mlx_dt_1, np_dt_1), (mlx_dt_2, np_dt_2) in promotion_pairs:
with self.subTest(dtype1=np_dt_1, dtype2=np_dt_2):
a_npy = np.ones((3,), dtype=np_dt_1)
b_npy = np.ones((3,), dtype=np_dt_2)
c_npy = a_npy + b_npy