gemm_testbed_3x.hpp 63.5 KB
Newer Older
zhoux's avatar
zhoux committed
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
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
/***************************************************************************************************
 * Copyright (c) 2023 - 2025 Hygon Information Technology Co., Ltd. All rights reserved.
 * Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: BSD-3-Clause
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 **************************************************************************************************/
/*! \file
    \brief Tests for device-wide GEMM interface
*/

#pragma once

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <random>

#include "../../common/hytlass_unit_test.h"
#include "hytlass/util/host_tensor.h"
#include "hytlass/util/tensor_view_io.h"
#include "hytlass/util/distribution.h"
#include "hytlass/util/packed_stride.hpp"
#include "hytlass/util/reference/host/tensor_fill.h"
#include "hytlass/util/reference/host/tensor_copy.h"
#include "hytlass/util/reference/host/tensor_compare.h"
#include "hytlass/util/reference/host/tensor_norm.h"
#include "hytlass/util/reference/host/gett.hpp"
#include "hytlass/epilogue/collective/default_epilogue.hpp"
#include "hytlass/epilogue/fusion/operations.hpp"
#include "hytlass/complex.h"
#include "testbed_utils.h"

#include "hytlass/kernel_hardware_info.hpp"
#include "hytlass/layout/matrix.h"
#include "hytlass/matrix_coord.h"
#include "hytlass/gemm/gemm.h"

#include "hute/int_tuple.hpp"
#include "hute/layout.hpp"
#include "hute/numeric/int.hpp"

namespace test {
namespace gemm {
namespace device {

/////////////////////////////////////////////////////////////////////////////////////////////////

enum class ScalarLoc {
  ON_HOST = 0,
  ON_DEVICE = 1
};

enum class VectorBeta {
  DISABLED = 0,
  ENABLED = 1
};

enum class CheckEquality {
  EXACT = 0,
  RELATIVE = 1
};

namespace detail{

// Helper classes that take default data type when
// the Gemm::EpilogueOutputOp does not have ElementCompute
// and ElementScalar.
template <typename Gemm, typename Default, typename = void>
struct ElementComputeType {
  using Type = Default;
};

template <typename Gemm, typename Default>
struct ElementComputeType<Gemm, Default, std::void_t<typename Gemm::EpilogueOutputOp::ElementCompute>> {
  using Type = typename Gemm::EpilogueOutputOp::ElementCompute;
};

template <typename Gemm, typename Default, typename = void>
struct ElementScalarType {
  using Type = Default;
};

template <typename Gemm, typename Default>
struct ElementScalarType<Gemm, Default, std::void_t<typename Gemm::EpilogueOutputOp::ElementScalar>> {
  using Type = typename Gemm::EpilogueOutputOp::ElementScalar;
};

// The maximum swizzle size to use
//
// This class, like Splits above makes it harder to confuse
// the order of arguments of the various run(...) functions in this file.
class MaxSwizzleSize {
public:
  MaxSwizzleSize() = default;

  template<class IntegralNotBool,
    __HUTE_REQUIRES((std::is_integral_v<IntegralNotBool> &&
      !hute::is_same_v<IntegralNotBool, bool>)) >
  explicit MaxSwizzleSize(IntegralNotBool max_swizzle_size) : max_swizzle_size_(max_swizzle_size) {}
  explicit operator int() const { return max_swizzle_size_; }
private:
  int max_swizzle_size_ = 1;
};

template <typename T>
auto make_iterator(T* ptr) {
  using namespace hute;
  if constexpr (hute::is_subbyte_v<T>) {
    return subbyte_iterator<T>(ptr);
  }
  else {
    return ptr;
  }
}

template<class T>
struct IsDefaultEpilogue {
  static constexpr bool value = false;
};

template<class ...args>
struct IsDefaultEpilogue<hytlass::epilogue::collective::DefaultEpilogue<args...>> {
  static constexpr bool value = true;
};

template<class ...args>
struct IsDefaultEpilogue<hytlass::epilogue::collective::Epilogue<args...>> {
  static constexpr bool value = true;
};

// The number of splits to test.
//
// This class makes it harder to confuse the order of arguments
// of the various run(...) functions in this file.  The constructor
// is explicit, so one can't just type 42 (or false, which the
// compiler unhelpfully turns into 0); one has to type Splits(42).
// Splits() picks the default number of splits, 1.
//
// The conversion-to-int operator (operator int()) MUST be explicit!
// Conversion to int MUST require static_cast<int>.
// Otherwise, that defeats a key purpose of this class,
// which is to catch common errors of confusing the order
// of function arguments.
class Splits {
public:
  Splits() = default;

  template<class IntegralNotBool,
    __HUTE_REQUIRES((std::is_integral_v<IntegralNotBool> &&
      !hute::is_same_v<IntegralNotBool, bool>)) >
  explicit Splits(IntegralNotBool splits) : splits_(splits) {}
  explicit operator int() const { return splits_; }
private:
  int splits_ = 1;
};

// The number of iterations to test.
//
// This class, like Splits above makes it harder to confuse
// the order of arguments of the various run(...) functions in this file.
// Iterations() picks the default number of iterations, 20.
class Iterations {
public:
  Iterations() = default;

  template<class IntegralNotBool,
    __HUTE_REQUIRES((std::is_integral_v<IntegralNotBool> &&
      !hute::is_same_v<IntegralNotBool, bool>)) >
  explicit Iterations(IntegralNotBool iterations) : iterations_(iterations) {}
  explicit operator int() const { return iterations_; }
private:
  int iterations_ = 20;
};

template <typename Element, typename Layout>
bool initialize_tensor(
  hytlass::TensorView<Element, Layout> view,
  hytlass::Distribution::Kind dist_kind,
  uint64_t seed) {

  if (dist_kind == hytlass::Distribution::Uniform) {
    double scope_max, scope_min;
    int bits_input = hytlass::sizeof_bits<Element>::value;

    if (bits_input == 1) {
      scope_max = 2;
      scope_min = 0;
    }
    else if (bits_input <= 8) {
        scope_max = 1;
        scope_min = -1;
    }
    else{
      scope_max = 4;
      scope_min = -4;
    }
    hytlass::reference::host::TensorFillRandomUniform(
      view, seed, scope_max, scope_min, 0);
  }

  else if (dist_kind == hytlass::Distribution::Identity) {
    hytlass::reference::host::TensorFillIdentity(view);
  }

  else if (dist_kind == hytlass::Distribution::Gaussian) {
    hytlass::reference::host::TensorFillRandomGaussian(view, seed, 0, 0.5);
  }

  else if (dist_kind == hytlass::Distribution::Sequential) {
    hytlass::reference::host::BlockFillSequential(
      view.data(), view.capacity());
  }

  else if (dist_kind == hytlass::Distribution::AllOnes) {
    hytlass::reference::host::TensorFill(view, Element(1));
  }

  else {
    EXPECT_TRUE(false) << "Not implemented";
    return false;
  }

  return true;
}

// Looks at Hute Stride to check Row / Column Major
template<typename Stride>
static constexpr bool is_row_or_col_major(){
  int stride_0 = int(hute::size<0>(Stride{}));
  int stride_1 = int(hute::size<1>(Stride{}));
  int depth = hute::depth(Stride{});
  return ((stride_0 == 1) || (stride_1 == 1)) && (depth == 1);
}


//
// Default MMA input Operands : A , B
//
template<
  class ScheduleType_, 
  class Gemm, 
  class ElementA_ = typename Gemm::GemmKernel::ElementA,
  class ElementB_ = typename Gemm::GemmKernel::ElementB> 
struct HostCollectiveMainloop {
  // Kernel data types
  using ElementA = ElementA_;
  using StrideA  = typename Gemm::GemmKernel::StrideA;
  using ElementB = ElementB_;
  using StrideB  = typename Gemm::GemmKernel::StrideB;
  using ScheduleType = ScheduleType_;
  using LayoutTagA = hytlass::detail::StrideToLayoutTagA_t<StrideA>;
  using LayoutTagB = hytlass::detail::StrideToLayoutTagB_t<StrideB>;

  using ElementAccumulator = typename Gemm::GemmKernel::ElementAccumulator;
  using ElementScalingFactor = ElementAccumulator;
  using ProblemShapeType = typename Gemm::GemmKernel::ProblemShape;
  using EpilogueOutputOp = typename Gemm::EpilogueOutputOp;

  using Arguments = typename Gemm::GemmKernel::MainloopArguments;

