Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Modifications Copyright (c) Microsoft.
 
#include "core/util/math_cpuonly.h"
#include "core/util/math.h"
#include "core/common/float16.h"
#include "core/common/inlined_containers.h"
 
#include <algorithm>
#include <cmath>
#include <type_traits>
#include "core/common/narrow.h"
#include "core/mlas/inc/mlas.h"
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-result"
#endif
#include "Eigen/src/Core/arch/Default/Half.h"
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
using onnxruntime::concurrency::ThreadPool;
 
namespace onnxruntime {
namespace math {
 
// MatMul implementation purely based on Eigen.
#define EIGEN_MATMUL_FUNCTION(T)                                                                                \
  template <>                                                                                                   \
  void MatMul<T>(ptrdiff_t M, ptrdiff_t N, ptrdiff_t K, const T* A, const T* B, T* C, concurrency::ThreadPool*, \
                 const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG*) {                                                  \
    auto C_mat = EigenMatrixMap<T>(C, N, M);                                                                    \
    C_mat.noalias() = ConstEigenMatrixMap<T>(B, N, K) * ConstEigenMatrixMap<T>(A, K, M);                        \
  }
 
EIGEN_MATMUL_FUNCTION(int32_t)
EIGEN_MATMUL_FUNCTION(uint32_t)
EIGEN_MATMUL_FUNCTION(int64_t)
EIGEN_MATMUL_FUNCTION(uint64_t)
 
////////////////////////////////////////////////////////////////////////////////
// BLAS alternatives.
// Depending on whether we have specified an external BLAS library or not, we
// will delegate the Caffe math functions that are BLAS-related to either the
// CBLAS call or the Eigen implementation.
////////////////////////////////////////////////////////////////////////////////
 
// Caffe2 gemm provides a simpler interface to the gemm functions, with the
// limitation that the data has to be contiguous in memory.
//
// The gemm call implements the following operation:
//
//                  C = alpha * op(A) * op(B) + beta * C
//
// where op(A) has size M x K, op(B) has size K x N, and C has size M x N. Each
// of A, B, and C are matrices and alpha and beta are scalars. Note that the
// most common use case of gemm will involve setting alpha to 1 and beta to 0.
//
// op(A) and op(B) represent the transformations that are done to A and B before
// the matrix multiply; depending on the flags set, op(A) is equal to A or A^T
// (transpose) if the argument TransA or TransB is set to CblasNoTrans or
// CblasTrans, respectively, for each of A and B.
template <>
void Gemm<float, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M,
                             ptrdiff_t N, ptrdiff_t K, float alpha, const float* A, const float* B, float beta,
                             float* C, ThreadPool* threadpool, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  int lda = static_cast<int>((TransA == CblasNoTrans) ? K : M);
  int ldb = static_cast<int>((TransB == CblasNoTrans) ? N : K);
  MlasGemm(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, N, threadpool, mlas_backend_kernel_selector_config);
}
 
template <>
void Gemm<Eigen::half, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M,
                                   ptrdiff_t N, ptrdiff_t K, Eigen::half alpha, const Eigen::half* A, const Eigen::half* B, Eigen::half beta,
                                   Eigen::half* C, ThreadPool*, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  auto C_mat = EigenMatrixMap<Eigen::half>(C, N, M);
  if (beta == static_cast<Eigen::half>(0)) {
    C_mat.setZero();
  } else {
    C_mat *= beta;
  }
  switch (TransA) {
    case CblasNoTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<Eigen::half>(B, N, K) *
                                      ConstEigenMatrixMap<Eigen::half>(A, K, M));
          return;
        case CblasTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<Eigen::half>(B, K, N).transpose() *
                                      ConstEigenMatrixMap<Eigen::half>(A, K, M));
          return;
        default:
          ORT_THROW("CblasNoTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    case CblasTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<Eigen::half>(B, N, K) *
                                      ConstEigenMatrixMap<Eigen::half>(A, M, K).transpose());
          return;
        case CblasTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<Eigen::half>(B, K, N).transpose() *
                                      ConstEigenMatrixMap<Eigen::half>(A, M, K).transpose());
          return;
        default:
          ORT_THROW("CblasTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    default:
      ORT_THROW("Unexpected CBLAS_TRANSPOSE for TransA of ", TransA);
  }
}
 
#ifdef MLAS_SUPPORTS_GEMM_DOUBLE
template <>
void Gemm<double, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M,
                              ptrdiff_t N, ptrdiff_t K, double alpha, const double* A, const double* B, double beta,
                              double* C, ThreadPool* threadpool, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  int lda = static_cast<int>((TransA == CblasNoTrans) ? K : M);
  int ldb = static_cast<int>((TransB == CblasNoTrans) ? N : K);
  MlasGemm(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, N, threadpool);
}
#else
template <>
void Gemm<double, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M,
                              ptrdiff_t N, ptrdiff_t K, double alpha, const double* A, const double* B, double beta,
                              double* C, ThreadPool*, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  auto C_mat = EigenMatrixMap<double>(C, N, M);
  if (beta == 0) {
    C_mat.setZero();
  } else {
    C_mat *= beta;
  }
  switch (TransA) {
    case CblasNoTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<double>(B, N, K) *
                                      ConstEigenMatrixMap<double>(A, K, M));
          return;
        case CblasTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<double>(B, K, N).transpose() *
                                      ConstEigenMatrixMap<double>(A, K, M));
          return;
        default:
          ORT_THROW("CblasNoTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    case CblasTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<double>(B, N, K) *
                                      ConstEigenMatrixMap<double>(A, M, K).transpose());
          return;
        case CblasTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMap<double>(B, K, N).transpose() *
                                      ConstEigenMatrixMap<double>(A, M, K).transpose());
          return;
        default:
          ORT_THROW("CblasTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    default:
      ORT_THROW("Unexpected CBLAS_TRANSPOSE for TransA of ", TransA);
  }
}
#endif
 
template <>
void MatMul<float>(ptrdiff_t M, ptrdiff_t N, ptrdiff_t K, const float* A, const float* B, float* C, ThreadPool* threadpool,
                   const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  MlasGemm(CblasNoTrans, CblasNoTrans, M, N, K, 1.f, A, K, B, N, 0.f, C, N, threadpool, mlas_backend_kernel_selector_config);
}
 
