forked from pytorch/executorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMLXInterpreter.h
More file actions
2250 lines (2008 loc) · 72.8 KB
/
Copy pathMLXInterpreter.h
File metadata and controls
2250 lines (2008 loc) · 72.8 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 (c) Meta Platforms, Inc. and affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//
#pragma once
#include "MLXExecutor.h"
#include <mlx/array.h>
#include <mlx/fast.h>
#include <mlx/mlx.h>
#include <mlx/ops.h>
namespace executorch {
namespace backends {
namespace mlx {
namespace ops {
using namespace ::mlx::core;
/**
* Normalize axis to be in range [0, rank) and validate.
* @param axis The axis value (can be negative)
* @param rank The tensor rank
* @param op_name Name of the operation for error messages
* @return Normalized axis in range [0, rank)
* @throws std::out_of_range if axis is out of range
*/
inline int normalize_axis(int axis, int rank, const char* op_name) {
if (axis < -rank || axis >= rank) {
throw std::out_of_range(std::string(op_name) + ": axis out of range");
}
if (axis < 0)
axis += rank;
return axis;
}
/**
* Infers dimensions with -1 in a reshape-like operation.
*
* PyTorch allows -1 in shapes to mean "infer this dimension from total size".
* MLX requires concrete positive integers, so we must resolve -1 values.
*
* @param shape The shape to resolve (may contain -1)
* @param input_size Total number of elements in the input tensor
* @return Resolved shape with all positive integers
* @throws std::runtime_error if shape has multiple -1 or incompatible sizes
*/
inline std::vector<int> infer_shape_with_minus_one(
const std::vector<int>& shape,
size_t input_size) {
std::vector<int> resolved_shape = shape;
int neg_one_idx = -1;
int64_t known_size = 1; // Use int64_t to avoid overflow
// Find -1 dimension and compute product of known dimensions
for (size_t i = 0; i < resolved_shape.size(); i++) {
if (resolved_shape[i] == -1) {
if (neg_one_idx != -1) {
throw std::runtime_error("infer_shape: only one dimension can be -1");
}
neg_one_idx = static_cast<int>(i);
} else {
known_size *= static_cast<int64_t>(resolved_shape[i]);
}
}
// Infer the -1 dimension if present
if (neg_one_idx != -1) {
if (known_size == 0) {
throw std::runtime_error(
"infer_shape: cannot infer -1 dimension when known product is 0");
}
int64_t input_size_i64 = static_cast<int64_t>(input_size);
if (input_size_i64 % known_size != 0) {
throw std::runtime_error(
"infer_shape: cannot infer dimension - size mismatch");
}
int64_t inferred_dim = input_size_i64 / known_size;
// Check that inferred dimension fits in int
if (inferred_dim > std::numeric_limits<int>::max()) {
throw std::runtime_error(
"infer_shape: inferred dimension exceeds int max");
}
resolved_shape[static_cast<size_t>(neg_one_idx)] =
static_cast<int>(inferred_dim);
}
return resolved_shape;
}
// Formula: 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x³)))
inline array gelu_tanh_impl(const array& x, StreamOrDevice s = {}) {
constexpr float sqrt_2_over_pi = 0.7978845608f;
auto dtype = x.dtype();
auto x3 = multiply(x, multiply(x, x, s), s);
auto term = multiply(array(0.044715f, dtype), x3, s);
auto inner = add(x, term, s);
inner = multiply(array(sqrt_2_over_pi, dtype), inner, s);
auto tanh_val = tanh(inner, s);
auto one_plus_tanh = add(array(1.0f, dtype), tanh_val, s);
auto out = multiply(x, one_plus_tanh, s);
out = multiply(array(0.5f, dtype), out, s);
return out;
}
// Formula: 0.5 * x * (1 + erf(x / sqrt(2)))
inline array gelu_none_impl(const array& x, StreamOrDevice s = {}) {
constexpr float inv_sqrt_2 = 0.7071067812f;
auto dtype = x.dtype();
auto scaled = multiply(array(inv_sqrt_2, dtype), x, s);
auto erf_val = erf(scaled, s);
auto one_plus_erf = add(array(1.0f, dtype), erf_val, s);
auto out = multiply(x, one_plus_erf, s);
out = multiply(array(0.5f, dtype), out, s);
return out;
}
inline void exec_noop(const NoopNode&, ExecutionState&, StreamOrDevice) {}
inline void
exec_id_copy(const IdCopyNode& n, ExecutionState& st, StreamOrDevice) {
st.set_tensor(n.out, st.const_tensor_ref(n.x));
}
inline void
exec_addmm(const AddmmNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& mat1 = st.const_tensor_ref(n.mat1);
const auto& mat2 = st.const_tensor_ref(n.mat2);
array Y = n.bias ? addmm(
st.const_tensor_ref(*n.bias),
mat1,
mat2,
/*alpha=*/n.alpha,
/*beta=*/n.beta,
s)
: matmul(mat1, mat2, s);
st.set_tensor(n.out, std::move(Y));
}
inline void
exec_item_int(const ItemIntNode& n, ExecutionState& st, StreamOrDevice) {
// Intentional sync: item() requires a concrete scalar value for SymInt
// shape computation, so we must force GPU evaluation here.
auto x = st.const_tensor_ref(n.x);
eval(x);
int item = x.item<int>();
st.set_value(n.out, item);
}
inline void exec_expand_dims(
const ExpandDimsNode& n,
ExecutionState& st,
StreamOrDevice s) {
st.set_tensor(n.out, expand_dims(st.const_tensor_ref(n.x), n.axis, s));
}
inline void exec_tile(const TileNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
auto reps = resolve_ints(n.reps, st);
st.set_tensor(n.out, tile(x, reps, s));
}
inline void exec_take_along_axis(
const TakeAlongAxisNode& n,
ExecutionState& st,
StreamOrDevice s) {
st.set_tensor(
n.out,
take_along_axis(
st.const_tensor_ref(n.x), st.const_tensor_ref(n.indices), n.axis, s));
}
inline void exec_take(const TakeNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
int axis = normalize_axis(n.axis, static_cast<int>(x.ndim()), "Take");
switch (n.index.kind) {
case 0: { // literal int
int index = normalize_axis(
clamp_to_int32(n.index.literal), x.shape(axis), "Take");
st.set_tensor(n.out, take(x, index, axis, s));
break;
}
case 1: { // Vid (dynamic int)
int index = normalize_axis(
st.const_value_ref<int32_t>(n.index.vid), x.shape(axis), "Take");
st.set_tensor(n.out, take(x, index, axis, s));
break;
}
case 2: { // Tid (tensor of indices)
const auto& indices = st.const_tensor_ref(n.index.tid);
st.set_tensor(n.out, take(x, indices, axis, s));
break;
}
default:
throw std::runtime_error(
"TakeNode: invalid index kind: " + std::to_string(n.index.kind));
}
}
inline void
exec_rms_norm(const RMSNormNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
std::optional<array> w = std::nullopt;
if (n.weight) {
w = st.const_tensor_ref(*n.weight);
}
st.set_tensor(n.out, fast::rms_norm(x, w, n.eps, s));
}
inline void
exec_layer_norm(const LayerNormNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
std::optional<array> w = std::nullopt;
if (n.weight) {
w = st.const_tensor_ref(*n.weight);
}
std::optional<array> bias = std::nullopt;
if (n.bias) {
bias = st.const_tensor_ref(*n.bias);
}
st.set_tensor(n.out, fast::layer_norm(x, w, bias, n.eps, s));
}
inline void exec_rope(const RopeNode& n, ExecutionState& st, StreamOrDevice s) {
const array& x = st.const_tensor_ref(n.x);
std::optional<array> freqs_arr = std::nullopt;
if (n.freqs) {
freqs_arr = st.const_tensor_ref(*n.freqs);
}
// MLX has two overloads: rope(..., int offset, ...) and rope(..., const
// array& offset, ...) Call the appropriate one based on is_vid
if (n.offset.is_vid) {
// Scalar offset from Vid
int offset = st.const_value_ref<int32_t>(n.offset.vid);
st.set_tensor(
n.out,
fast::rope(
x, n.dims, n.traditional, n.base, n.scale, offset, freqs_arr, s));
} else {
// Tensor offset from Tid
const array& offset = st.const_tensor_ref(n.offset.tid);
st.set_tensor(
n.out,
fast::rope(
x, n.dims, n.traditional, n.base, n.scale, offset, freqs_arr, s));
}
}
inline void exec_sdpa(const SdpaNode& n, ExecutionState& st, StreamOrDevice s) {
array Q = st.const_tensor_ref(n.q);
array K = st.const_tensor_ref(n.k);
array V = st.const_tensor_ref(n.v);
std::string mask_mode = "";
std::optional<array> mask_arr = std::nullopt;
std::optional<array> sinks = std::nullopt;
if (n.mask) {
array M = st.const_tensor_ref(*n.mask);
// MLX's SDPA handles bool masks natively (True=attend, False=masked)
// For non-bool masks, ensure dtype matches Q
if (M.dtype() != bool_ && M.dtype() != Q.dtype()) {
M = astype(M, Q.dtype(), s);
}
mask_arr = std::move(M);
}
if (n.causal) {
mask_mode = "causal";
}
array out = fast::scaled_dot_product_attention(
Q, K, V, static_cast<float>(n.scale), mask_mode, mask_arr, sinks, s);
st.set_tensor(n.out, std::move(out));
}
inline void exec_add(const AddNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, add(st.const_tensor_ref(n.a), st.const_tensor_ref(n.b), s));
}
inline void
exec_add_int(const AddIntNode& n, ExecutionState& st, StreamOrDevice) {
int64_t a = resolve_int(n.a, st);
int64_t b = resolve_int(n.b, st);
int64_t result = a + b;
if (result > std::numeric_limits<int32_t>::max() ||
result < std::numeric_limits<int32_t>::min()) {
throw std::runtime_error("add_int: overflow");
}
st.set_value(n.out, static_cast<int32_t>(result));
}
inline void exec_subtract_int(
const SubtractIntNode& n,
ExecutionState& st,
StreamOrDevice) {
int64_t a = resolve_int(n.a, st);
int64_t b = resolve_int(n.b, st);
int64_t result = a - b;
if (result > std::numeric_limits<int32_t>::max() ||
result < std::numeric_limits<int32_t>::min()) {
throw std::runtime_error("subtract_int: overflow");
}
st.set_value(n.out, static_cast<int32_t>(result));
}
inline void exec_multiply_int(
const MultiplyIntNode& n,
ExecutionState& st,
StreamOrDevice) {
int64_t a = resolve_int(n.a, st);
int64_t b = resolve_int(n.b, st);
int64_t result = a * b;
if (result > std::numeric_limits<int32_t>::max() ||
result < std::numeric_limits<int32_t>::min()) {
throw std::runtime_error("multiply_int: overflow");
}
st.set_value(n.out, static_cast<int32_t>(result));
}
inline void exec_floor_divide_int(
const FloorDivideIntNode& n,
ExecutionState& st,
StreamOrDevice) {
int32_t a = resolve_int(n.a, st);
int32_t b = resolve_int(n.b, st);
if (b == 0) {
throw std::runtime_error("floor_divide_int: division by zero");
}
if (a == std::numeric_limits<int32_t>::min() && b == -1) {
throw std::runtime_error("floor_divide_int: overflow (INT32_MIN / -1)");
}
// Floor division for integers (Python semantics: rounds towards negative
// infinity)
int32_t result = a / b;
// Adjust for floor division when signs differ and there's a remainder
if ((a % b != 0) && ((a < 0) != (b < 0))) {
result -= 1;
}
st.set_value(n.out, result);
}
inline void
exec_mod_int(const ModIntNode& n, ExecutionState& st, StreamOrDevice) {
int32_t a = resolve_int(n.a, st);
int32_t b = resolve_int(n.b, st);
if (b == 0) {
throw std::runtime_error("mod_int: division by zero");
}
// Python modulo semantics: result has same sign as divisor
int32_t result = a % b;
if ((result != 0) && ((result < 0) != (b < 0))) {
result += b;
}
st.set_value(n.out, result);
}
inline void
exec_sym_size(const SymSizeNode& n, ExecutionState& st, StreamOrDevice) {
const array& a = st.const_tensor_ref(n.a);
int rank = static_cast<int>(a.ndim());
int dim = n.dim;
if (dim < 0) {
dim += rank;
}
if (dim < 0 || dim >= rank) {
throw std::out_of_range("SYM_SIZE: dim out of range");
}
int32_t size = static_cast<int32_t>(a.shape()[static_cast<size_t>(dim)]);
st.set_value(n.out, size);
}
inline void
exec_multiply(const MultiplyNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, multiply(st.const_tensor_ref(n.a), st.const_tensor_ref(n.b), s));
}
inline void
exec_divide(const DivideNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, divide(st.const_tensor_ref(n.a), st.const_tensor_ref(n.b), s));
}
inline void
exec_subtract(const SubtractNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, subtract(st.const_tensor_ref(n.a), st.const_tensor_ref(n.b), s));
}
inline void
exec_conv1d(const Conv1DNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& w = st.const_tensor_ref(n.w);
auto out = conv1d(x, w, n.stride, n.padding, n.dilation, n.groups, s);
st.set_tensor(n.out, std::move(out));
}
inline void
exec_conv2d(const Conv2DNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& w = st.const_tensor_ref(n.w);
std::pair<int, int> stride = {n.stride_h, n.stride_w};
std::pair<int, int> padding = {n.padding_h, n.padding_w};
std::pair<int, int> dilation = {n.dilation_h, n.dilation_w};
auto out = conv2d(x, w, stride, padding, dilation, n.groups, s);
st.set_tensor(n.out, std::move(out));
}
inline void
exec_conv3d(const Conv3DNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& w = st.const_tensor_ref(n.w);
std::tuple<int, int, int> stride = {n.stride_d, n.stride_h, n.stride_w};
std::tuple<int, int, int> padding = {n.padding_d, n.padding_h, n.padding_w};
std::tuple<int, int, int> dilation = {
n.dilation_d, n.dilation_h, n.dilation_w};
auto out = conv3d(x, w, stride, padding, dilation, n.groups, s);
st.set_tensor(n.out, std::move(out));
}
inline void exec_conv_transpose1d(
const ConvTranspose1DNode& n,
ExecutionState& st,
StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& w = st.const_tensor_ref(n.w);
auto out = conv_transpose1d(
x, w, n.stride, n.padding, n.dilation, n.output_padding, n.groups, s);
st.set_tensor(n.out, std::move(out));
}
inline void exec_conv_transpose2d(
const ConvTranspose2DNode& n,
ExecutionState& st,
StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& w = st.const_tensor_ref(n.w);
std::pair<int, int> stride = {n.stride_h, n.stride_w};
std::pair<int, int> padding = {n.padding_h, n.padding_w};
std::pair<int, int> dilation = {n.dilation_h, n.dilation_w};
std::pair<int, int> output_padding = {n.output_padding_h, n.output_padding_w};
auto out = conv_transpose2d(
x, w, stride, padding, dilation, output_padding, n.groups, s);
st.set_tensor(n.out, std::move(out));
}
inline void exec_conv_transpose3d(
const ConvTranspose3DNode& n,
ExecutionState& st,
StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& w = st.const_tensor_ref(n.w);
std::tuple<int, int, int> stride = {n.stride_d, n.stride_h, n.stride_w};
std::tuple<int, int, int> padding = {n.padding_d, n.padding_h, n.padding_w};
std::tuple<int, int, int> dilation = {
n.dilation_d, n.dilation_h, n.dilation_w};
std::tuple<int, int, int> output_padding = {
n.output_padding_d, n.output_padding_h, n.output_padding_w};
auto out = conv_transpose3d(
x, w, stride, padding, dilation, output_padding, n.groups, s);
st.set_tensor(n.out, std::move(out));
}
inline void exec_gelu(const GeluNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
if (n.approximate == "tanh") {
st.set_tensor(n.out, gelu_tanh_impl(x, s));
} else {
// "none" or any other value uses exact GELU
st.set_tensor(n.out, gelu_none_impl(x, s));
}
}
inline void
exec_arange(const ARangeNode& n, ExecutionState& st, StreamOrDevice s) {
// Get start, stop, step - may be literal int64 or dynamic Vid
int start_val = resolve_int(n.start, st);
int stop_val = resolve_int(n.stop, st);
int step_val = resolve_int(n.step, st);
if (step_val == 0) {
throw std::runtime_error("arange: step must not be zero");
}
// Bound the output size: numel = ceil((stop - start) / step)
int64_t range = static_cast<int64_t>(stop_val) - start_val;
int64_t numel = 0;
if ((range > 0 && step_val > 0) || (range < 0 && step_val < 0)) {
numel = (range / step_val) + (range % step_val != 0 ? 1 : 0);
}
auto dtype = n.scalar_type.has_value() ? resolve_dtype(n.scalar_type.value())
: ::mlx::core::int32;
check_allocation_bounded(
{static_cast<int>(std::min(
numel, static_cast<int64_t>(std::numeric_limits<int>::max())))},
dtype,
"arange");
if (n.scalar_type.has_value()) {
st.set_tensor(n.out, arange(start_val, stop_val, step_val, dtype, s));
} else {
// No dtype specified - use MLX's default (infers from inputs).
// The bounds check above conservatively assumes int32.
st.set_tensor(n.out, arange(start_val, stop_val, step_val, s));
}
}
inline void exec_silu(const SiluNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
st.set_tensor(n.out, multiply(x, sigmoid(x, s), s));
}
inline void
exec_sigmoid(const SigmoidNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
st.set_tensor(n.out, sigmoid(x, s));
}
inline void exec_tanh(const TanhNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
st.set_tensor(n.out, tanh(x, s));
}
inline void
exec_squeeze(const SqueezeNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& dims_fb = n.dims;
if (dims_fb.size() > 0) {
// Squeeze specific dimensions, filtering out non-size-1 dims to match
// PyTorch semantics where squeeze on a non-size-1 dim is a no-op.
std::vector<int> dims;
for (auto d : dims_fb) {
int axis = d < 0 ? d + static_cast<int>(x.ndim()) : d;
if (axis >= 0 && axis < static_cast<int>(x.ndim()) &&
x.shape(axis) == 1) {
dims.push_back(d);
}
}
if (dims.size() > 0) {
st.set_tensor(n.out, squeeze(x, dims, s));
} else {
st.set_tensor(n.out, x);
}
} else {
// Squeeze all dimensions of size 1
st.set_tensor(n.out, squeeze(x, s));
}
}
inline void
exec_split(const SplitNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
// Resolve dynamic sizes to std::vector<int>
std::vector<int32_t> sizes_vec = resolve_ints(n.sizes, st);
// Get results based on split mode
auto outs_fb = n.outs;
if (sizes_vec.size() == 1) {
// Single value means split_size (chunk size)
// Compute actual sizes: e.g., dim_size=10, split_size=3 -> [3, 3, 3, 1]
int split_size = sizes_vec[0];
if (split_size <= 0) {
throw std::runtime_error(
"split: split_size must be positive, got " +
std::to_string(split_size));
}
int axis = n.axis < 0 ? n.axis + static_cast<int>(x.ndim()) : n.axis;
int dim_size = x.shape(axis);
std::vector<int> indices;
for (int pos = split_size; pos < dim_size; pos += split_size) {
indices.push_back(pos);
}
auto results = split(x, to_shape(indices), n.axis, s);
if (results.size() != outs_fb.size()) {
throw std::runtime_error("Split: output count mismatch");
}
for (size_t i = 0; i < results.size(); ++i) {
st.set_tensor(outs_fb[i], std::move(results[i]));
}
} else {
// Multiple sizes: convert to cumulative indices for MLX
// sizes=[10, 20, 30] -> indices=[10, 30] (split at positions 10 and 30)
std::vector<int> indices;
indices.reserve(sizes_vec.size() - 1);
int64_t cumsum = 0;
for (size_t i = 0; i < sizes_vec.size() - 1; ++i) {
cumsum += static_cast<int64_t>(sizes_vec[i]);
if (cumsum > std::numeric_limits<int32_t>::max() ||
cumsum < std::numeric_limits<int32_t>::min()) {
throw std::runtime_error("split: cumulative size overflow");
}
indices.push_back(static_cast<int>(cumsum));
}
auto results = split(x, to_shape(indices), n.axis, s);
if (results.size() != outs_fb.size()) {
throw std::runtime_error("Split: output count mismatch");
}
for (size_t i = 0; i < results.size(); ++i) {
st.set_tensor(outs_fb[i], std::move(results[i]));
}
}
}
inline void
exec_rsqrt(const RsqrtNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
st.set_tensor(n.out, rsqrt(x, s));
}
inline void
exec_maximum(const MaximumNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, maximum(st.const_tensor_ref(n.a), st.const_tensor_ref(n.b), s));
}
inline void
exec_minimum(const MinimumNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, minimum(st.const_tensor_ref(n.a), st.const_tensor_ref(n.b), s));
}
inline void exec_log(const LogNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
st.set_tensor(n.out, log(x, s));
}
inline void
exec_softmax(const SoftmaxNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
st.set_tensor(n.out, softmax(x, n.axis, n.precise, s));
}
inline void exec_broadcast_to(
const BroadcastToNode& n,
ExecutionState& st,
StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
auto shape_vec = resolve_ints(n.shape, st);
// Replace -1 with actual input dimensions (PyTorch expand semantics:
// -1 means "keep this dimension unchanged from input").
// Dimensions are aligned from the RIGHT (broadcast semantics).
const auto& x_shape = x.shape();
int offset =
static_cast<int>(shape_vec.size()) - static_cast<int>(x_shape.size());
for (size_t i = 0; i < shape_vec.size(); i++) {
if (shape_vec[i] == -1) {
int input_dim = static_cast<int>(i) - offset;
if (input_dim >= 0 && input_dim < static_cast<int>(x_shape.size())) {
shape_vec[i] =
static_cast<int>(x_shape[static_cast<size_t>(input_dim)]);
}
}
}
st.set_tensor(
n.out,
broadcast_to(
x, ::mlx::core::Shape(shape_vec.begin(), shape_vec.end()), s));
}
inline void exec_pad(const PadNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
// Convert flat pad_width to vector of pairs
std::vector<std::pair<int, int>> pad_width_pairs;
auto pad_width_resolved = resolve_ints(n.pad_width, st);
if (pad_width_resolved.size() % 2 != 0) {
throw std::runtime_error(
"pad: pad_width must have even length, got " +
std::to_string(pad_width_resolved.size()));
}
for (size_t i = 0; i < pad_width_resolved.size(); i += 2) {
pad_width_pairs.push_back(
{pad_width_resolved[i], pad_width_resolved[i + 1]});
}
// MLX pad signature: pad(array, pad_width, pad_value, mode, stream)
if (n.mode == "constant") {
array pad_value(n.constant_value);
st.set_tensor(n.out, pad(x, pad_width_pairs, pad_value, "constant", s));
} else if (n.mode == "edge") {
array pad_value(0.0f);
st.set_tensor(n.out, pad(x, pad_width_pairs, pad_value, "edge", s));
} else {
throw std::runtime_error("Unsupported pad mode: " + n.mode);
}
}
inline void
exec_where(const WhereNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& condition = st.const_tensor_ref(n.condition);
const auto& x = st.const_tensor_ref(n.x);
const auto& y = st.const_tensor_ref(n.y);
st.set_tensor(n.out, where(condition, x, y, s));
}
inline void
exec_reshape(const ReshapeNode& n, ExecutionState& st, StreamOrDevice s) {
auto new_shape = to_shape(n.shape, st);
st.set_tensor(n.out, reshape(st.const_tensor_ref(n.x), new_shape, s));
}
inline void
exec_transpose(const TransposeNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(n.out, transpose(st.const_tensor_ref(n.x), n.perm, s));
}
inline void
exec_as_strided(const AsStridedNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
auto shape = to_shape(n.shape, st);
auto resolved_strides = resolve_ints(n.strides, st);
Strides strides(resolved_strides.begin(), resolved_strides.end());
st.set_tensor(n.out, as_strided(x, shape, strides, n.offset, s));
}
inline void
exec_contiguous(const ContiguousNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(n.out, contiguous(st.const_tensor_ref(n.x), false, s));
}
inline void
exec_gather(const GatherNode& n, ExecutionState& st, StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const int rank = static_cast<int>(x.ndim());
if (n.indices.size() != n.axes.size()) {
throw std::runtime_error(
"GatherNode: indices count (" + std::to_string(n.indices.size()) +
") must match axes count (" + std::to_string(n.axes.size()) + ")");
}
if (static_cast<int>(n.slice_sizes.size()) != rank) {
throw std::runtime_error(
"GatherNode: slice_sizes length (" +
std::to_string(n.slice_sizes.size()) + ") must match input ndim (" +
std::to_string(rank) + ")");
}
for (auto axis : n.axes) {
if (axis < 0 || axis >= rank) {
throw std::runtime_error(
"GatherNode: axis " + std::to_string(axis) +
" out of range for input with ndim " + std::to_string(rank));
}
}
Shape slice_sizes(n.slice_sizes.begin(), n.slice_sizes.end());
check_allocation_bounded(slice_sizes, x.dtype(), "gather");
std::vector<array> indices;
indices.reserve(n.indices.size());
for (auto tid : n.indices) {
indices.push_back(st.const_tensor_ref(tid));
}
st.set_tensor(n.out, gather(x, indices, n.axes, slice_sizes, s));
}
inline void exec_scatter_add(
const ScatterAddNode& n,
ExecutionState& st,
StreamOrDevice s) {
const auto& x = st.const_tensor_ref(n.x);
const auto& indices = st.const_tensor_ref(n.indices);
const auto& updates = st.const_tensor_ref(n.updates);
st.set_tensor(n.out, scatter_add_axis(x, indices, updates, n.axis, s));
}
inline void
exec_slice(const SliceNode& n, ExecutionState& st, StreamOrDevice s) {
const array& x = st.const_tensor_ref(n.x);
const int rank = static_cast<int>(x.ndim());
int axis = normalize_axis(resolve_int(n.axis, st), rank, "Slice");
int start = resolve_int(n.start, st);
int stop = resolve_int(n.stop, st);
std::vector<int> vstart(static_cast<size_t>(rank), 0);
std::vector<int> vstop;
vstop.reserve(static_cast<size_t>(rank));
auto sh = x.shape();
for (size_t i = 0; i < static_cast<size_t>(rank); ++i) {
vstop.push_back(static_cast<int>(sh[i]));
}
if (n.step == 0) {
throw std::invalid_argument("Slice: step must not be 0");
}
vstart[static_cast<size_t>(axis)] = start;
vstop[static_cast<size_t>(axis)] = stop;
std::vector<int> vstrides(static_cast<size_t>(rank), 1);
vstrides[static_cast<size_t>(axis)] = n.step;
st.set_tensor(
n.out,
slice(x, to_shape(vstart), to_shape(vstop), to_shape(vstrides), s));
}
inline void
exec_astype(const AsTypeNode& n, ExecutionState& st, StreamOrDevice s) {
st.set_tensor(
n.out, astype(st.const_tensor_ref(n.x), resolve_dtype(n.scalar_type), s));
}
inline void exec_quantized_matmul(
const QuantizedMatmulNode& n,
ExecutionState& st,
StreamOrDevice s) {
array X = st.const_tensor_ref(n.x);
array Wq = st.const_tensor_ref(n.w);
array Sc = st.const_tensor_ref(n.scales);
std::optional<array> Qb = std::nullopt;
if (n.biases.has_value()) {
Qb = st.const_tensor_ref(*n.biases);
}
array Y = quantized_matmul(
X, Wq, Sc, Qb, n.transpose, n.group_size, n.bits, n.mode, s);
st.set_tensor(n.out, std::move(Y));
}
inline void
exec_gather_mm(const GatherMmNode& n, ExecutionState& st, StreamOrDevice s) {
array A = st.const_tensor_ref(n.a);
array B = st.const_tensor_ref(n.b);
std::optional<array> lhs_idx = std::nullopt;
if (n.lhs_indices.has_value()) {
lhs_idx = st.const_tensor_ref(*n.lhs_indices);
}
std::optional<array> rhs_idx = std::nullopt;
if (n.rhs_indices.has_value()) {
rhs_idx = st.const_tensor_ref(*n.rhs_indices);
}
array Y = gather_mm(A, B, lhs_idx, rhs_idx, n.sorted_indices, s);
st.set_tensor(n.out, std::move(Y));
}
inline void
exec_gather_qmm(const GatherQmmNode& n, ExecutionState& st, StreamOrDevice s) {
array X = st.const_tensor_ref(n.x);
array Wq = st.const_tensor_ref(n.w);
array Sc = st.const_tensor_ref(n.scales);
std::optional<array> Qb = std::nullopt;
if (n.biases.has_value()) {
Qb = st.const_tensor_ref(*n.biases);
}
std::optional<array> lhs_idx = std::nullopt;
if (n.lhs_indices.has_value()) {
lhs_idx = st.const_tensor_ref(*n.lhs_indices);
}
std::optional<array> rhs_idx = std::nullopt;
if (n.rhs_indices.has_value()) {
rhs_idx = st.const_tensor_ref(*n.rhs_indices);
}
array Y = gather_qmm(
X,
Wq,
Sc,
Qb,
lhs_idx,
rhs_idx,
n.transpose,
n.group_size,
n.bits,
n.mode,
n.sorted_indices,
s);
st.set_tensor(n.out, std::move(Y));
}
inline void exec_metal_kernel(
const MetalKernelNode& n,
ExecutionState& st,
StreamOrDevice s) {
#ifndef ET_MLX_ALLOW_CUSTOM_KERNEL_EXECUTION
throw std::runtime_error(
"MetalKernelNode: custom kernel execution is disabled. "
"Rebuild with -DET_MLX_ALLOW_CUSTOM_KERNEL_EXECUTION to enable. "
"WARNING: enabling this allows .pte files to execute arbitrary GPU code.");
#else
// Validate parallel array lengths
if (n.input_names.size() != n.inputs.size()) {
throw std::runtime_error(
"MetalKernelNode: input_names length (" +
std::to_string(n.input_names.size()) + ") must match inputs length (" +
std::to_string(n.inputs.size()) + ")");
}
if (n.output_names.size() != n.outputs.size()) {
throw std::runtime_error(
"MetalKernelNode: output_names length (" +
std::to_string(n.output_names.size()) +
") must match outputs length (" + std::to_string(n.outputs.size()) +
")");
}
if (n.outputs.empty()) {
throw std::runtime_error("MetalKernelNode: outputs must not be empty");
}
if (n.inputs.empty()) {
throw std::runtime_error("MetalKernelNode: inputs must not be empty");
}
if (n.output_shape_lengths.size() != n.outputs.size()) {
throw std::runtime_error(
"MetalKernelNode: output_shape_lengths length (" +
std::to_string(n.output_shape_lengths.size()) +
") must match outputs length (" + std::to_string(n.outputs.size()) +
")");
}
if (n.output_dtypes.size() != n.outputs.size()) {
throw std::runtime_error(
"MetalKernelNode: output_dtypes length (" +
std::to_string(n.output_dtypes.size()) +
") must match outputs length (" + std::to_string(n.outputs.size()) +
")");
}
// Validate output_shapes_flat length matches sum of output_shape_lengths
size_t expected_flat_len = 0;
for (int32_t len : n.output_shape_lengths) {
if (len < 0) {
throw std::runtime_error(
"MetalKernelNode: output_shape_lengths contains negative value " +
std::to_string(len));
}
expected_flat_len += static_cast<size_t>(len);
}
if (n.output_shapes_flat.size() != expected_flat_len) {
throw std::runtime_error(
"MetalKernelNode: output_shapes_flat length (" +
std::to_string(n.output_shapes_flat.size()) +
") must equal sum of output_shape_lengths (" +
std::to_string(expected_flat_len) + ")");
}
// Validate template arg parallel arrays
if (n.template_arg_kinds.size() != n.template_arg_names.size() ||
n.template_arg_values.size() != n.template_arg_names.size()) {
throw std::runtime_error(
"MetalKernelNode: template_arg_names/kinds/values must have same length (" +
std::to_string(n.template_arg_names.size()) + "/" +
std::to_string(n.template_arg_kinds.size()) + "/" +
std::to_string(n.template_arg_values.size()) + ")");
}
// Build the kernel function (cached internally by MLX based on name+source)
auto kernel_fn = ::mlx::core::fast::metal_kernel(
n.name,
n.input_names,
n.output_names,
n.source,
n.header,
n.ensure_row_contiguous,
n.atomic_outputs);
// Resolve inputs
std::vector<array> inputs;
inputs.reserve(n.inputs.size());
for (const auto& tid : n.inputs) {
inputs.push_back(st.const_tensor_ref(tid));
}
// Resolve grid and threadgroup (IntOrVid → int)