  hytlass::ComplexTransform TransformA = Gemm::kTransformA;
  hytlass::ComplexTransform TransformB = Gemm::kTransformB;

  StrideA stride_a;
  StrideB stride_b;

  typename LayoutTagA::Stride stride_factor_A;
  typename LayoutTagB::Stride stride_factor_B;

  hytlass::Distribution::Kind init_A;
  hytlass::Distribution::Kind init_B;

  hytlass::HostTensor<ElementA, LayoutTagA> tensor_A;
  hytlass::HostTensor<ElementB, LayoutTagB> tensor_B;
  // Whether to use relative equality checks
  CheckEquality check_relative_equality = CheckEquality::EXACT;

  uint64_t seed;
  static constexpr uint64_t kDefaultSeed = 4096;

  // Note: this limitation comes from testbed / not the library
  static_assert(is_row_or_col_major<StrideA>(),
    "ERROR : A Layout is neither Row / Column Major)");
  static_assert(is_row_or_col_major<StrideB>(),
    "ERROR : B Layout is neither Row / Column Major)");

  HostCollectiveMainloop(
    CheckEquality check_relative_equality_ = CheckEquality::EXACT,
    hytlass::Distribution::Kind init_A_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_B_ = hytlass::Distribution::Uniform,
    uint64_t seed_ = kDefaultSeed,
    typename LayoutTagA::Stride stride_factor_A_ = typename LayoutTagA::Stride(),
    typename LayoutTagB::Stride stride_factor_B_ = typename LayoutTagB::Stride()
  ):
    stride_factor_A(stride_factor_A_),
    stride_factor_B(stride_factor_B_),
    init_A(init_A_), init_B(init_B_), seed(seed_),
    check_relative_equality(check_relative_equality_) { }

  template<class ProblemShapeType>
  bool initialize(ProblemShapeType problem_size) {
    //
    // Allocate the GEMM workspace
    //
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto M = hute::size<0>(problem_shape_MNKL);
    auto N = hute::size<1>(problem_shape_MNKL);
    auto K = hute::size<2>(problem_shape_MNKL);
    auto L = hute::size<3>(problem_shape_MNKL);

    stride_a = hytlass::make_hute_packed_stride(StrideA{}, hute::make_shape(M, K, L));
    stride_b = hytlass::make_hute_packed_stride(StrideB{}, hute::make_shape(N, K, L));

    // 2.x host tensor does not natively contain a batch stride or coord, so we spoof if by folding it into the outer mode
    auto a_coord = hytlass::make_Coord(M * L, K);
    // Hytlass has Row/Col major refers to MxK times KxN matrix product,
    // so the HostTensorB should be treated as KxN in "coord"'s view
    auto b_coord = hytlass::make_Coord(K, N * L);


    tensor_A.resize(a_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagA>::layout_factory(a_coord, stride_factor_A));
    tensor_B.resize(b_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagB>::layout_factory(b_coord, stride_factor_B));
 
    EXPECT_TRUE(initialize_tensor(tensor_A.host_view(), init_A, seed + 2022));
    EXPECT_TRUE(initialize_tensor(tensor_B.host_view(), init_B, seed + 2021));

    // It is possible to randomly initialize to all zeros, so override this with non-zeros
    // in the upper left corner of each operand.
    tensor_A.host_view().at({0, 0}) = ElementA(1);
    tensor_B.host_view().at({0, 0}) = ElementB(1);

    tensor_A.sync_device();
    tensor_B.sync_device();

    return true;
  }

  Arguments to_args() {

    Arguments arguments = 
    {
      tensor_A.device_data(), stride_a, tensor_B.device_data(), stride_b
    };
    return arguments;
  }

  auto to_host_args(ProblemShapeType problem_size) {
    using namespace hute;
    //
    // Allocate the GEMM workspace
    //
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto M = hute::size<0>(problem_shape_MNKL);
    auto N = hute::size<1>(problem_shape_MNKL);
    auto K = hute::size<2>(problem_shape_MNKL);
    auto L = hute::size<3>(problem_shape_MNKL);
    auto A = make_tensor(make_iterator(tensor_A.host_data()),
          make_layout(make_shape(M, K, L), stride_a));
    auto B = make_tensor(make_iterator(tensor_B.host_data()),
        make_layout(make_shape(N, K, L), stride_b));

    hytlass::reference::host::GettMainloopParams<ElementAccumulator, 
                                                 decltype(A), 
                                                 decltype(B)
                                                 > mainloop_params{};

    mainloop_params.A = A;
    mainloop_params.B = B;
    mainloop_params.transform_A = TransformA;
    mainloop_params.transform_B = TransformB;

    return mainloop_params;
  }

  void print_tensors(std::ofstream& file) {
    file << "A =\n" << tensor_A.host_view()
         << "\nB =\n" << tensor_B.host_view();
  }

  template <
    class Element,
    class Layout
  >
  bool equality_check(
    hytlass::TensorView<Element, Layout> const& lhs,
    hytlass::TensorView<Element, Layout> const& rhs) const {

    // Factors used for calculating relative equality. HYTLASS's relative-equality
    // checks in include/hytlass/relatively_equal.h  are inspired by
    // https://floating-point-gui.de/errors/comparison/. This reference suggests using
    // the minimum normal value of a given type as the nonzero_floor.
    Element epsilon(static_cast<Element>(0.1f));
    Element nonzero_floor(std::numeric_limits<Element>::min());

    if constexpr (!hytlass::is_complex<Element>::value) {
      if (check_relative_equality == CheckEquality::RELATIVE) {
        return hytlass::reference::host::TensorRelativelyEquals(
          lhs, rhs, epsilon, nonzero_floor);
      }
      else {
        return hytlass::reference::host::TensorEquals(lhs, rhs);
      }
    }
    else {
      return hytlass::reference::host::TensorEquals(lhs, rhs);
    }
  }

  bool compare_reference(
      hute::Shape<int,int,int,int> problem_shape_MNKL) {
    EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_A.host_view()), 0);
    EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_B.host_view()), 0);

    bool passed = true;
    return passed;
  }
};

template<class Gemm>
struct HostCollectiveDefaultEpilogue {
  // fusion types are potentially void if the fusion is not supported
  // helper so we don't try to construct HostTensor with void type
  template <typename T, typename U = uint8_t>
  using non_void_t = hute::conditional_t<hute::is_void_v<T>, U, T>;

  using ScheduleType = typename Gemm::GemmKernel::CollectiveMainloop::DispatchPolicy::Schedule;
  using kernel   = typename Gemm::GemmKernel;
  using Epilogue = typename kernel::CollectiveEpilogue;

  using ElementD = typename kernel::ElementD;
  using StrideD  = typename kernel::StrideD;
  using ElementC = non_void_t<typename kernel::ElementC, ElementD>;
  using StrideC  = typename kernel::StrideC;

  using FusionOp = typename Gemm::EpilogueOutputOp;

