-
Notifications
You must be signed in to change notification settings - Fork 530
/
Copy pathDefaultDomainGtoP.cpp
3732 lines (3396 loc) · 170 KB
/
DefaultDomainGtoP.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
//===------------------------------------------------------------*- C++ -*-===//
//
// This file is licensed 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
// Also available under a BSD-style license. See LICENSE.
//
//===----------------------------------------------------------------------===//
#include "torch-mlir/Conversion/TorchOnnxToTorch/Patterns.h"
#include "torch-mlir/Conversion/TorchOnnxToTorch/Utils.h"
#include "torch-mlir/Dialect/Torch/Utils/Utils.h"
using namespace mlir;
using namespace mlir::torch;
using namespace mlir::torch::onnx_c;
// Simple rewrites for the default domain.
// See: https://onnx.ai/onnx/operators/
// For operators that are effectively version invariant, we register with
// sinceVersion==1. We interpret this to include the following spec
// diffs that are irrelevant to this level of lowering:
// * Supported element types.
// * Limited broadcasting to full broadcasting support.
//
// There are a lot of spec revisions that basically generalized elementwise
// to be more normal and a direct translation vs a special case. This
// results in a lot of ONNX test cases that all reduce to the exact same
// thing here, so we simplify.
void mlir::torch::onnx_c::populateDefaultDomainGtoP(
OnnxCustomOpConversionPattern &patterns) {
patterns.onOp(
"HardSigmoid", 6,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value tensorOperand;
float alpha, beta;
if (binder.tensorOperand(tensorOperand) ||
binder.f32FloatAttr(alpha, "alpha", 0.2f) ||
binder.f32FloatAttr(beta, "beta", 0.5f) ||
binder.tensorResultType(resultType))
return failure();
// HardSigmoid computes the following expression:
// max(0, min(1, alpha * x + beta))
Value constAlpha = rewriter.create<Torch::ConstantFloatOp>(
binder.getLoc(), rewriter.getType<Torch::FloatType>(),
rewriter.getF64FloatAttr(alpha));
Value constBeta = rewriter.create<Torch::ConstantFloatOp>(
binder.getLoc(), rewriter.getType<Torch::FloatType>(),
rewriter.getF64FloatAttr(beta));
// Expression: alpha * x + beta
Value alphaMulX = rewriter.create<Torch::AtenMulScalarOp>(
binder.getLoc(), resultType, tensorOperand, constAlpha);
Value constOne = rewriter.create<Torch::ConstantFloatOp>(
binder.getLoc(), rewriter.getType<Torch::FloatType>(),
rewriter.getF64FloatAttr(1.0));
Value alphaMulXPlusBeta = rewriter.create<Torch::AtenAddScalarOp>(
binder.getLoc(), resultType, alphaMulX, constBeta,
/*alpha=*/constOne);
// Expression: min(1, alpha * x + beta)
Value oneTensor =
createRank0Tensor(rewriter, binder.getLoc(), resultType, constOne);
Value minExpression = rewriter.create<Torch::AtenMinimumOp>(
binder.getLoc(), resultType, oneTensor, alphaMulXPlusBeta);
// Expression: max(0, min(1, alpha * x + beta))
Value constZero = rewriter.create<Torch::ConstantFloatOp>(
binder.getLoc(), rewriter.getF64FloatAttr(0.0));
Value zeroTensor =
createRank0Tensor(rewriter, binder.getLoc(), resultType, constZero);
rewriter.replaceOpWithNewOp<Torch::AtenMaximumOp>(
binder.op, resultType, zeroTensor, minExpression);
return success();
});
patterns.onOp(
"Gelu", 20, [](OpBinder binder, ConversionPatternRewriter &rewriter) {
Value operand;
Torch::ValueTensorType resultType;
std::string approximate;
if (binder.tensorOperand(operand) ||
binder.tensorResultType(resultType) ||
binder.customOpNameStringAttr(approximate, "approximate", "none"))
return failure();
Value vApproximate = rewriter.create<Torch::ConstantStrOp>(
binder.getLoc(), rewriter.getType<Torch::StringType>(),
rewriter.getStringAttr(approximate));
rewriter.replaceOpWithNewOp<Torch::AtenGeluOp>(binder.op, resultType,
operand, vApproximate);
return success();
});
patterns.onOp(
"GridSample", 17,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value input;
Value grid;
if (binder.tensorOperandAtIndex(input, 0) ||
binder.tensorOperandAtIndex(grid, 1) ||
binder.tensorResultType(resultType))
return rewriter.notifyMatchFailure(
binder.op, "operand grid_sampler bind failure");
auto inputTensorType = cast<Torch::ValueTensorType>(input.getType());
ArrayRef<int64_t> inputShape = inputTensorType.getSizes();
uint32_t inputRank = inputShape.size();
auto gridTensorType = cast<Torch::ValueTensorType>(grid.getType());
ArrayRef<int64_t> gridShape = gridTensorType.getSizes();
uint32_t gridRank = gridShape.size();
if (inputRank != 4)
return rewriter.notifyMatchFailure(binder.op,
"only input rank 4 supported");
if (gridRank != 4)
return rewriter.notifyMatchFailure(binder.op,
"only grid rank 4 supported");
if (inputShape[0] != gridShape[0])
return rewriter.notifyMatchFailure(
binder.op, "N must be same for input and grid");
if (gridShape[3] != 2)
return rewriter.notifyMatchFailure(binder.op,
"gridShape[3] expected to be 2");
std::string iModeString;
int64_t iModeInt;
if (binder.customOpNameStringAttr(iModeString, "mode", "linear"))
return rewriter.notifyMatchFailure(binder.op, "mode bind failure");
if (iModeString == "linear" || iModeString == "bilinear") {
iModeInt = 0;
} else if (iModeString == "nearest") {
iModeInt = 1;
} else {
return rewriter.notifyMatchFailure(
binder.op, "currently only mode : linear and nearest supported");
}
std::string padding;
if (binder.customOpNameStringAttr(padding, "padding_mode", "zeros"))
return rewriter.notifyMatchFailure(binder.op,
"padding_mode bind failure");
if (padding != "zeros")
return rewriter.notifyMatchFailure(
binder.op, "currently only padding_mode : zeros supported");
int64_t align;
if (binder.s64IntegerAttr(align, "align_corners", 0))
return rewriter.notifyMatchFailure(binder.op,
"align_corners bind failure");
Value interpolationMode = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
rewriter.getIntegerAttr(rewriter.getIntegerType(64), iModeInt));
Value paddingMode = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
rewriter.getIntegerAttr(rewriter.getIntegerType(64), 0));
bool alignMode = align;
Value alignCorners = rewriter.create<Torch::ConstantBoolOp>(
binder.getLoc(), rewriter.getType<Torch::BoolType>(),
rewriter.getBoolAttr(alignMode));
rewriter.replaceOpWithNewOp<Torch::AtenGridSamplerOp>(
binder.op, resultType, input, grid, interpolationMode, paddingMode,
alignCorners);
return success();
});
patterns.onOp("GRU", 1, onnx_c::OnnxGruExpander);
patterns.onOp(
"If", 1, [](OpBinder binder, ConversionPatternRewriter &rewriter) {
Value conditionTensor;
if (binder.tensorOperand(conditionTensor)) {
return rewriter.notifyMatchFailure(binder.op,
"condition bind failure");
}
auto conditionType =
cast<Torch::ValueTensorType>(conditionTensor.getType());
if (!conditionType || conditionType.getSizes().size() > 1)
return rewriter.notifyMatchFailure(
binder.op, "condition must have one single element per "
"https://onnx.ai/onnx/operators/onnx__If.html");
auto conditionInt = rewriter.create<Torch::AtenItemOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
conditionTensor);
auto conditionBool = rewriter.create<Torch::AtenBoolIntOp>(
binder.getLoc(), rewriter.getType<Torch::BoolType>(), conditionInt);
llvm::SmallVector<mlir::Type> resultTypes;
if (binder.tensorResultTypes(resultTypes)) {
return rewriter.notifyMatchFailure(binder.op,
"result type bind failure");
}
Region *thenRegion, *elseRegion;
if (binder.getRegionAtIndex(elseRegion, 0) ||
binder.getRegionAtIndex(thenRegion, 1)) {
return rewriter.notifyMatchFailure(binder.op, "region bind failure");
}
auto primIfOp = rewriter.create<Torch::PrimIfOp>(
binder.getLoc(), TypeRange(resultTypes), conditionBool);
auto inlineIfCase = [&](Region &srcRegion, Region &dstRegion) {
rewriter.inlineRegionBefore(srcRegion, dstRegion, dstRegion.begin());
};
inlineIfCase(*thenRegion, primIfOp.getThenRegion());
inlineIfCase(*elseRegion, primIfOp.getElseRegion());
auto replaceTerminator = [&](Region ®ion) -> LogicalResult {
PatternRewriter::InsertionGuard guard(rewriter);
Operation *terminator = region.front().getTerminator();
rewriter.setInsertionPoint(terminator);
// cast result shape if there is static/dynamic difference
llvm::SmallVector<Value> terOperands = terminator->getOperands();
if (terOperands.size() != resultTypes.size())
return failure();
for (size_t i = 0; i < terOperands.size(); i++) {
mlir::Type terType = terOperands[i].getType();
int64_t terOpRank =
dyn_cast<Torch::ValueTensorType>(terType).getSizes().size();
int64_t resRank = dyn_cast<Torch::ValueTensorType>(resultTypes[i])
.getSizes()
.size();
if (terOpRank != resRank)
return failure();
if (terType != resultTypes[i]) {
Value cast = rewriter.create<Torch::TensorStaticInfoCastOp>(
binder.getLoc(), resultTypes[i], terOperands[i]);
terOperands[i] = cast;
}
}
rewriter.replaceOpWithNewOp<Torch::PrimIfYieldOp>(terminator,
terOperands);
return success();
};
if (failed(replaceTerminator(primIfOp.getThenRegion())) ||
failed(replaceTerminator(primIfOp.getElseRegion())))
return rewriter.notifyMatchFailure(binder.op,
"terminator replace failure");
rewriter.replaceOp(binder.op, primIfOp.getResults());
return success();
});
patterns.onOp("Less", 13,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value lhs, rhs;
if (binder.tensorOperands(lhs, rhs) ||
binder.tensorResultType(resultType)) {
return failure();
}
rewriter.replaceOpWithNewOp<Torch::AtenLtTensorOp>(
binder.op, resultType, lhs, rhs);
return success();
});
patterns.onOp("LessOrEqual", 1,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value lhs, rhs;
if (binder.tensorOperands(lhs, rhs) ||
binder.tensorResultType(resultType)) {
return failure();
}
rewriter.replaceOpWithNewOp<Torch::AtenLeTensorOp>(
binder.op, resultType, lhs, rhs);
return success();
});
patterns.onOp("Log", 1,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value operand;
if (binder.tensorOperand(operand) ||
binder.tensorResultType(resultType)) {
return failure();
}
rewriter.replaceOpWithNewOp<Torch::AtenLogOp>(
binder.op, resultType, operand);
return success();
});
patterns.onOp(
"Loop", 13, [](OpBinder binder, ConversionPatternRewriter &rewriter) {
// Get all operands (maxTripCount, cond, ....inits....)
llvm::SmallVector<Value> operands;
if (binder.tensorOperandsList(operands) || operands.size() == 0 ||
binder.getNumOperands() < 2) {
return rewriter.notifyMatchFailure(binder.op,
"Failed to get required operands");
}
llvm::SmallVector<mlir::Type> operandTypeVec;
if (binder.tensorOperandTypes(operandTypeVec) ||
operandTypeVec.size() == 0) {
return rewriter.notifyMatchFailure(binder.op,
"Failed to get operandTypes");
}
Region *loopBodyIn;
if (binder.getRegionAtIndex(loopBodyIn, 0)) {
return rewriter.notifyMatchFailure(binder.op,
"Failed getting LoopBody Region");
}
// MaxTripCount - tensor int64 scalar (or empty)
Value maxTripCountTensor = operands[0];
auto maxTripCountInt = rewriter.create<Torch::AtenItemOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
maxTripCountTensor);
// Condition - tensor bool scalar (or empty)
Value conditionTensor = operands[1];
auto conditionInt = rewriter.create<Torch::AtenItemOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
conditionTensor);
auto conditionBool = rewriter.create<Torch::AtenBoolIntOp>(
binder.getLoc(), rewriter.getType<Torch::BoolType>(), conditionInt);
// To be used for "for like" loop case
auto constBoolTrue = rewriter.create<Torch::ConstantBoolOp>(
binder.getLoc(), rewriter.getBoolAttr(true));
// Others (if present) - variadic (can be tensors and scalar values)
if (binder.getNumOperands() > 2) {
operandTypeVec.erase(operandTypeVec.begin(),
operandTypeVec.begin() + 2);
operands.erase(operands.begin(), operands.begin() + 2);
}
auto getOpName = [](Operation *op) -> std::string {
std::string name = op->getName().getStringRef().str();
if (name != "torch.operator")
return name;
// for unconverted onnx ops
return mlir::dyn_cast<StringAttr>(op->getAttr("name"))
.getValue()
.str();
};
// PrimLoop Op expectes inputCondition to be boolConstantTrue
// to decide if the loopOp is `forlike`. Use loopIsForLike to
// ensure appropriate inputCondition is set
// Case 1 : loopCondInp -> identity -> terminator(loopCondOut)
bool loopIsForLike = false;
auto case1ForLike = [&getOpName](Region *loopBody) -> bool {
Value onnxLoopBodyCondIn = loopBody->front().getArgument(1);
if (!onnxLoopBodyCondIn.hasOneUse())
return false;
Operation *inpCondUser = *onnxLoopBodyCondIn.getUsers().begin();
if (getOpName(inpCondUser) != "onnx.Identity") {
return false;
}
if (!inpCondUser->hasOneUse() ||
getOpName(*(inpCondUser->getUsers().begin())) !=
"torch.operator_terminator")
return false;
return true;
};
loopIsForLike = case1ForLike(loopBodyIn);
Value loopInitCondition =
loopIsForLike ? constBoolTrue : conditionBool.getResult();
auto loc = binder.getLoc();
mlir::ImplicitLocOpBuilder b(loc, rewriter);
auto loop = b.create<Torch::PrimLoopOp>(
TypeRange(operandTypeVec), maxTripCountInt, loopInitCondition,
ValueRange(operands));
rewriter.cloneRegionBefore(*loopBodyIn, loop.getRegion(),
loop.getRegion().begin());
// primLoopOp loopBody expects torch.int as first arg
// insert torch.int arg in loop body, convert to tensor,
// replace all uses of old arg, delete old arg.
auto loopVarArg = loop.getRegion().front().getArgument(0);
// insert new Arg
loop.getRegion().front().insertArgument(
0U, rewriter.getType<Torch::IntType>(), binder.getLoc());
auto newLoopVarArg = loop.getRegion().front().getArgument(0);
// convert int arg to tensor of original Type
rewriter.setInsertionPointToStart(&loop.getRegion().front());
Value loopVarVal = BlockArgument::Value(loopVarArg);
auto newTensor = rewriter.create<Torch::PrimNumToTensorScalarOp>(
loop.getRegion().op_begin()->getLoc(), loopVarVal.getType(),
newLoopVarArg);
loopVarArg.replaceAllUsesWith(newTensor);
loop.getRegion().eraseArgument(1);
// primLoopOp loopBody has no condition arg
auto condArg = loop.getRegion().front().getArgument(1);
if (!condArg.use_empty())
condArg.replaceAllUsesWith(conditionTensor);
// replace terminator
PatternRewriter::InsertionGuard guard(rewriter);
Operation *terminator = loop.getRegion().front().getTerminator();
rewriter.setInsertionPoint(terminator);
// results - n loop carried dependencies and k scan outputs
// Fail when there are scanOutputs in onnxLoop (K>0);
// unsupported for now
if (terminator->getNumOperands() !=
loop.getRegion().getNumArguments() - 1) {
return rewriter.notifyMatchFailure(
binder.op, "scanOutputs in loop body unsupported");
}
// Get remaining operands from onnxLoopBody's terminator Op
// these are all the loop carried dependencies in the loop body
auto terminatorOperands = terminator->getOperands();
llvm::SmallVector<Value> remTerminatorOperands(
terminatorOperands.begin() + 1, terminatorOperands.end());
Value terminatorCond;
if (loopIsForLike) {
terminatorCond = constBoolTrue;
} else {
// Only use when loop is not forlike
Value terminatorCondTensor = terminatorOperands[0];
auto terminatorCondInt = rewriter.create<Torch::AtenItemOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
terminatorCondTensor);
auto terminatorCondBool = rewriter.create<Torch::AtenBoolIntOp>(
binder.getLoc(), rewriter.getType<Torch::BoolType>(),
terminatorCondInt);
terminatorCond = terminatorCondBool.getResult();
}
rewriter.replaceOpWithNewOp<Torch::PrimLoopConditionOp>(
terminator, terminatorCond, remTerminatorOperands);
loop.getRegion().eraseArgument(1);
rewriter.replaceOp(binder.op, loop);
return success();
});
patterns.onOp("LSTM", 1, onnx_c::OnnxLstmExpander);
patterns.onOp(
"LogSoftmax", 13,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Value input;
Torch::ValueTensorType resultType;
if (binder.tensorOperand(input) || binder.tensorResultType(resultType))
return failure();
int64_t axis;
if (binder.s64IntegerAttr(axis, "axis", -1))
return rewriter.notifyMatchFailure(binder.op, "axis bind failure");
Value axisConst = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getI64IntegerAttr(axis));
Value none = rewriter.create<Torch::ConstantNoneOp>(binder.getLoc());
rewriter.replaceOpWithNewOp<Torch::AtenLogSoftmaxIntOp>(
binder.op, resultType, input, axisConst, none);
return success();
});
patterns.onOp(
"LogSoftmax", 1,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Value input;
Torch::ValueTensorType resultType;
if (binder.tensorOperand(input) || binder.tensorResultType(resultType))
return failure();
int64_t axis;
if (binder.s64IntegerAttr(axis, "axis", 1))
return rewriter.notifyMatchFailure(binder.op, "axis bind failure");
std::optional<unsigned> maybeRank = Torch::getTensorRank(input);
if (!maybeRank)
return rewriter.notifyMatchFailure(binder.op,
"Unsupported: unranked tensor");
int64_t rank = *maybeRank;
// if negative axis is provided, then flip it to a positive axis
if (axis < 0) {
axis = rank + axis;
}
// need input type and sizes to flatten/unflatten later.
auto inputTy = cast<Torch::ValueTensorType>(input.getType());
if (!inputTy || !inputTy.hasSizes())
return rewriter.notifyMatchFailure(
binder.op, "failed to get input type or sizes");
Value axisConst = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getI64IntegerAttr(axis));
Value none = rewriter.create<Torch::ConstantNoneOp>(binder.getLoc());
Value cstEnd = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getI64IntegerAttr(rank - 1));
// The old version of LogSoftmax flattens post-axis dims, performs
// LogSoftmax on the flattened dim, then unflattens back to the original
// shape.
// this section gets some size information necessary for
// flattening/unflattening
if (!inputTy || !inputTy.hasSizes())
return failure();
llvm::ArrayRef<int64_t> allDims(inputTy.getSizes());
llvm::ArrayRef<int64_t> rightDims(allDims.begin() + axis,
allDims.end());
llvm::SmallVector<int64_t> leftDims(allDims.begin(),
allDims.begin() + axis);
int64_t prodRightSizes = 1;
llvm::SmallVector<Value> rightDimConsts;
for (int64_t n : rightDims) {
rightDimConsts.push_back(rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getI64IntegerAttr(n)));
if (n == Torch::kUnknownSize) {
prodRightSizes = -1;
break;
}
prodRightSizes *= n;
}
leftDims.push_back(prodRightSizes);
// the following list will be used to unflatten the right side
Value rightDimsPrimList = rewriter.create<Torch::PrimListConstructOp>(
binder.getLoc(),
rewriter.getType<Torch::ListType>(
rewriter.getType<Torch::IntType>()),
rightDimConsts);
auto flatRightTy = rewriter.getType<Torch::ValueTensorType>(
leftDims, inputTy.getOptionalDtype());
// flatten input
Value inputFlatRight = rewriter.create<Torch::AtenFlattenUsingIntsOp>(
binder.getLoc(), flatRightTy, input, axisConst, cstEnd);
// compute lsm over flattened index
Value outputFlatRight = rewriter.create<Torch::AtenLogSoftmaxIntOp>(
binder.getLoc(), flatRightTy, inputFlatRight, axisConst, none);
// unflatten
rewriter.replaceOpWithNewOp<Torch::AtenUnflattenIntOp>(
binder.op, resultType, outputFlatRight, axisConst,
rightDimsPrimList);
return success();
});
patterns.onOp("MatMul", 1,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value lhs, rhs;
if (binder.tensorOperands(lhs, rhs) ||
binder.tensorResultType(resultType))
return failure();
rewriter.replaceOpWithNewOp<Torch::AtenMatmulOp>(
binder.op, resultType, lhs, rhs);
return success();
});
patterns.onOp(
"MatMulInteger", 10,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value lhs, rhs, lhsZp, rhsZp;
if (binder.tensorOperandAtIndex(lhs, 0) ||
binder.tensorOperandAtIndex(rhs, 1) ||
binder.tensorResultType(resultType))
return failure();
auto lhsTy = dyn_cast<Torch::ValueTensorType>(lhs.getType());
auto rhsTy = dyn_cast<Torch::ValueTensorType>(rhs.getType());
if (binder.tensorOperandAtIndex(lhsZp, 2)) {
lhsZp = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
rewriter.getIntegerAttr(rewriter.getIntegerType(64), 0));
}
if (binder.tensorOperandAtIndex(rhsZp, 3)) {
rhsZp = rewriter.create<Torch::ConstantIntOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(),
rewriter.getIntegerAttr(rewriter.getIntegerType(64), 0));
}
if (auto zpTy = dyn_cast<Torch::ValueTensorType>(lhsZp.getType())) {
for (auto dim : zpTy.getSizes())
if (dim != 1)
return failure();
lhsZp = rewriter.create<Torch::AtenItemOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(), lhsZp);
}
if (auto zpTy = dyn_cast<Torch::ValueTensorType>(rhsZp.getType())) {
for (auto dim : zpTy.getSizes())
if (dim != 1)
return failure();
rhsZp = rewriter.create<Torch::AtenItemOp>(
binder.getLoc(), rewriter.getType<Torch::IntType>(), rhsZp);
}
Value scale = rewriter.create<Torch::ConstantFloatOp>(
binder.getLoc(), rewriter.getType<Torch::FloatType>(),
rewriter.getF64FloatAttr(1.0));
auto lhsQTy = getQTorchTypeFromTorchIntType(lhsTy);
auto rhsQTy = getQTorchTypeFromTorchIntType(rhsTy);
if (!lhsQTy || !rhsQTy)
return rewriter.notifyMatchFailure(binder.op, "failed to get qtype");
lhs = rewriter.create<Torch::Aten_MakePerTensorQuantizedTensorOp>(
binder.getLoc(), lhsQTy, lhs, scale, lhsZp);
rhs = rewriter.create<Torch::Aten_MakePerTensorQuantizedTensorOp>(
binder.getLoc(), rhsQTy, rhs, scale, rhsZp);
rewriter.replaceOpWithNewOp<Torch::AtenMatmulOp>(binder.op, resultType,
lhs, rhs);
return success();
});
patterns.onOp("Mul", 7,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value lhs, rhs;
if (binder.tensorOperands(lhs, rhs) ||
binder.tensorResultType(resultType)) {
return failure();
}
rewriter.replaceOpWithNewOp<Torch::AtenMulTensorOp>(
binder.op, resultType, lhs, rhs);
return success();
});
patterns.onOp(
"MelWeightMatrix", 17,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
llvm::SmallVector<Value> operands;
Torch::ValueTensorType resultType;
int64_t output_dtype_attr;
if (binder.tensorOperands(operands, 5) ||
binder.tensorResultType(resultType) || operands.size() != 5 ||
binder.s64IntegerAttr(output_dtype_attr, "output_datatype", 1)) {
return failure();
}
// operands sequence :
// num_mel_bins, dft_length, sample_rate -> int32/64 tensors
// lower_edge_hertz, upper_edge_hertz -> f16/32/64
// Need to backtrack the values of num_mel_bins and dft_length//2+1 from
// result shape since the inputs are tensors and we cannot know their
// values at compile time. if the result type does not contain static
// shapes, then the implementation will be unsupported.
if (!resultType.areAllSizesKnown())
return rewriter.notifyMatchFailure(
binder.op, "Unknown result sizes, not supported.");
ArrayRef<int64_t> resShape = resultType.getSizes();
if (resShape.size() != 2)
return rewriter.notifyMatchFailure(
binder.op,
"Expected result rank to be 2, not supported for other ranks.");
std::optional<int64_t> torchDTypeInt =
onnxDtypeIntToTorchDtypeInt(output_dtype_attr);
if (!torchDTypeInt.has_value()) {
return rewriter.notifyMatchFailure(
binder.op, "conversion to given output dtype unsupported");
}
// Here Onwards all shapes will be computed using these sizes
int64_t numSpectrogramBinsInt = resShape[0];
int64_t numMelBinsInt = resShape[1];
Torch::ValueTensorType inputIntType = binder.toValidTensorType(
operands[0].getType()); // Since operands[0 / 1 / 2] will have the
// same int type.
Torch::ValueTensorType inputFloatType = binder.toValidTensorType(
operands[3].getType()); // Since operands[3 / 4] will have the same
// float type
Value numMelBinsItem =
getItemOp<Torch::IntType>(binder, rewriter, operands[0]);
Value sampleRateItem =
getItemOp<Torch::IntType>(binder, rewriter, operands[2]);
Value lowerEdgeHzItem =
getItemOp<Torch::FloatType>(binder, rewriter, operands[3]);
Value upperEdgeHzItem =
getItemOp<Torch::FloatType>(binder, rewriter, operands[4]);
// Helpers
ImplicitLocOpBuilder b(binder.getLoc(), rewriter);
auto ctx = binder.op->getContext();
// Recurring shapes
SmallVector<int64_t> unranked({});
SmallVector<int64_t> shapeNMB({numMelBinsInt});
SmallVector<int64_t> shape1xNMB({1, numMelBinsInt});
SmallVector<int64_t> shapeNSB({numSpectrogramBinsInt});
SmallVector<int64_t> shapeNSBx1({numSpectrogramBinsInt, 1});
SmallVector<int64_t> shapeNSBxNMB(
{numSpectrogramBinsInt, numMelBinsInt});
// Recurring DTypes
Type inpFpDType = inputFloatType.getDtype();
Type inpIntDType = inputIntType.getDtype();
Type si32Ty = rewriter.getIntegerType(32, true);
Type f32Ty = rewriter.getF32Type();
Type i1Ty = rewriter.getI1Type();
// Value constants
Value noneConst = b.create<Torch::ConstantNoneOp>();
Value zeroConst =
b.create<Torch::ConstantIntOp>(rewriter.getI64IntegerAttr(0));
Value oneConst =
b.create<Torch::ConstantIntOp>(rewriter.getI64IntegerAttr(1));
Value twoConst =
b.create<Torch::ConstantIntOp>(rewriter.getI64IntegerAttr(2));
Value int32DTypeConst =
b.create<Torch::ConstantIntOp>(rewriter.getI64IntegerAttr(3));
Value float32DTypeConst =
b.create<Torch::ConstantIntOp>(rewriter.getI64IntegerAttr(6));
Torch::ValueTensorType dftLenType =
Torch::ValueTensorType::get(ctx, unranked, inpIntDType);
Type freqBinsIntType =
Torch::ValueTensorType::get(ctx, shapeNMB, si32Ty);
Type freqBinsFltType =
Torch::ValueTensorType::get(ctx, shapeNMB, f32Ty);
Value dftLengthDivTwoTensor = b.create<Torch::AtenFloorDivideScalarOp>(
dftLenType, operands[1], twoConst);
Value numSpectrogramBinsTensor = b.create<Torch::AtenAddScalarOp>(
dftLenType, dftLengthDivTwoTensor, oneConst, /*alpha =*/oneConst);
Value numSpectrogramBinsItem = getItemOp<Torch::IntType>(
binder, rewriter, numSpectrogramBinsTensor);
// From Ref Impl of Onnx.MelWeightMatrix:
// https://github.com/onnx/onnx/blob/main/onnx/reference/ops/op_mel_weight_matrix.py#L25-L32
// convert input Freq Hz to Mel
Value twoFiveNineFiveConst =
b.create<Torch::ConstantFloatOp>(rewriter.getF64FloatAttr(2595));
Value sevenHConst =
b.create<Torch::ConstantFloatOp>(rewriter.getF64FloatAttr(700));
Value tenConst =
b.create<Torch::ConstantFloatOp>(rewriter.getF64FloatAttr(10));
Value oneFltConst =
b.create<Torch::ConstantFloatOp>(rewriter.getF64FloatAttr(1));
Value LnToLog10Const = b.create<Torch::ConstantFloatOp>(
rewriter.getF64FloatAttr(M_LOG10E));
Value lfDiv7Hfloat =
b.create<Torch::AtenDivFloatOp>(lowerEdgeHzItem, sevenHConst);
Type freqType = Torch::ValueTensorType::get(ctx, unranked, inpFpDType);
Value lfDiv7H =
b.create<Torch::PrimNumToTensorScalarOp>(freqType, lfDiv7Hfloat);
Value lfDiv7HAdd1 = b.create<Torch::AtenAddScalarOp>(
freqType, lfDiv7H, oneConst, /*alpha =*/oneConst);
Value lfDiv7HAdd1Ln = b.create<Torch::AtenLogOp>(freqType, lfDiv7HAdd1);
Value lfDiv7HAdd1Log10 = b.create<Torch::AtenMulScalarOp>(
freqType, lfDiv7HAdd1Ln, LnToLog10Const);
Value lfMel = b.create<Torch::AtenMulScalarOp>(
freqType, lfDiv7HAdd1Log10, twoFiveNineFiveConst);
Value hfDiv7Hfloat =
b.create<Torch::AtenDivFloatOp>(upperEdgeHzItem, sevenHConst);
Value hfDiv7H =
b.create<Torch::PrimNumToTensorScalarOp>(freqType, hfDiv7Hfloat);
Value hfDiv7HAdd1 = b.create<Torch::AtenAddScalarOp>(
freqType, hfDiv7H, oneConst, /*alpha =*/oneConst);
Value hfDiv7HAdd1Ln = b.create<Torch::AtenLogOp>(freqType, hfDiv7HAdd1);
Value hfDiv7HAdd1Log10 = b.create<Torch::AtenMulScalarOp>(
freqType, hfDiv7HAdd1Ln, LnToLog10Const);
Value hfMel = b.create<Torch::AtenMulScalarOp>(
freqType, hfDiv7HAdd1Log10, twoFiveNineFiveConst);
Value hfSubLf = b.create<Torch::AtenSubTensorOp>(
hfMel.getType(), hfMel, lfMel, /*alpha=*/oneConst);
Value numMelBinsPlus2 =
b.create<Torch::AtenAddIntOp>(numMelBinsItem, twoConst);
Value melStep = b.create<Torch::AtenDivScalarOp>(
hfSubLf.getType(), hfSubLf, numMelBinsPlus2);
Value lowBinsInit = b.create<Torch::AtenArangeOp>(
freqBinsIntType, numMelBinsItem, /*dtype=*/int32DTypeConst,
/*layout=*/noneConst, /*device=*/noneConst,
/*pin_memory=*/noneConst);
Value centerBinsInit = b.create<Torch::AtenArangeOp>(
freqBinsIntType, numMelBinsItem, /*dtype=*/int32DTypeConst,
/*layout=*/noneConst, /*device=*/noneConst,
/*pin_memory=*/noneConst);
Value highBinsInit = b.create<Torch::AtenArangeOp>(
freqBinsIntType, numMelBinsItem, /*dtype=*/int32DTypeConst,
/*layout=*/noneConst, /*device=*/noneConst,
/*pin_memory=*/noneConst);
// Common values used in conversion
Value dftLenPlusOne = b.create<Torch::AtenAddScalarOp>(
dftLenType, operands[1], oneConst, /*alpha=*/oneConst);
Value dftLenPlusOneItem =
getItemOp<Torch::IntType>(binder, rewriter, dftLenPlusOne);
Value falseConst = b.create<Torch::ConstantBoolOp>(false);
Torch::ValueTensorType unsqueezeBinsResType =
Torch::ValueTensorType::get(ctx, shape1xNMB, si32Ty);
// Low bins Mel to hz
Value lowBinsMulMelStep = b.create<Torch::AtenMulTensorOp>(
freqBinsFltType, lowBinsInit, melStep);
Value lowBinsScaled = b.create<Torch::AtenAddTensorOp>(
freqBinsFltType, lowBinsMulMelStep, lfMel, /*alpha=*/oneConst);
Value lbDiv = b.create<Torch::AtenDivScalarOp>(
freqBinsFltType, lowBinsScaled, twoFiveNineFiveConst);
Value lbClone = b.create<Torch::AtenCloneOp>(
freqBinsFltType, lowBinsScaled, /*memory_format=*/noneConst);
Value lbTenTensor = b.create<Torch::AtenFillScalarOp>(
freqBinsFltType, lbClone, tenConst);
Value lbPow = b.create<Torch::AtenPowTensorTensorOp>(
freqBinsFltType, lbTenTensor, lbDiv);
Value lbPowSubOne = b.create<Torch::AtenSubScalarOp>(
freqBinsFltType, lbPow, oneConst, /*alpha=*/oneConst);
Value lowBinsHz = b.create<Torch::AtenMulScalarOp>(
freqBinsFltType, lbPowSubOne, sevenHConst);
// Normalize freqBinsHz
Value lbMulDft = b.create<Torch::AtenMulScalarOp>(
freqBinsFltType, lowBinsHz, dftLenPlusOneItem);
Value lowBinsNormalized = b.create<Torch::AtenDivScalarOp>(
freqBinsFltType, lbMulDft, sampleRateItem);
// cast to int32
Value lowBinsInt = b.create<Torch::AtenToDtypeOp>(
freqBinsIntType, lowBinsNormalized, /*dtype=*/int32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Value lowBins = b.create<Torch::AtenUnsqueezeOp>(
unsqueezeBinsResType, lowBinsInt, /*dim=*/zeroConst);
// Center bins mel to hz
Value centerBinsInitInc = b.create<Torch::AtenAddScalarOp>(
freqBinsIntType, centerBinsInit, oneConst, /*alpha=*/oneConst);
Value centerBinsMulMelStep = b.create<Torch::AtenMulTensorOp>(
freqBinsFltType, centerBinsInitInc, melStep);
Value centerBinsScaled = b.create<Torch::AtenAddTensorOp>(
freqBinsFltType, centerBinsMulMelStep, lfMel, /*alpha=*/oneConst);
Value cbDiv = b.create<Torch::AtenDivScalarOp>(
freqBinsFltType, centerBinsScaled, twoFiveNineFiveConst);
Value cbClone = b.create<Torch::AtenCloneOp>(
freqBinsFltType, centerBinsScaled, /*memory_format=*/noneConst);
Value cbTenTensor = b.create<Torch::AtenFillScalarOp>(
freqBinsFltType, cbClone, tenConst);
Value cbPow = b.create<Torch::AtenPowTensorTensorOp>(
freqBinsFltType, cbTenTensor, cbDiv);
Value cbPowSubOne = b.create<Torch::AtenSubScalarOp>(
freqBinsFltType, cbPow, oneConst, /*alpha=*/oneConst);
Value centerBinsHz = b.create<Torch::AtenMulScalarOp>(
freqBinsFltType, cbPowSubOne, sevenHConst);
// Normalize freqBinsHz
Value cbMulDft = b.create<Torch::AtenMulScalarOp>(
freqBinsFltType, centerBinsHz, dftLenPlusOneItem);
Value centerBinsNormalized = b.create<Torch::AtenDivScalarOp>(
freqBinsFltType, cbMulDft, sampleRateItem);
// cast to int32
Value centerBinsInt = b.create<Torch::AtenToDtypeOp>(
freqBinsIntType, centerBinsNormalized, /*dtype=*/int32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Value centerBins = b.create<Torch::AtenUnsqueezeOp>(
unsqueezeBinsResType, centerBinsInt, /*dim=*/zeroConst);
// High bins mel to hz
Value highBinsInitInc = b.create<Torch::AtenAddScalarOp>(
freqBinsIntType, highBinsInit, twoConst, /*alpha=*/oneConst);
Value highBinsMulMelStep = b.create<Torch::AtenMulTensorOp>(
freqBinsFltType, highBinsInitInc, melStep);
Value highBinsScaled = b.create<Torch::AtenAddTensorOp>(
freqBinsFltType, highBinsMulMelStep, lfMel, /*alpha=*/oneConst);
Value hbDiv = b.create<Torch::AtenDivScalarOp>(
freqBinsFltType, highBinsScaled, twoFiveNineFiveConst);
Value hbClone = b.create<Torch::AtenCloneOp>(
freqBinsFltType, highBinsScaled, /*memory_format=*/noneConst);
Value hbTenTensor = b.create<Torch::AtenFillScalarOp>(
freqBinsFltType, hbClone, tenConst);
Value hbPow = b.create<Torch::AtenPowTensorTensorOp>(
freqBinsFltType, hbTenTensor, hbDiv);
Value hbPowSubOne = b.create<Torch::AtenSubScalarOp>(
freqBinsFltType, hbPow, oneConst, /*alpha=*/oneConst);
Value highBinsHz = b.create<Torch::AtenMulScalarOp>(
freqBinsFltType, hbPowSubOne, sevenHConst);
// Normalize freqBinsHz
Value hbMulDft = b.create<Torch::AtenMulScalarOp>(
freqBinsFltType, highBinsHz, dftLenPlusOneItem);
Value highBinsNormalized = b.create<Torch::AtenDivScalarOp>(
freqBinsFltType, hbMulDft, sampleRateItem);
// cast to int32
Value highBinsInt = b.create<Torch::AtenToDtypeOp>(
freqBinsIntType, highBinsNormalized, /*dtype=*/int32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Value highBins = b.create<Torch::AtenUnsqueezeOp>(
unsqueezeBinsResType, highBinsInt, /*dim=*/zeroConst);
Type iotaInitType = inputIntType.getWithSizesAndDtype(shapeNSB, si32Ty);
Value iotaInit = b.create<Torch::AtenArangeOp>(
iotaInitType, numSpectrogramBinsItem,
/*dtype=*/int32DTypeConst,
/*layout=*/noneConst, /*device=*/noneConst,
/*pin_memory=*/noneConst);
Torch::ValueTensorType unsqueezeIotaResType =
Torch::ValueTensorType::get(ctx, shapeNSBx1, si32Ty);
Value iota = b.create<Torch::AtenUnsqueezeOp>(
unsqueezeIotaResType, iotaInit, /*dim=*/oneConst);
Value lowToCenter = b.create<Torch::AtenSubTensorOp>(
unsqueezeBinsResType, centerBins, lowBins, /*alpha=*/oneConst);
Value centerToHigh = b.create<Torch::AtenSubTensorOp>(
unsqueezeBinsResType, highBins, centerBins, /*alpha=*/oneConst);
Value oneConstTensor = Torch::createRank0Tensor(
rewriter, binder.getLoc(),
Torch::ValueTensorType::get(ctx, std::nullopt, f32Ty), oneConst);
Type scaledType = inputIntType.getWithSizesAndDtype(shape1xNMB, f32Ty);
Value upscaleInit = b.create<Torch::AtenMaximumOp>(
unsqueezeBinsResType, oneConstTensor, lowToCenter);
Value upscale = b.create<Torch::AtenToDtypeOp>(
scaledType, upscaleInit, /*dtype=*/float32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Value downscaleInit = b.create<Torch::AtenMaximumOp>(
unsqueezeBinsResType, oneConstTensor, centerToHigh);
Value downscale = b.create<Torch::AtenToDtypeOp>(
scaledType, downscaleInit, /*dtype=*/float32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Torch::ValueTensorType binsDiffType =
Torch::ValueTensorType::get(ctx, shapeNSBxNMB, si32Ty);
Torch::ValueTensorType diffFloatType =
Torch::ValueTensorType::get(ctx, shapeNSBxNMB, f32Ty);
Value iotaSubLBInt = b.create<Torch::AtenSubTensorOp>(
binsDiffType, iota, lowBins, /*alpha=*/oneConst);
Value iotaSubLB = b.create<Torch::AtenToDtypeOp>(
diffFloatType, iotaSubLBInt, /*dtype=*/float32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Value rampUp =
b.create<Torch::AtenDivTensorOp>(diffFloatType, iotaSubLB, upscale);
Value hbSubIotaInt = b.create<Torch::AtenSubTensorOp>(
binsDiffType, highBins, iota, /*alpha=*/oneConst);
Value hbSubIota = b.create<Torch::AtenToDtypeOp>(
diffFloatType, hbSubIotaInt, /*dtype=*/float32DTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
Value rampDown = b.create<Torch::AtenDivTensorOp>(diffFloatType,
hbSubIota, downscale);
// ramp values
Type iotaCmpBinsType =
inputIntType.getWithSizesAndDtype(shapeNSBxNMB, i1Ty);
// Iota Cmp Bins
Value iotaGtEqCBins =
b.create<Torch::AtenGeTensorOp>(iotaCmpBinsType, iota, centerBins);
Value iotaEqCBins =
b.create<Torch::AtenEqTensorOp>(iotaCmpBinsType, iota, centerBins);
Value iotaLtLBins =
b.create<Torch::AtenLtTensorOp>(iotaCmpBinsType, iota, lowBins);
Value iotaGtLBins =
b.create<Torch::AtenGtTensorOp>(iotaCmpBinsType, iota, highBins);
// Create output freq ramps Low-Center-High
Type rampInitType =
inputIntType.getWithSizesAndDtype(shapeNSBxNMB, f32Ty);
Value rampInit = b.create<Torch::AtenWhereSelfOp>(
rampInitType, iotaGtEqCBins, rampDown, rampUp);
Value rampInitLt = b.create<Torch::AtenWhereScalarSelfOp>(
rampInitType, iotaLtLBins, zeroConst, rampInit);
Value rampInitLtGt = b.create<Torch::AtenWhereScalarSelfOp>(
rampInitType, iotaGtLBins, zeroConst, rampInitLt);
Type C2HCmpBinsType =
inputIntType.getWithSizesAndDtype(shape1xNMB, i1Ty);
Value C2HEqZero = b.create<Torch::AtenEqScalarOp>(
C2HCmpBinsType, centerToHigh, zeroConst);
Value cornerCases = b.create<Torch::AtenLogicalAndOp>(
iotaCmpBinsType, iotaEqCBins, C2HEqZero);
Value rampOutput = b.create<Torch::AtenWhereScalarSelfOp>(
rampInitType, cornerCases, oneFltConst, rampInitLtGt);
Value outputDTypeConst = b.create<Torch::ConstantIntOp>(
rewriter.getType<Torch::IntType>(),
rewriter.getI64IntegerAttr(torchDTypeInt.value()));
Value finalOutput = b.create<Torch::AtenToDtypeOp>(
resultType, rampOutput, /*dtype=*/outputDTypeConst,
/*non_blocking=*/falseConst, /*copy=*/falseConst,
/*memory_format=*/noneConst);
rewriter.replaceOp(binder.op, finalOutput);
return success();
});
patterns.onOp(
"Multinomial", 7,
[](OpBinder binder, ConversionPatternRewriter &rewriter) {
Torch::ValueTensorType resultType;
Value self;
int64_t onnxDtype, sampleSize;
if (binder.tensorOperand(self) ||
binder.s64IntegerAttr(onnxDtype, "dtype", 6) ||
binder.s64IntegerAttr(sampleSize, "sample_size", 1) ||