template <>
void MatMul<MLFloat16>(ptrdiff_t M, ptrdiff_t N, ptrdiff_t K, const MLFloat16* A, const MLFloat16* B, MLFloat16* C, ThreadPool* threadpool,
                       const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  // Guard against using generic half GEMM when no accelerated implementation is
  // available. Native packing support currently also signals an accelerated
  // backend path.
  const bool has_accelerated_half_gemm =
      MlasFp16AccelerationSupported() ||
      MlasHalfGemmNativePackBSize(CblasNoTrans, CblasNoTrans,
                                  static_cast<size_t>(N), static_cast<size_t>(K),
                                  mlas_backend_kernel_selector_config) != 0;
  if (has_accelerated_half_gemm) {
    MLAS_HALF_GEMM_DATA_PARAMS data{};
    data.A = A;
    data.lda = static_cast<size_t>(K);
    data.B = B;
    data.ldb = static_cast<size_t>(N);
    data.C = C;
    data.ldc = static_cast<size_t>(N);
    data.BackendKernelSelectorConfig = mlas_backend_kernel_selector_config;
    MlasHalfGemmBatch(static_cast<size_t>(M), static_cast<size_t>(N), static_cast<size_t>(K), 1, &data, threadpool);
    return;
  }
 
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
  auto C_mat = EigenMatrixMap<Eigen::half>(reinterpret_cast<Eigen::half*>(C), N, M);
  // Accumulate the fallback in fp32 and round only the result to fp16.
  C_mat.noalias() =
      (ConstEigenMatrixMap<Eigen::half>(reinterpret_cast<const Eigen::half*>(B), N, K).cast<float>() *
       ConstEigenMatrixMap<Eigen::half>(reinterpret_cast<const Eigen::half*>(A), K, M).cast<float>())
          .cast<Eigen::half>();
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
 
#ifdef MLAS_SUPPORTS_GEMM_DOUBLE
template <>
void MatMul<double>(ptrdiff_t M, ptrdiff_t N, ptrdiff_t K, const double* A, const double* B, double* C, ThreadPool* threadpool,
                    const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  MlasGemm(CblasNoTrans, CblasNoTrans, M, N, K, 1.f, A, K, B, N, 0.f, C, N, threadpool);
}
#else
EIGEN_MATMUL_FUNCTION(double)
#endif
 
template <>
void GemmEx<float, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M, ptrdiff_t N, ptrdiff_t K,
                               float alpha, const float* A, int lda, const float* B, int ldb, float beta, float* C,
                               int ldc, ThreadPool* threadpool, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  MlasGemm(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc, threadpool, mlas_backend_kernel_selector_config);
}
 
#ifdef MLAS_SUPPORTS_GEMM_DOUBLE
template <>
void GemmEx<double, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M, ptrdiff_t N, ptrdiff_t K,
                                double alpha, const double* A, int lda, const double* B, int ldb, double beta, double* C,
                                int ldc, ThreadPool* threadpool, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  MlasGemm(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc, threadpool);
}
#else
template <>
void GemmEx<double, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M, ptrdiff_t N, ptrdiff_t K,
                                double alpha, const double* A, int lda, const double* B, int ldb, double beta, double* C,
                                int ldc, ThreadPool*, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  auto C_mat = EigenMatrixMapWithStrides<double>(C, N, M, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldc, 1));
  if (beta == 0) {
    C_mat.setZero();
  } else {
    C_mat *= beta;
  }
  switch (TransA) {
    case CblasNoTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMapWithStrides<double>(
                                          B, N, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1)) *
                                      ConstEigenMatrixMapWithStrides<double>(
                                          A, K, M, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1)));
          return;
        case CblasTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMapWithStrides<double>(
                                          B, K, N, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1))
                                          .transpose() *
                                      ConstEigenMatrixMapWithStrides<double>(
                                          A, K, M, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1)));
          return;
        default:
          ORT_THROW("CblasNoTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    case CblasTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMapWithStrides<double>(
                                          B, N, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1)) *
                                      ConstEigenMatrixMapWithStrides<double>(
                                          A, M, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1))
                                          .transpose());
          return;
        case CblasTrans:
          C_mat.noalias() += alpha * (ConstEigenMatrixMapWithStrides<double>(
                                          B, K, N, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1))
                                          .transpose() *
                                      ConstEigenMatrixMapWithStrides<double>(
                                          A, M, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1))
                                          .transpose());
          return;
        default:
          ORT_THROW("CblasTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    default:
      ORT_THROW("Unexpected CBLAS_TRANSPOSE for TransA of ", TransA);
  }
}
#endif
 
template <>
void GemmEx<MLFloat16, ThreadPool>(CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, ptrdiff_t M, ptrdiff_t N, ptrdiff_t K,
                                   MLFloat16 alpha, const MLFloat16* A, int lda, const MLFloat16* B, int ldb, MLFloat16 beta,
                                   MLFloat16* C, int ldc, ThreadPool*, const MLAS_BACKEND_KERNEL_SELECTOR_CONFIG* mlas_backend_kernel_selector_config) {
  ORT_UNUSED_PARAMETER(mlas_backend_kernel_selector_config);
  // The following function is not implemented for MLFloat16 in Mlas.
  // MlasGemm(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc, threadpool);
  // Threadpool is not used.
  auto C_mat = EigenMatrixMapWithStrides<Eigen::half>(reinterpret_cast<Eigen::half*>(C), N, M, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldc, 1));
 
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
  if (beta == MLFloat16(0.f)) {
    C_mat.setZero();
  } else {
    C_mat *= *reinterpret_cast<Eigen::half*>(&beta);
  }
  Eigen::half alpha_half = *reinterpret_cast<const Eigen::half*>(&alpha);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
 
  switch (TransA) {
    case CblasNoTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha_half * (ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(B), N, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1)) *
                                           ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(A), K, M, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1)));
          return;
        case CblasTrans:
          C_mat.noalias() += alpha_half * (ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(B), K, N, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1))
                                               .transpose() *
                                           ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(A), K, M, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1)));
          return;
        default:
          ORT_THROW("CblasNoTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    case CblasTrans: {
      switch (TransB) {
        case CblasNoTrans:
          C_mat.noalias() += alpha_half * (ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(B), N, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1)) *
                                           ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(A), M, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1))
                                               .transpose());
          return;
        case CblasTrans:
          C_mat.noalias() += alpha_half * (ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(B), K, N, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(ldb, 1))
                                               .transpose() *
                                           ConstEigenMatrixMapWithStrides<Eigen::half>(
                                               reinterpret_cast<const Eigen::half*>(A), M, K, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(lda, 1))
                                               .transpose());
          return;
        default:
          ORT_THROW("CblasTrans Unexpected CBLAS_TRANSPOSE for TransB of ", TransB);
      }
    }
    default:
      ORT_THROW("Unexpected CBLAS_TRANSPOSE for TransA of ", TransA);
  }
}
 