  static_assert(rank(StrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]");
  static_assert(rank(StrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");

  static_assert(is_row_or_col_major<StrideC>(),
    "ERROR : C Layout is neither Row / Column Major)");
  static_assert(is_row_or_col_major<StrideD>(),
    "ERROR : D Layout is neither Row / Column Major)");

  // Deduce Hytlass Layouts (RowMajor & ColumnMajor)
  using LayoutTagC = hytlass::detail::StrideToLayoutTagC_t<StrideC>;
  using LayoutTagD = hytlass::detail::StrideToLayoutTagC_t<StrideD>;
  using LayoutTagScalar = hytlass::layout::PackedVectorLayout; // scalars are size-1 vectors
  using LayoutTagVector = hytlass::layout::PackedVectorLayout;

  using ElementAccumulator = typename kernel::ElementAccumulator;
  using ElementScalingFactor = ElementAccumulator;
  using ProblemShapeType = typename kernel::ProblemShape;
  using ElementCompute = typename ElementComputeType<Gemm, ElementAccumulator>::Type;
  using ElementScalar = typename ElementScalarType<Gemm, ElementCompute>::Type;

  using Arguments = typename Gemm::GemmKernel::EpilogueArguments;

  /// Initialization
  StrideC stride_c;
  StrideD stride_d;

  typename LayoutTagC::Stride stride_factor_C;
  typename LayoutTagD::Stride stride_factor_D;

  hytlass::HostTensor<ElementC, LayoutTagC> tensor_C;
  // Inputs
  ElementScalar alpha;
  ElementScalar beta;

  hytlass::HostTensor<ElementD, LayoutTagD> tensor_D;
  hytlass::HostTensor<ElementD, LayoutTagD> reference_D;

  // Whether to use relative equality checks
  CheckEquality check_relative_equality = CheckEquality::EXACT;
  // Are scalars copied to device memory before kernel launch
  ScalarLoc use_device_scalars = ScalarLoc::ON_HOST;
  // If per-row scale is enabled and this is true, beta is passed as a host scalar instead of device vector
  VectorBeta disable_vector_beta = VectorBeta::DISABLED;

  hytlass::Distribution::Kind init_C;
  uint64_t seed;
  static constexpr uint64_t kDefaultSeed = 4096;

  HostCollectiveDefaultEpilogue(
    CheckEquality check_relative_equality_ = CheckEquality::EXACT,
    ScalarLoc use_device_scalars_ = ScalarLoc::ON_HOST,
    VectorBeta disable_vector_beta_ = VectorBeta::DISABLED,
    hytlass::Distribution::Kind init_C_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_scale_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_bias_ = hytlass::Distribution::Uniform,
    uint64_t seed_ = kDefaultSeed
  ): init_C(init_C_), seed(seed_), 
     stride_factor_C(typename LayoutTagC::Stride()), 
     stride_factor_D(typename LayoutTagD::Stride()),
     check_relative_equality(check_relative_equality_),
     use_device_scalars(use_device_scalars_){ }

  bool initialize(ProblemShapeType problem_size, ElementScalar alpha_=1.f, ElementScalar beta_=0.f) {
    // Initialize Epilogue tensors
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto [M, N, K, L] = problem_shape_MNKL;

    stride_c = hytlass::make_hute_packed_stride(StrideC{}, hute::make_shape(M, N, L));
    stride_d = hytlass::make_hute_packed_stride(StrideD{}, hute::make_shape(M, N, L));

    // 2.x host tensor does not natively contain a batch stride or coord, so we spoof if by folding it into the outer mode
    auto c_coord = hytlass::make_Coord(M * L, N);
    tensor_C.resize(c_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagC>::layout_factory(c_coord, stride_factor_C));
    tensor_D.resize(c_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagD>::layout_factory(c_coord, stride_factor_D));
    reference_D.resize(c_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagD>::layout_factory(c_coord, stride_factor_D), false);
    EXPECT_TRUE(initialize_tensor(tensor_C.host_view(), init_C, seed + 2020));
    tensor_C.host_view().at({0, 0}) = ElementC(1);

    hytlass::reference::host::TensorCopy(reference_D.host_view(), tensor_C.host_view());
    tensor_C.sync_device();
    tensor_D.sync_device();

    alpha = alpha_;
    beta = beta_;

    return true;
  }

  template <
    class Element,
    class Layout
  >
  bool equality_check(
    hytlass::TensorView<Element, Layout> const& lhs,
    hytlass::TensorView<Element, Layout> const& rhs) const {

    // Factors used for calculating relative equality. HYTLASS's relative-equality
    // checks in include/hytlass/relatively_equal.h  are inspired by
    // https://floating-point-gui.de/errors/comparison/. This reference suggests using
    // the minimum normal value of a given type as the nonzero_floor.
    Element epsilon(static_cast<Element>(0.1f));
    Element nonzero_floor(std::numeric_limits<Element>::min());

    if constexpr (!hytlass::is_complex<Element>::value) {
      if (check_relative_equality == CheckEquality::RELATIVE) {
        return hytlass::reference::host::TensorRelativelyEquals(
          lhs, rhs, epsilon, nonzero_floor);
      }
      else {
        return hytlass::reference::host::TensorEquals(lhs, rhs);
      }
    }
    else {
      return hytlass::reference::host::TensorEquals(lhs, rhs);
    }
  }

  bool compare_reference(
      hute::Shape<int,int,int,int> problem_shape_MNKL,
      ElementScalar alpha,
      ElementScalar beta) {
    auto [M, N, K, L] = problem_shape_MNKL;

    tensor_D.sync_host();
    EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_C.host_view()), 0);

    if (tensor_D.size() > 1) {
      EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_D.host_view()), 0);
    }

    if (reference_D.size() > 1) {
      EXPECT_GT(hytlass::reference::host::TensorNorm(reference_D.host_view()), 0);
    }

    bool passed = equality_check(reference_D.host_view(), tensor_D.host_view());
    if(!passed) {
      std::cout<<"D is incorrect"<<std::endl;  
    }
    return passed;
  }

  void print_tensors(std::ofstream& file) {
    file
    << "\nC =\n" << tensor_C.host_view()
    << "\n\nReference =\n" << reference_D.host_view()
    << "\n\nComputed =\n" << tensor_D.host_view();
  }

  Arguments to_args(ProblemShapeType problem_size) {
    Arguments arguments = 
      {
        {alpha, beta},
        tensor_C.device_data(), stride_c, tensor_D.device_data(), stride_d
      };

    return arguments;
  }

  auto to_host_args(ProblemShapeType problem_size) {
    using namespace hute;
    //
    // Allocate the GEMM workspace
    //
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto M = hute::get<0>(problem_shape_MNKL);
    auto N = hute::get<1>(problem_shape_MNKL);
    auto K = hute::get<2>(problem_shape_MNKL);
    auto L = hute::get<3>(problem_shape_MNKL);
    auto coord_0 = hytlass::make_Coord(0);
    auto C = hute::make_tensor(detail::make_iterator(tensor_C.host_data()),
        hute::make_layout(hute::make_shape(M, N, L), stride_c));
    auto D = hute::make_tensor(detail::make_iterator(reference_D.host_data()),
        hute::make_layout(hute::make_shape(M, N, L), stride_d));

    hytlass::reference::host::GettEpilogueParams<
      ElementScalar,
      ElementScalar,
      ElementAccumulator,
      ElementCompute,
      decltype(C),
      decltype(D)>
        epilogue_params{};

    epilogue_params.C = C;
    epilogue_params.D = D;
    epilogue_params.alpha = alpha;
    epilogue_params.beta = beta;

    return epilogue_params;
  }
};

template<class Gemm>
struct HostCollectiveEpilogue {
  // fusion types are potentially void if the fusion is not supported
  // helper so we don't try to construct HostTensor with void type
  template <typename T, typename U = uint8_t>
  using non_void_t = hute::conditional_t<hute::is_void_v<T>, U, T>;

  using ScheduleType = typename Gemm::GemmKernel::CollectiveMainloop::DispatchPolicy::Schedule;
  using kernel   = typename Gemm::GemmKernel;
  using Epilogue = typename kernel::CollectiveEpilogue;
  static_assert(IsDefaultEpilogue<Epilogue>::value == false, "Default Epilogue is not supported");

  using ElementD = typename kernel::ElementD;
  using StrideD  = typename kernel::StrideD;
  using ElementC = non_void_t<typename kernel::ElementC, ElementD>;
  using StrideC  = typename kernel::StrideC;

