-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmlx_cxx_bridge.cpp
More file actions
5895 lines (5097 loc) · 224 KB
/
mlx_cxx_bridge.cpp
File metadata and controls
5895 lines (5097 loc) · 224 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 2025 mlx-lm-rs authors
// Direct C++ bridge implementation for MLX via cxx
#include "mlx_cxx_bridge.h"
#include "sparse_v_sdpa.h" // Issue #505: fused Sparse-V SDPA kernel.
#include "turbo4_delegated_sdpa.h" // Issue #528: fused Turbo4Delegated SDPA kernel.
#include "mlx/ops.h"
#include "mlx/transforms.h"
#include "mlx/compile.h"
#include "mlx/memory.h"
#include "mlx/linalg.h"
#include "mlx/fft.h"
#include "mlx/graph_utils.h"
#include "mlx/random.h"
#include "mlx/einsum.h"
#include "mlx/utils.h"
#ifdef __APPLE__
#include "mlx/backend/metal/metal.h"
#endif
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <unordered_map>
namespace mlx_cxx {
using namespace mlx::core;
// Helper to convert rust slice to std::vector<int32_t> (Shape)
static Shape to_shape(rust::Slice<const int32_t> slice) {
return Shape(slice.begin(), slice.end());
}
// Helper to convert Dtype int to mlx::core::Dtype
static Dtype to_dtype(int32_t dtype) {
switch (dtype) {
case 0: return bool_;
case 1: return uint8;
case 2: return uint16;
case 3: return uint32;
case 4: return uint64;
case 5: return int8;
case 6: return int16;
case 7: return int32;
case 8: return int64;
case 9: return float16;
case 10: return float32;
case 11: return float64;
case 12: return bfloat16;
case 13: return complex64;
default: return float32;
}
}
// Helper to convert mlx::core::Dtype to int
static int32_t from_dtype(Dtype dtype) {
switch (dtype.val()) {
case bool_.val(): return 0;
case uint8.val(): return 1;
case uint16.val(): return 2;
case uint32.val(): return 3;
case uint64.val(): return 4;
case int8.val(): return 5;
case int16.val(): return 6;
case int32.val(): return 7;
case int64.val(): return 8;
case float16.val(): return 9;
case float32.val(): return 10;
case float64.val(): return 11;
case bfloat16.val(): return 12;
case complex64.val(): return 13;
default: return 10; // float32
}
}
// MLX Python's nn.gelu_approx uses the tanh approximation:
// 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3))).
// Keep this helper local so exact-GELU models can continue to use the
// erf-based compiled_geglu_activation path.
static array gelu_tanh_approx(const array& x) {
auto dtype = x.dtype();
auto half = array(0.5f, dtype);
auto one = array(1.0f, dtype);
auto coeff = array(0.7978845608028654f, dtype); // sqrt(2/pi)
auto cubic_coeff = array(0.044715f, dtype);
auto x2 = mlx::core::multiply(x, x);
auto x3 = mlx::core::multiply(x2, x);
auto inner = mlx::core::multiply(
coeff,
mlx::core::add(x, mlx::core::multiply(cubic_coeff, x3)));
auto cdf = mlx::core::multiply(half, mlx::core::add(one, mlx::core::tanh(inner)));
return mlx::core::multiply(x, cdf);
}
// Stream functions.
std::unique_ptr<MlxStream> default_stream() {
return std::make_unique<MlxStream>(mlx::core::default_stream(mlx::core::default_device()));
}
std::unique_ptr<MlxStream> new_stream_on_device(bool gpu) {
Device d = gpu ? Device::gpu : Device::cpu;
return std::make_unique<MlxStream>(mlx::core::new_stream(d));
}
void synchronize_stream(const MlxStream& stream) {
mlx::core::synchronize(stream.inner);
}
// Thread-local stream surface (issue #556 / mlx-vlm PR #1050).
//
// Each `ThreadLocalStream` registers a TLS slot keyed by a stream
// index. When a different thread first calls
// `stream_from_thread_local_stream` with the same handle, MLX
// transparently allocates a dedicated `Stream` for that thread on the
// same device. Synchronization through `synchronize(ThreadLocalStream)`
// targets the calling thread's resolved stream — exactly what the
// generation stream owners want so dispatch and sync stay paired.
std::unique_ptr<MlxThreadLocalStream> new_thread_local_stream_gpu() {
return std::make_unique<MlxThreadLocalStream>(
mlx::core::new_thread_local_stream(mlx::core::Device::gpu));
}
std::unique_ptr<MlxStream> stream_from_thread_local_stream(const MlxThreadLocalStream& tls) {
return std::make_unique<MlxStream>(mlx::core::stream_from_thread_local_stream(tls.inner));
}
void synchronize_thread_local_stream(const MlxThreadLocalStream& tls) {
mlx::core::synchronize(tls.inner);
}
// Array factory functions.
std::unique_ptr<MlxArray> zeros(rust::Slice<const int32_t> shape, int32_t dtype) {
return std::make_unique<MlxArray>(mlx::core::zeros(to_shape(shape), to_dtype(dtype)));
}
std::unique_ptr<MlxArray> zeros_stream(rust::Slice<const int32_t> shape, int32_t dtype, const MlxStream& stream) {
return std::make_unique<MlxArray>(mlx::core::zeros(to_shape(shape), to_dtype(dtype), stream.inner));
}
std::unique_ptr<MlxArray> ones(rust::Slice<const int32_t> shape, int32_t dtype) {
return std::make_unique<MlxArray>(mlx::core::ones(to_shape(shape), to_dtype(dtype)));
}
std::unique_ptr<MlxArray> ones_stream(rust::Slice<const int32_t> shape, int32_t dtype, const MlxStream& stream) {
return std::make_unique<MlxArray>(mlx::core::ones(to_shape(shape), to_dtype(dtype), stream.inner));
}
std::unique_ptr<MlxArray> full_f32(rust::Slice<const int32_t> shape, float value, int32_t dtype) {
return std::make_unique<MlxArray>(mlx::core::full(to_shape(shape), value, to_dtype(dtype)));
}
std::unique_ptr<MlxArray> eye(int32_t n, int32_t m, int32_t k, int32_t dtype) {
return std::make_unique<MlxArray>(mlx::core::eye(n, m, k, to_dtype(dtype)));
}
std::unique_ptr<MlxArray> linspace(float start, float stop, int32_t num, int32_t dtype) {
return std::make_unique<MlxArray>(mlx::core::linspace(start, stop, num, to_dtype(dtype)));
}
std::unique_ptr<MlxArray> zeros_like(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::zeros_like(a.inner));
}
std::unique_ptr<MlxArray> ones_like(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::ones_like(a.inner));
}
std::unique_ptr<MlxArray> full_like(const MlxArray& a, float value) {
return std::make_unique<MlxArray>(mlx::core::full_like(a.inner, value));
}
std::unique_ptr<MlxArray> from_slice_f32(rust::Slice<const float> data, rust::Slice<const int32_t> shape) {
return std::make_unique<MlxArray>(array(data.data(), to_shape(shape)));
}
std::unique_ptr<MlxArray> from_slice_i32(rust::Slice<const int32_t> data, rust::Slice<const int32_t> shape) {
return std::make_unique<MlxArray>(array(data.data(), to_shape(shape)));
}
std::unique_ptr<MlxArray> from_slice_u32(rust::Slice<const uint32_t> data, rust::Slice<const int32_t> shape) {
return std::make_unique<MlxArray>(array(data.data(), to_shape(shape)));
}
std::unique_ptr<MlxArray> from_slice_i64(rust::Slice<const int64_t> data, rust::Slice<const int32_t> shape) {
return std::make_unique<MlxArray>(array(data.data(), to_shape(shape)));
}
// Helper to create array from typed pointer
// Does NOT call eval - caller is responsible for ensuring data remains valid until eval
template<typename T>
static std::unique_ptr<MlxArray> make_array_typed(const uint8_t* data, const Shape& shape, Dtype dtype) {
auto result = array(reinterpret_cast<const T*>(data), shape, dtype);
return std::make_unique<MlxArray>(result);
}
// Create array from raw bytes with specified dtype
// Uses MLX's array constructor with typed pointer cast
// IMPORTANT: Caller must call eval() on the result before source data goes out of scope
std::unique_ptr<MlxArray> from_bytes(rust::Slice<const uint8_t> data, rust::Slice<const int32_t> shape, int32_t dtype) {
auto mlx_dtype = to_dtype(dtype);
auto mlx_shape = to_shape(shape);
// Create array from raw data with correct pointer type
switch (dtype) {
case 3: // UINT32
return make_array_typed<uint32_t>(data.data(), mlx_shape, mlx_dtype);
case 4: // UINT64
return make_array_typed<uint64_t>(data.data(), mlx_shape, mlx_dtype);
case 7: // INT32
return make_array_typed<int32_t>(data.data(), mlx_shape, mlx_dtype);
case 8: // INT64
return make_array_typed<int64_t>(data.data(), mlx_shape, mlx_dtype);
case 10: // FLOAT32
return make_array_typed<float>(data.data(), mlx_shape, mlx_dtype);
case 1: // UINT8
default:
return std::make_unique<MlxArray>(array(data.data(), mlx_shape, mlx_dtype));
}
}
std::unique_ptr<MlxArray> from_bytes_nocopy(
rust::Slice<const uint8_t> data,
rust::Slice<const int32_t> shape,
int32_t dtype) {
auto mlx_dtype = to_dtype(dtype);
auto mlx_shape = to_shape(shape);
void* ptr = const_cast<uint8_t*>(data.data());
auto noop_deleter = [](void*) {};
return std::make_unique<MlxArray>(array(ptr, mlx_shape, mlx_dtype, noop_deleter));
}
// Helper function to convert float16 bits to float32
inline float f16_to_f32_bits(uint16_t h) {
uint32_t sign = (h >> 15) & 0x1;
uint32_t exp = (h >> 10) & 0x1F;
uint32_t mant = h & 0x3FF;
uint32_t f;
if (exp == 0) {
if (mant == 0) {
f = sign << 31; // Zero
} else {
// Denormalized - convert to normalized
exp = 1;
while ((mant & 0x400) == 0) {
mant <<= 1;
exp--;
}
mant &= 0x3FF;
f = (sign << 31) | ((exp + 112) << 23) | (mant << 13);
}
} else if (exp == 31) {
f = (sign << 31) | 0x7F800000 | (mant << 13); // Inf/NaN
} else {
f = (sign << 31) | ((exp + 112) << 23) | (mant << 13); // Normalized
}
float result;
memcpy(&result, &f, sizeof(float));
return result;
}
// Helper function to convert bfloat16 bits to float32
inline float bf16_to_f32_bits(uint16_t h) {
// bfloat16 is just the upper 16 bits of float32
uint32_t f = static_cast<uint32_t>(h) << 16;
float result;
memcpy(&result, &f, sizeof(float));
return result;
}
// Create half-precision array from raw bytes (bfloat16 or float16).
//
// Native bf16/fp16 mode (default): Creates arrays in their native dtype.
// The CUDA backend patches (#36-#39) ensure bf16 tensors compute natively
// without copy_v conversion overhead, halving memory usage for bf16 models.
//
// Legacy fp32 mode (MLX_BF16_NATIVE=0): Converts to fp32 at load time.
// Use when running on hardware/configurations without bf16 compute patches.
std::unique_ptr<MlxArray> from_bytes_f16(rust::Slice<const uint8_t> data, rust::Slice<const int32_t> shape, bool is_bfloat16) {
auto mlx_shape = to_shape(shape);
size_t num_elements = 1;
for (auto s : mlx_shape) num_elements *= s;
// Check for legacy fp32 conversion mode
static bool use_native = []() {
const char* env = std::getenv("MLX_BF16_NATIVE");
return env == nullptr || std::string(env) != "0";
}();
if (use_native && is_bfloat16) {
// Native bf16: create array directly with bfloat16 dtype.
// SAFETY: bfloat16_t is a trivial struct wrapping uint16_t (2-byte aligned).
// Safetensors data is memory-mapped with naturally aligned tensor offsets,
// so the uint8_t* pointer is guaranteed to be 2-byte aligned for bf16 data.
// MLX's array constructor copies the data immediately via std::copy.
const mlx::core::bfloat16_t* bf16_src =
reinterpret_cast<const mlx::core::bfloat16_t*>(data.data());
return std::make_unique<MlxArray>(
array(bf16_src, mlx_shape, mlx::core::bfloat16));
}
// fp16: keep native on Metal (macOS). On CUDA, fall through to fp32
// conversion because CUDA SDPA doesn't support fp16 output with fp32 mask.
#ifdef __APPLE__
if (!is_bfloat16) {
const mlx::core::float16_t* f16_src =
reinterpret_cast<const mlx::core::float16_t*>(data.data());
return std::make_unique<MlxArray>(
array(f16_src, mlx_shape, mlx::core::float16));
}
#endif
// Legacy fp32 conversion path
std::vector<float> float_data(num_elements);
const uint16_t* src = reinterpret_cast<const uint16_t*>(data.data());
if (is_bfloat16) {
for (size_t i = 0; i < num_elements; ++i) {
float_data[i] = bf16_to_f32_bits(src[i]);
}
} else {
for (size_t i = 0; i < num_elements; ++i) {
float_data[i] = f16_to_f32_bits(src[i]);
}
}
return std::make_unique<MlxArray>(array(float_data.data(), mlx_shape));
}
// Array property accessors.
rust::Vec<int32_t> array_shape(const MlxArray& arr) {
rust::Vec<int32_t> result;
const auto& shape = arr.inner.shape();
for (auto s : shape) {
result.push_back(s);
}
return result;
}
int32_t array_dtype(const MlxArray& arr) {
return from_dtype(arr.inner.dtype());
}
size_t array_size(const MlxArray& arr) {
return arr.inner.size();
}
size_t array_ndim(const MlxArray& arr) {
return arr.inner.ndim();
}
size_t array_itemsize(const MlxArray& arr) {
return arr.inner.itemsize();
}
size_t array_nbytes(const MlxArray& arr) {
return arr.inner.nbytes();
}
// Array data access (scalar extraction).
float item_f32(const MlxArray& arr) {
return const_cast<array&>(arr.inner).item<float>();
}
int32_t item_i32(const MlxArray& arr) {
return const_cast<array&>(arr.inner).item<int32_t>();
}
int64_t item_i64(const MlxArray& arr) {
return const_cast<array&>(arr.inner).item<int64_t>();
}
bool item_bool(const MlxArray& arr) {
return const_cast<array&>(arr.inner).item<bool>();
}
rust::Vec<uint8_t> array_to_raw_bytes(const MlxArray& arr) {
// Ensure the array is evaluated and contiguous
auto a = mlx::core::contiguous(arr.inner);
mlx::core::eval(a);
size_t nbytes = a.nbytes();
const auto* data = reinterpret_cast<const uint8_t*>(a.data<void>());
rust::Vec<uint8_t> result;
result.reserve(nbytes);
for (size_t i = 0; i < nbytes; ++i) {
result.push_back(data[i]);
}
return result;
}
// Evaluation.
void eval(const MlxArray& arr) {
const_cast<array&>(arr.inner).eval();
}
void eval_all(rust::Slice<const MlxArray* const> arrays) {
std::vector<array> arrs;
arrs.reserve(arrays.size());
for (const auto* a : arrays) {
arrs.push_back(a->inner);
}
mlx::core::eval(arrs);
}
// Element-wise binary operations.
std::unique_ptr<MlxArray> add(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::add(a.inner, b.inner));
}
std::unique_ptr<MlxArray> subtract(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::subtract(a.inner, b.inner));
}
std::unique_ptr<MlxArray> remainder(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::remainder(a.inner, b.inner));
}
std::unique_ptr<MlxArray> multiply(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::multiply(a.inner, b.inner));
}
std::unique_ptr<MlxArray> divide(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::divide(a.inner, b.inner));
}
std::unique_ptr<MlxArray> maximum(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::maximum(a.inner, b.inner));
}
std::unique_ptr<MlxArray> minimum(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::minimum(a.inner, b.inner));
}
// Element-wise unary operations.
std::unique_ptr<MlxArray> negative(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::negative(a.inner));
}
std::unique_ptr<MlxArray> abs(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::abs(a.inner));
}
std::unique_ptr<MlxArray> exp(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::exp(a.inner));
}
std::unique_ptr<MlxArray> log(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::log(a.inner));
}
std::unique_ptr<MlxArray> sqrt(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::sqrt(a.inner));
}
std::unique_ptr<MlxArray> rsqrt(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::rsqrt(a.inner));
}
std::unique_ptr<MlxArray> square(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::square(a.inner));
}
std::unique_ptr<MlxArray> sin(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::sin(a.inner));
}
std::unique_ptr<MlxArray> cos(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::cos(a.inner));
}
std::unique_ptr<MlxArray> tanh(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::tanh(a.inner));
}
std::unique_ptr<MlxArray> sigmoid(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::sigmoid(a.inner));
}
std::unique_ptr<MlxArray> floor(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::floor(a.inner));
}
std::unique_ptr<MlxArray> ceil(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::ceil(a.inner));
}
std::unique_ptr<MlxArray> round(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::round(a.inner));
}
std::unique_ptr<MlxArray> sign(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::sign(a.inner));
}
std::unique_ptr<MlxArray> reciprocal(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::reciprocal(a.inner));
}
// Trigonometric functions
std::unique_ptr<MlxArray> tan(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::tan(a.inner));
}
std::unique_ptr<MlxArray> sinh(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::sinh(a.inner));
}
std::unique_ptr<MlxArray> cosh(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::cosh(a.inner));
}
std::unique_ptr<MlxArray> arcsin(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::arcsin(a.inner));
}
std::unique_ptr<MlxArray> arccos(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::arccos(a.inner));
}
std::unique_ptr<MlxArray> arctan(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::arctan(a.inner));
}
std::unique_ptr<MlxArray> arctan2(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::arctan2(a.inner, b.inner));
}
std::unique_ptr<MlxArray> arcsinh(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::arcsinh(a.inner));
}
std::unique_ptr<MlxArray> arccosh(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::arccosh(a.inner));
}
std::unique_ptr<MlxArray> arctanh(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::arctanh(a.inner));
}
std::unique_ptr<MlxArray> degrees(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::degrees(a.inner));
}
std::unique_ptr<MlxArray> radians(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::radians(a.inner));
}
// Mathematical/Special functions
std::unique_ptr<MlxArray> erf(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::erf(a.inner));
}
std::unique_ptr<MlxArray> erfinv(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::erfinv(a.inner));
}
std::unique_ptr<MlxArray> expm1(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::expm1(a.inner));
}
std::unique_ptr<MlxArray> log2(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::log2(a.inner));
}
std::unique_ptr<MlxArray> log10(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::log10(a.inner));
}
std::unique_ptr<MlxArray> logaddexp(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::logaddexp(a.inner, b.inner));
}
std::unique_ptr<MlxArray> power(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::power(a.inner, b.inner));
}
// Checks
std::unique_ptr<MlxArray> isnan(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::isnan(a.inner));
}
std::unique_ptr<MlxArray> isinf(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::isinf(a.inner));
}
std::unique_ptr<MlxArray> isfinite(const MlxArray& a) {
// isfinite = !isnan && !isinf
auto nan_check = mlx::core::isnan(a.inner);
auto inf_check = mlx::core::isinf(a.inner);
auto either = mlx::core::logical_or(nan_check, inf_check);
return std::make_unique<MlxArray>(mlx::core::logical_not(either));
}
std::unique_ptr<MlxArray> isneginf(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::isneginf(a.inner));
}
std::unique_ptr<MlxArray> isposinf(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::isposinf(a.inner));
}
// Reduction operations.
std::unique_ptr<MlxArray> sum_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::sum(a.inner));
}
std::unique_ptr<MlxArray> sum_axis(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::sum(a.inner, axis, keepdims));
}
std::unique_ptr<MlxArray> mean_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::mean(a.inner));
}
std::unique_ptr<MlxArray> mean_axis(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::mean(a.inner, axis, keepdims));
}
std::unique_ptr<MlxArray> max_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::max(a.inner));
}
std::unique_ptr<MlxArray> max_axis(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::max(a.inner, axis, keepdims));
}
std::unique_ptr<MlxArray> min_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::min(a.inner));
}
std::unique_ptr<MlxArray> min_axis(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::min(a.inner, axis, keepdims));
}
// Product reduction
std::unique_ptr<MlxArray> prod_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::prod(a.inner));
}
std::unique_ptr<MlxArray> prod_axis(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::prod(a.inner, axis, keepdims));
}
// Variance and standard deviation
std::unique_ptr<MlxArray> var_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::var(a.inner));
}
std::unique_ptr<MlxArray> var_axis(const MlxArray& a, int32_t axis, bool keepdims, int32_t ddof) {
return std::make_unique<MlxArray>(mlx::core::var(a.inner, axis, keepdims, ddof));
}
std::unique_ptr<MlxArray> std_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::std(a.inner));
}
std::unique_ptr<MlxArray> std_axis(const MlxArray& a, int32_t axis, bool keepdims, int32_t ddof) {
return std::make_unique<MlxArray>(mlx::core::std(a.inner, axis, keepdims, ddof));
}
// Logsumexp
std::unique_ptr<MlxArray> logsumexp_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::logsumexp(a.inner));
}
std::unique_ptr<MlxArray> logsumexp_axis(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::logsumexp(a.inner, axis, keepdims));
}
// All/any reductions
std::unique_ptr<MlxArray> all_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::all(a.inner));
}
std::unique_ptr<MlxArray> any_all(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::any(a.inner));
}
// Matrix operations.
std::unique_ptr<MlxArray> matmul(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::matmul(a.inner, b.inner));
}
std::unique_ptr<MlxArray> transpose(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::transpose(a.inner));
}
std::unique_ptr<MlxArray> transpose_axes(const MlxArray& a, rust::Slice<const int32_t> axes) {
std::vector<int> axes_vec(axes.begin(), axes.end());
return std::make_unique<MlxArray>(mlx::core::transpose(a.inner, axes_vec));
}
std::unique_ptr<MlxArray> reshape(const MlxArray& a, rust::Slice<const int32_t> shape) {
return std::make_unique<MlxArray>(mlx::core::reshape(a.inner, to_shape(shape)));
}
// Shape operations.
std::unique_ptr<MlxArray> expand_dims(const MlxArray& a, int32_t axis) {
return std::make_unique<MlxArray>(mlx::core::expand_dims(a.inner, axis));
}
// Multi-axis variant: mirrors Python's `mx.expand_dims(a, (ax0, ax1, ...))`,
// which ends up in the `expand_dims(array, std::vector<int>)` MLX overload.
// A single bridge call avoids the per-axis FFI + UniquePtr alloc overhead
// that was showing up in SwitchGeGLU decode profiles (first expand_dims
// taking ~0.8 ms because the preceding layer's graph had to sync, even
// though the second back-to-back call was ~0.02 ms).
std::unique_ptr<MlxArray> expand_dims_multi(
const MlxArray& a,
rust::Slice<const int32_t> axes
) {
std::vector<int> ax;
ax.reserve(axes.size());
for (int32_t axis : axes) {
ax.push_back(static_cast<int>(axis));
}
return std::make_unique<MlxArray>(mlx::core::expand_dims(a.inner, ax));
}
std::unique_ptr<MlxArray> squeeze(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::squeeze(a.inner));
}
std::unique_ptr<MlxArray> squeeze_axis(const MlxArray& a, int32_t axis) {
return std::make_unique<MlxArray>(mlx::core::squeeze(a.inner, axis));
}
std::unique_ptr<MlxArray> broadcast_to(const MlxArray& a, rust::Slice<const int32_t> shape) {
return std::make_unique<MlxArray>(mlx::core::broadcast_to(a.inner, to_shape(shape)));
}
// Flatten array
std::unique_ptr<MlxArray> flatten(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::flatten(a.inner));
}
std::unique_ptr<MlxArray> flatten_range(const MlxArray& a, int32_t start_axis, int32_t end_axis) {
return std::make_unique<MlxArray>(mlx::core::flatten(a.inner, start_axis, end_axis));
}
// Move axis
std::unique_ptr<MlxArray> moveaxis(const MlxArray& a, int32_t source, int32_t destination) {
return std::make_unique<MlxArray>(mlx::core::moveaxis(a.inner, source, destination));
}
// Pad array
std::unique_ptr<MlxArray> pad(const MlxArray& a, rust::Slice<const int32_t> pad_width, float pad_value) {
// pad_width is pairs of [before, after] for each dimension
// Convert to vector of pairs
std::vector<std::pair<int, int>> width_pairs;
for (size_t i = 0; i + 1 < pad_width.size(); i += 2) {
width_pairs.push_back({pad_width[i], pad_width[i + 1]});
}
return std::make_unique<MlxArray>(mlx::core::pad(a.inner, width_pairs, array(pad_value)));
}
// Split array at indices - returns single concatenated result for simplicity
// For proper multi-output support, users should use slice
std::unique_ptr<MlxArray> split_at_indices(const MlxArray& a, rust::Slice<const int32_t> indices, int32_t axis) {
// Convert to Shape (SmallVector<int>) which MLX expects
Shape idx_shape(indices.begin(), indices.end());
// This returns vector of arrays - we just return the first for simple use cases
// Full split support would need different approach
auto splits = mlx::core::split(a.inner, idx_shape, axis);
if (splits.empty()) {
return std::make_unique<MlxArray>(a.inner);
}
return std::make_unique<MlxArray>(std::move(splits[0]));
}
// Diagonal operations
std::unique_ptr<MlxArray> diag(const MlxArray& a, int32_t k) {
return std::make_unique<MlxArray>(mlx::core::diag(a.inner, k));
}
std::unique_ptr<MlxArray> diagonal(const MlxArray& a, int32_t offset, int32_t axis1, int32_t axis2) {
return std::make_unique<MlxArray>(mlx::core::diagonal(a.inner, offset, axis1, axis2));
}
// Type conversion.
std::unique_ptr<MlxArray> astype(const MlxArray& a, int32_t dtype) {
return std::make_unique<MlxArray>(mlx::core::astype(a.inner, to_dtype(dtype)));
}
// Copy.
std::unique_ptr<MlxArray> copy(const MlxArray& a) {
return std::make_unique<MlxArray>(mlx::core::copy(a.inner));
}
// High-level operations for LLM inference.
std::unique_ptr<MlxArray> softmax(const MlxArray& a, int32_t axis) {
return std::make_unique<MlxArray>(mlx::core::softmax(a.inner, axis));
}
std::unique_ptr<MlxArray> softmax_precise(const MlxArray& a, int32_t axis) {
return std::make_unique<MlxArray>(mlx::core::softmax(a.inner, axis, true));
}
std::unique_ptr<MlxArray> log_softmax(const MlxArray& a, int32_t axis) {
// log_softmax(x) = x - logsumexp(x)
auto lse = mlx::core::logsumexp(a.inner, axis, true);
return std::make_unique<MlxArray>(mlx::core::subtract(a.inner, lse));
}
std::unique_ptr<MlxArray> rms_norm(const MlxArray& x, const MlxArray& weight, float eps) {
// RMS norm: x * weight / sqrt(mean(x^2) + eps)
auto x_sq = mlx::core::square(x.inner);
auto mean_sq = mlx::core::mean(x_sq, -1, true);
auto norm = mlx::core::rsqrt(mlx::core::add(mean_sq, array(eps)));
auto normalized = mlx::core::multiply(x.inner, norm);
auto out = mlx::core::multiply(normalized, weight.inner);
// Keep the high-level fallback dtype-compatible with MLX fast::rms_norm:
// scalar eps arithmetic may promote bf16/f16 inputs to fp32, but model
// layers expect the normalization result to stay on the activation dtype
// to avoid extra memory traffic and copy kernels.
if (out.dtype() != x.inner.dtype()) {
out = mlx::core::astype(out, x.inner.dtype());
}
return std::make_unique<MlxArray>(out);
}
std::unique_ptr<MlxArray> layer_norm(const MlxArray& x, const MlxArray& weight,
const MlxArray& bias, float eps) {
// Layer norm: (x - mean) / sqrt(var + eps) * weight + bias
auto mean = mlx::core::mean(x.inner, -1, true);
auto centered = mlx::core::subtract(x.inner, mean);
auto var = mlx::core::mean(mlx::core::square(centered), -1, true);
auto norm = mlx::core::rsqrt(mlx::core::add(var, array(eps)));
auto normalized = mlx::core::multiply(centered, norm);
auto scaled = mlx::core::multiply(normalized, weight.inner);
return std::make_unique<MlxArray>(mlx::core::add(scaled, bias.inner));
}
std::unique_ptr<MlxArray> concatenate(rust::Slice<const MlxArray* const> arrays, int32_t axis) {
std::vector<array> arrs;
arrs.reserve(arrays.size());
for (const auto* a : arrays) {
arrs.push_back(a->inner);
}
return std::make_unique<MlxArray>(mlx::core::concatenate(arrs, axis));
}
rust::Vec<std::unique_ptr<MlxArray>> split(const MlxArray& a, int32_t num_splits, int32_t axis) {
auto splits = mlx::core::split(a.inner, num_splits, axis);
rust::Vec<std::unique_ptr<MlxArray>> result;
for (auto& s : splits) {
result.push_back(std::make_unique<MlxArray>(std::move(s)));
}
return result;
}
std::unique_ptr<MlxArray> slice(const MlxArray& a,
rust::Slice<const int32_t> starts,
rust::Slice<const int32_t> stops) {
Shape starts_shape(starts.begin(), starts.end());
Shape stops_shape(stops.begin(), stops.end());
return std::make_unique<MlxArray>(mlx::core::slice(a.inner, starts_shape, stops_shape));
}
std::unique_ptr<MlxArray> slice_update(const MlxArray& src,
const MlxArray& update,
rust::Slice<const int32_t> starts,
rust::Slice<const int32_t> stops) {
Shape starts_shape(starts.begin(), starts.end());
Shape stops_shape(stops.begin(), stops.end());
return std::make_unique<MlxArray>(mlx::core::slice_update(src.inner, update.inner, starts_shape, stops_shape));
}
std::unique_ptr<MlxArray> argmax(const MlxArray& a, int32_t axis, bool keepdims) {
return std::make_unique<MlxArray>(mlx::core::argmax(a.inner, axis, keepdims));
}
std::unique_ptr<MlxArray> where_cond(const MlxArray& condition, const MlxArray& x, const MlxArray& y) {
return std::make_unique<MlxArray>(mlx::core::where(condition.inner, x.inner, y.inner));
}
std::unique_ptr<MlxArray> greater(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::greater(a.inner, b.inner));
}
std::unique_ptr<MlxArray> less(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::less(a.inner, b.inner));
}
std::unique_ptr<MlxArray> equal(const MlxArray& a, const MlxArray& b) {
return std::make_unique<MlxArray>(mlx::core::equal(a.inner, b.inner));
}
void random_seed(uint64_t seed) {
mlx::core::random::seed(seed);
}
std::unique_ptr<MlxArray> random_categorical(const MlxArray& logits, int32_t axis) {
return std::make_unique<MlxArray>(mlx::core::random::categorical(logits.inner, axis));
}
// Transformer-specific high-level operations.
std::unique_ptr<MlxArray> rope_forward(
const MlxArray& x,
int32_t head_dim,
float theta,
int32_t offset,
bool traditional
) {
// Generate position-dependent rotation frequencies
// freq = theta^(-2i/d) for i in [0, d/2)
auto half_dim = head_dim / 2;
std::vector<float> inv_freq;
inv_freq.reserve(half_dim);
for (int i = 0; i < half_dim; ++i) {
inv_freq.push_back(1.0f / std::pow(theta, static_cast<float>(2 * i) / head_dim));
}
auto freqs = array(inv_freq.data(), {half_dim});
// Get sequence length from input shape
auto shape = x.inner.shape();
int seq_len = shape[shape.size() - 2]; // [..., seq_len, head_dim]
// Create position indices
std::vector<int> pos;
pos.reserve(seq_len);
for (int i = 0; i < seq_len; ++i) {
pos.push_back(offset + i);
}
auto positions = array(pos.data(), {seq_len});
// Compute angles: pos * freq -> [seq_len, half_dim]
auto pos_f = mlx::core::astype(positions, float32);
pos_f = mlx::core::expand_dims(pos_f, 1); // [seq_len, 1]
freqs = mlx::core::expand_dims(freqs, 0); // [1, half_dim]
auto angles = mlx::core::matmul(pos_f, freqs); // [seq_len, half_dim]
// Compute cos and sin
auto cos_vals = mlx::core::cos(angles);
auto sin_vals = mlx::core::sin(angles);
// Interleave or concatenate based on traditional flag
if (traditional) {
// Traditional: interleave cos, sin
cos_vals = mlx::core::repeat(cos_vals, 2, -1);
sin_vals = mlx::core::repeat(sin_vals, 2, -1);
} else {
// Modern: concatenate cos, sin
cos_vals = mlx::core::concatenate({cos_vals, cos_vals}, -1);
sin_vals = mlx::core::concatenate({sin_vals, sin_vals}, -1);
}
// Apply rotation
auto x1 = mlx::core::slice(x.inner, {}, {}, {2}); // even indices
auto x2 = mlx::core::slice(x.inner, {1}, {}, {2}); // odd indices
// Rotate: x * cos + rotate(x) * sin
auto rotated = mlx::core::concatenate({
mlx::core::subtract(
mlx::core::multiply(x.inner, cos_vals),
mlx::core::multiply(
mlx::core::concatenate({mlx::core::negative(x2), x1}, -1),
sin_vals
)
)
}, -1);
return std::make_unique<MlxArray>(std::move(rotated));
}
std::unique_ptr<MlxArray> apply_rope(
const MlxArray& x,
const MlxArray& cos,
const MlxArray& sin
) {
// Split x into two halves
int dim = x.inner.shape().back();
int half_dim = dim / 2;
auto x1 = mlx::core::slice(x.inner, {0, 0, 0, 0}, {-1, -1, -1, half_dim});
auto x2 = mlx::core::slice(x.inner, {0, 0, 0, half_dim}, {-1, -1, -1, dim});
// Rotate: [x1, x2] * cos + [-x2, x1] * sin
auto rotated_x1 = mlx::core::subtract(
mlx::core::multiply(x1, cos.inner),
mlx::core::multiply(x2, sin.inner)
);
auto rotated_x2 = mlx::core::add(
mlx::core::multiply(x2, cos.inner),
mlx::core::multiply(x1, sin.inner)
);
return std::make_unique<MlxArray>(mlx::core::concatenate({rotated_x1, rotated_x2}, -1));
}
std::unique_ptr<MlxArray> scaled_dot_product_attention(
const MlxArray& q,
const MlxArray& k,
const MlxArray& v,