template <typename T, class Provider>
void Gemv(CBLAS_TRANSPOSE TransA,
          int M,
          int N,
          float alpha,
          const T* A,
          const T* x,
          float beta,
          T* y,
          Provider* /*provider*/) {
  EigenVectorMap<T> y_vec(y, TransA == CblasNoTrans ? M : N);
  if (beta == 0) {
    // In Caffe2 we often do a lazy initialization, which may contain NaNs in
    // the float-pointing values. As a result, if beta is 0, we explicitly do a setzero.
    y_vec.setZero();
  } else {
    y_vec *= beta;
  }
  switch (TransA) {
    case CblasNoTrans: {
      y_vec.noalias() += alpha * (ConstEigenMatrixMap<T>(A, N, M).transpose() *
                                  ConstEigenVectorMap<T>(x, N));
      return;
    }
    case CblasTrans: {
      y_vec.noalias() += alpha * (ConstEigenMatrixMap<T>(A, N, M) *
                                  ConstEigenVectorMap<T>(x, M));
      return;
    }
    default:
      ORT_THROW("Gemv found an unexpected CBLAS_TRANSPOSE input of", TransA);
  }
}
 
template void Gemv<float, CPUMathUtil>(const CBLAS_TRANSPOSE TransA, int M, int N, float alpha, const float* A, const float* x,
                                       float beta, float* y, CPUMathUtil*);
template void Gemv<double, CPUMathUtil>(const CBLAS_TRANSPOSE TransA, int M, int N, float alpha, const double* A, const double* x,
                                        float beta, double* y, CPUMathUtil*);
#define SPECIALIZED_AXPY(T)                                                                       \
  template <>                                                                                     \
  void Axpy<T, CPUMathUtil>(int N, const T alpha, const T* x, T* Y, CPUMathUtil* /*provider*/) {  \
    EigenVectorMap<T>(Y, N) += ConstEigenVectorMap<T>(x, N) * alpha;                              \
  }                                                                                               \
  template <>                                                                                     \
  void Axpy<T, CPUMathUtil>(int N, const T* alpha, const T* x, T* Y, CPUMathUtil* /*provider*/) { \
    EigenVectorMap<T>(Y, N) += ConstEigenVectorMap<T>(x, N) * (*alpha);                           \
  }
SPECIALIZED_AXPY(float)
#undef SPECIALIZED_AXPY
 
#define DELEGATE_SIMPLE_UNARY_FUNCTION(T, Funcname, expr)                      \
  template <>                                                                  \
  void Funcname<T, CPUMathUtil>(ptrdiff_t N, const T* x, T* y, CPUMathUtil*) { \
    EigenVectorMap<T>(y, N) = ConstEigenVectorMap<T>(x, N).array().expr();     \
  }
DELEGATE_SIMPLE_UNARY_FUNCTION(float, Exp, exp)
DELEGATE_SIMPLE_UNARY_FUNCTION(double, Exp, exp)
DELEGATE_SIMPLE_UNARY_FUNCTION(float, Log, log)
DELEGATE_SIMPLE_UNARY_FUNCTION(float, Sqr, square)
#undef DELEGATE_SIMPLE_UNARY_FUNCTION
 
#define EIGEN_SIMPLE_BINARY_FUNCTION(T, Funcname, expr)                                                       \
  template <>                                                                                                 \
  void Funcname<T, CPUMathUtil>(ptrdiff_t N, const T* a, const T* b, T* y, CPUMathUtil*) {                    \
    EigenVectorMap<T>(y, N) = ConstEigenVectorMap<T>(a, N).array() expr ConstEigenVectorMap<T>(b, N).array(); \
  }
 
#define DEFINE_SIMPLE_BINARY_FUNCTION(Funcname, expr)   \
  EIGEN_SIMPLE_BINARY_FUNCTION(float, Funcname, expr)   \
  EIGEN_SIMPLE_BINARY_FUNCTION(int32_t, Funcname, expr) \
  EIGEN_SIMPLE_BINARY_FUNCTION(int64_t, Funcname, expr)
 
DEFINE_SIMPLE_BINARY_FUNCTION(Add, +)
DEFINE_SIMPLE_BINARY_FUNCTION(Sub, -)
DEFINE_SIMPLE_BINARY_FUNCTION(Mul, *)
DEFINE_SIMPLE_BINARY_FUNCTION(Div, /)
 
#undef EIGEN_SIMPLE_BINARY_FUNCTION
#undef DEFINE_FLOAT_BINARY_FUNCTION
 
////////////////////////////////////////////////////////////////////////////////
// common math functions being used in Caffe that do not have a BLAS or MKL
// equivalent. For all these functions, we will simply implement them either via
// Eigen or via custom code.
////////////////////////////////////////////////////////////////////////////////
 
#define SPECIALIZED_ROWWISEMAX(T)                                                   \
  template <>                                                                       \
  void RowwiseMax<T, CPUMathUtil>(int N, int D, const T* x, T* y, CPUMathUtil*) {   \
    EigenVectorMap<T>(y, N) = ConstEigenMatrixMap<T>(x, D, N).colwise().maxCoeff(); \
  }
SPECIALIZED_ROWWISEMAX(float)
SPECIALIZED_ROWWISEMAX(double)
#undef SPECIALIZED_ROWWISEMAX
 
#define SPECIALIZED_SET(T)                                                         \
  template <>                                                                      \
  void Set<T, CPUMathUtil>(const ptrdiff_t N, const T alpha, T* Y, CPUMathUtil*) { \
    if (alpha == (T)0) {                                                           \
      memset(Y, 0, N * sizeof(T));                                                 \
    } else {                                                                       \
      EigenVectorMap<T>(Y, N).setConstant(alpha);                                  \
    }                                                                              \
  }
 
SPECIALIZED_SET(float);
SPECIALIZED_SET(double);
SPECIALIZED_SET(int8_t);
SPECIALIZED_SET(int16_t);
SPECIALIZED_SET(int32_t);
SPECIALIZED_SET(int64_t);
SPECIALIZED_SET(bool);
SPECIALIZED_SET(char);
SPECIALIZED_SET(uint8_t);
SPECIALIZED_SET(uint16_t);
#undef SPECIALIZED_SET
 
// Loop over spatial axes in reverse order to choose an index, like counting.
static inline bool NextPosition(int64_t N, const int64_t* shape, int64_t* dims) {
  bool has_next_output = false;
  for (int64_t d_i = N - 1; d_i >= 0; --d_i) {
    int64_t d_max = shape[d_i];
    ORT_ENFORCE(dims[d_i] < d_max);
    if (dims[d_i] == d_max - 1) {
      dims[d_i] = 0;
    } else {  // dims[d_i] < d_max - 1
      ++dims[d_i];
      has_next_output = true;
      break;
    }
  }
  return has_next_output;
}
 