  static_assert(rank(StrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]");
  static_assert(rank(StrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");

  static_assert(is_row_or_col_major<StrideC>(),
    "ERROR : C Layout is neither Row / Column Major)");
  static_assert(is_row_or_col_major<StrideD>(),
    "ERROR : D Layout is neither Row / Column Major)");

  // Deduce Hytlass Layouts (RowMajor & ColumnMajor)
  using LayoutTagC = hytlass::detail::StrideToLayoutTagC_t<StrideC>;
  using LayoutTagD = hytlass::detail::StrideToLayoutTagC_t<StrideD>;
  using LayoutTagScalar = hytlass::layout::PackedVectorLayout; // scalars are size-1 vectors
  using LayoutTagVector = hytlass::layout::PackedVectorLayout;

  using ElementAccumulator = typename kernel::ElementAccumulator;
  using ElementScalingFactor = ElementAccumulator;
  using ProblemShapeType = typename kernel::ProblemShape;

  //
  // FusionOperation derived types/queries
  //
  using EpiloguePolicy = typename Epilogue::DispatchPolicy;
  using FusionOp = typename Gemm::EpilogueOutputOp;
  static_assert(hute::is_base_of_v<hytlass::epilogue::fusion::FusionOperation, FusionOp>);

  using ElementCompute    = typename FusionOp::ElementCompute;
  using ElementScalar     = typename FusionOp::ElementScalar;
  using ElementBias       = non_void_t<typename FusionOp::ElementBias>;
  using ElementAux        = non_void_t<typename FusionOp::ElementAux>;
  using ElementAmax       = non_void_t<typename FusionOp::ElementAmax>;
  using LayoutTagAux      = non_void_t<typename FusionOp::GmemLayoutTagAux, LayoutTagD>;
  using ActivationFunctor = non_void_t<typename FusionOp::ActivationFn,
                              hytlass::epilogue::thread::Identity<ElementCompute>>;

  static constexpr bool IsBiasEnabled        = FusionOp::IsPerRowBiasSupported;
  static constexpr bool IsDeBiasEnabled      = FusionOp::IsDePerRowBiasSupported;
  static constexpr bool IsPerRowScaleEnabled = FusionOp::IsPerRowScaleSupported;
  static constexpr bool IsScaleFactorEnabled = FusionOp::IsScaleFactorSupported;
  static constexpr bool IsAuxInEnabled       = FusionOp::IsAuxInSupported;
  static constexpr bool IsAuxOutEnabled      = FusionOp::IsAuxOutSupported;
  static constexpr bool IsAbsMaxEnabledD     = FusionOp::IsAbsMaxSupported &&
                                                (hute::is_same_v<ElementD, hytlass::float_e4m3_t> ||
                                                 hute::is_same_v<ElementD, hytlass::float_e5m2_t>);
  static constexpr bool IsAbsMaxEnabledAux   = IsAuxOutEnabled && FusionOp::IsAbsMaxSupported &&
                                                (hute::is_same_v<ElementAux, hytlass::float_e4m3_t> ||
                                                 hute::is_same_v<ElementAux, hytlass::float_e5m2_t>);

  using Arguments = typename Gemm::GemmKernel::EpilogueArguments;

  /// Initialization
  StrideC stride_c;
  StrideD stride_d;

  typename LayoutTagC::Stride stride_factor_C;
  typename LayoutTagD::Stride stride_factor_D;

  // Inputs
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> alpha;
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> beta;
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> scale_A;
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> scale_B;
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> scale_C;
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> scale_D;
  hytlass::HostTensor<ElementScalar, LayoutTagScalar> scale_Aux;
  hytlass::HostTensor<ElementBias  , LayoutTagVector> bias;
  hytlass::HostTensor<ElementC, LayoutTagC> tensor_C;
  hytlass::HostTensor<ElementCompute, LayoutTagScalar> norm_constant;

  // Outputs
  hytlass::HostTensor<ElementAmax, LayoutTagScalar> abs_max_Aux;
  hytlass::HostTensor<ElementAmax, LayoutTagScalar> abs_max_D;
  hytlass::HostTensor<ElementAux , LayoutTagAux   > tensor_Aux;
  hytlass::gemm::TagToStrideC_t<   LayoutTagAux   > stride_Aux;
  hytlass::HostTensor<ElementD, LayoutTagD> tensor_D;
  hytlass::HostTensor<ElementD, LayoutTagD> reference_D;

  // References
  hytlass::HostTensor<ElementBias, LayoutTagVector> reference_dbias;
  hytlass::HostTensor<ElementAux , LayoutTagAux   > reference_Aux;
  hytlass::HostTensor<ElementAmax, LayoutTagScalar> reference_abs_max_Aux;
  hytlass::HostTensor<ElementAmax, LayoutTagScalar> reference_abs_max_D;

  // Whether to use relative equality checks
  CheckEquality check_relative_equality = CheckEquality::EXACT;
  // Are scalars copied to device memory before kernel launch
  ScalarLoc use_device_scalars = ScalarLoc::ON_HOST;
  // If per-row scale is enabled and this is true, beta is passed as a host scalar instead of device vector
  VectorBeta disable_vector_beta = VectorBeta::DISABLED;

  // Random distribution with which to initialize the A/B/C/D/Aux scaling factors
  hytlass::Distribution::Kind init_scale = hytlass::Distribution::Uniform;
  // Random distribution with which to initialize the bias vector
  hytlass::Distribution::Kind init_bias = hytlass::Distribution::Uniform;
  hytlass::Distribution::Kind init_C;
  uint64_t seed;
  static constexpr uint64_t kDefaultSeed = 4096;

  HostCollectiveEpilogue(
    CheckEquality check_relative_equality_ = CheckEquality::EXACT,
    ScalarLoc use_device_scalars_ = ScalarLoc::ON_HOST,
    VectorBeta disable_vector_beta_ = VectorBeta::DISABLED,
    hytlass::Distribution::Kind init_C_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_scale_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_bias_ = hytlass::Distribution::Uniform,
    uint64_t seed_ = kDefaultSeed
  ): init_scale(init_scale_), init_bias(init_bias_), 
     init_C(init_C_), seed(seed_), 
     stride_factor_C(typename LayoutTagC::Stride()), 
     stride_factor_D(typename LayoutTagD::Stride()),
     check_relative_equality(check_relative_equality_),
     use_device_scalars(use_device_scalars_){ }

  bool initialize(ProblemShapeType problem_size, ElementScalar alpha_=1.f, ElementScalar beta_=0.f) {
    // Initialize Epilogue tensors
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto M = hute::size<0>(problem_shape_MNKL);
    auto N = hute::size<1>(problem_shape_MNKL);
    auto K = hute::size<2>(problem_shape_MNKL);
    auto L = hute::size<3>(problem_shape_MNKL);

    stride_c = hytlass::make_hute_packed_stride(StrideC{}, hute::make_shape(M, N, L));
    stride_d = hytlass::make_hute_packed_stride(StrideD{}, hute::make_shape(M, N, L));

    // 2.x host tensor does not natively contain a batch stride or coord, so we spoof if by folding it into the outer mode
    auto c_coord = hytlass::make_Coord(M * L, N);
    tensor_C.resize(c_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagC>::layout_factory(c_coord, stride_factor_C));
    tensor_D.resize(c_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagD>::layout_factory(c_coord, stride_factor_D));
    reference_D.resize(c_coord, hytlass::layout::Affine2Layout_Factory<LayoutTagD>::layout_factory(c_coord, stride_factor_D), false);
    EXPECT_TRUE(initialize_tensor(tensor_C.host_view(), init_C, seed + 2020));
    tensor_C.host_view().at({0, 0}) = ElementC(1);

    hytlass::reference::host::TensorCopy(reference_D.host_view(), tensor_C.host_view());
    tensor_C.sync_device();
    tensor_D.sync_device();

    auto scalar_coord = hytlass::make_Coord(1);
    auto col_vector_coord = hytlass::make_Coord(M);
    if constexpr (IsPerRowScaleEnabled) {
      alpha.resize(col_vector_coord);
      EXPECT_TRUE(initialize_tensor(alpha.host_view(), init_scale, seed + 2023));
      if (disable_vector_beta == VectorBeta::DISABLED) {
        beta.resize(scalar_coord, false);
        hytlass::reference::host::TensorFill(beta.host_view(), beta_);
      }
      else {
        beta.resize(col_vector_coord);
        EXPECT_TRUE(initialize_tensor(beta.host_view(), init_scale, seed + 2024));
      }
    }
    else {
      alpha.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
      beta.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
      hytlass::reference::host::TensorFill(alpha.host_view(), alpha_);
      hytlass::reference::host::TensorFill(beta.host_view(), beta_);
    }
    alpha.sync_device();
    beta.sync_device();

    if constexpr (IsScaleFactorEnabled) {
      scale_A.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
      scale_B.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
      scale_C.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
      scale_D.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
      EXPECT_TRUE(initialize_tensor(scale_A.host_view(), init_scale, seed + 2023));
      EXPECT_TRUE(initialize_tensor(scale_B.host_view(), init_scale, seed + 2024));
      EXPECT_TRUE(initialize_tensor(scale_C.host_view(), init_scale, seed + 2025));
      EXPECT_TRUE(initialize_tensor(scale_D.host_view(), init_scale, seed + 2026));
      scale_A.sync_device();
      scale_B.sync_device();
      scale_C.sync_device();
      scale_D.sync_device();
    }

    if constexpr (IsBiasEnabled) {
      bias.resize(col_vector_coord);
      EXPECT_TRUE(initialize_tensor(bias.host_view(), init_bias, seed + 2023));
      bias.sync_device();
    }

    if constexpr (IsDeBiasEnabled) {
      bias.resize(col_vector_coord);
      reference_dbias.resize(col_vector_coord);
      hytlass::reference::host::TensorFill(bias.host_view(), ElementBias(0));
      hytlass::reference::host::TensorFill(reference_dbias.host_view(), ElementBias(0));
      bias.sync_device();
    }

    if constexpr (IsAbsMaxEnabledD) {
      abs_max_D.resize(scalar_coord);
      // ensure in-place device reductions perform their own initialization
      hytlass::reference::host::TensorFill(abs_max_D.host_view(),
                                           HYTLASS_STL_NAMESPACE::numeric_limits<ElementAmax>::max());
      abs_max_D.sync_device();
      reference_abs_max_D.resize(scalar_coord);
      hytlass::reference::host::TensorFill(reference_abs_max_D.host_view(), ElementAmax(0));
    }

    if constexpr (IsAuxInEnabled) {
      auto aux_coord = hytlass::make_Coord(M * L, N);
      auto aux_layout = hytlass::layout::Affine2Layout_Factory<LayoutTagD>::layout_factory(aux_coord, typename LayoutTagAux::Stride{});
      tensor_Aux.resize(aux_coord, aux_layout);
      EXPECT_TRUE(initialize_tensor(tensor_Aux.host_view(), init_C, seed + 2023));
      tensor_Aux.sync_device();
      stride_Aux = hytlass::make_hute_packed_stride(hytlass::gemm::TagToStrideC_t<LayoutTagAux>{}, hute::make_shape(M, N, L));
    }

    if constexpr (IsAuxOutEnabled) {
      auto aux_coord = hytlass::make_Coord(M * L, N);
      auto aux_layout = hytlass::layout::Affine2Layout_Factory<LayoutTagD>::layout_factory(aux_coord, typename LayoutTagAux::Stride{});
      tensor_Aux.resize(aux_coord, aux_layout);
      reference_Aux.resize(aux_coord, aux_layout, false);
      tensor_Aux.sync_device();
      stride_Aux = hytlass::make_hute_packed_stride(hytlass::gemm::TagToStrideC_t<LayoutTagAux>{}, hute::make_shape(M, N, L));

      if constexpr (IsScaleFactorEnabled) {
        scale_Aux.resize(scalar_coord, (use_device_scalars == ScalarLoc::ON_DEVICE));
        EXPECT_TRUE(initialize_tensor(scale_Aux.host_view(), init_scale, seed + 2027));
        scale_Aux.sync_device();
      }

      if constexpr (IsAbsMaxEnabledAux) {
        abs_max_Aux.resize(scalar_coord);
        // ensure in-place device reductions perform their own initialization
        hytlass::reference::host::TensorFill(abs_max_Aux.host_view(),
                                             HYTLASS_STL_NAMESPACE::numeric_limits<ElementAmax>::max());
        abs_max_Aux.sync_device();
        reference_abs_max_Aux.resize(scalar_coord);
        hytlass::reference::host::TensorFill(reference_abs_max_Aux.host_view(), ElementAmax(0));
      }
    }

    return true;
  }

  template <
    class Element,
    class Layout
  >
  bool equality_check(
    hytlass::TensorView<Element, Layout> const& lhs,
    hytlass::TensorView<Element, Layout> const& rhs) const {

    // Factors used for calculating relative equality. HYTLASS's relative-equality
    // checks in include/hytlass/relatively_equal.h  are inspired by
    // https://floating-point-gui.de/errors/comparison/. This reference suggests using
    // the minimum normal value of a given type as the nonzero_floor.
    Element epsilon(static_cast<Element>(0.1f));
    Element nonzero_floor(std::numeric_limits<Element>::min());

    if constexpr (!hytlass::is_complex<Element>::value) {
      if (check_relative_equality == CheckEquality::RELATIVE) {
        return hytlass::reference::host::TensorRelativelyEquals(
          lhs, rhs, epsilon, nonzero_floor);
      }
      else {
        return hytlass::reference::host::TensorEquals(lhs, rhs);
      }
    }
    else {
      return hytlass::reference::host::TensorEquals(lhs, rhs);
    }
  }

  bool compare_reference(
      hute::Shape<int,int,int,int> problem_shape_MNKL,
      ElementScalar alpha,
      ElementScalar beta) {
    tensor_D.sync_host();
    EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_C.host_view()), 0);

    if (tensor_D.size() > 1) {
      EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_D.host_view()), 0);
    }

