-
Notifications
You must be signed in to change notification settings - Fork 29
/
auto_sharding.cc
1655 lines (1449 loc) · 58.2 KB
/
auto_sharding.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
#include "tensorflow/compiler/xla/service/gpu/auto_sharding.h"
#include "tensorflow/compiler/xla/service/gpu/auto_sharding_util.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "tensorflow/compiler/xla/service/heap_simulator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_live_range.h"
#include "tensorflow/compiler/xla/service/hlo_memory_scheduler.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_ordering.h"
#include "tensorflow/compiler/xla/service/hlo_sharding.h"
#include "tensorflow/compiler/xla/service/hlo_sharding_util.h"
#include "tensorflow/compiler/xla/service/dump.h"
#include "tensorflow/compiler/xla/service/pass_context.h"
namespace xla {
namespace gpu {
namespace py = pybind11;
// A constant to represent infinity cost
constexpr double INFINITY_COST = 1e10;
// Options for the auto-sharding solver
struct AutoShardingSolverOption {
bool force_batch_dim_to_mesh_dim;
int64 forward_backward_sep_id;
bool override_all_gather_cost;
double all_gather_cost;
bool override_all_reduce_cost;
double all_reduce_cost;
bool override_reduce_scatter_cost;
double reduce_scatter_cost;
};
// One sharding strategy
struct ShardingStrategy {
std::string name;
HloSharding output_sharding;
double compute_cost;
double communication_cost;
double memory_cost;
std::vector<std::vector<double>> resharding_costs;
};
// Forward declerations and type aliases
using LivenessSet = std::vector<std::vector<const HloValue*>>;
using StrategyMap = absl::flat_hash_map<const HloInstruction*, std::vector<ShardingStrategy>>;
using InstructionIdMap = absl::flat_hash_map<const HloInstruction*, size_t>;
using InstructionDepthMap = absl::flat_hash_map<const HloInstruction*, size_t>;
using FollowMap = absl::flat_hash_map<const HloInstruction*, const HloInstruction*>;
using AliasSet = absl::flat_hash_set<std::pair<size_t, size_t>>;
class ClusterEnvironment;
// Create a tiled HloSharding. Map tensor dims to mesh dims.
HloSharding Tile(const Shape& shape,
const std::vector<int64> tensor_dims,
const std::vector<int64> mesh_dims,
const ClusterEnvironment& cluster_env);
// The cluster has a multi-dimensional device mesh topology.
// Each mesh dimension has its own latency and bandwidth.
// We use alpha-beta model to model the communication cost.
class ClusterEnvironment {
public:
ClusterEnvironment(const Array<int64>& device_mesh,
const std::vector<double>& mesh_alpha,
const std::vector<double>& mesh_beta,
const AutoShardingSolverOption& solver_option)
: device_mesh(device_mesh), total_devices(device_mesh.num_elements()),
mesh_alpha(mesh_alpha), mesh_beta(mesh_beta),
solver_option(solver_option) {}
double AllGatherCost(double num_bytes, int mesh_dim) const {
if (solver_option.override_all_gather_cost) {
return solver_option.all_gather_cost;
}
int64 num_devices = device_mesh.dim(mesh_dim);
return (mesh_alpha[mesh_dim] +
mesh_beta[mesh_dim] * (num_devices - 1) / num_devices * num_bytes +
0.1);
}
double AllReduceCost(double num_bytes, int mesh_dim) const {
if (solver_option.override_all_reduce_cost) {
return solver_option.all_reduce_cost;
}
int64 num_devices = device_mesh.dim(mesh_dim);
return (mesh_alpha[mesh_dim] +
mesh_beta[mesh_dim] * 2 * (num_devices - 1) / num_devices * num_bytes +
0.01);
}
double ReduceScatterCost(double num_bytes, int mesh_dim) const {
if (solver_option.override_reduce_scatter_cost) {
return solver_option.reduce_scatter_cost;
}
int64 num_devices = device_mesh.dim(mesh_dim);
return (mesh_alpha[mesh_dim] +
mesh_beta[mesh_dim] * (num_devices - 1) / num_devices * num_bytes +
0.001);
}
// Get the corresponding mesh dimension for ever tensor dimension
// -1 means replicated on that dimension
std::vector<int> GetTensorDimToMeshDim(const Shape& shape,
const HloSharding& spec) const {
CHECK(shape.IsArray());
if (spec.IsReplicated()) {
return std::vector<int>(shape.rank(), -1);
}
std::vector<int> tensor_dim_vals(shape.rank(), 0);
for (int64 i = 0; i < shape.rank(); ++i) {
tensor_dim_vals[i] = GetDimLastValue(spec.tile_assignment(), i);
}
std::vector<int> mesh_dim_vals(device_mesh.num_dimensions(), 0);
for (int64 j = 0; j < device_mesh.num_dimensions(); ++j) {
mesh_dim_vals[j] = GetDimLastValue(device_mesh, j);
}
std::vector<int> ret(shape.rank(), -1);
for (int64 i = 0; i < shape.rank(); ++i) {
if (spec.tile_assignment().dim(i) != 1) {
for (int64 j = 0; j < device_mesh.num_dimensions(); ++j) {
if (tensor_dim_vals[i] == mesh_dim_vals[j]) {
ret[i] = j;
}
}
}
}
return ret;
}
// The communication cost of resharding a tensor from src to dst
double ReshardingCost(const Shape& shape, const HloSharding& src_spec,
const HloSharding& dst_spec) const {
if (src_spec == dst_spec) {
return 0.0;
}
std::vector<int> src_tensor_dim_to_mesh_dim =
GetTensorDimToMeshDim(shape, src_spec);
std::vector<int> dst_tensor_dim_to_mesh_dim =
GetTensorDimToMeshDim(shape, dst_spec);
double cost = 0.0;
for (int64 i = 0; i < shape.rank(); ++i) {
int src_mesh_dim = src_tensor_dim_to_mesh_dim[i];
if (src_mesh_dim == -1) {
continue;
}
if (src_mesh_dim == dst_tensor_dim_to_mesh_dim[i]) {
continue;
}
// TODO: this can be more accurate
if (dst_tensor_dim_to_mesh_dim[i] == -1) {
cost += AllGatherCost(GetBytes(shape), src_mesh_dim);
}
// do not allow other re-sharding strategies (e.g., collective-permute)
return INFINITY_COST;
}
return cost;
}
std::string ToString() {
std::ostringstream os;
os << "device_mesh: " << device_mesh.ToString() << "\n";
os << "mesh_alpha: ";
for (auto x : mesh_alpha) {
os << x << " ";
}
os << "\n";
os << "mesh_beta: ";
for (auto x : mesh_beta) {
os << x << " ";
}
os << "\n";
return os.str();
}
// Shape and bandwidth of the device mesh
const Array<int64> device_mesh;
const int total_devices;
const std::vector<double> mesh_alpha;
const std::vector<double> mesh_beta;
// Disencourage the apperance of partial reduction
const double partial_reduction_penalty = 10;
// The solver option may override the cost of communication primitives
const AutoShardingSolverOption& solver_option;
};
// Create a HloSharding that tiles some tensor dims on some device mesh dims.
HloSharding Tile(const Shape& shape,
const std::vector<int64> tensor_dims,
const std::vector<int64> mesh_dims,
const ClusterEnvironment& cluster_env) {
CHECK_EQ(tensor_dims.size(), mesh_dims.size());
CHECK(shape.IsArray());
std::vector<int64> tile_assignment_dimensions(shape.rank(), 1);
// Split on certain mesh dimensions
int64 split_prod = 1;
for (size_t i = 0; i < tensor_dims.size(); ++i) {
tile_assignment_dimensions[tensor_dims[i]] = cluster_env.device_mesh.dim(mesh_dims[i]);
split_prod *= cluster_env.device_mesh.dim(mesh_dims[i]);
}
// Replicate on reminding mesh dimensions
bool replicate_on_last_tile_dim = false;
if (split_prod < cluster_env.total_devices) {
tile_assignment_dimensions.push_back(cluster_env.total_devices / split_prod);
replicate_on_last_tile_dim = true;
}
// Map device ids from device_mesh to tile_assignment_devices
std::vector<int64> tile_assignment_devices;
tile_assignment_devices.reserve(cluster_env.total_devices);
std::vector<int64> tmp_indices(cluster_env.device_mesh.num_dimensions(), 0);
std::function<void(int64, std::vector<int64>)> generate_tile_assignment_devices;
generate_tile_assignment_devices = [&]
(int64 tensor_dim, std::vector<int64> mesh_indices) {
if (tensor_dim == shape.rank() - 1) {
AppendFlattenElements(&tile_assignment_devices, cluster_env.device_mesh,
mesh_indices, -1, tmp_indices);
} else {
int64 next_tensor_dim = tensor_dim + 1;
int64 next_mesh_dim = -1;
int64 index = GetIndex(tensor_dims, next_tensor_dim);
if (index >= 0) {
next_mesh_dim = mesh_dims[index];
}
for (int64 i = 0; i < tile_assignment_dimensions[next_tensor_dim]; ++i) {
if (next_mesh_dim != -1) {
mesh_indices[next_mesh_dim] = i;
}
generate_tile_assignment_devices(next_tensor_dim, mesh_indices);
}
}
};
std::vector<int64> mesh_indices(cluster_env.device_mesh.num_dimensions(), -1);
generate_tile_assignment_devices(-1, mesh_indices);
// Make HloSharding
Array<int64> tile_assignment(tile_assignment_dimensions);
//std::cerr << "shape: " << shape.ToString() << std::endl;
//std::cerr << "tensor dims: " << ToString(tensor_dims) << std::endl;
//std::cerr << "mesh dims: " << ToString(mesh_dims) << std::endl;
//std::cerr << "tile_assignment: " << ToString(tile_assignment.dimensions()) << std::endl;
tile_assignment.SetValues(tile_assignment_devices);
return replicate_on_last_tile_dim ?
HloSharding::PartialTile(tile_assignment):
HloSharding::Tile(tile_assignment);
}
// Build a map that maps an instruction to its index in a serial sequence
InstructionIdMap BuildInstructionIdMap(const HloInstructionSequence& sequence) {
InstructionIdMap ret;
const std::vector<HloInstruction*>& instructions = sequence.instructions();
for (size_t i = 0; i < instructions.size(); ++i) {
ret[instructions[i]] = i;
}
return ret;
}
// Estimate the separator location between forward pass and backward pass
int64 EstimateForwardBackwardSep(const HloModule* module,
const HloInstructionSequence& sequence,
const InstructionIdMap& ins_id_map) {
// Count used_by map for every parameter
absl::flat_hash_map<const HloInstruction*, std::vector<int64>> used_by;
for (const HloInstruction* inst : sequence.instructions()) {
for (size_t j = 0; j < inst->operand_count(); ++j) {
const HloInstruction* operand = inst->operand(j);
if (operand->opcode() == HloOpcode::kParameter) {
used_by[operand].push_back(ins_id_map.at(inst));
}
}
}
// Estimate forward/backward separation
int64 sep = 0;
for (const auto& iter : used_by) {
if (iter.second.size() > 2) {
sep = std::max(sep, iter.second.front() + 1);
}
}
return sep;
}
// Depth analysis (breadth first search)
InstructionDepthMap BuildInstructionDepthMap(const HloInstructionSequence& sequence) {
const std::vector<HloInstruction*>& instructions = sequence.instructions();
InstructionDepthMap depth_map;
absl::flat_hash_map<const HloInstruction*, std::vector<const HloInstruction*>> edge_dict;
absl::flat_hash_map<const HloInstruction*, size_t> degree_dict;
for (const HloInstruction* inst : instructions) {
for (int64 i = 0; i < inst->operand_count(); ++i) {
degree_dict[inst] += 1;
edge_dict[inst->operand(i)].push_back(inst);
}
}
// Init frontier
//std::cerr << "Depth : 0" << std::endl;
size_t collected = 0;
std::vector<const HloInstruction*> current_frontier;
for (const HloInstruction* inst : instructions) {
if (degree_dict[inst] == 0) {
depth_map[inst] = 0;
current_frontier.push_back(inst);
collected++;
//std::cerr << inst->ToString() << std::endl;
}
}
// Push forward
int depth = 0;
std::vector<const HloInstruction*> next_frontier;
while (collected < instructions.size()) {
next_frontier.clear();
for (const HloInstruction* inst : current_frontier) {
for (const HloInstruction* node : edge_dict[inst]) {
int now_degree = --degree_dict[node];
if (now_degree == 0) {
next_frontier.push_back(node);
collected += 1;
}
}
}
depth++;
std::swap(current_frontier, next_frontier);
//std::cerr << "Depth :" << depth << std::endl;
for (const HloInstruction* inst : current_frontier) {
depth_map[inst] = depth;
//std::cerr << inst->ToString() << std::endl;
}
}
return depth_map;
}
// Compute the resharding cost vector from multiple possible strategies
// to a desired sharding spec
std::vector<double> ReshardingCostVector(const std::vector<ShardingStrategy>& strategies,
const Shape& shape,
const HloSharding& required_sharding,
const ClusterEnvironment& cluster_env) {
std::vector<double> ret;
for (const auto& x : strategies) {
ret.push_back(cluster_env.ReshardingCost(shape, x.output_sharding, required_sharding));
}
return ret;
}
std::vector<double> FollowInsCostVecotr(int64 source_len, int64 index) {
std::vector<double> ret(source_len, INFINITY_COST);
ret[index] = 0;
return ret;
}
// Build possible sharding strategies and their costs for all instructions
std::pair<StrategyMap, FollowMap> BuildStrategyAndCost(
const HloInstructionSequence& sequence,
const InstructionDepthMap& depth_map,
const ClusterEnvironment& cluster_env,
const AutoShardingSolverOption& solver_option
) {
const Array<int64>& device_mesh = cluster_env.device_mesh;
StrategyMap strategy_map;
FollowMap follow_map;
const std::vector<HloInstruction*>& instructions = sequence.instructions();
for (const HloInstruction* ins : instructions) {
std::vector<ShardingStrategy> strategies;
switch (ins->opcode()) {
case HloOpcode::kParameter: {
// Split one dim
for (int64 i = 0; i < ins->shape().rank(); ++i) {
for (int64 j = 0; j < device_mesh.num_dimensions(); ++j) {
if (device_mesh.dim(j) == 1 ||
ins->shape().dimensions(i) < device_mesh.dim(j)) {
continue;
}
std::string name = "S" + std::to_string(i) + " @ " + std::to_string(j);
HloSharding output_spec = Tile(ins->shape(), {i}, {j}, cluster_env);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({name, output_spec,
compute_cost, communication_cost, memory_cost,
{}}));
}
}
// Replicate
strategies.push_back(
ShardingStrategy({"R", HloSharding::Replicate(),
2, 0, GetBytes(ins->shape()),
{}}));
break;
}
case HloOpcode::kConstant: {
strategies.push_back(
ShardingStrategy({"R", HloSharding::Replicate(),
0, 0, GetBytes(ins->shape()),
{}}));
break;
}
case HloOpcode::kBroadcast: {
const HloInstruction* operand = ins->operand(0);
follow_map[ins] = operand;
const std::vector<ShardingStrategy>& src_strategies = strategy_map.at(operand);
// Create follow strategies
for (int64 sid = 0; sid < src_strategies.size(); ++sid) {
HloSharding output_spec = BroadcastSharding(
src_strategies[sid].output_sharding, ins->shape(), ins->dimensions());
std::string name = SimpleToString(output_spec);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({name, output_spec,
compute_cost, communication_cost, memory_cost,
{FollowInsCostVecotr(src_strategies.size(), sid)}}));
}
// Split one dim if the operand is a constant
if (operand->shape().rank() == 0) {
follow_map.erase(ins); // erase follow
for (int64 i = 0; i < ins->shape().rank(); ++i) {
for (int64 j = 0; j < device_mesh.num_dimensions(); ++j) {
if (device_mesh.dim(j) == 1 ||
ins->shape().dimensions(i) < device_mesh.dim(j)) {
continue;
}
std::string name = "S" + std::to_string(i) + " @ " + std::to_string(j);
HloSharding output_spec = Tile(ins->shape(), {i}, {j}, cluster_env);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({name, output_spec,
compute_cost, communication_cost, memory_cost,
{std::vector<double>(src_strategies.size(), 0.0)}}));
}
}
}
break;
}
case HloOpcode::kReshape: {
const HloInstruction* operand = ins->operand(0);
follow_map[ins] = operand;
const std::vector<ShardingStrategy>& src_strategies = strategy_map.at(operand);
// Create follow strategies
for (int64 sid = 0; sid < src_strategies.size(); ++sid) {
absl::optional<HloSharding> output_spec = hlo_sharding_util::ReshapeSharding(
operand->shape(), ins->shape(),
src_strategies[sid].output_sharding);
if (!output_spec.has_value()) {
continue;
}
std::string name = SimpleToString(*output_spec);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec->NumTiles();
strategies.push_back(
ShardingStrategy({name, *output_spec,
compute_cost, communication_cost, memory_cost,
{FollowInsCostVecotr(src_strategies.size(), sid)}}));
}
break;
}
case HloOpcode::kTranspose: {
const HloInstruction* operand = ins->operand(0);
follow_map[ins] = operand;
const std::vector<ShardingStrategy>& src_strategies = strategy_map.at(operand);
// Create follow strategies
for (int64 sid = 0; sid < src_strategies.size(); ++sid) {
HloSharding output_spec = hlo_sharding_util::TransposeSharding(
src_strategies[sid].output_sharding, ins->dimensions());
std::string name = SimpleToString(output_spec);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({name, output_spec,
compute_cost, communication_cost, memory_cost,
{FollowInsCostVecotr(src_strategies.size(), sid)}}));
}
break;
}
case HloOpcode::kPad:
case HloOpcode::kSlice:
case HloOpcode::kDynamicSlice:
case HloOpcode::kDynamicUpdateSlice: {
const HloInstruction* operand = ins->operand(0);
follow_map[ins] = operand;
const std::vector<ShardingStrategy>& src_strategies = strategy_map.at(operand);
// Create follow strategies
for (int64 sid = 0; sid < src_strategies.size(); ++sid) {
absl::optional<HloSharding> output_spec = PropagateDimwiseSharding(
src_strategies[sid].output_sharding,
operand->shape(), ins->shape());
if (!output_spec.has_value()) {
continue;
}
std::string name = SimpleToString(*output_spec);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec->NumTiles();
std::vector<std::vector<double>> resharding_costs;
resharding_costs.push_back(
FollowInsCostVecotr(src_strategies.size(), sid));
for (int64 k = 1; k < ins->operand_count(); ++k) {
resharding_costs.push_back(
ReshardingCostVector(strategy_map[ins->operand(k)],
ins->operand(k)->shape(), *output_spec, cluster_env)
);
}
strategies.push_back(
ShardingStrategy({name, *output_spec,
compute_cost, communication_cost, memory_cost,
resharding_costs}));
}
break;
}
// Unary elementwise operations.
case HloOpcode::kAbs:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kCeil:
case HloOpcode::kClz:
case HloOpcode::kConvert:
case HloOpcode::kBitcastConvert:
case HloOpcode::kCopy:
case HloOpcode::kCos:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFloor:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kNot:
case HloOpcode::kNegate:
case HloOpcode::kPopulationCount:
case HloOpcode::kReal:
case HloOpcode::kReducePrecision:
case HloOpcode::kRsqrt:
case HloOpcode::kLogistic:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSqrt:
case HloOpcode::kCbrt:
case HloOpcode::kTanh:
// Binary elementwise operations
case HloOpcode::kAdd:
case HloOpcode::kAtan2:
case HloOpcode::kCompare:
case HloOpcode::kComplex:
case HloOpcode::kDivide:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kPower:
case HloOpcode::kRemainder:
case HloOpcode::kSubtract:
case HloOpcode::kAnd:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
// Ternary elementwise operations.
case HloOpcode::kSelect:
case HloOpcode::kClamp: {
int64 follow_idx = 0;
// Follow the deepest instruction
for (int64 i = 1; i < ins->operand_count(); ++i) {
if (depth_map.at(ins->operand(i)) > depth_map.at(ins->operand(follow_idx))) {
follow_idx = i;
}
}
const HloInstruction* operand = ins->operand(follow_idx);
follow_map[ins] = operand;
const std::vector<ShardingStrategy>& src_strategies = strategy_map.at(operand);
for (int64 sid = 0; sid < src_strategies.size(); ++sid) {
HloSharding output_spec = src_strategies[sid].output_sharding;
std::string name = SimpleToString(output_spec);
double compute_cost = 0;
double communication_cost = 0;
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
std::vector<std::vector<double>> resharding_costs;
for (int64 k = 0; k < ins->operand_count(); ++k) {
if (k == follow_idx) {
resharding_costs.push_back(
FollowInsCostVecotr(src_strategies.size(), sid));
} else {
resharding_costs.push_back(
ReshardingCostVector(strategy_map[ins->operand(k)],
ins->operand(k)->shape(), output_spec, cluster_env)
);
}
}
strategies.push_back(
ShardingStrategy({name, output_spec,
compute_cost, communication_cost, memory_cost,
resharding_costs}));
}
break;
}
case HloOpcode::kReduce: {
const HloInstruction* operand = ins->operand(0);
const HloInstruction* unit = ins->operand(1);
const auto& dimensions = ins->dimensions();
follow_map[ins] = operand;
const std::vector<ShardingStrategy>& src_strategies = strategy_map.at(operand);
// Map old dims to new dim
std::vector<int64> old_dim_to_new_dim;
old_dim_to_new_dim.reserve(operand->shape().rank());
int64 pt = 0;
for (int64 old_dim = 0; old_dim < operand->shape().rank(); ++old_dim) {
if (absl::c_find(dimensions, old_dim) != dimensions.end()) {
old_dim_to_new_dim.push_back(-1);
} else {
old_dim_to_new_dim.push_back(pt);
pt += 1;
}
}
CHECK_EQ(pt, ins->shape().rank());
// Create follow strategies
for (size_t sid = 0; sid < src_strategies.size(); ++sid) {
const auto& tensor_dim_to_mesh = cluster_env.GetTensorDimToMeshDim(
operand->shape(), src_strategies[sid].output_sharding);
std::vector<int64> tile_tensor_dims, tile_mesh_dims, all_reduce_dims;
for (int64 tensor_dim = 0; tensor_dim < operand->shape().rank(); ++tensor_dim) {
int64 mesh_dim = tensor_dim_to_mesh[tensor_dim];
if (absl::c_find(dimensions, tensor_dim) != dimensions.end()) {
if (mesh_dim == -1) { // Reduce on a replicated dim
continue;
} else { // Reduce on a split dim. Require an allreduce
all_reduce_dims.push_back(mesh_dim);
}
} else {
if (mesh_dim == -1) { // Follow a replicated dim
continue;
} else { // Follow a split dim
tile_tensor_dims.push_back(old_dim_to_new_dim[tensor_dim]);
tile_mesh_dims.push_back(mesh_dim);
}
}
}
HloSharding output_spec = Tile(ins->shape(),
tile_tensor_dims, tile_mesh_dims, cluster_env);
double compute_cost = 0.0;
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
double communication_cost = 0.0;
for (auto mesh_dim : all_reduce_dims) {
communication_cost += cluster_env.AllReduceCost(memory_cost, mesh_dim);
}
std::string name = SimpleToString(output_spec);
if (!all_reduce_dims.empty()) {
name += " (allreduce @ " + ToString(all_reduce_dims) + ")";
}
strategies.push_back(
ShardingStrategy({name, output_spec,
compute_cost, communication_cost, memory_cost,
{FollowInsCostVecotr(src_strategies.size(), sid),
ReshardingCostVector(strategy_map[unit], unit->shape(),
HloSharding::Replicate(), cluster_env)
}}));
}
break;
}
case HloOpcode::kDot: {
const HloInstruction* lhs = ins->operand(0);
const HloInstruction* rhs = ins->operand(1);
const DotDimensionNumbers& dot_dnums = ins->dot_dimension_numbers();
int64 space_base_dim = dot_dnums.lhs_batch_dimensions_size();
std::vector<int64> lhs_space_dims, rhs_space_dims;
std::tie(lhs_space_dims, rhs_space_dims) = GetSpaceDims(
lhs->shape(), rhs->shape(), dot_dnums);
const auto& lhs_con_dims = dot_dnums.lhs_contracting_dimensions();
const auto& rhs_con_dims = dot_dnums.rhs_contracting_dimensions();
const auto& lhs_batch_dims = dot_dnums.lhs_batch_dimensions();
const auto& rhs_batch_dims = dot_dnums.rhs_batch_dimensions();
CHECK_EQ(lhs_space_dims.size(), 1);
CHECK_EQ(rhs_space_dims.size(), 1);
CHECK_EQ(lhs_con_dims.size(), 1);
CHECK_EQ(rhs_con_dims.size(), 1);
// Only support 2 dimensional device mesh
CHECK_EQ(device_mesh.num_dimensions(), 2);
// Split lhs space dim + rhs space dim
// @ {0, 1}
HloSharding output_spec =
Tile(ins->shape(), {space_base_dim, space_base_dim + 1}, {0, 1}, cluster_env);
strategies.push_back(
ShardingStrategy({"SS = SR x RS @ {0, 1}", output_spec,
0, 0, GetBytes(ins->shape()) / output_spec.NumTiles(),
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_space_dims[0]}, {0}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_space_dims[0]}, {1}, cluster_env), cluster_env),
}}));
// @ {1, 0}
output_spec =
Tile(ins->shape(), {space_base_dim, space_base_dim + 1}, {1, 0}, cluster_env);
strategies.push_back(
ShardingStrategy({"SS = SR x RS @ {1, 0}", output_spec,
0, 0, GetBytes(ins->shape()) / output_spec.NumTiles(),
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_space_dims[0]}, {1}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_space_dims[0]}, {0}, cluster_env), cluster_env),
}}));
// Split lhs space dim + contracting dim
// @ {0, 1}
if (device_mesh.dim(1) > 1) {
HloSharding output_spec =
Tile(ins->shape(), {space_base_dim}, {0}, cluster_env);
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({"SR = SS x SR @ {0, 1} (allreduce @ 1)", output_spec,
0, cluster_env.AllReduceCost(memory_cost, 1), memory_cost,
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_space_dims[0], lhs_con_dims[0]}, {0, 1}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_con_dims[0]}, {1}, cluster_env), cluster_env),
}}));
}
// @ {1, 0}
if (device_mesh.dim(0) > 1) {
HloSharding output_spec =
Tile(ins->shape(), {space_base_dim}, {1}, cluster_env);
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({"SR = SS x SR @ {1, 0} (allreduce @ 0)", output_spec,
0, cluster_env.AllReduceCost(memory_cost, 0), memory_cost,
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_space_dims[0], lhs_con_dims[0]}, {1, 0}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_con_dims[0]}, {0}, cluster_env), cluster_env),
}}));
}
// Split rhs space dim + contracting dim
// @ {0, 1}
if (device_mesh.dim(0) > 1 && device_mesh.dim(1) > 1) {
HloSharding output_spec =
Tile(ins->shape(), {space_base_dim + 1}, {1}, cluster_env);
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({"RS = RS x SS @ {0, 1} (allreduce @ 0)", output_spec,
0, cluster_env.AllReduceCost(memory_cost, 0), memory_cost,
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_con_dims[0]}, {0}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_con_dims[0], rhs_space_dims[0]}, {0, 1}, cluster_env), cluster_env),
}}));
}
// @ {1, 0}
if (device_mesh.dim(0) > 1 && device_mesh.dim(1) > 1) {
HloSharding output_spec =
Tile(ins->shape(), {space_base_dim + 1}, {0}, cluster_env);
double memory_cost = GetBytes(ins->shape()) / output_spec.NumTiles();
strategies.push_back(
ShardingStrategy({"RS = RS x SS @ {1, 0} (allreduce @ 1)", output_spec,
0, cluster_env.AllReduceCost(memory_cost, 1), memory_cost,
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_con_dims[0]}, {1}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_con_dims[0], rhs_space_dims[0]}, {1, 0}, cluster_env), cluster_env),
}}));
}
// Split one batch dim
for (int64 i = 0; i < lhs_batch_dims.size(); ++i) {
for (int64 j = 0; j < device_mesh.num_dimensions(); ++j) {
if (device_mesh.dim(j) == 1 ||
ins->shape().dimensions(i) < device_mesh.dim(j)) {
continue;
}
HloSharding output_spec = Tile(ins->shape(), {i}, {j}, cluster_env);
std::string name = "Sb_" + std::to_string(i) + " = Sb x Sb @ {"
+ std::to_string(j) + "}";
strategies.push_back(
ShardingStrategy({name, output_spec,
0, 0, GetBytes(ins->shape()) / output_spec.NumTiles(),
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_batch_dims[i]}, {j}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_batch_dims[i]}, {j}, cluster_env), cluster_env),
}}));
}
}
// Split two batch dims
if (lhs_batch_dims.size() == 2 && device_mesh.dim(0) > 1 && device_mesh.dim(1) > 1) {
strategies.clear();
HloSharding output_spec = Tile(ins->shape(), {0, 1}, {0, 1}, cluster_env);
strategies.push_back(
ShardingStrategy({
"Sb = Sb x Sb @ {0, 1}", output_spec,
0, 0, GetBytes(ins->shape()) / output_spec.NumTiles(),
{
ReshardingCostVector(strategy_map[lhs], lhs->shape(),
Tile(lhs->shape(), {lhs_batch_dims[0], lhs_batch_dims[1]}, {0, 1}, cluster_env), cluster_env),
ReshardingCostVector(strategy_map[rhs], rhs->shape(),
Tile(rhs->shape(), {rhs_batch_dims[0], rhs_batch_dims[1]}, {0, 1}, cluster_env), cluster_env),
}}));
}
break;
}
case HloOpcode::kTuple: {
std::vector<std::vector<double>> resharding_costs;
for (size_t i = 0; i < ins->operand_count(); ++i) {
const HloInstruction* operand = ins->operand(i);
resharding_costs.push_back(std::vector<double>(strategy_map[operand].size(), 0));
}
strategies.push_back(
ShardingStrategy({
"tuple_follow", HloSharding::Replicate(),
0, 0, 0, resharding_costs}));
break;
}
default:
LOG(FATAL) << "Unhandled instruction: " + ins->name();
}
CHECK(!strategies.empty());
strategy_map[ins] = strategies;
}
return std::make_pair(std::move(strategy_map), std::move(follow_map));
}
AliasSet BuildAliasSet(
const HloModule* module,
const HloDataflowAnalysis& dataflow_analysis,
const InstructionIdMap& ins_id_map
) {
// Adjust the edge cost for alias (donated buffer).
// Typically, old weights and new weights are aliases, so we should
// let them have the same sharding spec.
const HloInputOutputAliasConfig& alias_config = module->input_output_alias_config();
HloComputation* entry = module->entry_computation();
const std::vector<HloInstruction*>& parameter_instructions =
entry->parameter_instructions();
const HloInstruction* output_tuple = entry->root_instruction();
// TODO: handle tuple args
AliasSet alias_set;
alias_config.ForEachAlias(
[&](const ShapeIndex& output_index, const HloInputOutputAliasConfig::Alias& alias) {
const HloInstruction* src_ins = parameter_instructions[alias.parameter_number];
const HloInstruction* dst_ins = dataflow_analysis.GetUniqueValueAt(
output_tuple, output_index).instruction();
alias_set.insert(std::make_pair(ins_id_map.at(src_ins), ins_id_map.at(dst_ins)));
});
return alias_set;
}
// A simple matrix class to store and manipulate on cost matrices on edges.
class Matrix {
public:
Matrix() : n(0), m(0), transpose(false), data(nullptr) {}
Matrix(size_t n, size_t m) {
this->n = n;
this->m = m;
transpose = false;
data = std::make_shared<std::vector<double>>(n * m, 0.0);
}
Matrix(size_t n, size_t m, bool transpose, std::shared_ptr<std::vector<double>> data) {
this->n = n;
this->m = m;
this->transpose = transpose;
this->data = data;
}
Matrix Transpose() {
return Matrix(m, n, !transpose, data);
}
double operator()(size_t i, size_t j) const {
size_t idx;
if (transpose) {
idx = j * n + i;
} else {
idx = i * m + j;
}
CHECK(data != nullptr) << n << " , " << m;
return (*data)[idx];
}
double& operator()(size_t i, size_t j) {
size_t idx;
if (transpose) {
idx = j * n + i;
} else {
idx = i * m + j;
}
CHECK(data != nullptr) << n << " . " << m;
return (*data)[idx];
}
Matrix operator+(const Matrix& other) {
CHECK_EQ(n, other.n);
CHECK_EQ(m, other.m);
Matrix ret = Matrix(n, m);
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
ret(i, j) = operator()(i, j) + other(i, j);
}
}
return ret;
}
std::string ToString() const {
std::ostringstream os;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
os << operator()(i, j) << " ";
}
os << "\n";
}