template <typename T>
void Im2col<T, StorageOrder::NCHW>::operator()(
    const T* data_im,
    int64_t channels,
    int64_t height,
    int64_t width,
    int64_t kernel_h,
    int64_t kernel_w,
    int64_t dilation_h,
    int64_t dilation_w,
    int64_t pad_t,
    int64_t pad_l,
    int64_t pad_b,
    int64_t pad_r,
    int64_t stride_h,
    int64_t stride_w,
    T* data_col,
    T padding_value) {
  const int64_t output_h = (height + pad_b + pad_t - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
  const int64_t output_w = (width + pad_l + pad_r - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;
 
  // From Intel, https://github.com/BVLC/caffe/pull/3536
  int64_t channel_size = height * width;
  for (int64_t channel = channels; channel--; data_im += channel_size) {
    for (int64_t kernel_row = 0; kernel_row < kernel_h; kernel_row++) {
      for (int64_t kernel_col = 0; kernel_col < kernel_w; kernel_col++) {
        int64_t input_row = -pad_t + kernel_row * dilation_h;
        for (int64_t output_rows = output_h; output_rows; output_rows--) {
          if (!is_a_ge_zero_and_a_lt_b(input_row, height)) {
            std::fill_n(data_col, output_w, padding_value);
            data_col += output_w;
          } else {
            int64_t input_col = -pad_l + kernel_col * dilation_w;
            const T* rdptr = data_im + input_row * width + input_col;
            for (int64_t i = 0; i < output_w;) {
              int64_t output_handled = 1;
              if (is_a_ge_zero_and_a_lt_b(input_col, width)) {
                if (stride_w == 1) {
                  // Compute the minimum of the number of input elements remaining
                  // and the number of output elements to produce.
                  output_handled = std::min(width - input_col, output_w - i);
                  data_col = std::copy_n(&rdptr[i], static_cast<size_t>(output_handled), data_col);
                } else if (stride_w == 2) {
                  // Same as above except using the number of strided input elements.
                  output_handled = std::min((width - input_col + 1) / 2, output_w - i);
                  const T* local_rdptr = &rdptr[i * 2];
                  for (int64_t x = output_handled; x > 0; x--) {
                    *(data_col++) = *local_rdptr;
                    local_rdptr += 2;
                  }
                } else {
                  *(data_col++) = rdptr[i * stride_w];
                }
              } else {
                *(data_col++) = padding_value;
              }
              input_col += output_handled * stride_w;
              i += output_handled;
            }
          }
          input_row += stride_h;
        }
      }
    }
  }
}
 
template <typename T>
void Im2col<T, StorageOrder::NCHW>::operator()(
    const T* data_im,
    const int64_t* im_shape,
    const int64_t* output_shape,
    int64_t channels_col,
    const int64_t* kernel_shape,
    const int64_t* stride,
    const int64_t* dilation,
    const int64_t* pad,
    ptrdiff_t rank,
    T* data_col,
    bool accumulate_output,
    T padding_value) {
  if (!accumulate_output && rank > 0) {
    const ptrdiff_t last = rank - 1;
    const int64_t width = im_shape[last];
    const int64_t row_size = output_shape[last];
    const int64_t step = stride[last];
    InlinedVector<int64_t> offsets(rank);
    InlinedVector<int64_t> position(last, 0);
    for (int64_t c = 0; c < channels_col; ++c) {
      int64_t channel = c;
      for (ptrdiff_t d = last; d >= 0; --d) {
        offsets[d] = (channel % kernel_shape[d]) * dilation[d] - pad[d];
        channel /= kernel_shape[d];
      }
      const int64_t first_col = offsets[last] < 0
                                    ? std::min(row_size, -(offsets[last] + 1) / step + 1)
                                    : 0;
      const int64_t first_x = offsets[last] < 0
                                  ? step - 1 - (-(offsets[last] + 1) % step)
                                  : offsets[last];
      const int64_t count = first_col == row_size || first_x >= width
                                ? 0
                                : std::min(row_size - first_col, (width - 1 - first_x) / step + 1);
      do {
        int64_t index = channel;
        bool valid = count > 0;
        for (ptrdiff_t d = 0; valid && d < last; ++d) {
          const int64_t coordinate = position[d] * stride[d] + offsets[d];
          valid = is_a_ge_zero_and_a_lt_b(coordinate, im_shape[d]);
          if (valid) {
            index = index * im_shape[d] + coordinate;
          }
        }
        if (valid) {
          std::fill_n(data_col, first_col, padding_value);
          const T* src = data_im + index * width + first_x;
          T* dst = data_col + first_col;
          if (step == 1) {
            std::copy_n(src, count, dst);
          } else {
            for (int64_t x = 0; x < count; ++x) {
              dst[x] = src[x * step];
            }
          }
          std::fill_n(dst + count, row_size - first_col - count, padding_value);
        } else {
          std::fill_n(data_col, row_size, padding_value);
        }
        data_col += row_size;
      } while (NextPosition(last, output_shape, position.data()));
    }
    return;
  }
  int64_t kernel_size = std::accumulate(kernel_shape, kernel_shape + rank, 1LL, std::multiplies<int64_t>());
  std::vector<int64_t> d_offset(rank, 0);
  std::vector<int64_t> d_iter(rank, 0);
  for (int64_t c_col = 0; c_col < channels_col; ++c_col) {
    // Loop over spatial axes in reverse order to compute a per-axis offset.
    int64_t offset = c_col;
    for (ptrdiff_t d_i = rank - 1; d_i >= 0; --d_i) {
      if (d_i < rank - 1) {
        offset /= kernel_shape[d_i + 1];
      }
      d_offset[d_i] = offset % kernel_shape[d_i];
    }
    do {
      // Loop over spatial axes in forward order to compute the indices in the
      // image and column, and whether the index lies in the padding.
      int64_t index_col = c_col;
      int64_t index_im = c_col / kernel_size;
      bool is_padding = false;
      for (ptrdiff_t d_i = 0; d_i < rank; ++d_i) {
        int64_t d = d_iter[d_i];
        int64_t d_im = d * stride[d_i] - pad[d_i] + d_offset[d_i] * dilation[d_i];
        is_padding |= !is_a_ge_zero_and_a_lt_b(d_im, im_shape[d_i]);
        index_col *= output_shape[d_i];
        index_col += d;
        index_im *= im_shape[d_i];
        index_im += d_im;
      }
      if (!accumulate_output) {
        if (is_padding) {
          data_col[index_col] = padding_value;
        } else {
          data_col[index_col] = data_im[index_im];
        }
      } else if (!is_padding) {  // col2im
        data_col[index_im] += data_im[index_col];
      }
    } while (NextPosition(rank, output_shape, d_iter.data()));
  }  // for (int c = 0; c < channels_col; ++c) {
}
 
template struct Im2col<float, StorageOrder::NCHW>;
template struct Im2col<uint8_t, StorageOrder::NCHW>;
template struct Im2col<int8_t, StorageOrder::NCHW>;
 
template <typename T>
void Im2col<T, StorageOrder::NHWC>::operator()(
    const T* data_im,
    int64_t group_channels,
    int64_t input_channels,
    int64_t input_h,
    int64_t input_w,
    int64_t kernel_h,
    int64_t kernel_w,
    int64_t dilation_h,
    int64_t dilation_w,
    int64_t pad_t,
    int64_t pad_l,
    int64_t stride_h,
    int64_t stride_w,
    int64_t output_w,
    int64_t output_start,
    int64_t output_count,
    T* data_col,
    T padding_value) {
  int64_t mh = output_start / output_w;
  int64_t mw = output_start % output_w;
  for (int64_t mz = output_start; mz < output_start + output_count; mz++) {
    int64_t oh = mh * stride_h;
    int64_t ow = mw * stride_w;
 
    for (int64_t kh = 0; kh < kernel_h; kh++) {
      int64_t ih = kh * dilation_h + oh - pad_t;
 
      if (is_a_ge_zero_and_a_lt_b(ih, input_h)) {
        int64_t iw = ow - pad_l;
        if (dilation_w == 1 && group_channels == input_channels) {
          int64_t kw = kernel_w;
          while (kw > 0) {
            if (is_a_ge_zero_and_a_lt_b(iw, input_w)) {
              // Increase the copy count size to reduce the number of copy calls.
              int64_t batch_w = std::min(kw, input_w - iw);
              std::memcpy(data_col, data_im + (ih * input_w + iw) * group_channels, narrow<size_t>(sizeof(T) * batch_w * group_channels));
              data_col += batch_w * group_channels;
              iw += batch_w;
              kw -= batch_w;
            } else {
              data_col = std::fill_n(data_col, group_channels, padding_value);
              iw++;
              kw--;
            }
          }
        } else {
          for (int64_t kw = 0; kw < kernel_w; kw++) {
            if (is_a_ge_zero_and_a_lt_b(iw, input_w)) {
              // N.B. Using std::memcpy helped here over std::copy_n when doing a
              // transform for an image with a small number of group channels.
              std::memcpy(data_col, data_im + (ih * input_w + iw) * input_channels, narrow<size_t>(sizeof(T) * group_channels));
              data_col += group_channels;
            } else {
              data_col = std::fill_n(data_col, group_channels, padding_value);
            }
            iw += dilation_w;
          }
        }
      } else {
        data_col = std::fill_n(data_col, kernel_w * group_channels, padding_value);
      }
    }
 
    if (++mw == output_w) {
      ++mh;
      mw = 0;
    }
  }
}
 
template <typename T>
void Im2col<T, StorageOrder::NHWC>::operator()(
    const T* data_im,
    int64_t group_channels,
    int64_t input_channels,
    const int64_t* im_shape,
    const int64_t* output_shape,
    const int64_t* kernel_shape,
    const int64_t* stride,
    const int64_t* dilation,
    const int64_t* pad,
    ptrdiff_t rank,
    T* data_col,
    T padding_value) {
  // iterate dimensions on output image shape (without Batch and Channel)
  std::vector<int64_t> d_output(rank, 0);
  // inner iterate dimensions on kernel shape (without output channel and input channel)
  std::vector<int64_t> d_kernel(rank, 0);
 
  // Loop over spatial axes along the output image shape
  do {
    // Loop over spatial axes in reverse order to choose an index on kernel dimensions
    do {
      // Loop over spatial axes in forward order to compute the indices in the image
      // and the inner col, and whether the index lies in the padding.
      int64_t index_im = 0;
      bool is_padding = false;
      for (ptrdiff_t d_i = 0; d_i < rank; ++d_i) {
        int64_t d_im = d_output[d_i] * stride[d_i] - pad[d_i] + d_kernel[d_i] * dilation[d_i];
        is_padding |= !is_a_ge_zero_and_a_lt_b(d_im, im_shape[d_i]);
        index_im *= im_shape[d_i];
        index_im += d_im;
      }
      index_im *= input_channels;
 
      if (is_padding) {
        data_col = std::fill_n(data_col, group_channels, padding_value);
      } else {
        data_col = std::copy_n(data_im + index_im, group_channels, data_col);
      }
    } while (NextPosition(rank, kernel_shape, d_kernel.data()));
  } while (NextPosition(rank, output_shape, d_output.data()));
}
 
template <typename T>
void Im2col<T, StorageOrder::NHWC>::operator()(
    const T* data_im,
    int64_t input_channels,
    const int64_t* input_shape,
    const int64_t* output_shape,
    const int64_t* kernel_shape,
    const int64_t* stride,
    const int64_t* dilation,
    const int64_t* pad,
    ptrdiff_t rank,
    int64_t output_start,
    int64_t output_count,
    T const** data_indirection,
    const T* padding_ptr) {
  if (rank == 1) {
    int64_t stride_w = stride[0];
    int64_t kernel_w = kernel_shape[0];
    int64_t dilation_w = dilation[0];
    int64_t pad_l = pad[0];
    int64_t input_w = input_shape[0];
 
    int64_t ow = output_start * stride_w;
 
    while (output_count--) {
      int64_t iw = ow - pad_l;
      for (int64_t kw = 0; kw < kernel_w; kw++) {
        const T* data_ptr = data_im + iw * input_channels;
        data_indirection[kw] = is_a_ge_zero_and_a_lt_b(iw, input_w) ? data_ptr : padding_ptr;
        iw += dilation_w;
      }
      data_indirection += kernel_w;
      ow += stride_w;
    }
 
  } else if (rank == 2) {
    int64_t stride_h = stride[0];
    int64_t stride_w = stride[1];
    int64_t kernel_h = kernel_shape[0];
    int64_t kernel_w = kernel_shape[1];
    int64_t dilation_h = dilation[0];
    int64_t dilation_w = dilation[1];
    int64_t pad_t = pad[0];
    int64_t pad_l = pad[1];
    int64_t input_h = input_shape[0];
    int64_t input_w = input_shape[1];
    int64_t output_w = output_shape[1];
 
    int64_t oh = (output_start / output_w) * stride_h;
    int64_t ow = (output_start % output_w) * stride_w;
    int64_t ow_end = output_w * stride_w;
 
    while (output_count--) {
      for (int64_t kh = 0; kh < kernel_h; kh++) {
        int64_t ih = kh * dilation_h + oh - pad_t;
        if (is_a_ge_zero_and_a_lt_b(ih, input_h)) {
          int64_t ihw = ih * input_w;
          int64_t iw = ow - pad_l;
          if (kernel_w == 3) {
            const T* data_ptr0 = data_im + (ihw + iw) * input_channels;
            data_indirection[0] = is_a_ge_zero_and_a_lt_b(iw, input_w) ? data_ptr0 : padding_ptr;
            iw += dilation_w;
            const T* data_ptr1 = data_im + (ihw + iw) * input_channels;
            data_indirection[1] = is_a_ge_zero_and_a_lt_b(iw, input_w) ? data_ptr1 : padding_ptr;
            iw += dilation_w;
            const T* data_ptr2 = data_im + (ihw + iw) * input_channels;
            data_indirection[2] = is_a_ge_zero_and_a_lt_b(iw, input_w) ? data_ptr2 : padding_ptr;
          } else {
            for (int64_t kw = 0; kw < kernel_w; kw++) {
              const T* data_ptr = data_im + (ihw + iw) * input_channels;
              data_indirection[kw] = is_a_ge_zero_and_a_lt_b(iw, input_w) ? data_ptr : padding_ptr;
              iw += dilation_w;
            }
          }
        } else {
          for (int64_t kw = 0; kw < kernel_w; kw++) {
            data_indirection[kw] = padding_ptr;
          }
        }
        data_indirection += kernel_w;
      }
      ow += stride_w;
      if (ow == ow_end) {
        oh += stride_h;
        ow = 0;
      }
    }
 
  } else {
    // iterate dimensions on output image shape (without Batch and Channel)
    std::vector<int64_t> d_output(rank, 0);
    // inner iterate dimensions on kernel shape (without output channel and input channel)
    std::vector<int64_t> d_kernel(rank, 0);
 
    // Skip ahead to the starting output index.
    for (ptrdiff_t d_i = rank - 1; d_i >= 0; --d_i) {
      d_output[d_i] = output_start % output_shape[d_i];
      output_start /= output_shape[d_i];
    }
 
    while (output_count--) {
      // Loop over spatial axes in reverse order to choose an index on kernel dimensions
      do {
        // Loop over spatial axes in forward order to compute the indices in the image
        // and the inner col, and whether the index lies in the padding.
        int64_t index_im = 0;
        bool is_padding = false;
        for (ptrdiff_t d_i = 0; d_i < rank; ++d_i) {
          int64_t d_input = d_output[d_i] * stride[d_i] - pad[d_i] + d_kernel[d_i] * dilation[d_i];
          is_padding |= !is_a_ge_zero_and_a_lt_b(d_input, input_shape[d_i]);
          index_im *= input_shape[d_i];
          index_im += d_input;
        }
        const T* data_ptr = data_im + index_im * input_channels;
        *data_indirection++ = is_padding ? padding_ptr : data_ptr;
      } while (NextPosition(rank, kernel_shape, d_kernel.data()));
      // Loop over spatial axes along the output image shape
      NextPosition(rank, output_shape, d_output.data());
    }
  }
}
 
template struct Im2col<int8_t, StorageOrder::NHWC>;
template struct Im2col<uint8_t, StorageOrder::NHWC>;
template struct Im2col<MLFloat16, StorageOrder::NHWC>;
template struct Im2col<float, StorageOrder::NHWC>;
 
template <>
void Col2im<float, CPUMathUtil, StorageOrder::NCHW>(const float* data_col, int64_t channels, int64_t height,
                                                    int64_t width, int64_t kernel_h, int64_t kernel_w,
                                                    int64_t dilation_h, int64_t dilation_w, int64_t pad_t,
                                                    int64_t pad_l, int64_t pad_b, int64_t pad_r, int64_t stride_h,
                                                    int64_t stride_w, float* data_im, CPUMathUtil* context) {
  const int64_t output_h =
      (height + pad_b + pad_t - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
  const int64_t output_w =
      (width + pad_l + pad_r - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;
  const int64_t output_hw = output_h * output_w;
  const int64_t hw = height * width;
  const int64_t hwc = hw * channels;
 
  // Fast path for zero padding and no dilation
  // From Torch, modified THNN_(unfolded_acc)
  if (dilation_h == 1 && dilation_w == 1 && pad_l == 0 && pad_r == 0 && pad_t == 0 && pad_b == 0) {
    if (kernel_h == 2 && kernel_w == 2 && stride_h == 2 && stride_w == 2 &&
        height % 2 == 0 && width % 2 == 0) {
      // Each output has one input value. Write adjacent values together,
      // without an output read or a separate zero fill.
      for (int64_t c = 0; c < channels; ++c) {
        for (int64_t h = 0; h < output_h; ++h) {
          const float* src = data_col + c * 4 * output_hw + h * output_w;
          float* dst = data_im + c * hw + h * 2 * width;
          for (int64_t w = 0; w < output_w; ++w) {
            // Keep the addition to positive zero for signed-zero behavior.
            dst[2 * w] = 0.0f + src[w];
            dst[2 * w + 1] = 0.0f + src[output_hw + w];
            dst[width + 2 * w] = 0.0f + src[2 * output_hw + w];
            dst[width + 2 * w + 1] = 0.0f + src[3 * output_hw + w];
          }
        }
      }
      return;
    }
 
    Set<float, CPUMathUtil>(narrow<ptrdiff_t>(hwc), 0, data_im, context);
    // Src (column) data cursor
    auto* src = data_col;
    // End of dst (image) data
    auto* dst_end = data_im + hwc;
    // Dst cursor step at end of row
    auto dst_row_step = stride_h * width - stride_w * output_w;
    // Dst channel data
    for (auto* dst_cb = data_im; dst_cb < dst_end; dst_cb += hw) {
      // First dst row for current kernel row
      auto* dst_hb = dst_cb;
      for (auto kh = 0; kh < kernel_h; ++kh, dst_hb += width) {
        // First dst element for current kernel element
        auto* dst_wb = dst_hb;
        for (auto kw = 0; kw < kernel_w; ++kw, ++dst_wb) {
          // Dst cursor
          auto* dst = dst_wb;
          // End of source data for kernel element
          for (auto* src_he = src + output_hw; src < src_he; dst += dst_row_step) {
            // End of source row
            auto* src_we = src + output_w;
            if (stride_w == 1) {
              for (; src < src_we; ++src, ++dst) {
                *dst += *src;
              }
            } else {
              for (; src < src_we; ++src, dst += stride_w) {
                *dst += *src;
              }
            }
          }
        }
      }
    }
    return;
  }
 
  // Fallback
  Set<float, CPUMathUtil>(narrow<ptrdiff_t>(hwc), 0, data_im, context);
 
  // Src (col data) cursor
  auto* src = data_col;
  // End of dst (image) data
  auto* dst_end = data_im + hwc;
  // Begin of src channel data
  for (auto* dst = data_im; dst < dst_end; dst += hw) {
    // Current kernel element starting vertical offset in dst data
    int64_t h_offset = -pad_t * width;
    int64_t h_offset_end = h_offset + kernel_h * dilation_h * width;
    for (; h_offset < h_offset_end; h_offset += dilation_h * width) {
      // Current kernel element starting horizontal offset in dst data
      int64_t w_offset = -pad_l;
      int64_t w_offset_end = w_offset + kernel_w * dilation_w;
      for (; w_offset < w_offset_end; w_offset += dilation_w) {
        // The valid source columns are the same for each row of this kernel element.
        const int64_t first_col = w_offset < 0 ? std::min(output_w, -(w_offset + 1) / stride_w + 1) : 0;
        if (first_col == output_w) {
          src += output_hw;
          continue;
        }
        const int64_t first_w = w_offset + first_col * stride_w;
        if (first_w >= width) {
          src += output_hw;
          continue;
        }
        const int64_t count = std::min(output_w - first_col, (width - 1 - first_w) / stride_w + 1);
        // End of src channel data
        auto* src_ce = src + output_hw;
        // Dst row offset
        for (int64_t h = h_offset; src < src_ce; h += stride_h * width) {
          // End of src row data
          auto* src_we = src + output_w;
          if (is_a_ge_zero_and_a_lt_b(h, hw)) {
            for (int64_t col = 0; col < count; ++col) {
              dst[h + first_w + col * stride_w] += src[first_col + col];
            }
          }
          src = src_we;
        }
      }
    }
  }
}
 
template <>
void Col2im<float, CPUMathUtil, StorageOrder::NHWC>(const float* data_col, int64_t channels, int64_t height,
                                                    int64_t width, int64_t kernel_h, int64_t kernel_w,
                                                    int64_t dilation_h, int64_t dilation_w, int64_t pad_t,
                                                    int64_t pad_l, int64_t pad_b, int64_t pad_r, int64_t stride_h,
                                                    int64_t stride_w, float* data_im, CPUMathUtil* context) {
  const int64_t dkernel_h = dilation_h * (kernel_h - 1) + 1;
  const int64_t dkernel_w = dilation_w * (kernel_w - 1) + 1;
 
  const int64_t hwc = height * width * channels;
  Set<float, CPUMathUtil>(narrow<ptrdiff_t>(hwc), 0, data_im, context);
  int64_t height_col = (height + pad_t + pad_b - dkernel_h) / stride_h + 1;
  int64_t width_col = (width + pad_l + pad_r - dkernel_w) / stride_w + 1;
  int64_t h_pad = -pad_t;
  for (int64_t h = 0; h < height_col; ++h) {
    int64_t w_pad = -pad_l;
    for (int64_t w = 0; w < width_col; ++w) {
      for (int64_t ih = h_pad; ih < h_pad + dkernel_h; ih += dilation_h) {
        for (int64_t iw = w_pad; iw < w_pad + dkernel_w; iw += dilation_w) {
          if (ih >= 0 && ih < height && iw >= 0 && iw < width) {
            auto* data_im_patch = data_im + (ih * width + iw) * channels;
            Add<float, CPUMathUtil>(
                static_cast<int>(channels), data_im_patch, data_col, data_im_patch, context);
          }
          data_col += channels;
        }
      }
      w_pad += stride_w;
    }
    h_pad += stride_h;
  }
}
 
template <>
void Col2imNd<float, CPUMathUtil, StorageOrder::NCHW>(const float* data_col, const int64_t* img_shape,
                                                      const int64_t* output_shape, int64_t channels_col, int64_t img_size,
                                                      const int64_t* kernel_shape, const int64_t* stride,
                                                      const int64_t* dilation, const int64_t* pad, ptrdiff_t N,
                                                      float* data_img, CPUMathUtil* context) {
  Set<float, CPUMathUtil>(narrow<ptrdiff_t>(img_size), 0, data_img, context);
  if (N == 0) {
    Im2col<float, StorageOrder::NCHW>()(data_col, img_shape, output_shape, channels_col,
                                        kernel_shape, stride, dilation, pad, N, data_img, true);
    return;
  }
  const ptrdiff_t last = N - 1;
  const int64_t width = img_shape[last];
  const int64_t row_size = output_shape[last];
  const int64_t step = stride[last];
  const int64_t column_size = std::accumulate(output_shape, output_shape + N, int64_t{1}, std::multiplies<int64_t>());
  InlinedVector<int64_t> offsets(N);
  InlinedVector<int64_t> position(last, 0);
  for (int64_t c = 0; c < channels_col; ++c) {
    int64_t kernel_index = c;
    for (ptrdiff_t d = last; d >= 0; --d) {
      offsets[d] = (kernel_index % kernel_shape[d]) * dilation[d] - pad[d];
      kernel_index /= kernel_shape[d];
    }
    const int64_t first_col = offsets[last] < 0
                                  ? std::min(row_size, -(offsets[last] + 1) / step + 1)
                                  : 0;
    if (first_col == row_size) {
      continue;
    }
    const int64_t first_x = offsets[last] < 0
                                ? step - 1 - (-(offsets[last] + 1) % step)
                                : offsets[last];
    if (first_x >= width) {
      continue;
    }
    const int64_t count = std::min(row_size - first_col, (width - 1 - first_x) / step + 1);
    const float* row = data_col + c * column_size;
    do {
      int64_t img_index = kernel_index;
      bool valid = true;
      for (ptrdiff_t d = 0; d < last; ++d) {
        const int64_t coordinate = position[d] * stride[d] + offsets[d];
        if (!is_a_ge_zero_and_a_lt_b(coordinate, img_shape[d])) {
          valid = false;
          break;
        }
        img_index = img_index * img_shape[d] + coordinate;
      }
      if (valid) {
        const float* src = row + first_col;
        float* dst = data_img + img_index * width + first_x;
        if (step == 1) {
          for (int64_t x = 0; x < count; ++x) {
            dst[x] += src[x];
          }
        } else {
          for (int64_t x = 0; x < count; ++x) {
            dst[x * step] += src[x];
          }
        }
      }
      row += row_size;
    } while (NextPosition(last, output_shape, position.data()));
  }
  bool may_overlap = false;
  for (ptrdiff_t d = 0; d < N; ++d) {
    if (kernel_shape[d] - 1 > (stride[d] - 1) / dilation[d]) {
      may_overlap = true;
      break;
    }
  }
  // A single contribution has no competing NaN payload. For overlapping windows,
  // use the original loop to preserve NaN payloads after vectorized additions.
  if (may_overlap && std::any_of(data_img, data_img + img_size, [](float value) { return std::isnan(value); })) {
    Set<float, CPUMathUtil>(narrow<ptrdiff_t>(img_size), 0, data_img, context);
    Im2col<float, StorageOrder::NCHW>()(data_col, img_shape, output_shape, channels_col,
                                        kernel_shape, stride, dilation, pad, N, data_img, true);
  }
}
 
#define SPECIALIZED_COPYVECTOR(T)                                                          \
  template <>                                                                              \
  void CopyVector<T, CPUMathUtil>(int N, const T* src, T* dst, CPUMathUtil* /*context*/) { \
    if (src != dst && N > 0) {                                                             \
      memcpy(dst, src, sizeof(T) * N);                                                     \
    }                                                                                      \
  }
SPECIALIZED_COPYVECTOR(float)
#undef SPECIALIZED_COPYVECTOR
 
// like C++20's std::bit_cast
// adapted from the example implementation here: https://en.cppreference.com/w/cpp/numeric/bit_cast
// TODO replace this with std::bit_cast when we move to C++20
template <typename Dst, typename Src>
static std::enable_if_t<
    sizeof(Src) == sizeof(Dst) &&
        std::is_trivially_copyable_v<Src> &&
        std::is_trivially_copyable_v<Dst> &&
        std::is_trivially_constructible_v<Dst>,
    Dst>
BitCast(const Src& src) {
  Dst dst;
  std::memcpy(&dst, &src, sizeof(dst));
  return dst;
}
 
uint16_t floatToHalf(float f) {
  return BitCast<uint16_t>(Eigen::half_impl::float_to_half_rtne(f).x);
}
 
uint16_t doubleToHalf(double f) {
  return BitCast<uint16_t>(Eigen::half_impl::float_to_half_rtne(static_cast<float>(f)).x);
}
 
float halfToFloat(uint16_t h) {
  return Eigen::half_impl::half_to_float(Eigen::half_impl::raw_uint16_to_half(h));
}
 
// AddToRow and AddToCol adds the corresponding row/col vector b to the matrix a
// of shape M x N. The actual implementation uses eigen which is column major,
// so notice the row/column swap in the actual implementation.
#define DELEGATE_BROADCAST_BINARY_FUNCTION(T, Funcname, expr)                                                    \
  template <>                                                                                                    \
  void Funcname##ToRow<T, CPUMathUtil>(int M, int N, const T* a, const T* b, T* y, CPUMathUtil*) {               \
    EigenArrayMap<T>(y, N, M) = ConstEigenArrayMap<T>(a, N, M).colwise() expr ConstEigenVectorArrayMap<T>(b, N); \
  }                                                                                                              \
  /* inplace versions */                                                                                         \
  template <>                                                                                                    \
  void Funcname##ToRow<T, CPUMathUtil>(int M, int N, const T* x, T* y, CPUMathUtil*) {                           \
    EigenArrayMap<T>(y, N, M).colwise() expr## = ConstEigenVectorArrayMap<T>(x, N);                              \
  }                                                                                                              \
  template <>                                                                                                    \
  void Funcname##ToCol<T, CPUMathUtil>(int M, int N, const T* x, T* y, CPUMathUtil*) {                           \
    EigenArrayMap<T>(y, N, M).rowwise() expr## = ConstEigenVectorArrayMap<T>(x, M).transpose();                  \
  }
 
#define DEFINE_BROADCAST_BINARY_FUNCTION(name, op)      \
  DELEGATE_BROADCAST_BINARY_FUNCTION(int32_t, name, op) \
  DELEGATE_BROADCAST_BINARY_FUNCTION(int64_t, name, op) \
  DELEGATE_BROADCAST_BINARY_FUNCTION(float, name, op)
 
DEFINE_BROADCAST_BINARY_FUNCTION(Add, +)
DEFINE_BROADCAST_BINARY_FUNCTION(Sub, -)
DEFINE_BROADCAST_BINARY_FUNCTION(Mul, *)
DEFINE_BROADCAST_BINARY_FUNCTION(Div, /)
 
#define SPECIALIZED_ROWWISESUM(T)                                                 \
  template <>                                                                     \
  void RowwiseSum<T, CPUMathUtil>(int N, int D, const T* x, T* y, CPUMathUtil*) { \
    EigenVectorMap<T>(y, N) = ConstEigenMatrixMap<T>(x, D, N).colwise().sum();    \
  }
SPECIALIZED_ROWWISESUM(float)
SPECIALIZED_ROWWISESUM(int32_t)
SPECIALIZED_ROWWISESUM(int64_t)
SPECIALIZED_ROWWISESUM(double)
#undef SPECIALIZED_ROWWISESUM
 
#define SPECIALIZED_SUM(T)                                                             \
  template <>                                                                          \
  void Sum<T, CPUMathUtil>(ptrdiff_t N, const T* x, T* y, CPUMathUtil* /* unused */) { \
    *y = ConstEigenVectorMap<T>(x, N).sum();                                           \
  }
 
SPECIALIZED_SUM(float);
SPECIALIZED_SUM(int32_t);
SPECIALIZED_SUM(int64_t);
 
#undef SPECIALIZED_SUM
 
#define SPECIALIZED_SCALE(T)                                                                                 \
  template <>                                                                                                \
  void Scale<T, CPUMathUtil>(ptrdiff_t n, float alpha, const T* x, T* y, CPUMathUtil* /*provider*/) {        \
    EigenVectorMap<T>(y, n) = ConstEigenVectorMap<T>(x, n) * alpha;                                          \
  }                                                                                                          \
  template <>                                                                                                \
  void Scale<T, CPUMathUtil>(ptrdiff_t n, const float* alpha, const T* x, T* y, CPUMathUtil* /*provider*/) { \
    EigenVectorMap<T>(y, n) = ConstEigenVectorMap<T>(x, n) * (*alpha);                                       \
  }
SPECIALIZED_SCALE(float)
#undef SPECIALIZED_SCALE
 
#define SPECIALIZED_DOT(T)                                                                   \
  template <>                                                                                \
  void Dot<T, CPUMathUtil>(int N, const T* a, const T* b, T* y, CPUMathUtil* /*provider*/) { \
    *y = ConstEigenVectorMap<T>(a, N).dot(ConstEigenVectorMap<T>(b, N));                     \
  }
SPECIALIZED_DOT(float)
#undef SPECIALIZED_DOT
 
}  // namespace math
}  // namespace onnxruntime