    if (reference_D.size() > 1) {
      EXPECT_GT(hytlass::reference::host::TensorNorm(reference_D.host_view()), 0);
    }

    bool passed = equality_check(reference_D.host_view(), tensor_D.host_view());
    if(!passed) {
      std::cout<<"D is incorrect"<<std::endl;  
    }

    if constexpr (IsAbsMaxEnabledD) {
      abs_max_D.sync_host();
      passed &= equality_check(reference_abs_max_D.host_view(), abs_max_D.host_view());
    }

    if constexpr (IsDeBiasEnabled) {
      bias.sync_host();
      EXPECT_GT(hytlass::reference::host::TensorNorm(bias.host_view()), 0);
      EXPECT_GT(hytlass::reference::host::TensorNorm(reference_dbias.host_view()), 0);
      passed &= equality_check(reference_dbias.host_view(), bias.host_view());
    }

    if constexpr (IsAuxOutEnabled) {
      tensor_Aux.sync_host();
      EXPECT_GT(hytlass::reference::host::TensorNorm(tensor_Aux.host_view()), 0);
      EXPECT_GT(hytlass::reference::host::TensorNorm(reference_Aux.host_view()), 0);
      passed &= equality_check(reference_Aux.host_view(), tensor_Aux.host_view());
      if(!passed) {
        std::cout<<"Aux is incorrect"<<std::endl;  
      }
      if constexpr (IsAbsMaxEnabledAux) {
        abs_max_Aux.sync_host();
        bool tmp =  equality_check(reference_abs_max_Aux.host_view(), abs_max_Aux.host_view());
        if(!tmp) {
          std::cout<<"AbsMax of Aux is incorrect"<<std::endl;  
        }
        passed &= tmp;
      }
    }

