-
Notifications
You must be signed in to change notification settings - Fork 344
/
algebraic_simplifier.cc
9149 lines (8461 loc) · 370 KB
/
algebraic_simplifier.cc
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
/* Copyright 2017 The OpenXLA Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "xla/service/algebraic_simplifier.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/log/check.h"
#include "absl/numeric/bits.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/comparison_util.h"
#include "xla/hlo/evaluator/hlo_evaluator.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instruction_utils.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/utils/hlo_sharding_util.h"
#include "xla/layout.h"
#include "xla/layout_util.h"
#include "xla/literal.h"
#include "xla/literal_comparison.h"
#include "xla/literal_util.h"
#include "xla/overflow_util.h"
#include "xla/permutation_util.h"
#include "xla/primitive_util.h"
#include "xla/service/hlo_cost_analysis.h"
#include "xla/service/hlo_creation_utils.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/host_memory_offload_annotations.h"
#include "xla/service/pattern_matcher.h"
#include "xla/service/shape_inference.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/util.h"
#include "xla/window_util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
namespace m = match;
using primitive_util::NativeTypeOf;
// Unwraps broadcasts hunting for a constant. If we find one, checks if the
// constant contains only the given value.
bool IsAll(const HloInstruction* op, int8_t value) {
switch (op->opcode()) {
case HloOpcode::kBroadcast:
return IsAll(op->operand(0), value);
case HloOpcode::kConstant:
return op->literal().IsAll(value);
default:
return false;
}
}
bool IsAll(const HloInstruction* op, const Literal& scalar) {
CHECK(ShapeUtil::IsScalar(scalar.shape()));
switch (op->opcode()) {
case HloOpcode::kBroadcast:
return IsAll(op->operand(0), scalar);
case HloOpcode::kConstant:
return op->literal().IsAll(scalar);
default:
return false;
}
}
bool IsAnyOperandComplex(const HloInstruction* hlo) {
for (auto operand : hlo->operands()) {
if (ShapeUtil::ElementIsComplex(operand->shape())) {
return true;
}
}
return false;
}
bool IsPositive(const HloInstruction* hlo,
const AlgebraicSimplifierOptions& options) {
// Utility only handles real types.
if (IsAnyOperandComplex(hlo)) {
return false;
}
switch (hlo->opcode()) {
case HloOpcode::kGetTupleElement: {
const HloInstruction* gte_operand = hlo->operand(0);
switch (gte_operand->opcode()) {
case HloOpcode::kCustomCall: {
const auto& target = gte_operand->custom_call_target();
return target ==
options.get_cudnn_batchnorm_forward_training_metadata() &&
hlo->tuple_index() == 2;
}
default:
return false;
}
}
case HloOpcode::kPower:
case HloOpcode::kAbs:
case HloOpcode::kRsqrt:
case HloOpcode::kSqrt:
return IsPositive(hlo->operand(0), options);
case HloOpcode::kMultiply: {
return hlo->operand(0) == hlo->operand(1) &&
IsPositive(hlo->operand(0), options);
}
default:
return false;
}
}
std::optional<double> GetConstantValue(const HloInstruction* inst) {
if (!ShapeUtil::IsEffectiveScalar(inst->shape())) {
return std::nullopt;
}
return primitive_util::PrimitiveTypeSwitch<std::optional<double>>(
[&](auto primitive_type_constant) -> std::optional<double> {
if constexpr (primitive_util::IsFloatingPointType(
primitive_type_constant)) {
using NativeT = NativeTypeOf<primitive_type_constant>;
return static_cast<double>(
inst->literal().GetFirstElement<NativeT>());
}
return std::nullopt;
},
inst->shape().element_type());
}
static bool IsScalarConstant(const HloInstruction* hlo,
const LiteralSlice& literal) {
return hlo->opcode() == HloOpcode::kConstant &&
ShapeUtil::IsEffectiveScalar(hlo->shape()) &&
literal_comparison::Equal(hlo->literal(), literal).ok();
}
static bool IsScalarConstantZero(const HloInstruction* hlo) {
return IsScalarConstant(hlo, LiteralUtil::Zero(hlo->shape().element_type()));
}
static bool IsScalarConstantNegInf(const HloInstruction* hlo) {
return !primitive_util::IsComplexType(hlo->shape().element_type()) &&
IsScalarConstant(hlo,
LiteralUtil::MinValue(hlo->shape().element_type()));
}
static bool IsScalarConstantInf(const HloInstruction* hlo) {
return !primitive_util::IsComplexType(hlo->shape().element_type()) &&
IsScalarConstant(hlo,
LiteralUtil::MaxValue(hlo->shape().element_type()));
}
bool IsNonNegative(const HloInstruction* hlo,
const AlgebraicSimplifierOptions& options) {
// Utility only handles real types.
if (IsAnyOperandComplex(hlo)) {
return false;
}
switch (hlo->opcode()) {
case HloOpcode::kMultiply: {
return hlo->operand(0) == hlo->operand(1);
}
case HloOpcode::kAbs: {
return true;
}
case HloOpcode::kBroadcast: {
return IsNonNegative(hlo->operand(0), options);
}
case HloOpcode::kConstant: {
if (std::optional<double> value = GetConstantValue(hlo)) {
return *value >= 0.0;
}
return false;
}
case HloOpcode::kMaximum: {
return IsNonNegative(hlo->operand(0), options) ||
IsNonNegative(hlo->operand(1), options);
}
case HloOpcode::kSelect: {
return IsNonNegative(hlo->operand(1), options) &&
IsNonNegative(hlo->operand(2), options);
}
default:
return IsPositive(hlo, options);
}
}
// Checks whether `op` is a floating-point constant or broadcast of a constant
// of the form +/- 2^k for some integer k positive, negative, or zero. Such
// values are interesting because multiplying by a power of 2 just moves the
// exponent.
bool IsAllFpConstantPowerOf2(const HloInstruction* op) {
// Unwrap the broadcast if necessary.
const HloInstruction* c;
if (!Match(op, m::ConstantEffectiveScalar(&c)) &&
!Match(op, m::Broadcast(m::Constant(&c).WithShape(
m::Shape().IsEffectiveScalar())))) {
return false;
}
auto val = GetConstantValue(c);
if (!val) {
return false;
}
int exp;
double mantissa = std::frexp(*val, &exp);
// frexp returns a value in the range (-1, -0.5] U [0.5, 1). A return value
// of +/-0.5 therefore indicates that the floating point value is a power of
// 2.
return mantissa == 0.5 || mantissa == -0.5;
}
// Returns whether the given transpose produces a result which is bit-wise
// identical to its operand and thus may be replaced with a bitcast.
bool TransposeIsBitcast(const HloInstruction* transpose) {
CHECK_EQ(HloOpcode::kTranspose, transpose->opcode());
const HloInstruction* operand = transpose->operand(0);
return ShapeUtil::TransposeIsBitcast(operand->shape(), transpose->shape(),
transpose->dimensions());
}
// Recursive helper for method below.
HloInstruction* BitcastingOperandOfReshapeOrCopyChainHelper(
HloInstruction* instr, HloInstruction* operand,
const AlgebraicSimplifierOptions& options) {
// Can't replace chain of copies and reshapes with bitcasts if the compiler
// used a memory layout which isn't compatible.
if (options.ReshapeIsBitcast(operand->shape(), instr->shape())) {
return operand;
}
// If the operand is a copy or reshape try to see if the operand's operand
// would produce a bitcast with initial instruction.
if (HloOpcode::kReshape == operand->opcode() ||
HloOpcode::kCopy == operand->opcode()) {
return BitcastingOperandOfReshapeOrCopyChainHelper(
instr, operand->mutable_operand(0), options);
}
return nullptr;
}
// Returns an operand of a chain of reshapes and copies that is bit-wise
// identical to first reshape or copy in the chain.
HloInstruction* BitcastingOperandOfReshapeOrCopyChain(
HloInstruction* instr, const AlgebraicSimplifierOptions& options) {
if (!options.is_layout_sensitive()) {
return nullptr;
}
CHECK(HloOpcode::kReshape == instr->opcode() ||
HloOpcode::kCopy == instr->opcode());
return BitcastingOperandOfReshapeOrCopyChainHelper(
instr, instr->mutable_operand(0), options);
}
// Returns bool to determine whether a pair of converts can be eliminated.
bool IsConvertPairNoOp(const HloInstruction* convert) {
// [operand_convert] [convert]
// (src)->convert-(intermediate)->convert-(dest)
const HloInstruction* operand_convert = convert->operand(0);
if (operand_convert->opcode() != HloOpcode::kConvert) {
return false;
}
const PrimitiveType src_type =
operand_convert->operand(0)->shape().element_type();
const PrimitiveType intermediate_type =
operand_convert->shape().element_type();
return src_type == convert->shape().element_type() &&
primitive_util::CastPreservesValues(src_type, intermediate_type);
}
PrecisionConfig SwapOperandsInDotPrecisionConfig(PrecisionConfig config) {
CHECK_EQ(config.operand_precision_size(), 2);
std::swap(config.mutable_operand_precision()->at(0),
config.mutable_operand_precision()->at(1));
return config;
}
// Validate whether tiling and padding assignments in the bitcasted shapes
// will make the two shapes non-equivalent.
bool ValidateTilingOfBitcast(
const Shape& bitcast_shape, const Shape& op_shape,
const std::vector<std::vector<int64_t>>& operand_map) {
if (op_shape.layout().tiles().empty() ||
bitcast_shape.layout().tiles().empty()) {
return true;
}
VLOG(2) << "op shape:" << op_shape.ToString(true) << "\n";
VLOG(2) << "bitcast shape:" << bitcast_shape.ToString(true) << "\n";
VLOG(2) << "operand_map size:" << operand_map.size() << "\n";
auto op_tile = op_shape.layout().tiles(0);
auto bitcast_tile = bitcast_shape.layout().tiles(0);
int64_t num_of_tiled_dims = op_tile.dimensions().size(),
tiled_dim_idx = num_of_tiled_dims - 1;
if (bitcast_tile.dimensions().size() != num_of_tiled_dims) {
return false;
}
for (auto op_dim : op_shape.layout().minor_to_major()) {
VLOG(3) << "op_dim = " << op_dim << "\n";
VLOG(3) << "tiled_dim_idx = " << tiled_dim_idx << "\n";
VLOG(3) << "tiled_dim_size = " << op_tile.dimension(tiled_dim_idx) << ":"
<< bitcast_tile.dimension(tiled_dim_idx) << "\n";
if (op_tile.dimensions()[tiled_dim_idx] !=
bitcast_tile.dimensions()[tiled_dim_idx]) {
VLOG(2) << "Abort b/c tiled dimension " << op_dim
<< " has different tiling sizes before and after bitcast.\n";
return false;
}
if (operand_map.size() <= op_dim || operand_map[op_dim].empty()) {
if (op_tile.dimensions()[tiled_dim_idx] != 1) {
VLOG(2) << "Abort b/c tiled dimension " << op_dim << " has size 1.\n";
return false;
}
} else if (bitcast_shape.dimensions_size() <= operand_map[op_dim][0]) {
VLOG(2) << "Abort because the bitcasted dimensions are not aligned!\n";
return false;
} else if (bitcast_shape.dimensions(operand_map[op_dim][0]) <
op_shape.dimensions(op_dim)) {
if (operand_map[op_dim].size() == 1) {
VLOG(2) << "Abort b/c a dimension (possibly padded) is shrank to a "
"smaller size.\n";
return false;
}
if (tiled_dim_idx > 0) {
VLOG(2) << "Abort b/c a non-major tiled dimension is split.\n";
return false;
}
if (bitcast_shape.dimensions(operand_map[op_dim][0]) %
op_tile.dimensions()[tiled_dim_idx] !=
0 ||
op_shape.dimensions(op_dim) %
bitcast_shape.dimensions(operand_map[op_dim][0]) !=
0) {
VLOG(2) << "Abort b/c tiled dimension " << op_dim
<< " has been split in bitcasted layout\n";
return false;
}
} else if (bitcast_shape.dimensions(operand_map[op_dim][0]) >
op_shape.dimensions(op_dim)) {
if (tiled_dim_idx > 0) {
VLOG(2) << "Abort b/c a non-major tiled dimension is combined.\n";
return false;
}
if (bitcast_shape.dimensions(operand_map[op_dim][0]) %
op_shape.dimensions(op_dim) !=
0 ||
op_shape.dimensions(op_dim) % op_tile.dimensions()[tiled_dim_idx] !=
0) {
VLOG(2) << "Abort b/c tiled dimension " << op_dim
<< " has been combined in bitcasted layout\n";
return false;
}
}
if (--tiled_dim_idx < 0) {
break;
}
}
return true;
}
// Constructs the maps that take dims of A and dims of B to dims of AB, mapping
// to -1 for dimensions not present in AB. For an example, consider we are
// computing a dot whose operands have shapes [m,n,p] and [n,q]. Assuming we
// contract over n, this produces an array with shape [m,p,q]. This function
// will return vectors map_a_ab = {0, -1, 1} and map_b_ab = {-1, 2}
std::pair<std::vector<int64_t>, std::vector<int64_t>> ConstructToDotMaps(
DotDimensionNumbers dnums, const Shape& a_shape, const Shape& b_shape) {
std::vector<int64_t> map_a_ab(a_shape.rank(), -1),
map_b_ab(b_shape.rank(), -1);
int64_t ab_index = 0;
// Extract a and b contraction dimensions from dnums
auto a_batch_dims = dnums.lhs_batch_dimensions();
auto b_batch_dims = dnums.rhs_batch_dimensions();
const auto& a_contracting_dims = dnums.lhs_contracting_dimensions();
const auto& b_contracting_dims = dnums.rhs_contracting_dimensions();
// First add the batch dimensions
for (int64_t i = 0; i < a_batch_dims.size(); i++) {
map_a_ab[a_batch_dims[i]] = ab_index;
map_b_ab[b_batch_dims[i]] = ab_index;
ab_index++;
}
// Then add the free dimensions from a
for (int64_t a_index = 0; a_index < a_shape.rank(); a_index++) {
if (!absl::c_linear_search(a_contracting_dims, a_index) &&
!absl::c_linear_search(a_batch_dims, a_index)) {
map_a_ab[a_index] = ab_index;
ab_index++;
}
}
// Finally add the free dimensions from b
for (int64_t b_index = 0; b_index < b_shape.rank(); b_index++) {
if (!absl::c_linear_search(b_contracting_dims, b_index) &&
!absl::c_linear_search(b_batch_dims, b_index)) {
map_b_ab[b_index] = ab_index;
ab_index++;
}
}
return {map_a_ab, map_b_ab};
}
// Constructs the maps that take dims of AB to dims of A and dims of B mapping
// to -1 for dimensions not present in A/B. For an example, consider we are
// computing a dot whose operands have shapes [m,n,p] and [n,q]. Assuming we
// contract over n, this produces an array with shape [m,p,q]. This function
// will return vectors map_ab_a = {0,2,-1} and map_ab_b = {-1,-1,1}
std::pair<std::vector<int64_t>, std::vector<int64_t>> ConstructFromDotMaps(
const HloInstruction* dot, const Shape& a_shape, const Shape& b_shape) {
// Reserve space for new maps
std::vector<int64_t> map_ab_a(dot->shape().rank(), -1),
map_ab_b(dot->shape().rank(), -1);
// Construct the maps going in the opposite direction
std::vector<int64_t> map_a_ab, map_b_ab;
std::tie(map_a_ab, map_b_ab) =
ConstructToDotMaps(dot->dot_dimension_numbers(), a_shape, b_shape);
// Construct these maps by inverting those above
int64_t a_index = 0;
for (auto ab_index : map_a_ab) {
if (ab_index != -1) {
map_ab_a[ab_index] = a_index;
}
a_index++;
}
int64_t b_index = 0;
for (auto ab_index : map_b_ab) {
if (ab_index != -1) {
map_ab_b[ab_index] = b_index;
}
b_index++;
}
return {map_ab_a, map_ab_b};
}
bool DotHasOnlyBatchAndContractingOnOneOperand(
int64_t lhs_rank, int64_t rhs_rank, const DotDimensionNumbers dnums) {
return (dnums.lhs_batch_dimensions_size() +
dnums.lhs_contracting_dimensions_size() ==
lhs_rank) ||
(dnums.rhs_contracting_dimensions_size() +
dnums.rhs_batch_dimensions_size() ==
rhs_rank);
}
// Estimates the number of flops a reduce requires
int64_t GetReduceFlops(const HloInstruction* reduce) {
int64_t reduce_product = 1;
for (int64_t dim : reduce->dimensions()) {
reduce_product *= reduce->operand(0)->shape().dimensions(dim);
}
// Reduce along a dimension of size n requires n-1 reductions
return ShapeUtil::ElementsIn(reduce->shape()) * (reduce_product - 1);
}
} // namespace
void AlgebraicSimplifierVisitor::ResetState(HloComputation* computation) {
ResetVisitStates();
computation_ = computation;
}
bool AlgebraicSimplifierVisitor::Run(HloComputation* computation,
const AlgebraicSimplifierOptions& options,
AlgebraicSimplifier* simplifier) {
ResetState(computation);
TF_CHECK_OK(computation->Accept(this));
return changed();
}
bool AlgebraicSimplifierVisitor::SameShape(const HloInstruction* lhs,
const HloInstruction* rhs) const {
return SameShape(lhs->shape(), rhs->shape());
}
bool AlgebraicSimplifierVisitor::SameShape(const Shape& lhs,
const Shape& rhs) const {
if (options_.is_layout_sensitive()) {
return ShapeUtil::Equal(lhs, rhs);
} else {
return ShapeUtil::Compatible(lhs, rhs);
}
}
namespace {
bool IsOpCodeMultiplyCommutative(HloOpcode opcode) {
switch (opcode) {
case HloOpcode::kMultiply:
case HloOpcode::kTranspose:
case HloOpcode::kReshape:
case HloOpcode::kSelect:
return true;
default:
return false;
}
}
std::unique_ptr<HloInstruction> MakeScalarInstruction(HloInstruction* target,
float multiplier) {
return primitive_util::PrimitiveTypeSwitch<std::unique_ptr<HloInstruction>>(
[&](auto primitive_type_constant) -> std::unique_ptr<HloInstruction> {
if constexpr (primitive_util::IsFloatingPointType(
primitive_type_constant)) {
using NativeT = NativeTypeOf<primitive_type_constant>;
return HloInstruction::CreateConstant(
LiteralUtil::CreateR0<NativeT>(static_cast<NativeT>(multiplier)));
}
LOG(FATAL) << "Unsupported data type: "
<< target->shape().element_type();
},
target->shape().element_type());
}
} // namespace
absl::Status AlgebraicSimplifierVisitor::ScalarMultiplyReduction(
HloInstruction* dot) {
// We only process bfloat16 and float32 for now.
if (dot->shape().element_type() != BF16 &&
dot->shape().element_type() != F32) {
return absl::OkStatus();
}
auto lhs = dot->mutable_operand(0);
auto rhs = dot->mutable_operand(1);
const int64_t dot_size = ShapeUtil::ElementsIn(dot->shape());
const int64_t lhs_size = ShapeUtil::ElementsIn(lhs->shape());
const int64_t rhs_size = ShapeUtil::ElementsIn(rhs->shape());
HloInstruction* target = nullptr;
// (current node, user, operand_index)
std::vector<std::tuple<HloInstruction*, HloInstruction*, int64_t>> operands;
std::vector<HloInstruction*> users;
// Find which side of dot has the smallest size:
// operand 0, operand 1, or output.
if (dot_size <= std::min(lhs_size, rhs_size)) {
target = dot;
if (dot_size < lhs_size) {
operands.emplace_back(lhs, dot, 0);
}
if (dot_size < rhs_size) {
operands.emplace_back(rhs, dot, 1);
}
} else if (lhs_size <= rhs_size) {
target = lhs;
if (lhs_size < rhs_size) {
operands.emplace_back(rhs, dot, 1);
}
if (lhs_size < dot_size && dot->user_count() == 1) {
users.push_back(dot->users().front());
}
} else {
target = rhs;
if (rhs_size < lhs_size) {
operands.emplace_back(lhs, dot, 0);
}
if (rhs_size < dot_size && dot->user_count() == 1) {
users.push_back(dot->users().front());
}
}
std::vector<float> values;
// DFS to find scalar multiply ops from the operands.
while (!operands.empty()) {
HloInstruction* inst;
HloInstruction* user;
int64_t index;
std::tie(inst, user, index) = operands.back();
operands.pop_back();
// Skip the op types that are not commutative with multiply.
if (!IsOpCodeMultiplyCommutative(inst->opcode())) {
continue;
}
HloInstruction* operand;
HloInstruction* multiplier;
// Pattern match a scalar multiply.
if (Match(inst, m::MultiplyAnyOrder(
m::Op(&operand),
m::Broadcast(m::ConstantScalar(&multiplier))))) {
CHECK_LT(index, user->operand_count());
CHECK_EQ(inst, user->operands()[index]);
// When found a scalar multiply, save its scalar value.
values.push_back(*GetConstantValue(multiplier));
// And remove the scalar multiply op.
TF_RETURN_IF_ERROR(user->ReplaceOperandWith(index, operand));
inst = operand;
}
// Push the operands of inst.
int64_t i = 0;
for (auto* operand : inst->operands()) {
operands.emplace_back(operand, inst, i++);
}
}
// DFS to find scalar multiply ops from the users.
while (!users.empty()) {
auto inst = users.back();
users.pop_back();
if (!IsOpCodeMultiplyCommutative(inst->opcode())) {
continue;
}
HloInstruction* operand;
HloInstruction* multiplier;
if (Match(inst, m::MultiplyAnyOrder(
m::Op(&operand),
m::Broadcast(m::ConstantScalar(&multiplier))))) {
values.push_back(*GetConstantValue(multiplier));
TF_RETURN_IF_ERROR(inst->ReplaceAllUsesWith(operand));
inst = operand;
}
// Process the instructions with only one user.
// Otherwise moving scalar multiply to the operands changes the values of
// other users.
if (inst->user_count() == 1) {
users.push_back(inst->users().front());
}
}
if (values.empty()) {
return absl::OkStatus();
}
MarkAsChanged();
// Combine all constant multipliers.
float multiplier = 1.0;
for (const float v : values) {
multiplier *= v;
}
// Create a new const scalar multiply instruction.
HloInstruction* new_const_inst;
new_const_inst =
target->AddInstruction(MakeScalarInstruction(target, multiplier));
// Broadcast the scalar multiplier.
HloInstruction* new_broadcast = target->AddInstruction(
HloInstruction::CreateBroadcast(target->shape(), new_const_inst, {}));
// Create a new scalar multiply instruction.
HloInstruction* new_multiply =
target->AddInstruction(HloInstruction::CreateBinary(
target->shape(), HloOpcode::kMultiply, target, new_broadcast));
CHECK_EQ(new_multiply->shape(), target->shape());
// Update the dependency with the rest of the instructions.
if (target == lhs) {
return dot->ReplaceOperandWith(0, new_multiply);
} else if (target == rhs) {
return dot->ReplaceOperandWith(1, new_multiply);
} else {
CHECK_EQ(target, dot);
return dot->ReplaceAllUsesWith(new_multiply);
}
}
void AlgebraicSimplifierVisitor::ReplaceWithBitcast(HloInstruction* instruction,
HloInstruction* operand) {
CHECK_EQ(1, instruction->operand_count());
if (operand == nullptr) {
operand = instruction->mutable_operand(0);
}
CHECK_EQ(ShapeUtil::ElementsIn(instruction->shape()),
ShapeUtil::ElementsIn(operand->shape()));
CHECK_EQ(ShapeUtil::ByteSizeOf(instruction->shape()),
ShapeUtil::ByteSizeOf(operand->shape()));
auto bitcast = instruction->AddInstruction(
HloInstruction::CreateBitcast(instruction->shape(), operand));
TF_CHECK_OK(ReplaceInstruction(instruction, bitcast));
}
// Replace the old instruction with the new one if they are compatible, i.e.,
// 1. they have same shape
// 2. the replacement will not cause loss of sharding
bool AlgebraicSimplifierVisitor::ReplaceInstructionIfCompatible(
HloInstruction* old_instruction, HloInstruction* new_instruction) {
// It's tricky for the simplifier to determine whether
// it should remove the op when control deps are present. I.e.
// control deps might be added to preserve a certain order.
// It's better to not process in that case.
if (!old_instruction->control_predecessors().empty()) {
VLOG(3) << old_instruction->ToString()
<< " has control predecessors, skipping.";
return false;
}
if (!SameShape(old_instruction, new_instruction)) {
return false;
}
return ReplaceInstruction(old_instruction, new_instruction,
/*preserve_sharding=*/true)
.value();
}
bool AlgebraicSimplifierVisitor::ReplaceInstructionIfCompatible(
HloInstruction* old_instruction,
absl::Span<HloInstruction* const> new_instructions) {
// It's tricky for the simplifier to determine whether
// it should remove the op when control deps are present. I.e.
// control deps might be added to preserve a certain order.
// It's better to not process in that case.
if (!old_instruction->control_predecessors().empty()) {
VLOG(3) << old_instruction->ToString()
<< " has control predecessors, skipping.";
return false;
}
if (new_instructions.size() == 1) {
return ReplaceInstructionIfCompatible(old_instruction, new_instructions[0]);
}
CHECK(!new_instructions.empty());
if (!old_instruction->shape().IsTuple() ||
old_instruction->shape().tuple_shapes_size() != new_instructions.size()) {
return false;
}
for (int i = 0, n = new_instructions.size(); i < n; ++i) {
if (!SameShape(old_instruction->shape().tuple_shapes(i),
new_instructions[i]->shape())) {
return false;
}
}
return ReplaceInstruction(old_instruction, MaybeMakeTuple(new_instructions),
/*preserve_sharding=*/true)
.value();
}
absl::Status AlgebraicSimplifierVisitor::HandleAbs(HloInstruction* abs) {
HloInstruction* abs_operand = abs->mutable_operand(0);
VLOG(10) << "trying transform [Abs(A) => A] " << abs->ToString()
<< " Abs operand is: " << abs_operand->ToString();
if (IsNonNegative(abs->operand(0), options_)) {
return ReplaceInstruction(abs, abs_operand);
}
return absl::OkStatus();
}
absl::Status AlgebraicSimplifierVisitor::HandleAdd(HloInstruction* add) {
HloInstruction *lhs, *rhs;
CHECK(Match(add, m::Add(m::Op(&lhs), m::Op(&rhs))));
// A + 0 => A
VLOG(10) << "trying transform [A + 0 => A]: " << add->ToString();
if (IsAll(rhs, 0) && ReplaceInstructionIfCompatible(add, lhs)) {
return absl::OkStatus();
}
// 0 + A => A
VLOG(10) << "trying transform [0 + A => A]: " << add->ToString();
if (IsAll(lhs, 0) && ReplaceInstructionIfCompatible(add, rhs)) {
return absl::OkStatus();
}
// Canonicalization: Put constants on the right. This makes the reassociation
// rules below simpler.
VLOG(10) << "trying transform [Const + A => A + Const]";
if (Match(add, m::Add(m::Constant(), m::NonConstant()))) {
return ReplaceWithNewInstruction(
add,
HloInstruction::CreateBinary(add->shape(), HloOpcode::kAdd, rhs, lhs));
}
// Reassociate to allow constant folding.
//
// Note: This is not general. For example, we won't reassociate
//
// (A + C1) + (B + C2) => A + B + (C1 + C2).
//
VLOG(10) << "trying transform [(A + C1) + C2 => A + (C1 + C2)]";
HloInstruction *a, *c1, *c2;
if (Match(add, m::Add(m::Add(m::NonConstant(&a), m::Constant(&c1)),
m::Constant(&c2))) ||
Match(add, m::Add(m::Add(m::NonConstant(&a),
m::Broadcast(m::ConstantScalar(&c1))),
m::Broadcast(m::ConstantScalar(&c2))))) {
TF_ASSIGN_OR_RETURN(auto* sum_of_constants,
MakeBinaryHlo(HloOpcode::kAdd, c1, c2));
if (ShapeUtil::IsScalar(sum_of_constants->shape()) &&
!ShapeUtil::IsScalar(add->shape())) {
sum_of_constants = add->AddInstruction(
HloInstruction::CreateBroadcast(add->shape(), sum_of_constants, {}));
}
return ReplaceWithNewInstruction(
add, HloInstruction::CreateBinary(add->shape(), HloOpcode::kAdd, a,
sum_of_constants));
}
VLOG(10) << "trying transform [(C1 - A) + C2 => (C1 + C2) - A]";
if (Match(add, m::Add(m::Subtract(m::Constant(&c1), m::NonConstant(&a)),
m::Constant(&c2))) ||
Match(add, m::Add(m::Subtract(m::Broadcast(m::ConstantScalar(&c1)),
m::NonConstant(&a)),
m::Broadcast(m::ConstantScalar(&c2))))) {
TF_ASSIGN_OR_RETURN(HloInstruction * sum_of_constants,
MakeBinaryHlo(HloOpcode::kAdd, c1, c2));
if (ShapeUtil::IsScalar(sum_of_constants->shape()) &&
!ShapeUtil::IsScalar(add->shape())) {
sum_of_constants = add->AddInstruction(
HloInstruction::CreateBroadcast(add->shape(), sum_of_constants, {}));
}
return ReplaceWithNewInstruction(
add, HloInstruction::CreateBinary(add->shape(), HloOpcode::kSubtract,
sum_of_constants, a));
}
// Convert add with fullshape into add with partial shape when a
// portion of add is effective:
// zero (fullshape) rhs (partialshape)
// . | |
// . lhs . dynamic_update_slice (fullshape)
// . | |
// Add (fullshape)
//
// to:
// lhs
// |
// dynamic_slice (partialshape) rhs (partialshape)
// . | |
// . lhs . add (partial_shape)+----+
// . | |
// dynamic_update_slice (fullshape)
//
// This is pattern is discovered in control flow V2 gradient update.
if (Match(add,
m::AddAnyOrder(
m::Op(&lhs),
m::Op(&rhs)
.WithOpcode(HloOpcode::kDynamicUpdateSlice)
.WithOperand(
0, m::Broadcast(m::ConstantEffectiveScalar(0)))))) {
const Shape& partial_shape = rhs->operand(1)->shape();
auto sliced_lhs = lhs->AddInstruction(HloInstruction::CreateDynamicSlice(
partial_shape, lhs, absl::MakeSpan(rhs->operands()).subspan(2),
partial_shape.dimensions()));
auto add_partial = rhs->AddInstruction(
HloInstruction::CreateBinary(rhs->operand(1)->shape(), HloOpcode::kAdd,
sliced_lhs, rhs->mutable_operand(1)));
auto dynamic_update_slice_full = HloInstruction::CreateDynamicUpdateSlice(
lhs->shape(), lhs, add_partial,
absl::MakeSpan(rhs->operands()).subspan(2));
return ReplaceWithNewInstruction(add, std::move(dynamic_update_slice_full));
}
// A*C + B*C => (A+B)*C
//
// - If A, B, and C are integers, do this unconditionally. Proof of
// correctness: https://rise4fun.com/Alive/u9X.
//
// - If A, B, and C are floating point, do this if C is a scalar constant or
// broadcast of scalar constant and is equal to +/- 2^k for some (possibly
// negative) integer k.
//
// Multiplying by a power of 2 just moves the exponent, so our answer is
// exact modulo rounding of intermediate results so long as
//
// - none of the three products has an exponent which underflows (so the
// result is 0 or denormal), and
// - none of the three products overflows to inf.
//
// Proof: See algebraic_simplifier_proof_distributive_property.py.
//
// We deem these differences in rounding, underflow, and overflow
// acceptable in the ML context.
//
// Furthermore, if `enable_floats_are_real` is true, the simplification is
// done nonetheless. This might cause numerical differences even if there
// is no underflow or overflow.
HloInstruction *b, *c;
if (((Match(lhs, m::Multiply(m::Op(&a), m::Op(&c))) &&
Match(rhs, m::MultiplyAnyOrder(m::Op().Is(c), m::Op(&b)))) ||
(Match(lhs, m::Multiply(m::Op(&c), m::Op(&a))) &&
Match(rhs, m::MultiplyAnyOrder(m::Op().Is(c), m::Op(&b))))) &&
// Make sure we would decrease the number of multiplies.
(lhs->user_count() == 1 && rhs->user_count() == 1) &&
(ShapeUtil::ElementIsIntegral(add->shape()) ||
options_.enable_floats_are_real() || IsAllFpConstantPowerOf2(c))) {
return ReplaceWithNewInstruction(
add, HloInstruction::CreateBinary(
add->shape(), HloOpcode::kMultiply,
lhs->AddInstruction(HloInstruction::CreateBinary(
add->shape(), HloOpcode::kAdd, a, b)),
c));
}
if (options_.is_layout_sensitive()) {
return absl::OkStatus();
}
HloInstruction* lhs_scatter_operand = nullptr;
HloInstruction* rhs_scatter_operand = nullptr;
HloInstruction* lhs_scatter_update = nullptr;
HloInstruction* rhs_scatter_update = nullptr;
HloInstruction* lhs_scatter_index = nullptr;
HloInstruction* rhs_scatter_index = nullptr;
bool lhs_scatter = Match(lhs, m::Scatter(m::Op(&lhs_scatter_operand),
m::Op(&lhs_scatter_index),
m::Op(&lhs_scatter_update))
.WithOneUse()) &&
Match(lhs->to_apply()->root_instruction(),
m::Add(m::Parameter(), m::Parameter()));
bool rhs_scatter = Match(rhs, m::Scatter(m::Op(&rhs_scatter_operand),
m::Op(&rhs_scatter_index),
m::Op(&rhs_scatter_update))
.WithOneUse()) &&
Match(rhs->to_apply()->root_instruction(),
m::Add(m::Parameter(), m::Parameter()));
if (rhs_scatter && lhs_scatter) {
const auto& lhs_dnums = lhs->scatter_dimension_numbers();
const auto& rhs_dnums = rhs->scatter_dimension_numbers();
std::optional<int64_t> index_concat_dimension;
std::optional<int64_t> update_concat_dimension;
// Don't try to combine scatters of different ranks.
if (lhs_scatter_index->shape().rank() !=
rhs_scatter_index->shape().rank()) {
return absl::OkStatus();
}
int64_t first_index_dim = lhs_scatter_index->shape().rank();
int64_t first_update_dim = lhs_scatter_update->shape().rank();
// Find a dimension where it is possible to concatenate the indices and
// updates. This is the first and only non-equal dimension or the first
// equally sized dimension.
for (int64_t d = lhs_scatter_index->shape().rank() - 1,
update_dim = lhs_scatter_update->shape().rank() - 1;
d >= 0; --d) {
if (d == lhs_dnums.index_vector_dim()) {
continue;
}
while (
absl::c_linear_search(lhs_dnums.update_window_dims(), update_dim)) {
--update_dim;
}
if (lhs_scatter_index->shape().dimensions(d) ==
rhs_scatter_index->shape().dimensions(d)) {
first_index_dim = d;
first_update_dim = update_dim--;
continue;
}
// More than one dimension of unequal size was found, bail out.
if (index_concat_dimension) {
return absl::OkStatus();
}
index_concat_dimension = d;
update_concat_dimension = update_dim--;
}
if (!index_concat_dimension) {
index_concat_dimension = first_index_dim;
update_concat_dimension = first_update_dim;
}