/
xla_builder.cc
5867 lines (5279 loc) · 243 KB
/
xla_builder.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 2018 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/client/xla_builder.h"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <set>
#include <string>
#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/functional/function_ref.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/array.h"
#include "xla/client/padding.h"
#include "xla/client/sharding_builder.h"
#include "xla/client/xla_computation.h"
#include "xla/comparison_util.h"
#include "xla/hlo/ir/hlo_input_output_alias_config.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/ir/hlo_sharding.h"
#include "xla/layout.h"
#include "xla/layout_util.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/permutation_util.h"
#include "xla/primitive_util.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/shape_inference.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/sharding_op_util.h"
#include "xla/status.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/stacktrace.h"
#include "tsl/platform/statusor.h"
namespace xla {
using absl::StrCat;
namespace {
static const char kNameSeparator = '.';
// Retrieves the base name of an instruction or computation fully qualified
// name, using separator as boundary between the initial base name part, and
// the numeric identification.
std::string GetBaseName(const std::string& name, char separator) {
auto pos = name.rfind(separator);
CHECK_NE(pos, std::string::npos) << name;
return name.substr(0, pos);
}
// Generates a fully qualified computation/instruction name.
std::string GetFullName(const std::string& base_name, char separator,
int64_t id) {
const char separator_str[] = {separator, '\0'};
return StrCat(base_name, separator_str, id);
}
// Common function to standardize setting name and IDs on computation and
// instruction proto entities.
template <typename T>
void SetProtoIdAndName(T* entry, const std::string& base_name, char separator,
int64_t id) {
entry->set_id(id);
entry->set_name(GetFullName(base_name, separator, id));
}
bool InstrIsSetBound(const HloInstructionProto* instr_proto) {
HloOpcode opcode = StringToHloOpcode(instr_proto->opcode()).value();
if (opcode == HloOpcode::kCustomCall &&
instr_proto->custom_call_target() == "SetBound") {
return true;
}
return false;
}
Status NormalizeAndAssignSharing(HloInstructionProto* instr,
const OpSharding& op_sharding) {
// Normalize tuple sharding and fail the call if the sharding is invalid.
Shape shape(instr->shape());
TF_ASSIGN_OR_RETURN(HloSharding sharding,
HloSharding::FromProto(op_sharding));
sharding = sharding.NormalizeTupleSharding(shape);
TF_RETURN_IF_ERROR(sharding.Validate(shape));
*instr->mutable_sharding() = sharding.ToProto();
return OkStatus();
}
} // namespace
namespace internal {
XlaOp XlaBuilderFriend::BuildAddDependency(XlaBuilder* builder, XlaOp operand,
XlaOp token, const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kAddDependency,
{operand, token});
});
}
XlaOp XlaBuilderFriend::BuildFusion(
XlaBuilder* builder, absl::Span<const XlaOp> operands,
absl::string_view fusion_kind, const XlaComputation& fused_computation,
absl::Span<const std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>
output_operand_aliasing) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
instr.set_fusion_kind(std::string(fusion_kind));
if (!output_operand_aliasing.empty()) {
for (const auto& pair : output_operand_aliasing) {
auto aliasing = instr.add_output_operand_aliasing();
aliasing->set_operand_index(pair.second.first);
for (int64_t index : pair.second.second) {
aliasing->add_operand_shape_index(index);
}
for (int64_t index : pair.first) {
aliasing->add_output_shape_index(index);
}
}
}
std::vector<const Shape*> operand_shape_ptrs;
TF_ASSIGN_OR_RETURN(auto program_shape,
fused_computation.GetProgramShape());
*instr.mutable_shape() = program_shape.result().ToProto();
builder->AddCalledComputation(fused_computation, &instr);
return builder->AddInstruction(std::move(instr), HloOpcode::kFusion,
operands);
});
}
std::pair<XlaOp, int64_t> XlaBuilderFriend::BuildAsyncStart(
XlaBuilder* builder, absl::Span<const XlaOp> operands,
std::string execution_thread, const XlaComputation& called_computation,
const Shape& shape) {
int64_t called_computation_id;
auto start_op = builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
instr.set_async_execution_thread(execution_thread);
builder->AddCalledComputation(called_computation, &instr);
called_computation_id = instr.called_computation_ids()[0];
return builder->AddInstruction(std::move(instr), HloOpcode::kAsyncStart,
operands);
});
return {start_op, called_computation_id};
}
XlaOp XlaBuilderFriend::BuildAsyncUpdate(XlaBuilder* builder,
const XlaOp operand,
std::string execution_thread,
int64_t called_computation,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
instr.set_async_execution_thread(execution_thread);
instr.add_called_computation_ids(called_computation);
return builder->AddInstruction(std::move(instr), HloOpcode::kAsyncUpdate,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildAsyncDone(XlaBuilder* builder, const XlaOp operand,
std::string execution_thread,
int64_t called_computation,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
instr.set_async_execution_thread(execution_thread);
instr.add_called_computation_ids(called_computation);
return builder->AddInstruction(std::move(instr), HloOpcode::kAsyncDone,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildAllGatherStart(
XlaBuilder* builder, const XlaOp operand, int64_t all_gather_dimension,
int64_t shard_count, absl::Span<const ReplicaGroup> replica_groups,
const std::optional<ChannelHandle>& channel_id,
const std::optional<Layout>& layout,
const std::optional<bool> use_global_device_ids) {
return builder->AllGatherImpl(operand, all_gather_dimension, shard_count,
replica_groups, channel_id, layout,
use_global_device_ids, /*async=*/true);
}
XlaOp XlaBuilderFriend::BuildAllGatherDone(XlaBuilder* builder,
const XlaOp operand,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kAllGatherDone,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildAllReduceStart(
XlaBuilder* builder, XlaOp operand, const XlaComputation& computation,
absl::Span<const ReplicaGroup> replica_groups,
const std::optional<ChannelHandle>& channel_id,
const std::optional<Shape>& layout,
const std::optional<bool> use_global_device_ids) {
return builder->AllReduceImpl(operand, computation, replica_groups,
channel_id, layout, use_global_device_ids,
/*async=*/true);
}
XlaOp XlaBuilderFriend::BuildAllReduceDone(XlaBuilder* builder,
const XlaOp operand,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kAllReduceDone,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildCopyStart(
XlaBuilder* builder, const XlaOp operand,
std::optional<int> cross_program_prefetch_index) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
if (cross_program_prefetch_index) {
instr.set_cross_program_prefetch_index(*cross_program_prefetch_index);
}
TF_ASSIGN_OR_RETURN(const Shape* operand_shape,
builder->GetShapePtr(operand));
Shape u32 = ShapeUtil::MakeScalarShape(PrimitiveType::U32);
Shape shape =
ShapeUtil::MakeTupleShapeWithPtrs({operand_shape, operand_shape, &u32});
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kCopyStart,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildCopyDone(XlaBuilder* builder, const XlaOp operand,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kCopyDone,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildCollectivePermuteStart(
XlaBuilder* builder, XlaOp operand,
const std::vector<std::pair<int64_t, int64_t>>& source_target_pairs,
const std::optional<ChannelHandle>& channel_id) {
return builder->CollectivePermuteImpl(operand, source_target_pairs,
channel_id, /*async=*/true);
}
XlaOp XlaBuilderFriend::BuildCollectivePermuteDone(XlaBuilder* builder,
const XlaOp operand,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(
std::move(instr), HloOpcode::kCollectivePermuteDone, {operand});
});
}
XlaOp XlaBuilderFriend::BuildBitcast(XlaBuilder* builder, XlaOp operand,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kBitcast,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildDomain(XlaBuilder* builder, XlaOp operand,
const OpSharding entry,
const OpSharding exit, const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_domain_entry_sharding() = entry;
*instr.mutable_domain_exit_sharding() = exit;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kDomain,
{operand});
});
}
XlaOp XlaBuilderFriend::BuildPartitionId(XlaBuilder* builder,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr), HloOpcode::kPartitionId);
});
}
XlaOp XlaBuilderFriend::BuildSend(XlaBuilder* builder, XlaOp operand,
XlaOp token, const ChannelHandle& handle,
bool is_host_transfer) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto send_instr;
TF_ASSIGN_OR_RETURN(const Shape* shape, builder->GetShapePtr(operand));
// Send instruction produces a tuple of {aliased operand, U32 context,
// token}.
*send_instr.mutable_shape() =
ShapeUtil::MakeTupleShape({*shape, ShapeUtil::MakeShape(U32, {}),
ShapeUtil::MakeTokenShape()})
.ToProto();
send_instr.set_channel_id(handle.handle());
send_instr.set_is_host_transfer(is_host_transfer);
return builder->AddInstruction(std::move(send_instr), HloOpcode::kSend,
{operand, token});
});
}
XlaOp XlaBuilderFriend::BuildSendDone(XlaBuilder* builder, XlaOp operand,
const ChannelHandle& handle,
bool is_host_transfer) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto send_done_instr;
*send_done_instr.mutable_shape() = ShapeUtil::MakeTokenShape().ToProto();
send_done_instr.set_channel_id(handle.handle());
send_done_instr.set_is_host_transfer(is_host_transfer);
return builder->AddInstruction(std::move(send_done_instr),
HloOpcode::kSendDone, {operand});
});
}
XlaOp XlaBuilderFriend::BuildRecv(XlaBuilder* builder, XlaOp token,
const Shape& shape,
const ChannelHandle& handle,
bool is_host_transfer) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
// Recv instruction produces a tuple of {receive buffer, U32 context,
// token}.
HloInstructionProto recv_instr;
*recv_instr.mutable_shape() =
ShapeUtil::MakeTupleShape(
{shape, ShapeUtil::MakeShape(U32, {}), ShapeUtil::MakeTokenShape()})
.ToProto();
recv_instr.set_channel_id(handle.handle());
recv_instr.set_is_host_transfer(is_host_transfer);
return builder->AddInstruction(std::move(recv_instr), HloOpcode::kRecv,
{token});
});
}
XlaOp XlaBuilderFriend::BuildRecvDone(XlaBuilder* builder, XlaOp token,
const Shape& shape,
const ChannelHandle& handle,
bool is_host_transfer) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto recv_done_instr;
*recv_done_instr.mutable_shape() =
ShapeUtil::MakeTupleShape({shape, ShapeUtil::MakeTokenShape()})
.ToProto();
recv_done_instr.set_channel_id(handle.handle());
recv_done_instr.set_is_host_transfer(is_host_transfer);
return builder->AddInstruction(std::move(recv_done_instr),
HloOpcode::kRecvDone, {token});
});
}
XlaOp XlaBuilderFriend::BuildRngGetAndUpdateState(XlaBuilder* builder,
int64_t delta,
const Shape& shape) {
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
HloInstructionProto instr;
instr.set_delta(delta);
*instr.mutable_shape() = shape.ToProto();
return builder->AddInstruction(std::move(instr),
HloOpcode::kRngGetAndUpdateState);
});
}
HloInstructionProto* XlaBuilderFriend::GetInstruction(XlaOp op) {
return &op.builder()
->instructions_[op.builder()->handle_to_index_[op.handle_]];
}
HloInstructionProto* XlaBuilderFriend::GetInstructionByHandle(
XlaBuilder* builder, int64_t handle) {
return &builder->instructions_[builder->handle_to_index_[handle]];
}
} // namespace internal
XlaOp operator-(XlaOp x) { return Neg(x); }
XlaOp operator+(XlaOp x, XlaOp y) { return Add(x, y); }
XlaOp operator-(XlaOp x, XlaOp y) { return Sub(x, y); }
XlaOp operator*(XlaOp x, XlaOp y) { return Mul(x, y); }
XlaOp operator/(XlaOp x, XlaOp y) { return Div(x, y); }
XlaOp operator%(XlaOp x, XlaOp y) { return Rem(x, y); }
XlaOp operator~(XlaOp x) { return Not(x); }
XlaOp operator&(XlaOp x, XlaOp y) { return And(x, y); }
XlaOp operator|(XlaOp x, XlaOp y) { return Or(x, y); }
XlaOp operator^(XlaOp x, XlaOp y) { return Xor(x, y); }
XlaOp operator<<(XlaOp x, XlaOp y) { return ShiftLeft(x, y); }
XlaOp operator>>(XlaOp x, XlaOp y) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(const Shape* shape, builder->GetShapePtr(x));
if (!ShapeUtil::ElementIsIntegral(*shape)) {
return InvalidArgument(
"Argument to >> operator does not have an integral type (%s).",
ShapeUtil::HumanString(*shape));
}
if (ShapeUtil::ElementIsSigned(*shape)) {
return ShiftRightArithmetic(x, y);
} else {
return ShiftRightLogical(x, y);
}
});
}
absl::StatusOr<const Shape*> XlaBuilder::GetShapePtr(XlaOp op) const {
TF_RETURN_IF_ERROR(first_error_);
TF_RETURN_IF_ERROR(CheckOpBuilder(op));
auto it = handle_to_index_.find(op.handle());
if (it == handle_to_index_.end()) {
return InvalidArgument("No XlaOp with handle %d", op.handle());
}
return instruction_shapes_.at(it->second).get();
}
absl::StatusOr<Shape> XlaBuilder::GetShape(XlaOp op) const {
TF_ASSIGN_OR_RETURN(const Shape* shape, GetShapePtr(op));
return *shape;
}
absl::StatusOr<std::vector<Shape>> XlaBuilder::GetOperandShapes(
absl::Span<const XlaOp> operands) const {
std::vector<Shape> operand_shapes;
operand_shapes.reserve(operands.size());
for (XlaOp operand : operands) {
TF_ASSIGN_OR_RETURN(const Shape* shape, GetShapePtr(operand));
operand_shapes.push_back(*shape);
}
return operand_shapes;
}
absl::StatusOr<std::optional<OpSharding>> XlaBuilder::GetOpSharding(
XlaOp op) const {
TF_ASSIGN_OR_RETURN(auto instr_proto, LookUpInstruction(op));
if (instr_proto->has_sharding()) {
return instr_proto->sharding();
}
return std::nullopt;
}
std::string XlaBuilder::OpToString(XlaOp op) const {
std::string s;
ToStringHelper(&s, /*ident=*/0, op.handle());
return s;
}
static std::string ShapeToString(const ShapeProto& shape) {
if (shape.tuple_shapes_size() > 1) {
return absl::StrCat(
"(",
absl::StrJoin(shape.tuple_shapes(), ", ",
[&](std::string* s, const ShapeProto& subshape) {
absl::StrAppend(s, ShapeToString(subshape));
}),
")");
}
return absl::StrCat("[", absl::StrJoin(shape.dimensions(), ", "), "]");
}
void XlaBuilder::ToStringHelper(std::string* out, int ident,
int64_t op_handle) const {
const HloInstructionProto& instr =
*(LookUpInstructionByHandle(op_handle).value());
absl::StrAppend(out, std::string(ident, ' '), instr.opcode(),
", shape=", ShapeToString(instr.shape()));
if (instr.has_metadata()) {
absl::StrAppend(out, ", metadata={", instr.metadata().source_file(), ":",
instr.metadata().source_line(), "}");
}
if (instr.operand_ids_size()) {
absl::StrAppend(out, "\n");
}
absl::StrAppend(out, absl::StrJoin(instr.operand_ids(), "\n",
[&](std::string* s, int64_t subop) {
ToStringHelper(s, ident + 2, subop);
}));
}
XlaBuilder::XlaBuilder(const std::string& computation_name)
: name_(computation_name) {}
XlaBuilder::~XlaBuilder() = default;
XlaOp XlaBuilder::ReportError(const Status& error) {
CHECK(!error.ok());
if (die_immediately_on_error_) {
LOG(FATAL) << "error building computation: " << error;
}
if (first_error_.ok()) {
first_error_ = error;
first_error_backtrace_.CreateCurrent(/*skip_count=*/1);
}
return XlaOp(this);
}
XlaOp XlaBuilder::ReportErrorOrReturn(const absl::StatusOr<XlaOp>& op) {
if (!first_error_.ok()) {
return XlaOp(this);
}
if (!op.ok()) {
return ReportError(op.status());
}
return op.value();
}
XlaOp XlaBuilder::ReportErrorOrReturn(
absl::FunctionRef<absl::StatusOr<XlaOp>()> op_creator) {
return ReportErrorOrReturn(op_creator());
}
absl::StatusOr<ProgramShape> XlaBuilder::GetProgramShape(
int64_t root_id) const {
TF_RETURN_IF_ERROR(first_error_);
TF_ASSIGN_OR_RETURN(const HloInstructionProto* root_proto,
LookUpInstructionByHandle(root_id));
ProgramShape program_shape;
*program_shape.mutable_result() = Shape(root_proto->shape());
// Check that the parameter numbers are continuous from 0, and add parameter
// shapes and names to the program shape.
const int64_t param_count = parameter_numbers_.size();
for (int64_t i = 0; i < param_count; i++) {
program_shape.add_parameters();
program_shape.add_parameter_names();
}
for (const HloInstructionProto& instr : instructions_) {
// Parameter number uniqueness is guaranteed in XlaBuilder::Parameter(). So
// to verify continuity, we just need to verify that every parameter is in
// the right range.
if (instr.opcode() == HloOpcodeString(HloOpcode::kParameter)) {
const int64_t index = instr.parameter_number();
TF_RET_CHECK(index >= 0 && index < param_count)
<< "invalid parameter number: " << index;
*program_shape.mutable_parameters(index) = Shape(instr.shape());
*program_shape.mutable_parameter_names(index) = instr.name();
}
}
return program_shape;
}
absl::StatusOr<ProgramShape> XlaBuilder::GetProgramShape() const {
TF_RET_CHECK(!instructions_.empty());
return GetProgramShape(instructions_.back().id());
}
absl::StatusOr<ProgramShape> XlaBuilder::GetProgramShape(XlaOp root) const {
if (root.builder_ != this) {
return InvalidArgument("Given root operation is not in this computation.");
}
return GetProgramShape(root.handle());
}
void XlaBuilder::IsConstantVisitor(const int64_t op_handle, int depth,
absl::flat_hash_set<int64_t>* visited,
bool* is_constant) const {
if (visited->contains(op_handle) || !*is_constant) {
return;
}
const HloInstructionProto& instr =
*(LookUpInstructionByHandle(op_handle).value());
HloInstructionProto to_print(instr);
to_print.clear_shape();
const HloOpcode opcode = StringToHloOpcode(instr.opcode()).value();
const std::string indent =
absl::StrJoin(std::vector<absl::string_view>(depth, " "), "");
if (VLOG_IS_ON(2)) {
VLOG(2) << indent << "Visiting:";
for (const auto& l : absl::StrSplit(to_print.DebugString(), '\n')) {
VLOG(2) << indent << l;
}
}
switch (opcode) {
default:
for (const int64_t operand_id : instr.operand_ids()) {
IsConstantVisitor(operand_id, depth + 1, visited, is_constant);
}
// TODO(b/32495713): We aren't checking the called computations.
break;
case HloOpcode::kGetDimensionSize:
// GetDimensionSize is always considered constant in XLA -- If a dynamic
// dimension is presented, -1 is returned.
break;
// Non functional ops.
case HloOpcode::kRng:
case HloOpcode::kAllReduce:
case HloOpcode::kReduceScatter:
// TODO(b/33009255): Implement constant folding for cross replica sum.
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
case HloOpcode::kCall:
// TODO(b/32495713): We aren't checking the to_apply computation itself,
// so we conservatively say that computations containing the Call op
// cannot be constant. We cannot set is_functional=false in other similar
// cases since we're already relying on IsConstant to return true.
case HloOpcode::kCustomCall:
if (instr.custom_call_target() == "SetBound") {
// Set bound is considered constant -- the bound is used as the value.
break;
}
[[fallthrough]];
case HloOpcode::kWhile:
// TODO(b/32495713): We aren't checking the condition and body
// computations themselves.
case HloOpcode::kScatter:
// TODO(b/32495713): We aren't checking the embedded computation in
// Scatter.
case HloOpcode::kSend:
case HloOpcode::kRecv:
case HloOpcode::kParameter:
*is_constant = false;
break;
case HloOpcode::kGetTupleElement: {
const HloInstructionProto& operand_instr =
*(LookUpInstructionByHandle(instr.operand_ids(0)).value());
if (HloOpcodeString(HloOpcode::kTuple) == operand_instr.opcode()) {
IsConstantVisitor(operand_instr.operand_ids(instr.tuple_index()),
depth + 1, visited, is_constant);
} else {
for (const int64_t operand_id : instr.operand_ids()) {
IsConstantVisitor(operand_id, depth + 1, visited, is_constant);
}
}
}
}
if (VLOG_IS_ON(1) && !*is_constant) {
VLOG(1) << indent << "Non-constant: ";
for (const auto& l : absl::StrSplit(to_print.DebugString(), '\n')) {
VLOG(1) << indent << l;
}
}
visited->insert(op_handle);
}
Status XlaBuilder::SetInstructionFrontendAttribute(const XlaOp op,
std::string attribute,
std::string value) {
TF_ASSIGN_OR_RETURN(auto instr_proto, LookUpMutableInstruction(op));
auto* frontend_attributes = instr_proto->mutable_frontend_attributes();
(*frontend_attributes->mutable_map())[attribute] = std::move(value);
return OkStatus();
}
Status XlaBuilder::SetInstructionSharding(
XlaOp op, const std::optional<OpSharding>& sharding) {
TF_ASSIGN_OR_RETURN(auto instr_proto, LookUpMutableInstruction(op));
if (!sharding.has_value()) {
instr_proto->clear_sharding();
return OkStatus();
}
return NormalizeAndAssignSharing(instr_proto, sharding.value());
}
XlaComputation XlaBuilder::BuildAndNoteError() {
DCHECK(parent_builder_ != nullptr);
auto build_status = Build();
if (!build_status.ok()) {
parent_builder_->ReportError(
AddStatus(build_status.status(), absl::StrCat("error from: ", name_)));
return {};
}
return std::move(build_status).value();
}
Status XlaBuilder::GetCurrentStatus() const {
if (!first_error_.ok()) {
std::string backtrace;
first_error_backtrace_.Dump(tsl::DebugWriteToString, &backtrace);
return AppendStatus(first_error_, backtrace);
}
return OkStatus();
}
absl::StatusOr<XlaComputation> XlaBuilder::Build(
bool remove_dynamic_dimensions) {
TF_RETURN_IF_ERROR(GetCurrentStatus());
return Build(instructions_.back().id(), remove_dynamic_dimensions);
}
absl::StatusOr<XlaComputation> XlaBuilder::Build(
XlaOp root, bool remove_dynamic_dimensions) {
if (root.builder_ != this) {
return InvalidArgument("Given root operation is not in this computation.");
}
return Build(root.handle(), remove_dynamic_dimensions);
}
absl::StatusOr<XlaComputation> XlaBuilder::Build(
int64_t root_id, bool remove_dynamic_dimensions) {
TF_RETURN_IF_ERROR(GetCurrentStatus());
// TODO(b/121223198): XLA backend cannot handle dynamic dimensions yet, remove
// all dynamic dimensions before building xla program until we have support in
// the backend.
if (remove_dynamic_dimensions) {
std::function<void(Shape*)> remove_dynamic_dimension = [&](Shape* shape) {
if (shape->tuple_shapes_size() != 0) {
for (int i = 0; i < shape->tuple_shapes_size(); ++i) {
remove_dynamic_dimension(shape->mutable_tuple_shapes(i));
}
}
for (int64_t i = 0; i < shape->dimensions_size(); ++i) {
shape->set_dynamic_dimension(i, false);
}
};
for (size_t index = 0; index < instructions_.size(); ++index) {
remove_dynamic_dimension(instruction_shapes_[index].get());
*instructions_[index].mutable_shape() =
instruction_shapes_[index]->ToProto();
}
}
HloComputationProto entry;
SetProtoIdAndName(&entry, name_, kNameSeparator, GetNextId());
TF_ASSIGN_OR_RETURN(ProgramShape program_shape, GetProgramShape(root_id));
*entry.mutable_program_shape() = program_shape.ToProto();
entry.set_root_id(root_id);
for (auto& instruction : instructions_) {
// Ensures that the instruction names are unique among the whole graph.
instruction.set_name(
GetFullName(instruction.name(), kNameSeparator, instruction.id()));
entry.add_instructions()->Swap(&instruction);
}
XlaComputation computation(entry.id());
HloModuleProto* module = computation.mutable_proto();
module->set_name(entry.name());
module->set_id(entry.id());
module->set_entry_computation_name(entry.name());
module->set_entry_computation_id(entry.id());
*module->mutable_host_program_shape() = entry.program_shape();
for (auto& e : embedded_) {
module->add_computations()->Swap(&e.second);
}
module->add_computations()->Swap(&entry);
if (!input_output_aliases_.empty() || !buffer_donors_.empty()) {
TF_RETURN_IF_ERROR(PopulateInputOutputAliasAndBufferDonor(
module, program_shape, input_output_aliases_, buffer_donors_));
}
// Clear data held by this builder.
this->instructions_.clear();
this->instruction_shapes_.clear();
this->handle_to_index_.clear();
this->embedded_.clear();
this->parameter_numbers_.clear();
return std::move(computation);
}
/* static */ Status XlaBuilder::PopulateInputOutputAliasAndBufferDonor(
HloModuleProto* module, const ProgramShape& program_shape,
const std::vector<InputOutputAlias>& input_output_aliases,
const absl::flat_hash_set<HloBufferDonorConfig::BufferDonor>&
buffer_donors) {
// Step 1: populate input output alias information.
HloInputOutputAliasConfig io_alias_config(program_shape.result());
for (auto& alias : input_output_aliases) {
// The HloInputOutputAliasConfig does not do parameter validation as it only
// carries the result shape. Maybe it should be constructed with a
// ProgramShape to allow full validation. We will still get an error when
// trying to compile the HLO module, but would be better to have validation
// at this stage.
if (alias.param_number >= program_shape.parameters_size()) {
return InvalidArgument("Invalid parameter number %ld (total %ld)",
alias.param_number,
program_shape.parameters_size());
}
const Shape& parameter_shape = program_shape.parameters(alias.param_number);
if (!ShapeUtil::IndexIsValid(parameter_shape, alias.param_index)) {
return InvalidArgument("Invalid parameter %ld index: %s",
alias.param_number,
alias.param_index.ToString().c_str());
}
TF_RETURN_IF_ERROR(io_alias_config.SetUpAlias(
alias.output_index, alias.param_number, alias.param_index, alias.kind));
}
*module->mutable_input_output_alias() = io_alias_config.ToProto();
// Step 2: populate buffer donor information.
HloBufferDonorConfig buffer_donor_config;
for (auto& donor : buffer_donors) {
if (donor.param_number >= program_shape.parameters_size()) {
return InvalidArgument("Invalid parameter number %ld (total %ld)",
donor.param_number,
program_shape.parameters_size());
}
const Shape& parameter_shape = program_shape.parameters(donor.param_number);
if (!ShapeUtil::IndexIsValid(parameter_shape, donor.param_index)) {
return InvalidArgument("Invalid parameter %ld index: %s",
donor.param_number,
donor.param_index.ToString().c_str());
}
if (io_alias_config.ParameterHasAlias(donor.param_number,
donor.param_index)) {
return InvalidArgument(
"Parameter %ld index %s is already aliased with one output, thus it "
"cannot be added as a buffer donor for any output.",
donor.param_number, donor.param_index.ToString().c_str());
}
TF_RETURN_IF_ERROR(buffer_donor_config.AddBufferDonor(donor.param_number,
donor.param_index));
}
*module->mutable_buffer_donor() = buffer_donor_config.ToProto();
return OkStatus();
}
XlaOp XlaBuilder::DynamicBroadcastInDim(
const XlaOp operand, const XlaOp output_dimensions,
absl::Span<const int64_t> broadcast_dimensions, const Shape& output_shape) {
return ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(const Shape* operand_shape, GetShapePtr(operand));
TF_ASSIGN_OR_RETURN(const Shape* output_dimensions_shape,
GetShapePtr(output_dimensions));
if (!output_dimensions_shape->IsInteger()) {
return InvalidArgument("output_dimensions must be an integer type %s",
output_dimensions_shape->ToString());
}
if (output_dimensions_shape->rank() != 1) {
return InvalidArgument("output_dimensions must be rank 1 but got rank %d",
output_dimensions_shape->rank());
}
int64_t operand_rank = operand_shape->rank();
int64_t result_rank = output_shape.rank();
int64_t broadcast_dimensions_size = broadcast_dimensions.size();
if (broadcast_dimensions_size != operand_rank) {
return InvalidArgument(
"broadcast_dimensions size (%d) does not match operand rank (%d)",
broadcast_dimensions_size, operand_rank);
}
if (result_rank < operand_rank) {
return InvalidArgument("result rank (%d) is less than operand rank (%d)",
result_rank, operand_rank);
}
for (int64_t i = 0; i != broadcast_dimensions_size; ++i) {
int64_t dim_index = broadcast_dimensions[i];
if (dim_index < 0 || dim_index >= result_rank) {
return InvalidArgument(
"broadcast_dimensions contains invalid value %d for result with "
"rank %d",
dim_index, result_rank);
}
int64_t dim_size = operand_shape->dimensions(i);
int64_t result_dim_size = output_shape.dimensions(dim_index);
if (dim_size != 1 && dim_size != result_dim_size &&
dim_size != Shape::kUnboundedSize) {
return InvalidArgument(
"size of operand dimension %d (%d) is not compatible with size of "
"result dimension %d (%d)",
i, dim_size, dim_index, result_dim_size);
}
}
return xla::CustomCall(
operand.builder(), "mhlo.dynamic_broadcast_in_dim",
/*operands=*/{operand, output_dimensions},
/*shape=*/output_shape,
/*opaque=*/
absl::StrCat("{broadcast_dimensions=[",
absl::StrJoin(broadcast_dimensions, ","), "]}"));
});
}
absl::StatusOr<XlaOp> XlaBuilder::InDimBroadcast(
const Shape& shape, XlaOp operand,
absl::Span<const int64_t> broadcast_dimensions) {
TF_RETURN_IF_ERROR(first_error_);
HloInstructionProto instr;
*instr.mutable_shape() = shape.ToProto();
for (int64_t dim : broadcast_dimensions) {
instr.add_dimensions(dim);
}
TF_ASSIGN_OR_RETURN(const Shape* operand_shape, GetShapePtr(operand));
TF_RET_CHECK(!shape.is_unbounded_dynamic())
<< "broadcast op result shapes must be static";
for (int64_t i = 0; i < shape.rank(); i++) {
if (auto it = absl::c_find(broadcast_dimensions, i);
it != broadcast_dimensions.end()) {
// Broadcast dimensions are permitted to be dynamic iff the operand
// dimension is dynamic.
TF_RET_CHECK(operand_shape->is_bounded_dynamic_dimension(
it - broadcast_dimensions.begin()) ==
shape.is_bounded_dynamic_dimension(i))
<< " i: " << i << ", shape: " << shape.ToString()
<< ", operand_shape: " << operand_shape->ToString();
} else {
// Non-broadcast dimensions must be static.
TF_RET_CHECK(shape.is_static_dimension(i));
}
}
return AddInstruction(std::move(instr), HloOpcode::kBroadcast, {operand});
}
absl::StatusOr<XlaOp> XlaBuilder::AddBroadcastSequence(
const Shape& output_shape, XlaOp operand) {
TF_RETURN_IF_ERROR(first_error_);
TF_ASSIGN_OR_RETURN(const Shape* operand_shape, GetShapePtr(operand));
CHECK(ShapeUtil::IsScalar(*operand_shape) ||
operand_shape->rank() == output_shape.rank());
Shape broadcast_shape =
ShapeUtil::ChangeElementType(output_shape, operand_shape->element_type());
// Do explicit broadcast for scalar.
if (ShapeUtil::IsScalar(*operand_shape)) {
return InDimBroadcast(ShapeUtil::MakeStaticShape(broadcast_shape), operand,
{});
}
// Do explicit broadcast for degenerate broadcast.
std::vector<int64_t> broadcast_dimensions;
std::vector<int64_t> reshaped_dimensions;
std::vector<bool> reshaped_dynamic_dimensions;
for (int i = 0; i < operand_shape->rank(); i++) {
if (operand_shape->dimensions(i) == output_shape.dimensions(i)) {
broadcast_dimensions.push_back(i);
reshaped_dimensions.push_back(operand_shape->dimensions(i));
reshaped_dynamic_dimensions.push_back(
operand_shape->is_dynamic_dimension(i));
} else {
TF_RET_CHECK(operand_shape->dimensions(i) == 1 &&
operand_shape->is_static_dimension(i))
<< "An explicit broadcast sequence requires the broadcasted "
"dimensions to be trivial; operand shape: "
<< *operand_shape << "; output_shape: " << output_shape;
}