    return passed;
  }

  void print_tensors(std::ofstream& file) {
    auto coord_0 = hytlass::make_Coord(0);
    if constexpr (IsScaleFactorEnabled) {
      file
        << ", scale_a: " << scale_A.at(coord_0)
        << ", scale_b: " << scale_B.at(coord_0)
        << ", scale_c: " << scale_C.at(coord_0);
    }
    if constexpr (IsPerRowScaleEnabled) {
      file << "\n\nvalpha = \n" << alpha.host_view();
      file << "\n\nvbeta = \n" << beta.host_view();
    } else {
      file
        << ", alpha: " << alpha.at(coord_0) << ", beta: " << beta.at(coord_0);
    }
    file << "\n\n";

    if constexpr (IsAbsMaxEnabledD) {
      file << "scale_d: " << float(scale_D.at(coord_0));
      file << "\nReference abs_max_D :";
      file << " " << float(reference_abs_max_D.at(coord_0));

      file << "\nComputed abs_max_D :";
      file << " " << float(abs_max_D.at(coord_0));
      file << "\n\n";
    }

    if constexpr (IsAbsMaxEnabledAux) {
      file << "scale_aux: " << float(scale_Aux.at(coord_0));
      file << "\nReference abs_max_Aux :";
      file << " " << float(reference_abs_max_Aux.at(coord_0));

      file << "\nComputed abs_max_Aux :";
      file << " " << float(abs_max_Aux.at(coord_0));
      file << "\n\n";
    }

    if constexpr (IsBiasEnabled) {
      file << "\n\nBias = \n" << bias.host_view();
    }

    if constexpr (IsAuxInEnabled) {
      file << "\n\nAux Input = \n" << tensor_Aux.host_view();
    }

    if constexpr (IsDeBiasEnabled) {
      file << "\n\nReference dBias = \n" << reference_dbias.host_view();
      file << "\n\nComputed dBias = \n" << bias.host_view();
    }

    if constexpr (IsAuxOutEnabled) {
      file
        << "\n\nReference Aux =\n" << reference_Aux.host_view()
        << "\n\nComputed Aux =\n" << tensor_Aux.host_view();
    }
    file
    << "\nC =\n" << tensor_C.host_view()
    << "\n\nReference =\n" << reference_D.host_view()
    << "\n\nComputed =\n" << tensor_D.host_view();

  }

  Arguments to_args(ProblemShapeType problem_size) {
    auto coord_0 = hytlass::make_Coord(0);
    Arguments arguments = 
      {
        {},
        tensor_C.device_data(), stride_c, tensor_D.device_data(), stride_d
      };

    auto &fusion_args = arguments.thread;

    fusion_args.alpha = alpha.at(coord_0);
    fusion_args.beta = beta.at(coord_0);
    fusion_args.alpha_ptr = alpha.device_data();
    fusion_args.beta_ptr =
        beta.device_data();  // if disable_vector_beta is true this is nullptr

    if constexpr (IsScaleFactorEnabled) {
      fusion_args.scale_a = scale_A.at(coord_0);
      fusion_args.scale_b = scale_B.at(coord_0);
      fusion_args.scale_c = scale_C.at(coord_0);
      fusion_args.scale_d = scale_D.at(coord_0);
      fusion_args.scale_a_ptr = scale_A.device_data();
      fusion_args.scale_b_ptr = scale_B.device_data();
      fusion_args.scale_c_ptr = scale_C.device_data();
      fusion_args.scale_d_ptr = scale_D.device_data();
    }

    if constexpr (IsBiasEnabled) {
      fusion_args.bias_ptr = bias.device_data();
    }

    if constexpr (IsDeBiasEnabled) {
      fusion_args.dbias_ptr = bias.device_data();
    }

    // example of how to set kernel activation arguments
    // see ActivationFunctor::Arguments in activation.h for definition
    // if Arguments doesn't exist then fusion_args.activation is empty
    if constexpr (hute::is_same_v<ActivationFunctor,
                                  hytlass::epilogue::thread::ScaledGELU_taylor<
                                      ElementCompute>>) {
      fusion_args.activation.scale = ElementCompute(1);
    }

    // Treat Clamp as ReLU
    if constexpr (hute::is_same_v<
                      ActivationFunctor,
                      hytlass::epilogue::thread::Clamp<ElementCompute>>) {
      fusion_args.activation.lower_bound = 0;
      fusion_args.activation.upper_bound =
          std::numeric_limits<ElementCompute>::max();
    }

    if constexpr (IsAbsMaxEnabledD) {
      fusion_args.amax_D_ptr = abs_max_D.device_data();
    }

    if constexpr (IsAuxInEnabled) {
      fusion_args.aux_ptr = tensor_Aux.device_data();
      fusion_args.dAux = stride_Aux;
    }

    if constexpr (IsAuxOutEnabled) {
      fusion_args.aux_ptr = tensor_Aux.device_data();
      fusion_args.dAux = stride_Aux;
      if constexpr (IsScaleFactorEnabled) {
        fusion_args.scale_aux = scale_Aux.at(coord_0);
        fusion_args.scale_aux_ptr = scale_Aux.device_data();
      }
      if constexpr (IsAbsMaxEnabledAux) {
        fusion_args.amax_aux_ptr = abs_max_Aux.device_data();
      }
    }

    return arguments;
  }

  auto to_host_args(ProblemShapeType problem_size) {
    using namespace hute;
    //
    // Allocate the GEMM workspace
    //
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto M = hute::get<0>(problem_shape_MNKL);
    auto N = hute::get<1>(problem_shape_MNKL);
    auto K = hute::get<2>(problem_shape_MNKL);
    auto L = hute::get<3>(problem_shape_MNKL);
    auto coord_0 = hytlass::make_Coord(0);
    auto C = hute::make_tensor(detail::make_iterator(tensor_C.host_data()),
        hute::make_layout(hute::make_shape(M, N, L), stride_c));
    auto D = hute::make_tensor(detail::make_iterator(reference_D.host_data()),
        hute::make_layout(hute::make_shape(M, N, L), stride_d));
    auto Bias = hute::make_tensor(detail::make_iterator(IsDeBiasEnabled ? reference_dbias.host_data() : bias.host_data()),
        hute::make_layout(hute::make_shape(M, hute::_1{})));
    auto Aux = hute::make_tensor(detail::make_iterator(IsAuxInEnabled ? tensor_Aux.host_data() : reference_Aux.host_data()),
        hute::make_layout(hute::make_shape(M, N, L), stride_Aux));
    auto Valpha = hute::make_tensor(detail::make_iterator(alpha.host_data()),
        hute::make_layout(hute::make_shape(M, hute::_1{})));
    auto Vbeta = hute::make_tensor(detail::make_iterator(beta.host_data()),
        hute::make_layout(hute::make_shape(M, hute::_1{})));
    hytlass::reference::host::GettEpilogueParams<
      ElementScalar,
      ElementScalar,
      ElementAccumulator,
      ElementCompute,
      decltype(C),
      decltype(D),
      decltype(Bias),
      decltype(Aux),
      decltype(Valpha),
      decltype(Vbeta),
      ActivationFunctor
    > epilogue_params{};

    epilogue_params.C = C;
    epilogue_params.D = D;
    epilogue_params.alpha = alpha.at(coord_0);
    epilogue_params.beta = beta.at(coord_0);

    if constexpr (IsScaleFactorEnabled) {
      epilogue_params.scale_a = scale_A.at(coord_0);
      epilogue_params.scale_b = scale_B.at(coord_0);
      epilogue_params.scale_c = scale_C.at(coord_0);
      epilogue_params.scale_d = scale_D.at(coord_0);
    }

    if constexpr (IsBiasEnabled or IsDeBiasEnabled) {
      epilogue_params.Bias = Bias;
    }

    if constexpr (IsAbsMaxEnabledD) {
      epilogue_params.abs_max_D = reference_abs_max_D.host_data();
    }

    if constexpr (IsAuxInEnabled) {
      epilogue_params.Aux = Aux;
    }

    if constexpr (IsAuxOutEnabled) {
      epilogue_params.Aux = Aux;
      if constexpr (IsScaleFactorEnabled) {
        epilogue_params.scale_aux = scale_Aux.at(coord_0);
      }
      if constexpr (IsAbsMaxEnabledAux) {
        epilogue_params.abs_max_Aux = reference_abs_max_Aux.host_data();
      }
    }

    if constexpr (IsPerRowScaleEnabled) {
      epilogue_params.Valpha = Valpha;
      if (disable_vector_beta == VectorBeta::ENABLED) {
        epilogue_params.Vbeta = Vbeta;
      }
    }
    return epilogue_params;
  }
};

template <
  typename Gemm,
  template <class T> class ActivationFunctor_ = hytlass::epilogue::thread::Identity,
  bool force_legacy_epilogue = false,
  typename ElementA = typename Gemm::GemmKernel::ElementA,
  typename ElementB = typename Gemm::GemmKernel::ElementB
>
struct TestbedImpl {
  // Kernel data types
  using ScheduleType = typename Gemm::GemmKernel::CollectiveMainloop::DispatchPolicy::Schedule;
  // All Collective MMA operands are defined by HostCollectiveMainloopType based on the schedule type
  using HostCollectiveMainloopType = HostCollectiveMainloop<ScheduleType, Gemm, ElementA, ElementB>;
  using CollectiveEpilogue = hute::conditional_t<IsDefaultEpilogue<typename Gemm::GemmKernel::CollectiveEpilogue>::value || force_legacy_epilogue, 
                                                HostCollectiveDefaultEpilogue<Gemm>, 
                                                HostCollectiveEpilogue<Gemm>>;
  
  using ProblemShapeType = typename Gemm::GemmKernel::ProblemShape;
  using ElementAccumulator = typename Gemm::GemmKernel::ElementAccumulator;
  using ElementCompute = typename ElementComputeType<Gemm, ElementAccumulator>::Type;
  using ElementScalar = typename ElementScalarType<Gemm, ElementCompute>::Type;

  using LayoutTagA = typename HostCollectiveMainloopType::LayoutTagA;
  using LayoutTagB = typename HostCollectiveMainloopType::LayoutTagB;
  using LayoutTagC = typename CollectiveEpilogue::LayoutTagC;
  using LayoutTagD = typename CollectiveEpilogue::LayoutTagD;

  uint32_t sm_count;
  // Used to force multi-wave tests for persistent kernel schedules
  constexpr static int MaxSmCount = 16;
  static constexpr uint64_t kDefaultSeed = 4096;
  static constexpr uint32_t mma_promotion_interval = 4;
  using RasterOrderOptions = typename hytlass::gemm::kernel::detail::PersistentTileScheduler::RasterOrderOptions;

  HostCollectiveMainloopType collective_mma_inputs;
  CollectiveEpilogue collective_epilogue;

  //
  // Methods
  //

  TestbedImpl(
    CheckEquality check_relative_equality_ = CheckEquality::EXACT,
    ScalarLoc use_device_scalars_ = ScalarLoc::ON_HOST,
    VectorBeta disable_vector_beta_ = VectorBeta::DISABLED,
    hytlass::Distribution::Kind init_A_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_B_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_C_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_scale_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_bias_ = hytlass::Distribution::Uniform,
    uint64_t seed_ = kDefaultSeed
  ): collective_mma_inputs(HostCollectiveMainloopType(check_relative_equality_, init_A_, init_B_, seed_)), 
     collective_epilogue(CollectiveEpilogue(check_relative_equality_, use_device_scalars_, disable_vector_beta_, init_C_, init_scale_, init_bias_, seed_)) { }

