-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathConvertToCiphertextSemantics.cpp
More file actions
2628 lines (2280 loc) · 107 KB
/
ConvertToCiphertextSemantics.cpp
File metadata and controls
2628 lines (2280 loc) · 107 KB
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
#include "lib/Transforms/ConvertToCiphertextSemantics/ConvertToCiphertextSemantics.h"
#include <cstdint>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "lib/Dialect/ModuleAttributes.h"
#include "lib/Dialect/Secret/IR/SecretAttributes.h"
#include "lib/Dialect/Secret/IR/SecretDialect.h"
#include "lib/Dialect/Secret/IR/SecretOps.h"
#include "lib/Dialect/Secret/IR/SecretTypes.h"
#include "lib/Dialect/TensorExt/IR/TensorExtAttributes.h"
#include "lib/Dialect/TensorExt/IR/TensorExtDialect.h"
#include "lib/Dialect/TensorExt/IR/TensorExtOps.h"
#include "lib/Kernel/AbstractValue.h"
#include "lib/Kernel/ArithmeticDag.h"
#include "lib/Kernel/IRMaterializingVisitor.h"
#include "lib/Kernel/KernelImplementation.h"
#include "lib/Kernel/KernelName.h"
#include "lib/Kernel/Utils.h"
#include "lib/Transforms/ConvertToCiphertextSemantics/AssignLayout.h"
#include "lib/Transforms/ConvertToCiphertextSemantics/TypeConversion.h"
#include "lib/Transforms/DropUnitDims/DropUnitDims.h"
#include "lib/Utils/AttributeUtils.h"
#include "lib/Utils/ContextAwareConversionUtils.h"
#include "lib/Utils/ContextAwareDialectConversion.h"
#include "lib/Utils/ContextAwareTypeConversion.h"
#include "lib/Utils/Layout/Codegen.h"
#include "lib/Utils/Layout/Convolution.h"
#include "lib/Utils/Layout/Utils.h"
#include "lib/Utils/MathUtils.h"
#include "lib/Utils/Utils.h"
#include "llvm/include/llvm/ADT/ArrayRef.h" // from @llvm-project
#include "llvm/include/llvm/ADT/Hashing.h" // from @llvm-project
#include "llvm/include/llvm/ADT/STLExtras.h" // from @llvm-project
#include "llvm/include/llvm/ADT/SmallVector.h" // from @llvm-project
#include "llvm/include/llvm/ADT/StringExtras.h" // from @llvm-project
#include "llvm/include/llvm/Support/Debug.h" // from @llvm-project
#include "llvm/include/llvm/Support/FormatVariadic.h" // from @llvm-project
#include "llvm/include/llvm/Support/raw_ostream.h" // from @llvm-project
#include "mlir/include/mlir/Analysis/Presburger/IntegerRelation.h" // from @llvm-project
#include "mlir/include/mlir/Analysis/Presburger/PresburgerSpace.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Linalg/IR/Linalg.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/SCF/IR/SCF.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Utils/StaticValueUtils.h" // from @llvm-project
#include "mlir/include/mlir/IR/AffineExpr.h" // from @llvm-project
#include "mlir/include/mlir/IR/AffineMap.h" // from @llvm-project
#include "mlir/include/mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/include/mlir/IR/Builders.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinAttributes.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "mlir/include/mlir/IR/OpDefinition.h" // from @llvm-project
#include "mlir/include/mlir/IR/OperationSupport.h" // from @llvm-project
#include "mlir/include/mlir/IR/PatternMatch.h" // from @llvm-project
#include "mlir/include/mlir/IR/TypeUtilities.h" // from @llvm-project
#include "mlir/include/mlir/IR/Value.h" // from @llvm-project
#include "mlir/include/mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/include/mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/include/mlir/Transforms/DialectConversion.h" // from @llvm-project
#include "mlir/include/mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project
#define DEBUG_TYPE "convert-to-ciphertext-semantics"
namespace mlir {
namespace heir {
namespace {
using kernel::ArithmeticDagNode;
using kernel::implementHaleviShoup;
using kernel::IRMaterializingVisitor;
using kernel::SSAValue;
using ::mlir::heir::kernel::ArithmeticDagNode;
using ::mlir::heir::kernel::implementHaleviShoup;
using ::mlir::heir::kernel::implementRotateAndReduce;
using ::mlir::heir::kernel::IRMaterializingVisitor;
using ::mlir::heir::kernel::SSAValue;
using presburger::IntegerRelation;
using presburger::VarKind;
using tensor_ext::LayoutAttr;
auto& kLayoutAttrName = tensor_ext::TensorExtDialect::kLayoutAttrName;
auto& kMaterializedAttrName = "tensor_ext.layout_materialized";
auto& kOriginalTypeAttrName =
tensor_ext::TensorExtDialect::kOriginalTypeAttrName;
NamedAttribute getArithFMF(OpBuilder& builder) {
return mlir::NamedAttribute(
mlir::StringAttr::get(builder.getContext(), "fastmath"),
mlir::arith::FastMathFlagsAttr::get(
builder.getContext(),
mlir::arith::FastMathFlags::nsz | mlir::arith::FastMathFlags::nnan));
}
IntegerRelation restrictRelationToSlice(const IntegerRelation& relation,
llvm::ArrayRef<int64_t> offsets,
llvm::ArrayRef<int64_t> sizes) {
auto result = relation.clone();
// Set the domain vars to the range specified by the offset and size.
for (auto [dim, offset] : llvm::enumerate(offsets)) {
// d0 - offset >= 0
SmallVector<int64_t> leConstraint(result->getNumCols(), 0);
leConstraint[dim + result->getVarKindOffset(VarKind::Domain)] = 1;
leConstraint.back() = -offset;
result->addInequality(leConstraint);
// offset + size - d0 - 1 >= 0
SmallVector<int64_t> geConstraint(result->getNumCols(), 0);
geConstraint[dim + result->getVarKindOffset(VarKind::Domain)] = -1;
geConstraint.back() = offset + sizes[dim] - 1;
result->addInequality(geConstraint);
}
return *result;
}
// tensor_ext.remap constrains its input and output types to be the same,
// i.e., remap occurs within one set of ciphertexts. The output of an
// extract_slice, however, may have a layout that has fewer ciphertexts
// in it. For example, extracting one row from a data-semantic matrix that
// is packed with one row per ciphertext would result in a single output
// ciphertext, and the expected layout of the result will reflect that.
// To bridge this gap, kernels must post-processes the remap's output to
// extract the subset ciphertexts relevant to the layout of the output
// slice.
Operation* remapAndExtractResult(ImplicitLocOpBuilder& builder, Value input,
LayoutAttr resultLayout,
RankedTensorType resultType) {
auto remapOp = tensor_ext::RemapOp::create(builder, input, resultLayout);
SmallVector<OpFoldResult> strides(2, builder.getIndexAttr(1));
SmallVector<OpFoldResult> offsets(2, builder.getIndexAttr(0));
SmallVector<OpFoldResult> sizes;
sizes.push_back(builder.getIndexAttr(resultType.getDimSize(0)));
sizes.push_back(builder.getIndexAttr(resultType.getDimSize(1)));
auto extractRemap = tensor::ExtractSliceOp::create(
builder, resultType, remapOp.getResult(), offsets, sizes, strides);
return extractRemap;
}
} // namespace
// An unset value of a permutation as it's being built up.
static constexpr int kUnset = -1;
#define GEN_PASS_DEF_CONVERTTOCIPHERTEXTSEMANTICS
#include "lib/Transforms/ConvertToCiphertextSemantics/ConvertToCiphertextSemantics.h.inc"
// This type converter converts types like tensor<NxMxi16> where the dimensions
// represent tensor-semantic data to tensor<ciphertext_count x num_slots x
// i16>, where the last dimension represents the ciphertext or plaintext slot
// count, and the other dimensions are determined by a layout attribute
// indexing.
//
// The presence of a layout attribute on the op define a value is required
// for this type converter to trigger. So patterns that use this and convert
// types must remove any layout attributes when they are done.
//
// TODO(#1450): Determine if we should support non-cyclic slot algebras here
// i.e., for the usual 2xN/2 case, how would we determine this situation
// at this stage of the compilation pipeline, and how would this pass update
// to convert to tensor<AxBx2xN/2xi16> where the last two dimensions now
// correspond to the slot algebra direct product?
struct LayoutMaterializationTypeConverter
: public UniquelyNamedAttributeAwareTypeConverter {
public:
LayoutMaterializationTypeConverter(int ciphertextSize)
: UniquelyNamedAttributeAwareTypeConverter(kLayoutAttrName),
ciphertextSize(ciphertextSize) {
// For some reason, directly capturing ciphertextSize here leads to memory
// corruption on that int. Instead, pass the value to a member variable and
// query it at call time. I have no idea why C++ does this. Debugging it
// felt like having a stroke.
addConversion([&](Type type, Attribute attr) { return std::nullopt; });
addConversion([this](secret::SecretType type,
LayoutAttr attr) -> std::optional<Type> {
auto innerType = type.getValueType();
FailureOr<Type> convertedInnerType = materializeLayout(
getElementTypeOrSelf(innerType), attr, getCiphertextSize());
if (failed(convertedInnerType)) return std::nullopt;
return secret::SecretType::get(convertedInnerType.value());
});
addConversion(
[this](RankedTensorType type, LayoutAttr attr) -> std::optional<Type> {
return materializeLayout(getElementTypeOrSelf(type), attr,
getCiphertextSize());
});
addConversion(
[this](IntegerType type, LayoutAttr attr) -> std::optional<Type> {
return materializeLayout(type, attr, getCiphertextSize());
});
addConversion(
[this](FloatType type, LayoutAttr attr) -> std::optional<Type> {
return materializeLayout(type, attr, getCiphertextSize());
});
addConversion(
[this](IndexType type, LayoutAttr attr) -> std::optional<Type> {
return materializeLayout(type, attr, getCiphertextSize());
});
addConversion([this](secret::SecretType type,
DenseIntElementsAttr attr) -> std::optional<Type> {
return secret::SecretType::get(materializePermutationLayout(
getElementTypeOrSelf(type.getValueType()), attr,
getCiphertextSize()));
});
addConversion([this](RankedTensorType type,
DenseIntElementsAttr attr) -> std::optional<Type> {
return materializePermutationLayout(getElementTypeOrSelf(type), attr,
getCiphertextSize());
});
}
int getCiphertextSize() const { return ciphertextSize; }
private:
int ciphertextSize;
};
bool hasMaterializedAttr(Operation* op) {
return op->hasAttr(kMaterializedAttrName);
}
void setMaterializedAttr(Operation* op) {
op->setAttr(kMaterializedAttrName, UnitAttr::get(op->getContext()));
}
void setMaterializedAttr(ArrayRef<Operation*> ops) {
for (auto* op : ops) {
setMaterializedAttr(op);
}
}
Type maybeExtractSecretType(Type type) {
if (auto secretType = dyn_cast<secret::SecretType>(type)) {
return secretType.getValueType();
}
return type;
}
struct ConvertFunc : public ContextAwareFuncConversion {
public:
ConvertFunc(const ContextAwareTypeConverter& converter, MLIRContext* context)
: ContextAwareFuncConversion(converter, context) {}
LogicalResult finalizeFuncOpModification(
func::FuncOp op, ArrayRef<Type> oldArgTypes,
ArrayRef<Type> oldResultTypes, PatternRewriter& rewriter) const override {
// Replace layout arg attrs with secret.original_type arg attrs This is
// necessary so that later encoding/decoding functions can know what the
// original type of the tensor was and how it was encoded.
rewriter.modifyOpInPlace(op, [&] {
setMaterializedAttr(op);
for (int i = 0; i < op.getNumArguments(); ++i) {
auto layoutAttr = op.getArgAttr(i, kLayoutAttrName);
if (!layoutAttr || !isa<LayoutAttr>(layoutAttr)) {
continue;
}
op.setArgAttr(i, kOriginalTypeAttrName,
tensor_ext::OriginalTypeAttr::get(
getContext(), maybeExtractSecretType(oldArgTypes[i]),
layoutAttr));
}
for (int i = 0; i < op.getNumResults(); ++i) {
auto layoutAttr = op.getResultAttr(i, kLayoutAttrName);
if (!layoutAttr || !isa<LayoutAttr>(layoutAttr)) {
continue;
}
op.setResultAttr(
i, kOriginalTypeAttrName,
tensor_ext::OriginalTypeAttr::get(
getContext(), maybeExtractSecretType(oldResultTypes[i]),
layoutAttr));
}
});
return success();
};
};
struct ConvertSecretGeneric : public ConvertAnyContextAware<secret::GenericOp> {
public:
ConvertSecretGeneric(const ContextAwareTypeConverter& converter,
MLIRContext* context)
: ConvertAnyContextAware(converter, context) {
setDebugName("ConvertGeneric");
}
LogicalResult finalizeOpModification(
secret::GenericOp op,
ContextAwareConversionPatternRewriter& rewriter) const override {
rewriter.modifyOpInPlace(op, [&] { setMaterializedAttr(op); });
return success();
};
};
// Convert an op generically, marking it as materialized. Lowest priority
// because it is only meant to handle ops that don't have special
// materialization rules.
struct ConvertAnyAddingMaterializedAttr : public ConvertAnyContextAware<> {
ConvertAnyAddingMaterializedAttr(const ContextAwareTypeConverter& converter,
MLIRContext* context)
: ConvertAnyContextAware(converter, context, /*benefit=*/0) {
setDebugName("ConvertAnyAddingMaterializedAttr");
}
LogicalResult finalizeOpModification(
Operation* op,
ContextAwareConversionPatternRewriter& rewriter) const override {
rewriter.modifyOpInPlace(op, [&] { setMaterializedAttr(op); });
return success();
};
};
class ConvertAssignLayout
: public ContextAwareOpConversionPattern<tensor_ext::AssignLayoutOp> {
public:
ConvertAssignLayout(const ContextAwareTypeConverter& typeConverter,
mlir::MLIRContext* context, int64_t ciphertextSize)
: ContextAwareOpConversionPattern<tensor_ext::AssignLayoutOp>(
typeConverter, context),
ciphertextSize(ciphertextSize) {}
LogicalResult matchAndRewrite(
tensor_ext::AssignLayoutOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const final {
Value input = adaptor.getValue();
Attribute layout = op.getLayout();
if (!isa<LayoutAttr>(layout) && !isa<DenseIntElementsAttr>(layout)) {
return failure();
}
Type inputType = input.getType();
Type resultType = getTypeConverter()->convertType(op.getType(), layout);
FunctionKey key(layout, inputType, resultType);
// Check cache for existing complex layout assignment function.
func::FuncOp func;
auto it = functionCache.find(key);
if (it != functionCache.end()) {
func = it->second;
func::CallOp call = rewriter.replaceOpWithNewOp<func::CallOp>(
op, func, ValueRange{adaptor.getValue()});
setMaterializedAttr(call);
call->setAttr(kLayoutAttrName, op.getLayout());
return success();
}
// Try implementing the layout assignment for this specific input value
// in-place. If the implementation is simple, the block can be merged
// directly inline. Otherwise, the block is moved to a function and we call
// the layout assignment.
Block* currentBlock = op->getBlock();
Block* scratchBlock =
rewriter.splitBlock(currentBlock, Block::iterator(op));
Block* nextBlock = rewriter.splitBlock(scratchBlock, scratchBlock->begin());
rewriter.setInsertionPointToEnd(scratchBlock);
ImplicitLocOpBuilder b(op.getLoc(), rewriter);
SmallVector<Operation*> createdOps;
auto createdOpCallback = [&](Operation* createdOp) {
setMaterializedAttr(createdOp);
createdOps.push_back(createdOp);
};
auto res = implementAssignLayout(input, layout, ciphertextSize, b,
createdOpCallback, op.getDomainSchedule());
if (failed(res)) {
// Clean up split blocks if implementation failed
rewriter.mergeBlocks(nextBlock, scratchBlock);
rewriter.mergeBlocks(scratchBlock, currentBlock);
return failure();
}
// Simple if it's only a few ops and no loops.
bool isSimple = createdOps.size() <= 3;
for (auto* createdOp : createdOps) {
if (isa<scf::ForOp, scf::WhileOp>(createdOp)) {
isSimple = false;
break;
}
}
if (isSimple) {
// Keep implementation and merge blocks back.
rewriter.mergeBlocks(nextBlock, scratchBlock);
rewriter.mergeBlocks(scratchBlock, currentBlock);
setAttributeAssociatedWith(res.value(), kLayoutAttrName, layout);
rewriter.replaceOp(op, res.value());
return success();
}
// Create a new function for the layout assignment and move the block.
func = outlineAssignLayoutFunction(op, input, res.value(), scratchBlock,
resultType, rewriter);
functionCache[key] = func;
// scratchBlock is moved inside outlineAssignLayoutFunction, but we still
// need to merge with currentBlock.
rewriter.mergeBlocks(nextBlock, currentBlock);
rewriter.setInsertionPointAfter(op);
func::CallOp call = rewriter.replaceOpWithNewOp<func::CallOp>(
op, func, ValueRange{adaptor.getValue()});
setMaterializedAttr(call);
call->setAttr(kLayoutAttrName, op.getLayout());
return success();
};
private:
int64_t ciphertextSize;
func::FuncOp outlineAssignLayoutFunction(
tensor_ext::AssignLayoutOp op, Value originalInput, Value originalResult,
Block* scratchBlock, Type resultType,
ContextAwareConversionPatternRewriter& rewriter) const {
func::FuncOp originalFunc = op->getParentOfType<func::FuncOp>();
ModuleOp module = op->getParentOfType<ModuleOp>();
auto loc = op.getLoc();
Type inputType = originalInput.getType();
std::string funcName = llvm::formatv(
"_assign_layout_{0}",
llvm::hash_combine(op.getLayout(), inputType, resultType));
FunctionType funcType =
FunctionType::get(rewriter.getContext(), {inputType}, {resultType});
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToStart(module.getBody());
auto func = func::FuncOp::create(rewriter, loc, funcName, funcType);
func->setAttr(kClientPackFuncAttrName,
rewriter.getDictionaryAttr({rewriter.getNamedAttr(
kClientHelperFuncName,
rewriter.getStringAttr(originalFunc.getSymName()))}));
func.setPrivate();
Block* funcBlock = func.addEntryBlock();
// Move ops from scratchBlock to funcBlock and remap original input to the
// funcBlock->getArgument(0).
rewriter.replaceUsesWithIf(originalInput, funcBlock->getArgument(0),
[scratchBlock](OpOperand& use) {
return scratchBlock->findAncestorOpInBlock(
*use.getOwner()) != nullptr;
});
rewriter.mergeBlocks(scratchBlock, funcBlock);
rewriter.setInsertionPointToEnd(funcBlock);
func::ReturnOp::create(rewriter, loc, originalResult);
return func;
}
// Cache to store functions generated for a specific layout key is
// (LayoutAttribute, InputType, ResultType). Layout is uniqued by the layout
// string.
using FunctionKey = std::tuple<Attribute, Type, Type>;
mutable llvm::DenseMap<FunctionKey, func::FuncOp> functionCache;
};
class ConvertConvertLayout
: public ContextAwareOpConversionPattern<tensor_ext::ConvertLayoutOp> {
public:
using ContextAwareOpConversionPattern<
tensor_ext::ConvertLayoutOp>::ContextAwareOpConversionPattern;
LogicalResult matchAndRewrite(
tensor_ext::ConvertLayoutOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const final {
LayoutAttr fromLayout = dyn_cast<LayoutAttr>(op.getFromLayout());
LayoutAttr toLayout = dyn_cast<LayoutAttr>(op.getToLayout());
if (!fromLayout || !toLayout) {
return failure();
}
// This is persisted as an operation rather than lowered eagerly to a shift
// network so as to allow VosVosErkinShiftNetworks to cache its work across
// multiple instances of the same conversion.
std::shared_ptr<IntegerRelation> composedLayout =
fromLayout.getIntegerRelation().clone();
composedLayout->inverse();
composedLayout->compose(toLayout.getIntegerRelation());
ImplicitLocOpBuilder b(op.getLoc(), rewriter);
LayoutAttr newLayoutAttr =
LayoutAttr::getFromIntegerRelation(getContext(), *composedLayout);
auto resultCiphertextSemanticType = cast<RankedTensorType>(
getTypeConverter()->convertType(op.getResult().getType(), toLayout));
auto remapAndExtract = remapAndExtractResult(
b, adaptor.getValue(), newLayoutAttr, resultCiphertextSemanticType);
setMaterializedAttr(remapAndExtract);
setAttributeAssociatedWith(remapAndExtract->getResults()[0],
kLayoutAttrName, toLayout);
rewriter.replaceOp(op, remapAndExtract->getResults()[0]);
return success();
};
};
// If the mapping is a partial rotation, return the rotation shift amount.
std::optional<int64_t> tryDetectPartialRotation(
::llvm::ArrayRef<int64_t> perm) {
std::optional<int64_t> rotation = std::nullopt;
for (int64_t i = 0; i < perm.size(); ++i) {
int64_t input = i;
int64_t output = perm[i];
if (output == kUnset) continue;
// We rotate left in this codebase, so invert normal output - input
int64_t shiftAmount = -(output - input);
if (!rotation.has_value()) {
rotation = shiftAmount;
} else if (shiftAmount != rotation.value()) {
return std::nullopt;
}
}
return rotation;
}
// Extend a partial permutation to a full permutation in an FHE-friendly way.
void extendPermutationGreedily(::llvm::MutableArrayRef<int64_t> perm) {
std::set<int64_t> unmappedInputs;
// Start with values 0..n-1 and remove when found in the permutation
std::vector<int64_t> unmappedOutputsVector(perm.size());
std::iota(unmappedOutputsVector.begin(), unmappedOutputsVector.end(), 0);
std::set<int64_t> unmappedOutputs(unmappedOutputsVector.begin(),
unmappedOutputsVector.end());
for (int64_t i = 0; i < perm.size(); ++i) {
if (perm[i] == kUnset) {
unmappedInputs.insert(i);
} else {
unmappedOutputs.erase(perm[i]);
}
}
// Set iteration is in sorted order, so we're mapping each unused input to
// the first output index that hasn't been mapped to yet.
for (const auto& [input, output] :
llvm::zip(unmappedInputs, unmappedOutputs)) {
perm[input] = output;
}
}
// Extend a partial permutation to a full permutation in an FHE-friendly way.
//
// FHE-friendly means that the output permutation should lower to a small shift
// network. For example, if the permutation can be extended to a single
// rotation, it should be.
//
// The input partialPermutation must already be correctly sized (size n for a
// permutation on 1..n). Unset entries of the permutation are indicated by
// kUnset.
void extendPartialPermutation(MutableArrayRef<int64_t> partialPermutation) {
// If the partially set entries correspond to a single rotation, extend it.
std::optional<int64_t> rotation =
tryDetectPartialRotation(partialPermutation);
if (rotation.has_value()) {
LLVM_DEBUG(llvm::dbgs() << "Detected partial rotation of offset "
<< rotation.value() << "\n");
for (int64_t i = 0; i < partialPermutation.size(); ++i) {
if (partialPermutation[i] == kUnset) {
int64_t target = i - rotation.value();
if (target < 0) target += partialPermutation.size();
partialPermutation[i] = target;
}
}
return;
}
// Otherwise, try to fill in the unset entries greedily.
extendPermutationGreedily(partialPermutation);
}
class ConvertLinalgReduce
: public ContextAwareOpConversionPattern<linalg::ReduceOp> {
public:
using ContextAwareOpConversionPattern<
linalg::ReduceOp>::ContextAwareOpConversionPattern;
void rotateAndReduceKernel(linalg::ReduceOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter,
Operation* innerOp) const {
auto input = op.getInputs()[0];
auto originalShape = cast<RankedTensorType>(input.getType()).getShape();
// Pre-conditions enforce that the reduction operation occurs along the
// inputs single axis
unsigned steps = originalShape[op.getDimensions()[0]];
unsigned period = 1;
std::shared_ptr<ArithmeticDagNode<SSAValue>> implementedKernel;
SSAValue vectorLeaf(adaptor.getInputs()[0]);
kernel::DagType dagType = kernel::mlirTypeToDagType(input.getType());
// This requires 1 operation and 1 dimension to reduce
implementedKernel =
implementRotateAndReduce(vectorLeaf, {}, period, steps, dagType, {},
innerOp->getName().getStringRef().str());
rewriter.setInsertionPointAfter(op);
auto convertedType = getTypeConverter()->convertType(
input.getType(), cast<LayoutAttr>(op->getAttr(kLayoutAttrName)));
ImplicitLocOpBuilder b(op.getLoc(), rewriter);
IRMaterializingVisitor visitor(
convertedType, [&](Operation* createdOp) { setMaterializedAttr(op); });
Value finalOutput = visitor.process(implementedKernel, b)[0];
auto layoutAttr = cast<LayoutAttr>(op->getAttr(kLayoutAttrName));
auto* finalOutputOp = finalOutput.getDefiningOp();
finalOutputOp->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(finalOutputOp);
// Add the initial value.
Value result = adaptor.getInits()[0];
Operation* addBias =
makeAppropriatelyTypedAddOp(b, op->getLoc(), finalOutput, result);
addBias->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(addBias);
rewriter.replaceOp(op, addBias);
}
LayoutAttr getLayoutAttr(Value value) const {
auto layoutLookup = getTypeConverter()->getContextualAttr(value);
if (failed(layoutLookup)) {
return nullptr;
}
return dyn_cast<LayoutAttr>(layoutLookup.value());
}
LogicalResult matchAndRewrite(
linalg::ReduceOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const final {
// Ensure the reduction op is single addition or multiplication, otherwise
// there is no kernel.
Block* body = op.getBlock();
if (body->getOperations().size() != 2) {
return op.emitError(
"linalg.reduce only supported with a single reduction operation");
}
// TODO(#1543): support multi-dimension reductions
if (op.getDimensions().size() != 1) {
return op.emitError(
"linalg.reduce only supported with a single reduction dimension");
}
if (!op.isSingleInputOutput()) {
return op.emitError(
"linalg.reduce only supported with a single reduction dimension");
}
Operation* innerOp = &body->getOperations().front();
if (!isa<arith::AddFOp, arith::MulFOp, arith::AddIOp, arith::MulIOp>(
innerOp)) {
return op.emitError()
<< "linalg.reduce only supported with a single addition or "
"multiplication operation, but found: "
<< innerOp->getName();
}
Value input = adaptor.getInputs()[0];
LayoutAttr inputLayout = getLayoutAttr(input);
if (!inputLayout)
return rewriter.notifyMatchFailure(
op, "missing new layout attribute for input");
// Based on ImplementRotateAndReduce
rotateAndReduceKernel(op, adaptor, rewriter, innerOp);
return success();
}
};
struct ConvertLinalgDot
: public ContextAwareOpConversionPattern<linalg::DotOp> {
public:
using ContextAwareOpConversionPattern<
linalg::DotOp>::ContextAwareOpConversionPattern;
LayoutAttr getLayoutAttr(Value value) const {
auto layoutLookup = getTypeConverter()->getContextualAttr(value);
if (failed(layoutLookup)) {
return nullptr;
}
return dyn_cast<LayoutAttr>(layoutLookup.value());
}
LogicalResult matchAndRewrite(
linalg::DotOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const final {
Value lhs = adaptor.getInputs()[0];
Value rhs = adaptor.getInputs()[1];
Value acc = adaptor.getOutputs()[0];
LayoutAttr lhsLayout = getLayoutAttr(lhs);
LayoutAttr rhsLayout = getLayoutAttr(rhs);
if (!lhsLayout || !rhsLayout) {
return rewriter.notifyMatchFailure(
op, "missing new layout attribute for inputs");
}
ImplicitLocOpBuilder b(op.getLoc(), rewriter);
Type elementType = cast<RankedTensorType>(lhs.getType()).getElementType();
std::string reduceOpName;
if (isa<FloatType>(elementType)) {
reduceOpName = "arith.addf";
} else if (isa<IntegerType>(elementType)) {
reduceOpName = "arith.addi";
} else {
return op.emitError("unsupported element type for linalg.dot");
}
auto originalShape =
cast<RankedTensorType>(op.getInputs()[0].getType()).getShape();
unsigned steps = originalShape[0];
std::shared_ptr<ArithmeticDagNode<SSAValue>> implementedKernel;
kernel::DagType dagType = kernel::mlirTypeToDagType(lhs.getType());
implementedKernel =
implementDot(SSAValue(lhs), SSAValue(rhs), steps, dagType);
rewriter.setInsertionPointAfter(op);
auto layoutAttr = cast<LayoutAttr>(op->getAttr(kLayoutAttrName));
auto convertedType =
getTypeConverter()->convertType(lhs.getType(), layoutAttr);
IRMaterializingVisitor visitor(convertedType, [&](Operation* createdOp) {
setMaterializedAttr(createdOp);
});
Value finalOutput = visitor.process(implementedKernel, b)[0];
auto* finalOutputOp = finalOutput.getDefiningOp();
finalOutputOp->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(finalOutputOp);
Operation* addBias =
makeAppropriatelyTypedAddOp(b, op->getLoc(), finalOutput, acc);
addBias->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(addBias);
rewriter.replaceOp(op, addBias);
return success();
}
};
struct ConvertLinalgMatvecLayout
: public ContextAwareOpConversionPattern<linalg::MatvecOp> {
public:
using ContextAwareOpConversionPattern<
linalg::MatvecOp>::ContextAwareOpConversionPattern;
ConvertLinalgMatvecLayout(
const ContextAwareTypeConverter& contextAwareTypeConverter,
MLIRContext* context, bool unrollKernels = true)
: ContextAwareOpConversionPattern(contextAwareTypeConverter, context,
/*benefit=*/10),
unrollKernels(unrollKernels) {}
LayoutAttr getLayoutAttr(Value value) const {
auto layoutLookup = getTypeConverter()->getContextualAttr(value);
if (failed(layoutLookup)) {
return nullptr;
}
return dyn_cast<LayoutAttr>(layoutLookup.value());
}
bool supportsHaleviShoup(linalg::MatvecOp op, OpAdaptor adaptor) const {
Value matrix = adaptor.getInputs()[0];
auto matrixType = cast<RankedTensorType>(matrix.getType());
// If one of these dimensions is not a power of two, then we can't do
// the Halevi-Shoup or Squat Packing Matrix Multiplication conversion.
auto dimensions = matrixType.getShape();
int64_t numRows = dimensions[0];
int64_t numCols = dimensions[1];
bool isPowerOfTwoDims = isPowerOfTwo(numRows) && isPowerOfTwo(numCols);
auto kernelAttr = op->getAttrOfType<secret::KernelAttr>(
secret::SecretDialect::kKernelAttrName);
bool isMatvecDiagonal =
kernelAttr && kernelAttr.getName() == KernelName::MatvecDiagonal;
LLVM_DEBUG(llvm::dbgs()
<< "supports matvec with halevi-shoup: isPowerOfTwoDims="
<< isPowerOfTwoDims << " isMatvecDiagonal=" << isMatvecDiagonal
<< "\n");
return isPowerOfTwoDims && isMatvecDiagonal;
}
void haleviShoupKernel(
linalg::MatvecOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const {
LLVM_DEBUG(llvm::dbgs()
<< "Converting linalg.matvec op with halevi shoup kernel: " << op
<< "\n");
TypedValue<RankedTensorType> input =
cast<TypedValue<RankedTensorType>>(adaptor.getInputs()[1]);
SSAValue vectorLeaf(input);
TypedValue<RankedTensorType> matrix =
cast<TypedValue<RankedTensorType>>(adaptor.getInputs()[0]);
SSAValue matrixLeaf(matrix);
auto dagType = kernel::mlirTypeToDagType(input.getType());
std::shared_ptr<ArithmeticDagNode<SSAValue>> implementedKernel =
implementHaleviShoup(vectorLeaf, matrixLeaf,
cast<RankedTensorType>(op.getInputs()[0].getType())
.getShape()
.vec(),
dagType,
/*zeroDiagonals=*/{},
/*unroll=*/unrollKernels);
rewriter.setInsertionPointAfter(op);
ImplicitLocOpBuilder b(op.getLoc(), rewriter);
IRMaterializingVisitor visitor(input.getType(), [&](Operation* createdOp) {
setMaterializedAttr(createdOp);
});
Value finalOutput = visitor.process(implementedKernel, b)[0];
auto layoutAttr = cast<LayoutAttr>(op->getAttr(kLayoutAttrName));
auto* finalOutputOp = finalOutput.getDefiningOp();
finalOutputOp->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(finalOutputOp);
// Add the initial accumulator value.
Value result = adaptor.getOutputs()[0];
Operation* addBias =
makeAppropriatelyTypedAddOp(b, op->getLoc(), finalOutput, result);
addBias->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(addBias);
rewriter.replaceOp(op, addBias);
}
LogicalResult matchAndRewrite(
linalg::MatvecOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const final {
Value matrix = adaptor.getInputs()[0];
Value vector = adaptor.getInputs()[1];
LayoutAttr vectorLayout = getLayoutAttr(vector);
LayoutAttr matrixLayout = getLayoutAttr(matrix);
if (!matrixLayout || !vectorLayout)
return rewriter.notifyMatchFailure(
op, "missing new layout attribute for matrix and vector");
if (supportsHaleviShoup(op, adaptor)) {
haleviShoupKernel(op, adaptor, rewriter);
return success();
}
// TODO(#1589): implement row-major naive matvec kernel
return op.emitError() << "unsupported layout for matrix in matvec: "
<< matrixLayout;
}
private:
bool unrollKernels;
};
struct ConvertLinalgConv1D
: public ContextAwareOpConversionPattern<linalg::Conv1DOp> {
public:
using ContextAwareOpConversionPattern<
linalg::Conv1DOp>::ContextAwareOpConversionPattern;
ConvertLinalgConv1D(
const ContextAwareTypeConverter& contextAwareTypeConverter,
MLIRContext* context, bool unrollKernels = true)
: ContextAwareOpConversionPattern(contextAwareTypeConverter, context,
/*benefit=*/10),
unrollKernels(unrollKernels) {}
LayoutAttr getLayoutAttr(Value value) const {
auto layoutLookup = getTypeConverter()->getContextualAttr(value);
if (failed(layoutLookup)) {
return nullptr;
}
return dyn_cast<LayoutAttr>(layoutLookup.value());
}
bool supportsExpandedHaleviShoup(linalg::Conv1DOp op,
OpAdaptor adaptor) const {
Value filter = adaptor.getInputs().back();
auto materializedFilterType = cast<RankedTensorType>(filter.getType());
// If one of these dimensions is not a power of two, then we can't do
// the Halevi-Shoup or Squat Packing Matrix Multiplication conversion.
auto dimensions = materializedFilterType.getShape();
int64_t numRows = dimensions[0];
int64_t numCols = dimensions[1];
bool isPowerOfTwoDims = isPowerOfTwo(numRows) && isPowerOfTwo(numCols);
auto kernelAttr = op->getAttrOfType<secret::KernelAttr>(
secret::SecretDialect::kKernelAttrName);
bool isConv1dAsMatvec =
kernelAttr && kernelAttr.getName() == KernelName::MatvecDiagonal;
LLVM_DEBUG(llvm::dbgs()
<< "supports expanded conv1d as matvec with halevi-shoup: "
<< "isPowerOfTwoDims=" << isPowerOfTwoDims
<< " isConv1dAsMatvec=" << isConv1dAsMatvec << "\n");
return isPowerOfTwoDims && isConv1dAsMatvec;
}
void haleviShoupKernel(
linalg::Conv1DOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const {
LLVM_DEBUG(llvm::dbgs()
<< "Converting linalg.conv1d op with halevi shoup kernel: " << op
<< "\n");
TypedValue<RankedTensorType> data =
cast<TypedValue<RankedTensorType>>(adaptor.getInputs()[0]);
SSAValue vectorLeaf(data);
TypedValue<RankedTensorType> filter =
cast<TypedValue<RankedTensorType>>(adaptor.getInputs()[1]);
SSAValue matrixLeaf(filter);
// The original matrix shape is the shape of the expanded filter before
// diagonalization.
RankedTensorType expandedMatrixType = get1dConvFilterExpandedType(
cast<RankedTensorType>(op.getInputs()[1].getType()),
cast<RankedTensorType>(op.getInputs()[0].getType()), /*stride=*/1,
/*padding=*/0);
// Collect any zero diagonals of the filter matrix.
LayoutAttr filterLayout = getLayoutAttr(adaptor.getInputs()[1]);
auto filterRelation = filterLayout.getIntegerRelation();
PointCollector collector;
std::map<int, bool> zeroDiagonals;
getCtComplementPoints(filterRelation, collector, filter.getType());
for (const auto& point : collector.points) {
zeroDiagonals[point[0]] = true;
}
auto dagType = kernel::mlirTypeToDagType(data.getType());
std::shared_ptr<ArithmeticDagNode<SSAValue>> implementedKernel =
implementHaleviShoup(vectorLeaf, matrixLeaf,
expandedMatrixType.getShape().vec(), dagType,
zeroDiagonals,
/*unroll=*/unrollKernels);
rewriter.setInsertionPointAfter(op);
ImplicitLocOpBuilder b(op.getLoc(), rewriter);
IRMaterializingVisitor visitor(data.getType(), [&](Operation* createdOp) {
setMaterializedAttr(createdOp);
});
Value finalOutput = visitor.process(implementedKernel, b)[0];
auto layoutAttr = cast<LayoutAttr>(op->getAttr(kLayoutAttrName));
auto finalOutputOp = finalOutput.getDefiningOp();
finalOutputOp->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(finalOutputOp);
// Add the initial accumulator value.
Value result = adaptor.getOutputs()[0];
Operation* addBias =
makeAppropriatelyTypedAddOp(b, op->getLoc(), finalOutput, result);
addBias->setAttr(kLayoutAttrName, layoutAttr);
setMaterializedAttr(addBias);
rewriter.replaceOp(op, addBias);
}
LogicalResult matchAndRewrite(
linalg::Conv1DOp op, OpAdaptor adaptor,
ContextAwareConversionPatternRewriter& rewriter) const final {
Value data = adaptor.getInputs().front();
Value filter = adaptor.getInputs().back();
LayoutAttr dataLayout = getLayoutAttr(data);
LayoutAttr filterLayout = getLayoutAttr(filter);
if (!dataLayout || !filterLayout)
return rewriter.notifyMatchFailure(
op, "missing new layout attribute for data and filter");
if (supportsExpandedHaleviShoup(op, adaptor)) {
haleviShoupKernel(op, adaptor, rewriter);