-
Notifications
You must be signed in to change notification settings - Fork 21.5k
/
ReduceOps.mm
1651 lines (1350 loc) · 64.3 KB
/
ReduceOps.mm
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 © 2022 Apple Inc.
#include <ATen/ATen.h>
#include <ATen/Tensor.h>
#include <ATen/Utils.h>
#include <ATen/TensorUtils.h>
#include <ATen/mps/MPSStream.h>
#include <ATen/native/mps/OperationUtils.h>
#include <ATen/native/ReduceOpsUtils.h>
#include <ATen/native/Pool.h>
#include <torch/library.h>
namespace at {
namespace native {
enum StdVarType {
STANDARD_VARIANCE,
STANDARD_DEVIATION
};
enum MPSReductionType {
MAX,
MIN,
AMAX,
AMIN,
SUM,
PROD,
MEAN,
COUNT_NONZERO
};
void set_apparent_shapes(NSMutableArray<NSNumber*> * &apparent_out_shape,
NSMutableArray<NSNumber*> * &apparent_in_shape,
int64_t num_reduce_dims,
int64_t num_input_dims,
int64_t num_output_dims,
IntArrayRef& input_shape,
NSMutableArray<NSNumber*> * &axes) {
if(num_reduce_dims == 0) {
/* Output shape becomes a one
* Input shape becomes flattened
* Because 0 reduce dims means all dims are reduced
*/
apparent_in_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:1];
int64_t num_in_elements = 1;
for(int i = 0; i < num_input_dims; i++) {
num_in_elements *= input_shape[i];
}
apparent_in_shape[0] = [NSNumber numberWithInt:num_in_elements];
apparent_out_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:1];
apparent_out_shape[0] = @1;
}
else {
// num_output_dims in this case is number of input dims
apparent_out_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:num_output_dims];
for(int i = 0; i < num_output_dims; i++) {
int64_t current_input_dim = input_shape[i];
// If the current dim is to be reduced
bool is_reduce_dim = false;
for(int j = 0; j < num_reduce_dims; j++) {
if(i == [axes[j] intValue]) {
is_reduce_dim = true;
break;
}
}
if(is_reduce_dim) {
apparent_out_shape[i] = @1;
}
else {
apparent_out_shape[i] = [NSNumber numberWithInt:current_input_dim];
}
}
}
}
// Helper function to set the axes of reduction
void set_axes(NSMutableArray<NSNumber *> * &axes,
int64_t num_reduce_dims,
OptionalIntArrayRef opt_dim,
int64_t num_input_dims) {
if(num_reduce_dims == 0) {
axes = [NSMutableArray<NSNumber*> arrayWithCapacity:1];
axes[0] = @0;
}
else {
TORCH_INTERNAL_ASSERT(opt_dim.has_value());
IntArrayRef dim = opt_dim.value();
axes = [NSMutableArray<NSNumber*> arrayWithCapacity:num_reduce_dims];
for(int i = 0; i < num_reduce_dims; i++) {
axes[i] = [NSNumber numberWithInt:maybe_wrap_dim(dim[i], num_input_dims)];
}
}
}
// Helper function to prepare axes and tensor shapes
void set_axes_and_shapes(const Tensor& input_t,
OptionalIntArrayRef opt_dims,
NSMutableArray<NSNumber*> * &axes,
NSMutableArray<NSNumber*> * &apparent_input_shape,
NSMutableArray<NSNumber*> * &apparent_output_shape,
NSMutableArray<NSNumber*> * &output_shape) {
IntArrayRef input_shape = input_t.sizes();
int64_t num_input_dims = input_shape.size();
int64_t num_reduce_dims = opt_dims.has_value() ? opt_dims.value().size() : 0;
int64_t num_output_dims;
num_output_dims = num_reduce_dims == 0 ? 1 : num_input_dims;
// Reduction axes
set_axes(axes, num_reduce_dims, opt_dims, input_shape.size());
// Shapes
set_apparent_shapes(apparent_output_shape,
apparent_input_shape,
num_reduce_dims,
num_input_dims,
num_output_dims,
input_shape,
axes);
// Squeeze dims for output shape
output_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:0];
for(int i=0; i < num_output_dims; i++) {
if([apparent_output_shape[i] longValue] != 1) {
[output_shape addObject:apparent_output_shape[i]];
}
}
}
void reduction_out_mps
(const Tensor& input_tensor,
OptionalIntArrayRef opt_dim,
bool keepdim,
c10::optional<ScalarType> dtype,
const Tensor& output_t,
MPSReductionType reduction_type,
const std::string& func_name) {
auto input_t = (input_tensor.sizes().size() == 0) ? input_tensor.view({1}) : input_tensor;
IntArrayRef input_shape = input_t.sizes();
if (opt_dim.has_value()) {
IntArrayRef dim = opt_dim.value();
for(int i = 0; i < dim.size(); i++) {
auto wrap_dim = maybe_wrap_dim(dim[i], input_shape.size());
TORCH_CHECK(wrap_dim < input_shape.size(),
func_name+": reduction dim must be in the range of input shape")
}
}
namespace native_mps = at::native::mps;
NSMutableArray<NSNumber*> *axes = nil;
NSMutableArray<NSNumber*> *apparent_input_shape = nil;
NSMutableArray<NSNumber*> *apparent_output_shape = nil;
NSMutableArray<NSNumber*> *output_shape = nil;
set_axes_and_shapes(input_t, opt_dim, axes, apparent_input_shape, apparent_output_shape, output_shape);
auto cache_ = native_mps::MPSGraphCache::getInstance();
if (output_t.numel() == 0 || input_t.numel() == 0) {
return;
}
auto stream = at::mps::getCurrentMPSStream();
@autoreleasepool {
// TODO: Make this key proper
NSString* ns_key = [[axes valueForKey:@"description"] componentsJoinedByString:@","];
string key = func_name+":" + string([ns_key UTF8String]) + ":" + native_mps::getMPSTypeString(input_t.scalar_type()) + ":" + native_mps::getMPSTypeString(output_t.scalar_type());
using CachedGraph = native_mps::MPSUnaryCachedGraph;
auto cachedGraph = cache_->LookUpAs<CachedGraph>(key);
if(!cachedGraph) {
native_mps::MPSCachedGraph *tmpCachedGraph = cache_->CreateCachedGraph(key, ^ native_mps::MPSCachedGraph * () {
CachedGraph *newCachedGraph = nil;
@autoreleasepool {
MPSGraph* mpsGraph = native_mps::make_mps_graph();
newCachedGraph = new CachedGraph(mpsGraph);
MPSGraphTensor* inputTensor = native_mps::mpsGraphUnrankedPlaceHolder(mpsGraph, native_mps::getMPSDataType(input_t.scalar_type()));
MPSGraphTensor* castInputTensor = nil;
if(input_t.scalar_type() != ScalarType::Float && input_t.scalar_type() != ScalarType::Int)
castInputTensor = [mpsGraph castTensor:inputTensor
toType:MPSDataTypeFloat32
name:@"castInputTensor"];
else
castInputTensor = inputTensor;
MPSGraphTensor* castOutputTensor = nil;
if(reduction_type == MPSReductionType::SUM) {
castOutputTensor = [mpsGraph reductionSumWithTensor:castInputTensor
axes:axes
name:nil];
} else if(reduction_type == MPSReductionType::PROD) {
castOutputTensor = [mpsGraph reductionProductWithTensor:castInputTensor
axes:axes
name:nil];
} else if(reduction_type == MPSReductionType::MEAN) {
castOutputTensor = [mpsGraph meanOfTensor:inputTensor
axes:axes
name:nil];
} else if(reduction_type == MPSReductionType::COUNT_NONZERO) {
MPSGraphTensor* zeros = [mpsGraph constantWithScalar:0
dataType:castInputTensor.dataType];
MPSGraphTensor* nonZeros = [mpsGraph notEqualWithPrimaryTensor:castInputTensor
secondaryTensor:zeros
name:nil];
castOutputTensor = [mpsGraph reductionSumWithTensor:nonZeros
axes:axes
name:nil];
}
else if(reduction_type == MPSReductionType::AMAX) {
castOutputTensor = [mpsGraph reductionMaximumWithTensor:inputTensor
axes:axes
name:nil];
} else if(reduction_type == MPSReductionType::AMIN) {
castOutputTensor = [mpsGraph reductionMinimumWithTensor:inputTensor
axes:axes
name:nil];
}
MPSGraphTensor* outputTensor = nil;
if(output_t.scalar_type() != ScalarType::Float)
outputTensor = [mpsGraph castTensor:castOutputTensor
toType:(native_mps::getMPSDataType(output_t.scalar_type()))
name:@"outputTensor"];
else
outputTensor = castOutputTensor;
newCachedGraph->inputTensor_ = inputTensor;
newCachedGraph->outputTensor_ = outputTensor;
}
return newCachedGraph;
});
cachedGraph = tmpCachedGraph->as<CachedGraph>();
}
auto inputPlaceholder = native_mps::Placeholder();
if(apparent_input_shape)
inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t, apparent_input_shape);
else
inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t);
auto outputPlaceholder = native_mps::Placeholder(cachedGraph->outputTensor_, output_t, apparent_output_shape);
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *feeds = @{
inputPlaceholder.getMPSGraphTensor() : inputPlaceholder.getMPSGraphTensorData(),
};
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *results = @{
outputPlaceholder.getMPSGraphTensor() : outputPlaceholder.getMPSGraphTensorData()
};
native_mps::runMPSGraph(stream, cachedGraph->graph(), feeds, results);
}
}
TORCH_IMPL_FUNC(sum_out_mps)
(const Tensor& input_t,
OptionalIntArrayRef opt_dim,
bool keepdim,
c10::optional<ScalarType> dtype,
const Tensor& output_t) {
reduction_out_mps(input_t, opt_dim, keepdim, dtype, output_t, MPSReductionType::SUM, "sum_out_mps");
}
TORCH_IMPL_FUNC(prod_out_mps)
(const Tensor& input_t,
int64_t dim,
bool keepdim,
c10::optional<ScalarType> dtype,
const Tensor& output_t) {
int64_t dims[1] = {dim};
reduction_out_mps(input_t, IntArrayRef(dims, 1), keepdim, dtype, output_t, MPSReductionType::PROD, "prod_out_mps");
}
// Taken from ReduceOps.cpp
inline ScalarType get_dtype_from_self(
const Tensor& self,
const optional<ScalarType>& dtype,
bool promote_integers) {
if (dtype.has_value()) {
return dtype.value();
}
ScalarType src_type = self.scalar_type();
if (promote_integers && at::isIntegralType(src_type, /*includeBool=*/true)) {
return kLong;
}
return src_type;
}
TORCH_IMPL_FUNC(amax_out_mps)
(const Tensor& input_t,
IntArrayRef dim,
bool keepdim,
const Tensor& output_t) {
reduction_out_mps(input_t, dim, keepdim, c10::nullopt, output_t, MPSReductionType::AMAX, "amax_out_mps");
}
TORCH_IMPL_FUNC(amin_out_mps)
(const Tensor& input_t,
IntArrayRef dim,
bool keepdim,
const Tensor& output_t) {
reduction_out_mps(input_t, dim, keepdim, c10::nullopt, output_t, MPSReductionType::AMIN, "amin_out_mps");
}
Tensor prod_mps(const Tensor &self, c10::optional<ScalarType> opt_dtype) {
std::vector<int64_t> dims(self.dim());
std::iota(dims.begin(), dims.end(), 0);
Tensor output_t = at::native::empty_mps(
{},
get_dtype_from_self(self, opt_dtype, true),
c10::nullopt,
kMPS,
c10::nullopt,
c10::nullopt);
reduction_out_mps(self, IntArrayRef(dims), false, opt_dtype, const_cast<Tensor&>(output_t), MPSReductionType::PROD, "prod_mps");
return output_t;
}
Tensor count_nonzero_mps(const Tensor& self, IntArrayRef dims){
NSMutableArray<NSNumber*> *axes = nil;
NSMutableArray<NSNumber*> *apparent_input_shape = nil;
NSMutableArray<NSNumber*> *apparent_output_shape = nil;
NSMutableArray<NSNumber*> *output_shape = nil;
set_axes_and_shapes(self, dims, axes, apparent_input_shape, apparent_output_shape, output_shape);
std::vector<int64_t> raw_output_shape([output_shape count]);
for(auto i: c10::irange(raw_output_shape.size())) {
raw_output_shape[i] = [output_shape[i] longValue];
}
Tensor output_t = at::native::empty_mps(
IntArrayRef(raw_output_shape),
ScalarType::Long,
c10::nullopt,
kMPS,
c10::nullopt,
c10::nullopt);
reduction_out_mps(self, dims, false, self.scalar_type(), const_cast<Tensor&>(output_t), MPSReductionType::COUNT_NONZERO, "count_nonzero_mps");
return output_t;
}
TORCH_IMPL_FUNC(mean_out_mps)
(const Tensor& input_t,
OptionalIntArrayRef opt_dim,
bool keepdim,
c10::optional<ScalarType> dtype,
const Tensor& output_t) {
reduction_out_mps(input_t, opt_dim, keepdim, dtype, output_t, MPSReductionType::MEAN, "mean_out_mps");
}
TORCH_IMPL_FUNC(norm_out_mps)
(const Tensor& input_tensor,
const OptionalScalarRef opt_p,
IntArrayRef dim,
bool keepdim,
const Tensor& output_t)
{
if (input_tensor.numel() == 0)
return;
auto input_t = (input_tensor.sizes().size() == 0) ? input_tensor.view({1}) : input_tensor;
IntArrayRef input_shape = input_t.sizes();
for(int i = 0; i < dim.size(); i++) {
auto wrap_dim = maybe_wrap_dim(dim[i], input_shape.size());
TORCH_CHECK(wrap_dim < input_shape.size(),
"norm_out_mps: reduction dim must be in the range of input shape")
}
namespace native_mps = at::native::mps;
using CachedGraph = native_mps::MPSUnaryCachedGraph;
native_mps::MPSGraphCache* cache_ = native_mps::MPSGraphCache::getInstance();
auto p = opt_p.has_value() ? opt_p.get().to<double>() : Scalar(2.0).to<double>();
auto reciprocal_p = 1 / p;
bool pIsZero = (p == 0.0);
bool pIsPosInf = (p == numeric_limits<double>::infinity());
bool pIsNegInf = (p == -numeric_limits<double>::infinity());
int64_t num_input_dims = input_shape.size();
int64_t num_reduce_dims = dim.size();
int64_t num_output_dims;
// For output shape calculation, assume that keepdim is true
num_output_dims = num_input_dims;
NSMutableArray<NSNumber*> *apparent_output_shape = nil;
NSMutableArray<NSNumber*> *apparent_input_shape = nil;
// Reduction axes
NSMutableArray<NSNumber *> *axes;
set_axes(axes, num_reduce_dims, dim, input_shape.size());
set_apparent_shapes(apparent_output_shape,
apparent_input_shape,
num_reduce_dims,
num_input_dims,
num_output_dims,
input_shape,
axes);
if (output_t.numel() == 0) {
return;
}
auto stream = at::mps::getCurrentMPSStream();
@autoreleasepool {
NSString* ns_key = [[axes valueForKey:@"description"] componentsJoinedByString:@","];
string keepdim_info = (keepdim) ? "keepdim=1" : "keepdim=0";
string key = string("norm_out_mps:") + [ns_key UTF8String] + ":" + native_mps::getMPSTypeString(input_t.scalar_type()) + ":p" + to_string(p) + ":" + keepdim_info;
auto cachedGraph = cache_->LookUpAs<CachedGraph>(key);
if(!cachedGraph) {
native_mps::MPSCachedGraph *tmpCachedGraph = cache_->CreateCachedGraph(key, ^ native_mps::MPSCachedGraph * () {
CachedGraph *newCachedGraph = nil;
@autoreleasepool {
MPSGraph* mpsGraph = native_mps::make_mps_graph();
newCachedGraph = new CachedGraph(mpsGraph);
MPSGraphTensor* inputTensor = native_mps::mpsGraphUnrankedPlaceHolder(mpsGraph, native_mps::getMPSDataType(input_t.scalar_type()));
MPSGraphTensor *outputTensor;
if (pIsZero)
{
MPSGraphTensor *absoluteTensor = [mpsGraph absoluteWithTensor:inputTensor
name:nil];
MPSGraphTensor *powerValTensor = [mpsGraph constantWithScalar:p
dataType:native_mps::getMPSDataType(input_t.scalar_type())];
MPSGraphTensor *powerTensor = [mpsGraph powerWithPrimaryTensor:absoluteTensor
secondaryTensor:powerValTensor
name:nil];
outputTensor = [mpsGraph reductionSumWithTensor:powerTensor
axes:axes
name:nil];
}
else if (pIsPosInf)
{
MPSGraphTensor *absoluteTensor = [mpsGraph absoluteWithTensor:inputTensor
name:nil];
outputTensor = [mpsGraph reductionMaximumWithTensor:absoluteTensor
axes:axes
name:nil];
}
else if (pIsNegInf)
{
MPSGraphTensor *absoluteTensor = [mpsGraph absoluteWithTensor:inputTensor
name:nil];
outputTensor = [mpsGraph reductionMinimumWithTensor:absoluteTensor
axes:axes
name:nil];
}
else
{
MPSGraphTensor *absoluteTensor = [mpsGraph absoluteWithTensor:inputTensor
name:nil];
MPSGraphTensor *powerValTensor = [mpsGraph constantWithScalar:p
dataType:native_mps::getMPSDataType(input_t.scalar_type())];
MPSGraphTensor *reciprocalPowerValTensor = [mpsGraph constantWithScalar:reciprocal_p
dataType:native_mps::getMPSDataType(input_t.scalar_type())];
MPSGraphTensor *powerTensor = [mpsGraph powerWithPrimaryTensor:absoluteTensor
secondaryTensor:powerValTensor
name:nil];
MPSGraphTensor *reductionSumTensor = [mpsGraph reductionSumWithTensor:powerTensor
axes:axes
name:nil];
outputTensor = [mpsGraph powerWithPrimaryTensor:reductionSumTensor
secondaryTensor:reciprocalPowerValTensor
name:nil];
}
newCachedGraph->inputTensor_ = inputTensor;
newCachedGraph->outputTensor_ = outputTensor;
}
return newCachedGraph;
});
cachedGraph = tmpCachedGraph->as<CachedGraph>();
}
auto inputPlaceholder = native_mps::Placeholder();
if(apparent_input_shape)
inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t, apparent_input_shape);
else
inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t);
auto outputPlaceholder = native_mps::Placeholder(cachedGraph->outputTensor_, output_t, apparent_output_shape);
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *feeds = @{
inputPlaceholder.getMPSGraphTensor() : inputPlaceholder.getMPSGraphTensorData(),
};
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *results = @{
outputPlaceholder.getMPSGraphTensor() : outputPlaceholder.getMPSGraphTensorData()
};
native_mps::runMPSGraph(stream, cachedGraph->graph(), feeds, results);
}
}
Tensor std_var_common_impl_mps(
const Tensor & input_t,
at::OptionalIntArrayRef dim,
c10::optional<int64_t> correction,
bool keepdim,
StdVarType stdVarType)
{
namespace native_mps = at::native::mps;
using CachedGraph = native_mps::MPSUnaryCachedGraph;
IntArrayRef input_shape = input_t.sizes();
int64_t num_input_dims = input_shape.size();
bool use_dim = dim.has_value();
IntArrayRef dim_value = use_dim ? dim.value() : NULL;
if (use_dim)
{
string errMessage = (stdVarType == STANDARD_DEVIATION) ? "std_mps" : "var_mps";
errMessage += ": reduction dim must be in the range of input shape";
for(int i = 0; i < dim_value.size(); i++) {
auto wrap_dim = maybe_wrap_dim(dim_value[i], input_shape.size());
TORCH_CHECK(wrap_dim < input_shape.size(), errMessage.c_str())
}
}
bool use_correction = correction.has_value();
const auto correction_value = use_correction ? correction.value() : false;
int64_t correction_n = 1;
native_mps::MPSGraphCache* cache_ = native_mps::MPSGraphCache::getInstance();
int64_t num_output_dims = 0;
NSMutableArray<NSNumber *> *axes = nil;
NSMutableArray<NSNumber*> *apparent_output_shape = nil;
NSMutableArray<NSNumber*> *apparent_input_shape = nil;
std::vector<int64_t> output_shape;
if ((!keepdim && !use_dim) || (!keepdim && use_dim && dim_value.size() <= 0))
{
// Flatten the input tensor to reduce it to one value
apparent_input_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:1];
int64_t num_in_elements = 1;
for(int i = 0; i < num_input_dims; i++) {
num_in_elements *= input_shape[i];
}
apparent_input_shape[0] = [NSNumber numberWithInt:num_in_elements];
// Output is a single value
apparent_output_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:1];
apparent_output_shape[0] = @1;
num_output_dims = 0;
correction_n = num_in_elements;
// Reduction axes
axes = [NSMutableArray<NSNumber*> arrayWithCapacity:1];
axes[0] = @0;
}
else if (!keepdim && use_dim && dim_value.size() > 0)
{
int64_t num_reduce_dims = dim_value.size();
num_output_dims = num_input_dims;
set_axes(axes, num_reduce_dims, dim_value, num_input_dims);
set_apparent_shapes(apparent_output_shape,
apparent_input_shape,
num_reduce_dims,
num_input_dims,
num_output_dims,
input_shape,
axes);
num_output_dims = (num_input_dims >= num_reduce_dims) ? (num_input_dims - num_reduce_dims) : 0; //num_input_dims;
unsigned int curr_i = 0;
for (int i = 0; i < num_input_dims; i++)
{
bool found = false;
for (int j = 0; j < num_reduce_dims; j++)
{
if (i == dim_value[j])
{
found = true;
break;
}
}
if (found) continue;
output_shape.push_back(input_shape[i]);
curr_i += 1;
// End loop when output shape is filled
if (curr_i == num_output_dims)
break;
}
for(int i = 0; i < num_reduce_dims; i++)
{
auto wrap_dim = maybe_wrap_dim(dim_value[i], input_shape.size());
correction_n *= input_shape[wrap_dim];
}
// (3, 4, 5) --> (3, 5)
}
else if ((keepdim && !use_dim) || (keepdim && use_dim && dim_value.size() <= 0))
{
num_output_dims = 0;
int64_t num_reduce_dims = 0;
set_axes(axes, num_reduce_dims, dim_value, input_shape.size());
set_apparent_shapes(apparent_output_shape,
apparent_input_shape,
num_reduce_dims,
num_input_dims,
num_output_dims,
input_shape,
axes);
num_output_dims = num_input_dims;
for (int i = 0; i < num_input_dims; i++)
{
output_shape.push_back((int64_t) 1);
correction_n *= input_shape[i];
}
// scalar --> vector case [[1.0034567]]
}
else if (keepdim && use_dim && dim_value.size() > 0)
{
int64_t num_reduce_dims = dim_value.size();
num_output_dims = num_input_dims;
set_axes(axes, num_reduce_dims, dim_value, num_input_dims);
set_apparent_shapes(apparent_output_shape,
apparent_input_shape,
num_reduce_dims,
num_input_dims,
num_output_dims,
input_shape,
axes);
num_output_dims = num_input_dims;//(num_input_dims >= num_reduce_dims) ? (num_input_dims - num_reduce_dims) : 0;
for(int i = 0; i < num_reduce_dims; i++)
{
auto wrap_dim = maybe_wrap_dim(dim_value[i], input_shape.size());
correction_n *= input_shape[wrap_dim];
}
for (int i = 0; i < num_input_dims; i++)
{
output_shape.push_back([apparent_output_shape[i] longValue]);
}
}
Tensor output_t = at::native::empty_mps(
IntArrayRef(output_shape.data(), num_output_dims),
input_t.scalar_type(),
c10::nullopt,
kMPS,
c10::nullopt,
c10::nullopt);
if (output_t.numel() == 0 || input_t.numel() == 0)
{
return output_t;
}
double bessel_correction = ((double) correction_n) / ((double) (correction_n-1));
auto stream = at::mps::getCurrentMPSStream();
@autoreleasepool {
string op_key = (stdVarType == STANDARD_DEVIATION) ? "std_mps" : "var_mps";
NSString* ns_key = [[axes valueForKey:@"description"] componentsJoinedByString:@","];
string bessel_corrected = (use_correction && correction_value) ? "unbiased " : "biased ";
string use_dim_info = (use_dim) ? "use_dim=1:" + to_string(dim_value.size()) : "use_dim=0";
string keepdim_info = (keepdim) ? "keepdim=1" : "keepdim=0";
string key = op_key + use_dim_info + ":" + keepdim_info + ":" + string([ns_key UTF8String]) + ":" + native_mps::getTensorsStringKey(input_t) + ":" + bessel_corrected;
auto cachedGraph = cache_->LookUpAs<CachedGraph>(key);
// Initialize once if configuration not found in cache
if(!cachedGraph) {
native_mps::MPSCachedGraph *tmpCachedGraph = cache_->CreateCachedGraph(key, ^ native_mps::MPSCachedGraph * () {
CachedGraph *newCachedGraph = nil;
@autoreleasepool {
MPSGraph* mpsGraph = native_mps::make_mps_graph();
newCachedGraph = new CachedGraph(mpsGraph);
MPSGraphTensor *inputTensor = native_mps::mpsGraphUnrankedPlaceHolder(mpsGraph, native_mps::getMPSDataType(input_t.scalar_type()));
MPSGraphTensor *outputVarTensor = [mpsGraph varianceOfTensor:inputTensor
axes:axes
name:nil];
MPSGraphTensor *outputTensor;
if (use_correction && correction_value)
{
MPSGraphTensor *besselTensor= [mpsGraph constantWithScalar:bessel_correction
dataType:MPSDataTypeFloat32];
MPSGraphTensor *correctedTensor = [mpsGraph multiplicationWithPrimaryTensor: outputVarTensor
secondaryTensor: besselTensor
name: nil];
outputTensor = (stdVarType == STANDARD_DEVIATION) ?
[mpsGraph squareRootWithTensor:correctedTensor name:nil] : correctedTensor;
}
else
{
outputTensor = (stdVarType == STANDARD_DEVIATION) ?
[mpsGraph squareRootWithTensor:outputVarTensor name:nil] : outputVarTensor;
}
newCachedGraph->inputTensor_ = inputTensor;
newCachedGraph->outputTensor_ = outputTensor;
}
return newCachedGraph;
});
cachedGraph = static_cast<CachedGraph *>(tmpCachedGraph);
}
auto inputPlaceholder = native_mps::Placeholder();
if(apparent_input_shape)
{
inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t, apparent_input_shape);
}
else
{
inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t);
}
auto outputPlaceholder = native_mps::Placeholder(cachedGraph->outputTensor_, output_t, apparent_output_shape);
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *feeds = @{
inputPlaceholder.getMPSGraphTensor() : inputPlaceholder.getMPSGraphTensorData(),
};
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *results = @{
outputPlaceholder.getMPSGraphTensor() : outputPlaceholder.getMPSGraphTensorData()
};
native_mps::runMPSGraph(stream, cachedGraph->graph(), feeds, results);
}
return output_t;
}
Tensor var_mps(
const Tensor & input_t,
at::OptionalIntArrayRef dim,
c10::optional<int64_t> correction,
bool keepdim)
{
return std_var_common_impl_mps(input_t, dim, correction, keepdim, STANDARD_VARIANCE);
}
Tensor std_mps(
const Tensor & input_t,
at::OptionalIntArrayRef dim,
c10::optional<int64_t> correction,
bool keepdim)
{
return std_var_common_impl_mps(input_t, dim, correction, keepdim, STANDARD_DEVIATION);
}
TORCH_IMPL_FUNC(any_out_mps)
(const Tensor& input_t,
int64_t dim,
bool keepdim,
const Tensor& output_t)
{
namespace native_mps = at::native::mps;
using CachedGraph = native_mps::MPSUnaryCachedGraph;
if (output_t.numel() == 0 || input_t.numel() == 0) {
return;
}
native_mps::MPSGraphCache* cache_ = native_mps::MPSGraphCache::getInstance();
int64_t dim_ = maybe_wrap_dim(dim, input_t.dim());
native::zero_numel_check_dims(input_t, dim_, "any()");
// Calculate the output shape according to keepdim=True
// If there is no dim argument, the input shape is flattened
IntArrayRef input_shape = input_t.sizes();
int64_t num_input_dims = input_shape.size();
NSMutableArray<NSNumber*> *apparent_out_shape = nil;
apparent_out_shape = [NSMutableArray<NSNumber*> arrayWithCapacity:num_input_dims];
for(int i = 0; i < num_input_dims; i++) {
if(dim_ == i)
apparent_out_shape[i] = @1;
else
apparent_out_shape[i] = [NSNumber numberWithInt:input_shape[i]];
}
auto stream = at::mps::getCurrentMPSStream();
@autoreleasepool {
MPSShape* input_t_shape = native_mps::getMPSShape(input_t);
string key = string("any_out_mps:") + native_mps::getMPSShapeString(input_t_shape) + ":" + to_string(dim_) + ":" + native_mps::getMPSTypeString(input_t.scalar_type());
CachedGraph* cachedGraph = cache_->LookUpAs<CachedGraph>(key);
if(!cachedGraph) {
native_mps::MPSCachedGraph *tmpCachedGraph = cache_->CreateCachedGraph(key, ^ native_mps::MPSCachedGraph * () {
CachedGraph *newCachedGraph = nil;
@autoreleasepool {
MPSGraph* mpsGraph = native_mps::make_mps_graph();
newCachedGraph = new CachedGraph(mpsGraph);
MPSGraphTensor* outputTensor;
MPSDataType input_type = native_mps::getMPSDataType(input_t.scalar_type());
MPSGraphTensor* inputTensor = native_mps::mpsGraphRankedPlaceHolder(mpsGraph, input_type, input_t_shape);
if (input_type != MPSDataTypeInt32 &&
input_type != MPSDataTypeFloat32 &&
input_type != MPSDataTypeFloat16 )
{
MPSGraphTensor* inputCastedTensor = [mpsGraph castTensor:inputTensor
toType:MPSDataTypeInt32
name:@"any_all"];
MPSGraphTensor* outputCastedTensor = [mpsGraph reductionOrWithTensor:inputCastedTensor
axis:dim_
name:nil];
outputTensor = [mpsGraph castTensor:outputCastedTensor
toType:MPSDataTypeBool
name:@"any"];
}
else
{
MPSGraphTensor* outputUncastedTensor = [mpsGraph reductionOrWithTensor:inputTensor
axis:dim_
name:nil];
outputTensor = [mpsGraph castTensor:outputUncastedTensor
toType:MPSDataTypeBool
name:@"any"];
}
newCachedGraph->inputTensor_ = inputTensor;
newCachedGraph->outputTensor_ = outputTensor;
}
return newCachedGraph;
});
cachedGraph = tmpCachedGraph->as<CachedGraph>();
}
auto inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t);
auto outputPlaceholder = native_mps::Placeholder(cachedGraph->outputTensor_, output_t, apparent_out_shape);
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *feeds = @{
inputPlaceholder.getMPSGraphTensor() : inputPlaceholder.getMPSGraphTensorData(),
};
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *results = @{
outputPlaceholder.getMPSGraphTensor() : outputPlaceholder.getMPSGraphTensorData(),
};
native_mps::runMPSGraph(stream, cachedGraph->graph(), feeds, results);
}
}
TORCH_IMPL_FUNC(any_all_out_mps)(const Tensor& input_t, const Tensor& output_t)
{
namespace native_mps = at::native::mps;
using CachedGraph = native_mps::MPSUnaryCachedGraph;
if (output_t.numel() == 0 || input_t.numel() == 0) {
return;
}
auto cache_ = native_mps::MPSGraphCache::getInstance();
auto stream = at::mps::getCurrentMPSStream();
@autoreleasepool {
MPSShape* input_t_shape = native_mps::getMPSShape(input_t);
string key = string("any_all_out_mps:") + native_mps::getMPSShapeString(input_t_shape) +":" + native_mps::getMPSTypeString(input_t.scalar_type());
CachedGraph* cachedGraph = cache_->LookUpAs<CachedGraph>(key);
if(!cachedGraph) {
native_mps::MPSCachedGraph *tmpCachedGraph = cache_->CreateCachedGraph(key, ^ native_mps::MPSCachedGraph * () {
CachedGraph *newCachedGraph = nil;
@autoreleasepool {
MPSGraph* mpsGraph = native_mps::make_mps_graph();
newCachedGraph = new CachedGraph(mpsGraph);
MPSGraphTensor* outputTensor;
MPSDataType input_type = native_mps::getMPSDataType(input_t.scalar_type());
MPSGraphTensor* inputTensor = native_mps::mpsGraphRankedPlaceHolder(mpsGraph, input_type, input_t_shape);
if (input_type != MPSDataTypeInt32 &&
input_type != MPSDataTypeFloat32 &&
input_type != MPSDataTypeFloat16 )
{
MPSGraphTensor* inputCastedTensor = [mpsGraph castTensor:inputTensor
toType:MPSDataTypeInt32
name:@"any_all"];
MPSGraphTensor* outputCastedTensor = [mpsGraph reductionOrWithTensor:inputCastedTensor
axes:nil
name:nil];
outputTensor = [mpsGraph castTensor:outputCastedTensor
toType:MPSDataTypeBool
name:@"any_all"];
}
else
{
MPSGraphTensor* outputUncastedTensor = [mpsGraph reductionOrWithTensor:inputTensor
axes:nil
name:nil];
outputTensor = [mpsGraph castTensor:outputUncastedTensor
toType:MPSDataTypeBool
name:@"any_all"];
}
newCachedGraph->inputTensor_ = inputTensor;
newCachedGraph->outputTensor_ = outputTensor;
}
return newCachedGraph;
});
cachedGraph = static_cast<CachedGraph *>(tmpCachedGraph);
}
auto inputPlaceholder = native_mps::Placeholder(cachedGraph->inputTensor_, input_t);
auto outputPlaceholder = native_mps::Placeholder(cachedGraph->outputTensor_, output_t);
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *feeds = @{
inputPlaceholder.getMPSGraphTensor() : inputPlaceholder.getMPSGraphTensorData(),
};
NSDictionary<MPSGraphTensor *, MPSGraphTensorData *> *results = @{
outputPlaceholder.getMPSGraphTensor() : outputPlaceholder.getMPSGraphTensorData(),
};
native_mps::runMPSGraph(stream, cachedGraph->graph(), feeds, results);
}
}
TORCH_IMPL_FUNC(all_out_mps)
(const Tensor& input_t,
int64_t dim,
bool keepdim,
const Tensor& output_t)
{
namespace native_mps = at::native::mps;
using CachedGraph = native_mps::MPSUnaryCachedGraph;
if (output_t.numel() == 0 || input_t.numel() == 0) {
return;
}
native_mps::MPSGraphCache* cache_ = native_mps::MPSGraphCache::getInstance();
int64_t dim_ = maybe_wrap_dim(dim, input_t.dim());
native::zero_numel_check_dims(input_t, dim_, "all()");
// Calculate the output shape according to keepdim=True
// If there is no dim argument, the input shape is flattened