-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathrocmlir-gen.cpp
2682 lines (2362 loc) · 98.6 KB
/
rocmlir-gen.cpp
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
//===- rocmlir-gen.cpp - MLIR Rock Test Generator ------------------------===//
//
// Part of the MLIR Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Main entry function for rocmlir-gen test generator.
//
//===----------------------------------------------------------------------===//
#include "mlir/Analysis/CallGraph.h"
#include "mlir/Conversion/RocMLIRPasses.h"
#include "mlir/Conversion/RockToGPU/RockToGPU.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Rock/Generator/AmdArchDb.h"
#include "mlir/Dialect/Rock/Generator/Conv2dGenerator.h"
#include "mlir/Dialect/Rock/IR/Rock.h"
#include "mlir/Dialect/Rock/IR/RockTypes.h"
#include "mlir/Dialect/Rock/Passes.h"
#include "mlir/Dialect/Rock/utility/builderUtils.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/ExecutionEngine/RocmDeviceName.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Block.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/IR/Types.h"
#include "mlir/IR/ValueRange.h"
#include "mlir/InitAllDialects.h"
#include "mlir/InitAllPasses.h"
#include "mlir/InitRocMLIRDialects.h"
#include "mlir/Parser/Parser.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/FileUtilities.h"
#include "mlir/Support/LogicalResult.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
#include "bf16convert.hpp"
#include <unordered_map>
#include <tuple>
using namespace mlir;
static llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional,
llvm::cl::desc("<input file>"),
llvm::cl::init(""));
static llvm::cl::opt<std::string>
outputFilename("o", llvm::cl::desc("Output filename"),
llvm::cl::value_desc("filename"), llvm::cl::init("-"));
static llvm::cl::opt<std::string>
testFuncName("func-under-test", llvm::cl::desc("Name of func to test"),
llvm::cl::init(""));
static llvm::cl::alias aliasTestFuncName("fut",
llvm::cl::aliasopt(testFuncName));
//////////////////////////////////////////////////////////////////////////////////////////////////////
//// Rock Convolution spec
static llvm::cl::opt<rock::KernelType> operation(
"operation", llvm::cl::desc("Convolution operation,"),
llvm::cl::values(
clEnumValN(rock::KernelType::Conv2D, "conv2d", "Forward convolution"),
clEnumValN(rock::KernelType::Conv2DBwdData, "conv2d_bwd_data",
"Backpropogate convolution data"),
clEnumValN(rock::KernelType::Conv2DBwdWeight, "conv2d_bwd_weight",
"Backpropogate convolution weights"),
clEnumValN(rock::KernelType::Gemm, "gemm", "Matrix multiplication")),
llvm::cl::value_desc("kernel type"),
llvm::cl::init(rock::KernelType::Conv2D));
static llvm::cl::opt<std::string> arch(
"arch",
llvm::cl::desc("amdgpu architecture, eg: gfx803, gfx900, gfx906, gfx908"),
llvm::cl::value_desc("GFX architecture string"), llvm::cl::init(""));
static llvm::cl::opt<int> num_cu(
"num_cu",
llvm::cl::desc("Number of compute units, valid combinations include: "
"gfx803(36/64), gfx900(56/64), "
"gfx906(60/64), gfx908(120)"),
llvm::cl::value_desc("compute unit value"), llvm::cl::init(64));
static llvm::cl::opt<std::string> perfConfig(
"perf_config", llvm::cl::desc("performance config data used for tuning"),
llvm::cl::value_desc("Serialized tuning parameters"), llvm::cl::init(""));
static llvm::cl::opt<std::string>
filterLayout("fil_layout", llvm::cl::desc("Filter layout"),
llvm::cl::value_desc("layout string"),
llvm::cl::init("gkcyx"));
static llvm::cl::opt<std::string>
inputLayout("in_layout", llvm::cl::desc("Input layout"),
llvm::cl::value_desc("layout string"), llvm::cl::init("ngchw"));
static llvm::cl::opt<std::string>
outputLayout("out_layout", llvm::cl::desc("Output layout"),
llvm::cl::value_desc("layout string"),
llvm::cl::init("ngkhw"));
static llvm::cl::opt<int64_t> groupSize("groupsize",
llvm::cl::desc("Group size"),
llvm::cl::value_desc("dimension value"),
llvm::cl::init(1));
static llvm::cl::alias groupSizeShort("g",
llvm::cl::desc("alias for -groupsize"),
llvm::cl::aliasopt(groupSize));
// N
static llvm::cl::opt<int64_t> batchSize("batchsize",
llvm::cl::desc("Batch size"),
llvm::cl::value_desc("dimension value"),
llvm::cl::init(-1));
// C
static llvm::cl::opt<int64_t>
inputChannel("in_channels", llvm::cl::desc("Input channels"),
llvm::cl::value_desc("dimension value"), llvm::cl::init(-1));
// Hi
static llvm::cl::opt<int64_t>
inputHeight("in_h", llvm::cl::desc("Input height"),
llvm::cl::value_desc("dimension value"), llvm::cl::init(-1));
// Wi
static llvm::cl::opt<int64_t>
inputWidth("in_w", llvm::cl::desc("Input width"),
llvm::cl::value_desc("dimension value"), llvm::cl::init(-1));
// K
static llvm::cl::opt<int64_t>
outputChannel("out_channels", llvm::cl::desc("Output channels"),
llvm::cl::value_desc("dimension value"), llvm::cl::init(-1));
// Y
static llvm::cl::opt<int64_t>
filterWidth("fil_w", llvm::cl::desc("Filter width"),
llvm::cl::value_desc("dimension value"), llvm::cl::init(-1));
// X
static llvm::cl::opt<int64_t>
filterHeight("fil_h", llvm::cl::desc("Filter height"),
llvm::cl::value_desc("dimension value"), llvm::cl::init(-1));
// Ho
static llvm::cl::opt<int64_t> outputHeight(
"out_h", llvm::cl::desc("Output height"),
llvm::cl::value_desc("ouput dimension value, does not need to set."),
llvm::cl::init(-1));
// Wo
static llvm::cl::opt<int64_t> outputWidth(
"out_w", llvm::cl::desc("Output width"),
llvm::cl::value_desc("ouput dimension value, does not need to set."),
llvm::cl::init(-1));
// dilation height
static llvm::cl::opt<int>
dilationHeight("dilation_h", llvm::cl::desc("Dilation height"),
llvm::cl::value_desc("attribute value"), llvm::cl::init(1));
// dilation width
static llvm::cl::opt<int> dilationWidth("dilation_w",
llvm::cl::desc("Dilation width"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(1));
// stride height
static llvm::cl::opt<int> strideHeight("conv_stride_h",
llvm::cl::desc("Stride height"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(1));
// stride width
static llvm::cl::opt<int> strideWidth("conv_stride_w",
llvm::cl::desc("Stride width"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(1));
// padding height
static llvm::cl::opt<int> paddingHeight("padding_h",
llvm::cl::desc("Padding height"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(0));
static llvm::cl::opt<int>
paddingHeightLeft("padding_h_l", llvm::cl::desc("Padding height Left"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(0));
static llvm::cl::opt<int>
paddingHeightRight("padding_h_r", llvm::cl::desc("Padding height Right"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(0));
// padding width
static llvm::cl::opt<int> paddingWidth("padding_w",
llvm::cl::desc("Padding width"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(0));
static llvm::cl::opt<int>
paddingWidthLeft("padding_w_l", llvm::cl::desc("Padding width Left"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(0));
static llvm::cl::opt<int>
paddingWidthRight("padding_w_r", llvm::cl::desc("Padding width Right"),
llvm::cl::value_desc("attribute value"),
llvm::cl::init(0));
/// Matrix options
static llvm::cl::opt<int64_t> gemmM("m",
llvm::cl::desc("M dimennsion of gemm()"),
llvm::cl::value_desc("positive integer"),
llvm::cl::init(-1));
static llvm::cl::opt<int64_t> gemmK("k",
llvm::cl::desc("K dimennsion of gemm()"),
llvm::cl::value_desc("positive integer"),
llvm::cl::init(-1));
static llvm::cl::opt<int64_t> gemmN("n",
llvm::cl::desc("N dimennsion of gemm()"),
llvm::cl::value_desc("positive integer"),
llvm::cl::init(-1));
static llvm::cl::opt<bool>
transposeA("transA",
llvm::cl::desc("whether matrix A is GxMxK (default) or GxKxM"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
transposeB("transB",
llvm::cl::desc("whether matrix B is GxKxN (default) or GxNxK"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
transposeC("transC",
llvm::cl::desc("whether matrix C is GxMxN (default) or GxNxM"),
llvm::cl::init(false));
static llvm::cl::opt<rock::StoreMethod> storeMethod(
"store-method", llvm::cl::desc("storage method for gemm"),
llvm::cl::values(
clEnumValN(rock::StoreMethod::Set, "set", "set results in C (default)"),
clEnumValN(rock::StoreMethod::AtomicAdd, "atomic_add",
"atomically add results to values in matrix C")),
llvm::cl::init(rock::StoreMethod::Set));
// A toggle to control whether a feature should be added to the feature list
enum class FeatureToggle : uint32_t { infer, on, off };
// use the toggle on each feature
// mfma
static llvm::cl::opt<FeatureToggle> mfmaFeature(
"mfma", llvm::cl::desc("toggle feature mfma"),
llvm::cl::values(clEnumValN(FeatureToggle::infer, "infer",
"use the default value provided by the chip"),
clEnumValN(FeatureToggle::on, "on",
"force mfma into the feature list"),
clEnumValN(FeatureToggle::off, "off",
"remove mfma from the feature list")),
llvm::cl::init(FeatureToggle::infer));
// dot
static llvm::cl::opt<FeatureToggle> dotFeature(
"dot", llvm::cl::desc("toggle feature dot"),
llvm::cl::values(clEnumValN(FeatureToggle::infer, "infer",
"use the default value provided by the chip"),
clEnumValN(FeatureToggle::on, "on",
"force dot into the feature list"),
clEnumValN(FeatureToggle::off, "off",
"remove dot from the feature list")),
llvm::cl::init(FeatureToggle::infer));
// atomicAdd
static llvm::cl::opt<FeatureToggle> atomicAddFeature(
"atomic_add", llvm::cl::desc("toggle feature atomic_add"),
llvm::cl::values(clEnumValN(FeatureToggle::infer, "infer",
"use the default value provided by the chip"),
clEnumValN(FeatureToggle::on, "on",
"force atomic_add into the feature list"),
clEnumValN(FeatureToggle::off, "off",
"remove atomic_add from the feature list")),
llvm::cl::init(FeatureToggle::infer));
// data type
static llvm::cl::opt<std::string>
tensorDataType("t", llvm::cl::desc("Data type for convolution"),
llvm::cl::value_desc("Data type for convolution"),
llvm::cl::init("f32"));
// conv-config
static llvm::cl::opt<std::string> populateConvConfig(
"conv-config",
llvm::cl::desc(
"Populate full config settings (overrides all specific settings)"),
llvm::cl::value_desc("config settings matching the C-API"),
llvm::cl::init(""));
// populate default values
static llvm::cl::opt<bool>
populateDefaultValues("p", llvm::cl::desc("To populate default values"),
llvm::cl::value_desc("To populate default values"),
llvm::cl::init(false));
//////////////////////////////////////////////////////////////////////////
//// Host Generator options
//////////////////////////////////////////////////////////////////////////
//// * Host harness
//// * kernel options
//// * cmd-line def (see above)
//// * gpu gen
//// * cpu gen
//// * user defined (input file)
//// * verifier
//// * cpu gen
//// * gpu gen
//// * compare results
//// * print results
//// * optionally print inputs
//// * optionally print validation results
//// * profiling (TBD)
//// * plumb thru runner (TBD)
//////////////////////////////////////////////////////////////////////////
// generate host harness program.
static llvm::cl::opt<bool>
readHostHarness("host", llvm::cl::desc("To use host harness"),
llvm::cl::value_desc("To use host harness"),
llvm::cl::init(false));
static llvm::cl::opt<bool>
genHostHarness("host-harness", llvm::cl::desc("To use host harness"),
llvm::cl::value_desc("To use host harness"),
llvm::cl::init(false));
static llvm::cl::alias aliasGenHostHarness("ph",
llvm::cl::aliasopt(genHostHarness));
// print results
static llvm::cl::opt<bool>
printResults("print-results", llvm::cl::desc("To print result tensor"),
llvm::cl::init(false));
static llvm::cl::alias aliasPrintResults("pr",
llvm::cl::aliasopt(printResults));
static llvm::cl::opt<bool> printInputs("print-inputs",
llvm::cl::desc("To print input tensors"),
llvm::cl::init(false));
static llvm::cl::alias aliasPrintInputs("pi", llvm::cl::aliasopt(printInputs));
static llvm::cl::opt<bool> printValidationResults(
"print-validation-results",
llvm::cl::desc("To print result tensor for validation"),
llvm::cl::init(false));
static llvm::cl::alias
aliasPrintValidationResults("pvr",
llvm::cl::aliasopt(printValidationResults));
// populate host validation logic.
static llvm::cl::opt<std::string> genValidation(
"verifier",
llvm::cl::desc(
"Select verification from: none(default), cpu, gpu, cpp, mlir, clone"),
llvm::cl::cb<void, std::string>([](const std::string &v) {
if (!v.empty())
genHostHarness = true;
}),
llvm::cl::value_desc("Specify host validation logic"), llvm::cl::init(""));
static llvm::cl::opt<bool>
genCPUValidation("pv", llvm::cl::Hidden, llvm::cl::init(false),
llvm::cl::Optional, llvm::cl::cb<void, bool>([](bool v) {
if (v) {
genValidation = "mlir";
genHostHarness = true;
}
}));
static llvm::cl::opt<bool>
genCPPValidation("pv_with_cpp", llvm::cl::Hidden, llvm::cl::init(false),
llvm::cl::Optional, llvm::cl::cb<void, bool>([](bool v) {
if (v) {
genValidation = "cpp";
genHostHarness = true;
}
}));
static llvm::cl::opt<bool>
genMLIRValidation("pv_with_mlir", llvm::cl::Hidden, llvm::cl::init(false),
llvm::cl::Optional, llvm::cl::cb<void, bool>([](bool v) {
if (v) {
genValidation = "mlir";
genHostHarness = true;
}
}));
static llvm::cl::opt<bool>
genGPUValidation("pv_with_gpu", llvm::cl::Hidden, llvm::cl::init(false),
llvm::cl::Optional, llvm::cl::cb<void, bool>([](bool v) {
if (v) {
genValidation = "gpu";
genHostHarness = true;
}
}));
static llvm::cl::opt<bool>
genCPUKernel("cpu-kernels", llvm::cl::desc("Generate CPU kernel for test"),
llvm::cl::init(false), llvm::cl::Optional,
llvm::cl::cb<void, bool>([](bool v) {
if (v) {
genValidation = "mlir";
genHostHarness = true;
printResults = true;
}
}));
static llvm::cl::alias aliasGenCPUKernel("prc",
llvm::cl::aliasopt(genCPUKernel));
// Input data spec
static llvm::cl::opt<std::string> randomSeed(
"rand",
llvm::cl::desc(
"A positive integer or zero indicates the seed of random data generator"
"for convolution inputs, e.g. -rand 1. If not specifed, or 'fixed', "
"use a fixed nonuniform test pattern. If 'none', use all 1s as the "
"values. If 0, use time(0) as the seed."),
llvm::cl::value_desc("seed"), llvm::cl::init("fixed"));
static llvm::cl::opt<std::string> randomDataType(
"rand_type",
llvm::cl::desc("To specify data type for random number generator,"
"e.g. -rand_type float, -rand_type int (default)."),
llvm::cl::value_desc("type"), llvm::cl::init("int"));
static llvm::cl::opt<std::string> randomSide(
"rand_side",
llvm::cl::desc(
"To populate random numbers to a specified tensor: "
"For conv2d, -rand_side filter or -rand_side input; "
"For conv2d_bwd_data, -rand_side filter or -rand_side output; "
"For conv2d_bwd_weight, -rand_side input or -rand_side output. "
"By default, populate random numbers to both tensors."),
llvm::cl::value_desc("tensor"), llvm::cl::init("both"));
// Verification function options
static llvm::cl::opt<float>
RMSThreshold("RMS_threshold", llvm::cl::desc("Threshold for RMS metric"),
llvm::cl::value_desc("error"), llvm::cl::init(0.00003f));
static llvm::cl::opt<float>
absDiffThreshold("absDiff_threshold",
llvm::cl::desc("Threshold for absDiff metric"),
llvm::cl::value_desc("error"), llvm::cl::init(100.0f));
static llvm::cl::opt<float>
relDiffThreshold("relDiff_threshold",
llvm::cl::desc("Threshold for relDiff metric"),
llvm::cl::value_desc("error"), llvm::cl::init(100.0f));
static llvm::cl::opt<std::string> printVerifyResults(
"print-verify-results",
llvm::cl::desc("Choose when to print verbose debug information in the "
"verification function:"
"always: print debug info"
"failure: print debug info if the test fails (default)"
"off: do not print debug info"),
llvm::cl::value_desc("info"), llvm::cl::init("failure"));
static llvm::cl::alias
aliasPrintVerifyResults("p_verify", llvm::cl::aliasopt(printVerifyResults));
static llvm::cl::opt<int> deviceNum(
"device",
llvm::cl::desc(
"Device index on which to run the kernel (only with host code)"),
llvm::cl::value_desc("Between 0 and number of GPUs on system. "
"Omission leaves current device intact."));
static llvm::cl::alias deviceShort("dev", llvm::cl::aliasopt(deviceNum));
static llvm::cl::opt<int> kernelRepeats(
"kernel-repeats",
llvm::cl::desc("Number of times to repeat the kernel invocation"),
llvm::cl::value_desc("positive integer"), llvm::cl::init(1));
////////////////////////////////////////////////////////////////////////////////
//// Struct KernelIF
//// - Detected/capture kernel interface
////////////////////////////////////////////////////////////////////////////////
struct KernelIF {
func::FuncOp func;
SmallVector<Type, 8> params;
// CTOR w/ FuncOp
KernelIF(func::FuncOp _f) : func(_f) {
assert(func.getNumResults() == 0);
for (auto ¶mType : func.getFunctionType().getInputs())
params.push_back(paramType);
}
};
struct GenParams {
llvm::Optional<rock::KernelType> operation = llvm::None;
Type dtype = nullptr;
rock::GemmFeatures features = rock::GemmFeatures::none;
llvm::Optional<const rock::Conv2dGenerator::Config *> convConfig = llvm::None;
};
namespace test {
void registerTestDialect(DialectRegistry &);
} // namespace test
static void correctConvParameters() {
std::string filterLayoutValue = filterLayout.getValue();
std::string inputLayoutValue = inputLayout.getValue();
std::string outputLayoutValue = outputLayout.getValue();
// yxcgk not implement yet
if (filterLayoutValue == "kcyx")
filterLayout = "gkcyx";
else if (filterLayoutValue == "kyxc")
filterLayout = "gkyxc";
else if (filterLayoutValue.size() == 4)
filterLayout = "g" + filterLayoutValue;
if (outputLayoutValue == "nkhw")
outputLayout = "ngkhw";
else if (outputLayoutValue == "nhwk")
outputLayout = "nhwgk";
else if (outputLayoutValue.size() == 4)
outputLayout = "g" + outputLayoutValue;
if (inputLayoutValue == "nchw")
inputLayout = "ngchw";
else if (inputLayoutValue == "nhwc")
inputLayout = "nhwgc";
else if (inputLayoutValue.size() == 4)
inputLayout = "g" + inputLayoutValue;
auto validatePadding = [](llvm::cl::opt<int> &combined,
llvm::cl::opt<int> &left, llvm::cl::opt<int> &right,
StringRef name) {
if (combined.getValue() > 0) {
int combinedVal = combined.getValue();
int leftVal = left.getValue();
int rightVal = right.getValue();
if (leftVal == 0 && rightVal == 0) {
left = combinedVal;
right = combinedVal;
} else {
if (leftVal != combinedVal || rightVal != combinedVal) {
llvm::errs() << "you can't use both " << name << " and (" << name
<< "_l," << name << "_r).\n";
}
}
}
};
validatePadding(paddingHeight, paddingHeightLeft, paddingHeightRight,
"padding_h");
validatePadding(paddingWidth, paddingWidthLeft, paddingWidthRight,
"padding_w");
// adjust the padding size
// getOutputDim can give us correct output size
// output size = input size+ padding size
// then -(filter size-1) * dilation size -1
// ,/ stride size and add 1
auto getOutputDim = [](int64_t inputLen, int64_t filLen, int leftPadLen,
int rightPadLen, int strideLen, int dilLen) {
return (inputLen + leftPadLen + rightPadLen - (filLen - 1) * dilLen - 1) /
strideLen +
1;
};
int hi = inputHeight.getValue();
int y = filterHeight.getValue();
int in_left_pad_h = paddingHeightLeft.getValue();
int in_right_pad_h = paddingHeightRight.getValue();
int conv_stride_h = strideHeight.getValue();
int conv_dilation_h = dilationHeight.getValue();
int ho = getOutputDim(hi, y, in_left_pad_h, in_right_pad_h, conv_stride_h,
conv_dilation_h);
int hi_minimum = 1 + (y - 1) * conv_dilation_h + (ho - 1) * conv_stride_h;
int hi_specified = hi + in_left_pad_h + in_right_pad_h;
// hi_minimum is the miminum number of input elements needed to correctly
// apply the filter in the h direction, which is a function of the stride and
// dilation parameters. If the specified input height is less than this value,
// add extra padding on the right to allow the convolution to execute
// successfully.
if (hi_minimum > hi_specified)
paddingHeightRight = in_right_pad_h + (hi_minimum - hi_specified);
int wi = inputWidth.getValue();
int x = filterWidth.getValue();
int in_left_pad_w = paddingWidthLeft.getValue();
int in_right_pad_w = paddingWidthRight.getValue();
int conv_stride_w = strideWidth.getValue();
int conv_dilation_w = dilationWidth.getValue();
int wo = getOutputDim(wi, x, in_left_pad_w, in_right_pad_w, conv_stride_w,
conv_dilation_w);
int wi_minimum = 1 + (x - 1) * conv_dilation_w + (wo - 1) * conv_stride_w;
int wi_specified = wi + in_left_pad_w + in_right_pad_w;
// wi_minimum is the miminum number of input elements needed to correctly
// apply the filter in the w direction, which is a function of the stride and
// dilation parameters. If the specified input height is less than this value,
// add extra padding on the right to allow the convolution to execute
// successfully.
if (wi_minimum > wi_specified)
paddingWidthRight = in_right_pad_w + (wi_minimum - wi_specified);
}
static void verifyConvLayout() {
std::string filterLayoutValue = filterLayout.getValue();
std::string inputLayoutValue = inputLayout.getValue();
if (filterLayoutValue.find("yx") == std::string::npos &&
filterLayoutValue.find("xy") == std::string::npos) {
llvm::errs() << "Unsupported filter layout: disjointed yx!\n";
exit(1);
}
if (inputLayoutValue.find("hw") == std::string::npos &&
inputLayoutValue.find("wh") == std::string::npos) {
llvm::errs() << "Unsupported input layout: disjointed hw!\n";
exit(1);
}
}
static void populateDefaults() {
bool isGemm = operation == rock::KernelType::Gemm;
if (populateDefaultValues) {
if (isGemm) {
gemmM = 1024;
gemmK = 769;
gemmN = 512;
groupSize = 1;
}
if (mfmaFeature != FeatureToggle::on) {
groupSize = 1;
batchSize = 128;
inputChannel = 8;
outputChannel = 128;
inputHeight = 32;
inputWidth = 32;
filterHeight = 3;
filterWidth = 3;
dilationHeight = 1;
dilationWidth = 1;
strideHeight = 1;
strideWidth = 1;
paddingHeightLeft = 0;
paddingHeightRight = 0;
paddingWidthLeft = 0;
paddingWidthRight = 0;
} else {
groupSize = 1;
batchSize = 128;
inputChannel = 1024;
outputChannel = 1024;
inputHeight = 14;
inputWidth = 14;
filterHeight = 1;
filterWidth = 1;
dilationHeight = 1;
dilationWidth = 1;
strideHeight = 1;
strideWidth = 1;
paddingHeightLeft = 0;
paddingHeightRight = 0;
paddingWidthLeft = 0;
paddingWidthRight = 0;
num_cu = 120;
}
}
if (!isGemm && outputHeight.getNumOccurrences() == 0) {
outputHeight = rock::Conv2dGenerator::outputDim(
inputHeight.getValue(), filterHeight.getValue(),
paddingHeightLeft.getValue(), paddingHeightRight.getValue(),
strideHeight.getValue(), dilationHeight.getValue());
}
if (!isGemm && outputWidth.getNumOccurrences() == 0) {
outputWidth = rock::Conv2dGenerator::outputDim(
inputWidth.getValue(), filterWidth.getValue(),
paddingWidthLeft.getValue(), paddingWidthRight.getValue(),
strideWidth.getValue(), dilationWidth.getValue());
}
}
static LogicalResult detectMissingArguments() {
const static std::vector<const llvm::cl::opt<int64_t> *> requiredConvArgs = {
&groupSize, &batchSize, &inputChannel, &inputHeight,
&inputWidth, &outputChannel, &filterWidth, &filterHeight};
const static std::vector<const llvm::cl::opt<int64_t> *> requiredGemmArgs = {
&groupSize, &gemmM, &gemmK, &gemmN};
for (auto *arg : ((operation == rock::KernelType::Gemm) ? requiredGemmArgs
: requiredConvArgs)) {
if (arg->getValue() <= 0) {
llvm::errs() << "Value for: " << arg->ArgStr << " not specified\n";
return failure();
}
}
return success();
}
static func::FuncOp makeFuncDecl(ModuleOp module, StringRef funcName,
TypeRange inputs, TypeRange results = {}) {
func::FuncOp func = module.lookupSymbol<func::FuncOp>(funcName);
if (!func) {
OpBuilder builder(module.getContext());
func = func::FuncOp::create(builder.getUnknownLoc(), funcName,
builder.getFunctionType(inputs, results));
func.setSymVisibilityAttr(builder.getStringAttr("private"));
module.push_back(func);
}
return func;
}
static Value makeNDMemRef(OpBuilder &b, Value var, uint32_t ndim) {
MLIRContext *context = b.getContext();
auto oprType = var.getType().template cast<ShapedType>();
if (!oprType.hasStaticShape())
return Value();
auto shape = oprType.getShape();
auto loc = var.getLoc();
if (shape.size() > ndim) {
// Collapse last dims
SmallVector<int64_t, 5> colShape;
SmallVector<ReassociationExprs, 5> reassocs;
uint32_t dim = 0;
for (; dim < ndim - 1; ++dim) {
colShape.push_back(shape[dim]);
reassocs.push_back({getAffineDimExpr(dim, context)});
}
// Last dim
uint64_t lastDim = 1;
SmallVector<AffineExpr, 2> exprs;
for (; dim < shape.size(); ++dim) {
lastDim *= shape[dim];
exprs.push_back(getAffineDimExpr(dim, context));
}
colShape.push_back(lastDim);
reassocs.push_back(exprs);
auto colType = MemRefType::get(colShape, oprType.getElementType());
// Emit memref.collapse_shape
var = b.create<memref::CollapseShapeOp>(loc, colType, var, reassocs);
} else if (shape.size() < ndim) {
// Expand last dims
SmallVector<int64_t, 5> expShape;
SmallVector<ReassociationExprs, 5> reassocs;
uint32_t dim = 0;
for (; dim < shape.size() - 1; ++dim) {
expShape.push_back(shape[dim]);
reassocs.push_back({getAffineDimExpr(dim, context)});
}
// Last dim
expShape.push_back(shape[dim]);
SmallVector<AffineExpr, 2> exprs;
for (; dim < ndim; ++dim) {
expShape.push_back(1);
exprs.push_back(getAffineDimExpr(dim, context));
}
expShape.pop_back();
reassocs.push_back(exprs);
auto expType = MemRefType::get(expShape, oprType.getElementType());
// Emit memref.collapse_shape
var = b.create<memref::ExpandShapeOp>(loc, expType, var, reassocs);
}
return var;
}
static func::FuncOp createGPUWrapper(ModuleOp module, const KernelIF &kernel) {
MLIRContext *context = module.getContext();
OpBuilder b(context);
auto loc = kernel.func->getLoc();
// Create gpu wrapper function
auto kfunc = kernel.func;
std::string funcName = kfunc.getName().str() + "_gpu";
auto gpuWrapperFuncType = b.getFunctionType(kernel.params, {});
auto gpuWrapperFunc =
func::FuncOp::create(loc, StringRef(funcName), gpuWrapperFuncType);
module.push_back(gpuWrapperFunc);
// Emit gpu convolution logic.
Block *block = gpuWrapperFunc.addEntryBlock();
b.setInsertionPoint(block, block->begin());
// Emit device selection
if (deviceNum.getNumOccurrences() > 0)
b.create<gpu::SetDefaultDeviceOp>(
loc, b.create<arith::ConstantIntOp>(loc, deviceNum.getValue(),
b.getIntegerType(32)));
SmallVector<Value, 4> cpuMem;
SmallVector<Value, 4> gpuMem;
for (auto pair : llvm::enumerate(kernel.params)) {
Value arg = block->getArgument(pair.index());
cpuMem.push_back(arg);
// Emit GPU memory allocation function calls.
auto gpuAllocOp = b.create<gpu::AllocOp>(
loc, arg.getType(), Type(), /*asyncDependencies=*/ValueRange{},
/*dynamicSizes=*/ValueRange{}, /*symbolOperands=*/ValueRange{});
Value gpuAlloc = gpuAllocOp.getResult(0);
gpuMem.push_back(gpuAlloc);
// Emit CPU->GPU memcpy function calls.
b.create<gpu::MemcpyOp>(loc, TypeRange{}, ValueRange{gpuAlloc, arg});
}
// Emit kernel function call, repeating it if needed.
// We assume that the repeated atomic add usages in a wrw kernel will not
// substantially impact performance as the result becomes large
auto emitWrappedCall = [&kernel, &gpuMem](OpBuilder &b, Location loc,
Value ignoredIv,
ValueRange noArgs) {
auto wrappedCall = b.create<func::CallOp>(loc, kernel.func, gpuMem);
wrappedCall->setAttr("wrapped_call", b.getUnitAttr());
if (ignoredIv) { // we're creating an actual loop
b.create<scf::YieldOp>(loc);
}
};
if (kernelRepeats > 1) {
Value zeroOp = b.createOrFold<arith::ConstantIndexOp>(loc, 0);
Value kernelRepeatsOp =
b.createOrFold<arith::ConstantIndexOp>(loc, kernelRepeats);
Value step = b.createOrFold<arith::ConstantIndexOp>(loc, 1);
b.create<scf::ForOp>(loc, zeroOp, kernelRepeatsOp, step,
/*args=*/llvm::None, emitWrappedCall);
} else {
emitWrappedCall(b, loc, nullptr, {});
}
for (auto &pair : llvm::enumerate(kernel.params)) {
uint32_t i = pair.index();
b.create<gpu::MemcpyOp>(loc, TypeRange{}, ValueRange{cpuMem[i], gpuMem[i]});
b.create<gpu::DeallocOp>(loc, TypeRange{}, ValueRange{gpuMem[i]});
}
b.create<func::ReturnOp>(loc, ValueRange{});
return gpuWrapperFunc;
}
// Map data type string to MLIR type
static Type typeFromString(StringRef name, MLIRContext *ctx) {
llvm::Optional<Type> result = llvm::StringSwitch<llvm::Optional<Type>>(name)
.Case("f32", Float32Type::get(ctx))
.Case("f16", Float16Type::get(ctx))
.Case("bf16", BFloat16Type::get(ctx))
.Case("i8", IntegerType::get(ctx, 8))
.Default(llvm::None);
if (!result) {
llvm::errs() << "Unknown data type: " << name << "\n";
exit(1);
}
return *result;
}
// Determine the range and seed for the random data generator
static int getRandomSeed() {
std::string rseed = randomSeed;
if (rseed[0] >= '0' and rseed[0] <= '9')
return std::stoi(rseed);
return -1;
}
static std::tuple<short, short> getRandomTestData(int idx) {
short min = 1, max = 1;
int32_t idx_spec = -1;
switch (randomSide.getValue()[0]) {
case 'f':
idx_spec = 0;
break;
case 'i':
idx_spec = 1;
break;
case 'o':
idx_spec = 2;
break;
case 'b':
default:
break;
}
if (randomSeed != "none" && randomSeed != "fixed") {
if ((idx_spec >= 0) && (idx_spec != idx)) {
} else if (randomDataType.getValue() == "int") {
// generate random integer in [-5, 5)
min = -5;
max = 5;
} else {
// generate random floats in [-1, 1)
min = -1;
max = 1;
}
}
return std::make_tuple(min, max);
}
llvm::SmallVector<float, 3> getTensorInitPattern(Type elemType) {
llvm::SmallVector<float, 3> pattern;
if (randomSeed == "none") {
float fixedVal = 1.0f;
if (randomDataType == "float")
// Clamp the fixed rondam float by 0.1 to avoid infs in some f16 tests
fixedVal *= 0.1f;
pattern = {static_cast<float>(fixedVal)};
} else if (randomSeed == "fixed") {
if (elemType.isIntOrIndex())
pattern = {1.0, -1.0, 2.0};
else
pattern = {0.5, -1, 0.75};
} else {
llvm_unreachable("We shouldn't be here for random values");
}
return pattern;
}
static LogicalResult populateTensorFillLogic(OpBuilder &b, Location loc,
ArrayRef<float> pattern,
Type elemType, Value toFill) {
// TODO(kdrewnia) Refactor this to create the constant vector up front
// TODO(kdrewnia) Factor out the anti-bf16 pass from GPU lowering, apply
// it here
Type i16 = b.getIntegerType(16);
Value constantsVec;
if (elemType == b.getBF16Type()) {
uint16_t init = 0;
constantsVec = b.create<arith::ConstantOp>(
loc,
SplatElementsAttr::get(VectorType::get(pattern.size(), i16), init));
} else {
constantsVec = rock::createZeroConstantOp(
b, loc, VectorType::get(pattern.size(), elemType));
}
for (auto v : llvm::enumerate(pattern)) {
Value vOp;
if (elemType == b.getBF16Type()) {
llvm::APFloat fl(v.value());
bool losesInfo = false;
fl.convert(llvm::APFloat::BFloat(), llvm::APFloat::rmNearestTiesToEven,
&losesInfo);
llvm::APInt val = fl.bitcastToAPInt();
vOp = b.create<arith::ConstantOp>(loc, b.getIntegerAttr(i16, val));
} else if (elemType.isIntOrIndex()) {
vOp = rock::createConstantIntOp(b, loc, elemType, elemType,
static_cast<int64_t>(v.value()));
} else {
vOp = rock::createConstantFloatOp(b, loc, elemType, elemType, v.value());
}
constantsVec = b.create<vector::InsertElementOp>(
loc, vOp, constantsVec,
b.create<arith::ConstantIndexOp>(loc, v.index()))
.getResult();
}