  TestbedImpl(
    typename LayoutTagA::Stride stride_factor_A_,
    typename LayoutTagB::Stride stride_factor_B_,
    typename LayoutTagC::Stride stride_factor_C_,
    typename LayoutTagD::Stride stride_factor_D_,
    CheckEquality check_relative_equality_ = CheckEquality::EXACT,
    ScalarLoc use_device_scalars_ = ScalarLoc::ON_HOST,
    VectorBeta disable_vector_beta_ = VectorBeta::DISABLED,
    hytlass::Distribution::Kind init_A_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_B_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_C_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_scale_ = hytlass::Distribution::Uniform,
    hytlass::Distribution::Kind init_bias_ = hytlass::Distribution::Uniform,
    uint64_t seed_ = kDefaultSeed
  ): collective_mma_inputs(HostCollectiveMainloopType(check_relative_equality_, stride_factor_A_, stride_factor_B_, init_A_, init_B_, seed_)),
     collective_epilogue(CollectiveEpilogue(check_relative_equality_, use_device_scalars_, disable_vector_beta_, init_C_, init_scale_, init_bias_, seed_)) { }

  /// Initializes data structures
  bool initialize(ProblemShapeType problem_size, ElementScalar alpha_=1.f, ElementScalar beta_=0.f) {
    collective_mma_inputs.initialize(problem_size);
    collective_epilogue.initialize(problem_size, alpha_, beta_);

    return true;
  }

  /// Compares computed reference with device reference and outputs to a file if incorrect
  bool compare_reference(
      hute::Shape<int,int,int,int> problem_shape_MNKL,
      ElementScalar alpha,
      ElementScalar beta)
  {
    auto [M, N, K, L] = problem_shape_MNKL;

    bool passed = collective_mma_inputs.compare_reference(problem_shape_MNKL);
    passed &= collective_epilogue.compare_reference(problem_shape_MNKL, alpha, beta);
    EXPECT_TRUE(passed);
    if (!passed) {
      std::stringstream fname;
      fname << "error_Gemm_device_"
        << M << "x" << N << "x" << K << "x" << L << "_"
        << hute::get<0>(typename Gemm::GemmKernel::TileShape{}) << "_"
        << hute::get<1>(typename Gemm::GemmKernel::TileShape{}) << "_"
        << hute::get<2>(typename Gemm::GemmKernel::TileShape{}) << ".txt";

      std::ofstream file(fname.str());
      file
        << "problem: " << ' ' << M << "x" << N << "x" << K << ", Batch count = " << L
        << ", alpha: " << alpha << ", beta: " << beta << "\n\n";
      
      collective_mma_inputs.print_tensors(file);
      collective_epilogue.print_tensors(file);
    }

    return passed;
  }

  /// Verifies the result is a GEMM
  bool verify(
      ProblemShapeType problem_size,
      ElementScalar alpha,
      ElementScalar beta)
  {
    using namespace hute;
    auto problem_shape_MNKL = hute::append<4>(problem_size, 1);
    auto mainloop_params = collective_mma_inputs.to_host_args(problem_size);
    auto epilogue_params = collective_epilogue.to_host_args(problem_size);
    
    hytlass::reference::host::Gemm3x(mainloop_params, epilogue_params);

    bool passed = compare_reference(problem_shape_MNKL, alpha, beta);
    return passed;
  }

	/// Determine if the HIP device is sufficient to run the kernel
  bool sufficient() {
    //
    // Determine SMEM requirements and waive if not satisfied
    //

    size_t smem_size = static_cast<size_t>(Gemm::GemmKernel::SharedStorageSize);

    int device_idx;
    hipError_t result = hipGetDevice(&device_idx);

    if (result != hipSuccess) {
      throw std::runtime_error("hipGetDevice() API call failed.");
    }

    hipDeviceProp_t properties;
    result = hipGetDeviceProperties(&properties, device_idx);
    this->sm_count = properties.multiProcessorCount;

    if (result != hipSuccess) {
      throw std::runtime_error("hipGetDeviceProperties() failed");
    }

    if (properties.sharedMemPerBlock < smem_size) {
      printf("failed due to smem_size\n");
      printf("hardware smem_size: %d, required smem_size: %d\n\n", int(properties.sharedMemPerBlock), int(smem_size));
      return false;
    }

    return true;
  }

  bool profile(
    ProblemShapeType problem_size,
    int iterations,
    Gemm& gemm_op,
    typename Gemm::Arguments& arguments,
    hytlass::device_memory::allocation<uint8_t>& workspace) {
    int M = hute::size<0>(problem_size);
    int N = hute::size<1>(problem_size);
    int K = hute::size<2>(problem_size);
    int L = 1;
    if constexpr(hute::rank(ProblemShapeType{}) == 4) {
      L = hute::size<3>(problem_size);
    }


    hytlass::Status status;
    //
    // Run the GEMM
    //
    hipError_t result;

    for (int iter = 0; iter < iterations; ++iter) {
      status = gemm_op(arguments, workspace.get());
      if (status != hytlass::Status::kSuccess) {
        EXPECT_TRUE(status == hytlass::Status::kSuccess) << to_string(status);
        return false;
      }
    }

    result = hipDeviceSynchronize();
    if (result != hipSuccess) {
      EXPECT_EQ(result, hipSuccess) << "Error at Kernel Sync.";
      return false;
    }

    return true;
  }

  /// Executes one test
  bool run(
    ProblemShapeType problem_size,
    ElementScalar alpha = ElementScalar(1),
    ElementScalar beta = ElementScalar(0),
    bool profiling = false,
    detail::Iterations iterations = detail::Iterations{},
    detail::Splits splits = detail::Splits{}
    )
  {

    // Fail test if insufficient HIP device
    if (!sufficient()) {
      std::cout << "Test failed due to insufficient HIP device." << std::endl;
      return false;
    }

    if (!this->initialize(problem_size, alpha, beta)) {
      std::cerr << "Initialization failed \n";
      return false;
    }

    //
    // Initialize the GEMM operator
    //

    typename Gemm::Arguments arguments;
    hytlass::KernelHardwareInfo hw_info;
    hw_info.device_id = 0;
    if (not profiling) {
      this->sm_count = std::min(MaxSmCount, hytlass::KernelHardwareInfo::query_device_multiprocessor_count(hw_info.device_id));
      hw_info.sm_count = this->sm_count;
    }
    else {
      this->sm_count = hytlass::KernelHardwareInfo::query_device_multiprocessor_count(hw_info.device_id);
      hw_info.sm_count = this->sm_count;
    }

    typename Gemm::GemmKernel::TileScheduler::Arguments scheduler_args;
    if constexpr (hute::is_same_v<typename Gemm::GemmKernel::TileSchedulerTag, hytlass::gemm::StreamKScheduler>) {
      scheduler_args = { static_cast<int>(splits) };
    }
    typename HostCollectiveMainloopType::Arguments mainloop_args;

    mainloop_args = collective_mma_inputs.to_args();

    arguments =
    {
      hytlass::gemm::GemmUniversalMode::kGemm,
      problem_size,
      mainloop_args,
      collective_epilogue.to_args(problem_size),
      hw_info,
      scheduler_args
    };


    Gemm gemm_op;

    size_t workspace_size = Gemm::get_workspace_size(arguments);
    hytlass::device_memory::allocation<uint8_t> workspace(workspace_size);

    hytlass::Status status = gemm_op.can_implement(arguments);

    if (status != hytlass::Status::kSuccess) {
      hipError_t error = hipGetLastError();
      std::cerr << "This test is not supported: " << hipGetErrorString(error) << "\n";
      return true;
    }

    //
    // Run the GEMM
    //

    if (profiling) {
      return profile(problem_size, static_cast<int>(iterations), gemm_op, arguments, workspace);
    }
    else {
      hipError_t result;
      status = gemm_op.initialize(arguments, workspace.get());
      status = gemm_op.run();
      result = hipDeviceSynchronize();
      if (result != hipSuccess) {
        EXPECT_EQ(result, hipSuccess) << "Error at Kernel Sync.";
        return false;
      }

      EXPECT_TRUE(status == hytlass::Status::kSuccess) << to_string(status);

      //
      // Verify
      //
      bool passed = this->verify(problem_size, alpha, beta);
      if (!passed) {
        std::cout << "Error : Failed : with alpha: " << alpha << ", beta: " << beta
                  << "\n";
      }

      return passed;
    }
  }
};

} // namespace detail

/////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////////////////////

template <
  typename Gemm,
  template <class T> class ActivationFunctor = hytlass::epilogue::thread::Identity,
  bool force_legacy_epilogue = false,
  typename ElementA = typename Gemm::GemmKernel::ElementA,
  typename ElementB = typename Gemm::GemmKernel::ElementB
>
struct Testbed3x {

  using TestBedImpl = typename detail::TestbedImpl<
                        Gemm, 
                        ActivationFunctor, 
                        force_legacy_epilogue, 
                        ElementA, 
                        ElementB
                        >;
  using Kernel      = typename Gemm::GemmKernel;
  using Epilogue    = typename Gemm::GemmKernel::CollectiveEpilogue;

  using ElementAccumulator   = typename TestBedImpl::ElementAccumulator;
  using ElementCompute       = typename TestBedImpl::ElementCompute;
  using ElementScalar        = typename TestBedImpl::ElementScalar;

  using RasterOrderOptions = typename hytlass::gemm::kernel::detail::PersistentTileScheduler::RasterOrderOptions;

  // Detail Implementation
  TestBedImpl impl_;

  //
  // Methods
  //
  Testbed3x(
      CheckEquality check_relative_equality_ = CheckEquality::EXACT,
      ScalarLoc use_device_scalars_ = ScalarLoc::ON_DEVICE,
      VectorBeta disable_vector_beta_ = VectorBeta::DISABLED,
      hytlass::Distribution::Kind init_A_ = hytlass::Distribution::Uniform,
      hytlass::Distribution::Kind init_B_ = hytlass::Distribution::Uniform,
      hytlass::Distribution::Kind init_C_ = hytlass::Distribution::Uniform,
      hytlass::Distribution::Kind init_scale_ = hytlass::Distribution::Uniform,
      hytlass::Distribution::Kind init_bias_ = hytlass::Distribution::Uniform,
      uint64_t seed_ = TestBedImpl::kDefaultSeed)
      : impl_(check_relative_equality_, use_device_scalars_, disable_vector_beta_, init_A_, init_B_, init_C_, init_scale_, init_bias_, seed_) {}

  /// Executes one test
  bool run(
   typename TestBedImpl::ProblemShapeType problem_size,
    ElementScalar alpha = ElementScalar(1),
    ElementScalar beta = ElementScalar(0),
    detail::Splits splits = detail::Splits{},
    bool profiling = false,
    detail::Iterations iterations = detail::Iterations{}
    )
  {
    return impl_.run(
        problem_size, alpha, beta, profiling, iterations, splits
        );
  }
};

/////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Gemm>
bool TestGemmPerf3x(int iterations = 20) {
  using ProblemShapeType = typename Gemm::GemmKernel::ProblemShape;
  using ElementAccumulator = typename Gemm::GemmKernel::ElementAccumulator;
  using ElementScalar = ElementAccumulator;
  bool passed = true;
  using RasterOrderOptions = typename hytlass::gemm::kernel::detail::PersistentTileScheduler::RasterOrderOptions;

  std::vector<int> problem_size_m = { 4608 };
  std::vector<int> problem_size_n = { 4608 };
  std::vector<int> problem_size_k = { 8192 };

  Testbed3x<Gemm> testbed;

  for (int m : problem_size_m) {
    for (int n : problem_size_n) {
      for (int k : problem_size_k) {
        ProblemShapeType problem_size;
        if constexpr (hute::rank(ProblemShapeType{}) == 4) {
          problem_size = ProblemShapeType{m, n, k, /* l */ 1};
        }
        else {
          problem_size = ProblemShapeType{m, n, k};
        }

        passed = testbed.run(
          problem_size,
          hytlass::from_real<ElementScalar>(1),
          hytlass::from_real<ElementScalar>(0),
          detail::Splits{1},
          true, // profiling
          detail::Iterations{iterations});

        if (!passed) {
          return false;
        }
      }
    }
  }

  return true;
}

template <
  typename Gemm,
  template <class T> class ActivationFunctor = hytlass::epilogue::thread::Identity
>
bool TestAll(double alpha = 1.0, double beta = 0.0, CheckEquality check_relative_equality = CheckEquality::RELATIVE) {
  using ElementScalar = typename Gemm::EpilogueOutputOp::ElementScalar;
  using ProblemShapeType = typename Gemm::GemmKernel::ProblemShape;

  Testbed3x<Gemm, ActivationFunctor> testbed(check_relative_equality, ScalarLoc::ON_HOST, VectorBeta::DISABLED);

  int max_alignment = std::max(Gemm::kAlignmentA, Gemm::kAlignmentB);
  std::vector<int> problem_size_m = {max_alignment, 512 - 3 * max_alignment};
  std::vector<int> problem_size_n = {max_alignment, 512 - 2 * max_alignment};

  constexpr int Stages = Gemm::GemmKernel::DispatchPolicy::Stages;
  constexpr int TileShapeK = hute::size<2>(typename Gemm::GemmKernel::TileShape{});

  std::vector<int> problem_size_k = {max_alignment, TileShapeK * (Stages + 1) - max_alignment};

  std::vector problem_splits = {detail::Splits{1}};
  static constexpr bool UsesStreamKScheduler = hute::is_same_v<typename Gemm::GemmKernel::TileSchedulerTag, hytlass::gemm::StreamKScheduler>;
  if constexpr (UsesStreamKScheduler) {
    problem_splits.push_back(detail::Splits{2});
    problem_splits.push_back(detail::Splits{3});

    // Use larger K sizes for stream-K tests
    static constexpr int min_tiles_per_sk_unit = hytlass::gemm::kernel::detail::PersistentTileSchedulerStreamKParams::min_iters_per_sk_unit_;
    problem_size_k = {TileShapeK * min_tiles_per_sk_unit, TileShapeK * 3 * min_tiles_per_sk_unit - max_alignment};
  }

  using RasterOrderOptions = typename hytlass::gemm::kernel::detail::PersistentTileScheduler::RasterOrderOptions;

  bool passed = true;

  for (int m : problem_size_m) {
    for (int n : problem_size_n) {
      for (int k : problem_size_k) {
        std::vector problem_splits = {detail::Splits{1}};
        auto max_splits = (k + TileShapeK - 1) / TileShapeK;
        if (max_splits > 2) {
          problem_splits.push_back(detail::Splits{2});
        }
        if (max_splits > 3) {
          problem_splits.push_back(detail::Splits{3});
        }

        problem_splits.push_back(detail::Splits{max_splits});

        // Test the case in which we ask for more splits than there are K tiles
        // in the GEMM. In this case, split-K will fall back to a splitting
        // factor of `max_splits`.
        problem_splits.push_back(detail::Splits{max_splits + 1});
        for (auto splits : problem_splits) {
          ProblemShapeType problem_size;
          if constexpr (hute::rank(ProblemShapeType{}) == 4) {
            problem_size = ProblemShapeType{m, n, k, /* l */ 1};
          } else {
            problem_size = ProblemShapeType{m, n, k};
          }

          passed = testbed.run(
              problem_size, 
              hytlass::from_real<ElementScalar>(alpha),
              hytlass::from_real<ElementScalar>(beta),
              splits);

          if (!passed) {
            std::cout << __FILE__ << ':' << __LINE__ << " : GEMM MNK " << m
                      << " " << n << " " << k << " FAILED.\n";
            return false;
          }
        }  // splits
      }  // k
    }  // n
  }  // m

  // if we do support batched GEMM, just run one test on it to save on test time
  if constexpr (hute::rank(ProblemShapeType{}) == 4) {
    auto problem_size = ProblemShapeType{256 + max_alignment, 256 + max_alignment, 160 + max_alignment, /* l */ 3};
    passed = testbed.run(
      problem_size,
      hytlass::from_real<ElementScalar>(alpha),
      hytlass::from_real<ElementScalar>(beta)
    );

    if (!passed) {
      return false;
    }
  }

  return passed;
}

template <typename Gemm>
bool TestAllBiasElementwise(double alpha = 1.0, double beta = 0.0, CheckEquality check_relative_equality = CheckEquality::EXACT) {
  return TestAll<Gemm>(alpha, beta, check_relative_equality);
}

} // namespace device
} // namespace gemm
} // namespace test

/////////////////////////////////////////////////////////////////////////////////////////////////