1 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/compiler/xla/service/hlo_memory_scheduler.h"
17
18 #include <algorithm>
19 #include <limits>
20 #include <map>
21 #include <queue>
22 #include <utility>
23 #include <vector>
24
25 #include "absl/container/flat_hash_map.h"
26 #include "absl/container/flat_hash_set.h"
27 #include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
28 #include "tensorflow/compiler/xla/service/heap_simulator.h"
29 #include "tensorflow/compiler/xla/service/hlo_computation.h"
30 #include "tensorflow/compiler/xla/service/hlo_opcode.h"
31 #include "tensorflow/compiler/xla/service/hlo_schedule.h"
32 #include "tensorflow/compiler/xla/service/tuple_points_to_analysis.h"
33 #include "tensorflow/compiler/xla/shape_util.h"
34 #include "tensorflow/compiler/xla/status_macros.h"
35 #include "tensorflow/compiler/xla/statusor.h"
36 #include "tensorflow/compiler/xla/types.h"
37 #include "tensorflow/compiler/xla/util.h"
38 #include "tensorflow/core/lib/core/errors.h"
39 #include "tensorflow/core/lib/gtl/map_util.h"
40 #include "tensorflow/core/platform/logging.h"
41
42 namespace xla {
43 namespace {
44
45 using ::tensorflow::strings::HumanReadableNumBytes;
46
47 // Class implementing a list scheduler of HLO instructions which produces a
48 // sequence which minimizes memory usage by preferring to schedule the node that
49 // frees bigger buffer and defines smaller outputs.
50 //
51 // Note that list scheduler is a greedy algorithm which cannot guarantee a
52 // global optimal solution. As a counterexample, considering the following
53 // graph:
54 //
55 // +--> B ===> C -------+
56 // A -> | |
57 // | v
58 // +--> D ---> F=======>G
59 // | ^
60 // | |
61 // +--> E -----+
62 //
63 // --> : Buffer with size 1
64 // ==> : Buffer with size 2
65 //
66 // The list scheduler will always try to defer scheduling B in a greedy way
67 // since its output buffer is bigger than input. The sequence it creates will
68 // be:
69 // A D E F B C G
70 // , which has a maximum memory usage of 6 (B is alive while F is executing).
71 //
72 // An optimal way to schedule the previous graph is:
73 // A B C D E F G
74 // , which has a maximum memory usage of 5 (when F is executing).
75 //
76 class ListScheduler {
77 public:
78 // Construct and return a memory-minimizing sequence of HLO instructions
79 // containing the given HLO computation.
Run(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const BufferValue::SizeFunction & size_function,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation)80 static StatusOr<HloInstructionSequence> Run(
81 HloComputation* computation,
82 const TuplePointsToAnalysis& points_to_analysis,
83 const BufferValue::SizeFunction& size_function,
84 const absl::flat_hash_map<const HloComputation*, int64>&
85 memory_by_computation) {
86 ListScheduler scheduler(computation, points_to_analysis, size_function,
87 memory_by_computation);
88 return scheduler.CreateSchedule();
89 }
90
91 // Returns whether the memory used by the given HLO should be ignored by the
92 // scheduling heuristic.
IgnoreInstruction(const HloInstruction & instruction)93 static bool IgnoreInstruction(const HloInstruction& instruction) {
94 return instruction.opcode() == HloOpcode::kParameter ||
95 instruction.opcode() == HloOpcode::kConstant;
96 }
97
98 private:
99 // The scheduling priority of an instruction is first the number of bytes
100 // freed by scheduling the instruction, and second (tie-breaker) by the number
101 // of users. This is represented as a std::pair containing these two values
102 // (first element is the bytes freed). std::pair provides the necessary
103 // comparison operators.
104 using Priority = std::pair<int64, int64>;
105
ListScheduler(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const BufferValue::SizeFunction & size_function,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation)106 ListScheduler(HloComputation* computation,
107 const TuplePointsToAnalysis& points_to_analysis,
108 const BufferValue::SizeFunction& size_function,
109 const absl::flat_hash_map<const HloComputation*, int64>&
110 memory_by_computation)
111 : computation_(computation),
112 points_to_analysis_(points_to_analysis),
113 size_function_(size_function),
114 memory_by_computation_(memory_by_computation) {
115 // Create a map containing the LogicalBuffer uses for each HLO
116 // instruction. An HLO instruction "uses" a LogicalBuffer if the
117 // LogicalBuffer is in an operand of the instruction as indicated by
118 // points-to analysis.
119 for (auto* instruction : computation->instructions()) {
120 absl::flat_hash_set<const LogicalBuffer*> instr_uses;
121 for (auto* operand : instruction->operands()) {
122 points_to_analysis.GetPointsToSet(operand).ForEachElement(
123 [&](const ShapeIndex& /*index*/,
124 const PointsToSet::BufferList& buffers) {
125 instr_uses.insert(buffers.begin(), buffers.end());
126 });
127 }
128 buffer_uses_[instruction] = std::vector<const LogicalBuffer*>(
129 instr_uses.begin(), instr_uses.end());
130 }
131
132 // Create map containing the number of unscheduled uses (hlo instructions)
133 // of each logical buffer.
134 unscheduled_use_count_.reserve(points_to_analysis.num_logical_buffers());
135 for (auto* instruction : computation->instructions()) {
136 for (auto* buffer :
137 points_to_analysis.GetBuffersDefinedByInstruction(instruction)) {
138 unscheduled_use_count_[buffer] = 0;
139 }
140 }
141 for (auto* instruction : computation->instructions()) {
142 for (const LogicalBuffer* buffer : buffer_uses_.at(instruction)) {
143 ++unscheduled_use_count_[buffer];
144 }
145 }
146
147 // Buffers live out of the computation have an implicit use at the end of
148 // the computation.
149 for (const LogicalBuffer* live_out_buffer :
150 points_to_analysis.GetPointsToSet(computation->root_instruction())
151 .CreateFlattenedSet()) {
152 ++unscheduled_use_count_[live_out_buffer];
153 }
154 }
155
156 // Returns whether the memory used by the given buffer should be ignored by
157 // the scheduling heuristic.
IgnoreBuffer(const LogicalBuffer & buffer)158 static bool IgnoreBuffer(const LogicalBuffer& buffer) {
159 return IgnoreInstruction(*buffer.instruction());
160 }
161
162 // An entry in the worklist used by CreateSchedule. Corresponds to one
163 // HloInstruction, plus some cached metadata, saved for the purposes of making
164 // BytesFreedIfScheduled fast.
165 struct ReadyListEntry {
166 HloInstruction* instruction;
167
168 // The total size of all buffers defined by this instruction.
169 int64 bytes_defined;
170
171 // For each buffer B used by this instruction, we keep a pair (B, U), where
172 // U is the number of uses of B that have not yet been scheduled. This pair
173 // is a pointer into the unscheduled_use_count_ map, so it gets updated for
174 // free when we update counts in the map.
175 std::vector<const std::pair<const LogicalBuffer* const, int64>*>
176 used_buffer_unscheduled_use_counts;
177 };
178
179 // Creates a ReadyListEntry for the given instruction.
MakeReadyListEntry(HloInstruction * instruction)180 ReadyListEntry MakeReadyListEntry(HloInstruction* instruction) {
181 ReadyListEntry entry;
182 entry.instruction = instruction;
183
184 entry.bytes_defined = 0;
185 for (auto* buffer :
186 points_to_analysis_.GetBuffersDefinedByInstruction(instruction)) {
187 if (!IgnoreBuffer(*buffer)) {
188 entry.bytes_defined += size_function_(*buffer);
189 }
190 }
191
192 for (auto* buffer : buffer_uses_.at(instruction)) {
193 if (IgnoreBuffer(*buffer)) {
194 continue;
195 }
196 auto unscheduled_use_count_it = unscheduled_use_count_.find(buffer);
197 CHECK(unscheduled_use_count_it != unscheduled_use_count_.end());
198 entry.used_buffer_unscheduled_use_counts.push_back(
199 &*unscheduled_use_count_it);
200 }
201 return entry;
202 }
203
204 // Returns the number of bytes freed *after* the HLO instruction finishes.
205 // The current List algorithm only considers two states for an instruction:
206 // right before it runs, and after it finishes. We don't represent memory
207 // usage during the execution of an instruction. But if the instruction calls
208 // subcomputations, they are only live during the instruction's execution.
209 // We end up counting the memory used by subcomputations as memory "defined"
210 // by the instruction. This is not entirely accurate, but it is more accurate
211 // than not taking subcomputations into account at all. In the future, we may
212 // improve accounting for subcomputation memory (b/65409243).
BytesFreedIfScheduled(const ReadyListEntry & entry)213 int64 BytesFreedIfScheduled(const ReadyListEntry& entry) {
214 auto instruction = entry.instruction;
215 auto opcode = instruction->opcode();
216
217 // Scheduling the outfeed early and the infeed late gives more time to the
218 // communicating processor to do its work.
219 if (opcode == HloOpcode::kOutfeed &&
220 !instruction->outfeed_config().empty()) {
221 return INT_MAX;
222 }
223 if (opcode == HloOpcode::kInfeed && !instruction->infeed_config().empty()) {
224 return INT_MIN;
225 }
226
227 int64 freed_bytes = 0;
228 for (const auto& kv : entry.used_buffer_unscheduled_use_counts) {
229 auto buffer = kv->first;
230 auto use_count = kv->second;
231 if (use_count == 1) {
232 freed_bytes += size_function_(*buffer);
233 }
234 }
235 // We only count the memory usage of the largest subcomputation, instead of
236 // adding them all, because subcomputations won't execute in parallel.
237 int64 max_subcomputation_bytes = 0;
238 for (const auto* c : instruction->called_computations()) {
239 auto it = memory_by_computation_.find(c);
240 if (it != memory_by_computation_.end()) {
241 int64 subcomputation_bytes = it->second;
242 if (subcomputation_bytes > max_subcomputation_bytes) {
243 max_subcomputation_bytes = subcomputation_bytes;
244 }
245 }
246 }
247 int64 bytes_defined;
248 if (max_subcomputation_bytes > 0 &&
249 (opcode == HloOpcode::kWhile || opcode == HloOpcode::kCall ||
250 opcode == HloOpcode::kConditional)) {
251 // The output buffer of while/call/conditional is always aliased with the
252 // output buffer of the root instruction in the body. Don't double count.
253 bytes_defined = max_subcomputation_bytes;
254 } else {
255 bytes_defined = entry.bytes_defined + max_subcomputation_bytes;
256 }
257 return freed_bytes - bytes_defined;
258 }
259
260 // Constructs the scheduling priority of the given instruction.
GetPriority(const ReadyListEntry & entry)261 Priority GetPriority(const ReadyListEntry& entry) {
262 // Try to cluster scalars as close together as possible so that if they are
263 // in unfused hlos, they can still live in machine registers without
264 // excessive spilling.
265 if (ShapeUtil::IsEffectiveScalar(entry.instruction->shape())) {
266 return {std::numeric_limits<int64>::max(),
267 std::numeric_limits<int64>::max()};
268 }
269 return {BytesFreedIfScheduled(entry), entry.instruction->user_count()};
270 }
271
CreateSchedule()272 HloInstructionSequence CreateSchedule() {
273 HloInstructionSequence schedule;
274
275 // Populate the ready list with instructions which have no operands or
276 // control predecessors.
277 absl::flat_hash_map<const HloInstruction*, int64> unscheduled_pred_count;
278 for (auto* instruction : computation_->instructions()) {
279 // TODO(b/34466113): Replace this and above with successors() or
280 // predecessors() when these methods are added to HloInstruction.
281 for (HloInstruction* user : instruction->users()) {
282 unscheduled_pred_count[user]++;
283 }
284 for (HloInstruction* succ : instruction->control_successors()) {
285 unscheduled_pred_count[succ]++;
286 }
287 }
288
289 // Use a multimap to sort ReadyListEntry according to their priority.
290 std::multimap<Priority, ReadyListEntry> ready_queue;
291
292 // Map of ready instructions to their iterators in ready_queue.
293 absl::flat_hash_map<const HloInstruction*,
294 std::multimap<Priority, ReadyListEntry>::iterator>
295 ready_instructions;
296
297 auto add_to_ready_queue = [&](HloInstruction* inst) {
298 auto entry = MakeReadyListEntry(inst);
299 auto it = ready_queue.emplace(GetPriority(entry), std::move(entry));
300 ready_instructions[inst] = it;
301 };
302
303 for (auto* instruction : computation_->instructions()) {
304 if (instruction->operands().empty() &&
305 instruction->control_predecessors().empty()) {
306 add_to_ready_queue(instruction);
307 }
308 }
309
310 while (!ready_queue.empty()) {
311 // Remove the selected instruction from the ready list and add it to the
312 // schedule.
313 auto best_it = ready_queue.end();
314 --best_it;
315 HloInstruction* best = best_it->second.instruction;
316 VLOG(2) << "Schedule instruction: " << best->ToShortString()
317 << " Bytes freed: " << best_it->first.first;
318 ready_queue.erase(best_it);
319 ready_instructions.erase(best);
320 schedule.push_back(best);
321 scheduled_instructions_.insert(best);
322
323 bool adjust_ready_queue = false;
324 // Update the unscheduled uses of the logical buffers.
325 for (const LogicalBuffer* buffer : buffer_uses_.at(best)) {
326 int64& count = unscheduled_use_count_[buffer];
327 CHECK_GT(count, 0);
328 --count;
329 if (count == 1) {
330 adjust_ready_queue = true;
331 }
332 }
333
334 // Add new instructions to ready list.
335 auto update_pred_count = [&](HloInstruction* inst) {
336 int64 pred_count = --unscheduled_pred_count.at(inst);
337 CHECK_GE(pred_count, 0);
338 if (pred_count == 0) {
339 add_to_ready_queue(inst);
340 }
341 };
342 // TODO(b/34466113): Replace this and above with successors() or
343 // predecessors() when these methods are added to HloInstruction.
344 for (HloInstruction* user : best->users()) {
345 update_pred_count(user);
346 }
347 for (HloInstruction* succ : best->control_successors()) {
348 update_pred_count(succ);
349 }
350 // The unscheduled use count for a buffer has changed to 1, so the
351 // priorities of some ready instructions may go up. We update them in the
352 // ready queue, so that they can appear earlier.
353 if (adjust_ready_queue) {
354 for (HloInstruction* operand : best->operands()) {
355 for (HloInstruction* operand_user : operand->users()) {
356 auto ready_instructions_it = ready_instructions.find(operand_user);
357 if (ready_instructions_it == ready_instructions.end()) {
358 continue;
359 }
360 auto ready_queue_it = ready_instructions_it->second;
361 auto& entry = ready_queue_it->second;
362 Priority new_priority = GetPriority(entry);
363 if (new_priority == ready_queue_it->first) {
364 continue;
365 }
366 // Create a new entry in ready_queue, then update
367 // ready_instructions[operand_user] to refer to the new entry.
368 ready_instructions_it->second =
369 ready_queue.emplace(new_priority, std::move(entry));
370 // Remove the old entry in ready_queue.
371 ready_queue.erase(ready_queue_it);
372 }
373 }
374 }
375 }
376 CHECK_EQ(schedule.size(), computation_->instruction_count());
377 CHECK_EQ(scheduled_instructions_.size(), computation_->instruction_count());
378
379 return schedule;
380 }
381
382 HloComputation* computation_;
383 const TuplePointsToAnalysis& points_to_analysis_;
384 const BufferValue::SizeFunction& size_function_;
385 // Computations are analyzed in post-order. When scheduling an instruction
386 // that includes subcomputations, such as a while loop, we use this map to
387 // look up the memory needed by subcomputations.
388 const absl::flat_hash_map<const HloComputation*, int64>&
389 memory_by_computation_;
390
391 // A map containing the LogicalBuffers that each instruction uses.
392 absl::flat_hash_map<const HloInstruction*, std::vector<const LogicalBuffer*>>
393 buffer_uses_;
394
395 // A map containing the count of unscheduled HLOs which using a particular
396 // LogicalBuffer.
397 absl::flat_hash_map<const LogicalBuffer*, int64> unscheduled_use_count_;
398
399 // Set of instructions which have been scheduled.
400 absl::flat_hash_set<const HloInstruction*> scheduled_instructions_;
401 };
402
SumLogicalBufferSizes(const TuplePointsToAnalysis::BufferDefinitionVector & buffers,const BufferValue::SizeFunction & size_function)403 int64 SumLogicalBufferSizes(
404 const TuplePointsToAnalysis::BufferDefinitionVector& buffers,
405 const BufferValue::SizeFunction& size_function) {
406 int64 size = 0;
407 for (const LogicalBuffer* buffer : buffers) {
408 size += size_function(*buffer);
409 }
410 return size;
411 }
412
ScheduleComputationHelper(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const HloAliasAnalysis & alias_analysis,const BufferValue::SizeFunction & size_function,const MemorySchedulerAlgorithm & algorithm,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation,int64 * peak_memory)413 StatusOr<HloInstructionSequence> ScheduleComputationHelper(
414 HloComputation* computation,
415 const TuplePointsToAnalysis& points_to_analysis,
416 const HloAliasAnalysis& alias_analysis,
417 const BufferValue::SizeFunction& size_function,
418 const MemorySchedulerAlgorithm& algorithm,
419 const absl::flat_hash_map<const HloComputation*, int64>&
420 memory_by_computation,
421 int64* peak_memory) {
422 VLOG(2) << "Computation: " << computation->name();
423
424 if (algorithm) {
425 return algorithm(computation, points_to_analysis, alias_analysis,
426 size_function, memory_by_computation, peak_memory);
427 }
428 return DefaultMemoryScheduler(computation, points_to_analysis, alias_analysis,
429 size_function, memory_by_computation,
430 peak_memory);
431 }
432
433 } // namespace
434
DFSMemoryScheduler(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const HloAliasAnalysis & alias_analysis,const BufferValue::SizeFunction & size_function,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation,int64 * peak_memory)435 StatusOr<HloInstructionSequence> DFSMemoryScheduler(
436 HloComputation* computation,
437 const TuplePointsToAnalysis& points_to_analysis,
438 const HloAliasAnalysis& alias_analysis,
439 const BufferValue::SizeFunction& size_function,
440 const absl::flat_hash_map<const HloComputation*, int64>&
441 memory_by_computation,
442 int64* peak_memory) {
443 // These variables are a hack to prevent overflows.
444 int64 cumulative_total_size = 0;
445 int64 total_hlos = computation->parent()->instruction_count();
446 absl::flat_hash_map<const HloInstruction*, int64> extra_users;
447 absl::flat_hash_map<const HloInstruction*, int64> total_sizes;
448 for (const HloInstruction* hlo : computation->MakeInstructionPostOrder()) {
449 if (ListScheduler::IgnoreInstruction(*hlo)) {
450 extra_users[hlo] = 0;
451 total_sizes[hlo] = 0;
452 continue;
453 }
454 // This ordering is based on DFS post-order, with a heuristic to decide
455 // which operand to visit first. The heuristic is based on 'extra_users',
456 // which is simply users-1 for each instruction. By subtracting 1, we're
457 // saying that instructions with no users or a single user don't count;
458 // instructions with lots of fan-out will be visited earlier.
459 extra_users[hlo] = hlo->users().empty() ? 0 : hlo->users().size() - 1;
460 int64 logical_buffer_size = SumLogicalBufferSizes(
461 points_to_analysis.GetBuffersDefinedByInstruction(hlo), size_function);
462 total_sizes[hlo] = logical_buffer_size;
463 cumulative_total_size += logical_buffer_size;
464 absl::flat_hash_set<const HloInstruction*> unique_operands(
465 hlo->operands().begin(), hlo->operands().end());
466 for (const HloInstruction* operand : unique_operands) {
467 extra_users[hlo] += extra_users[operand];
468 total_sizes[hlo] += total_sizes[operand];
469 }
470 // total_sizes[hlo] transitively includes the sizes of all nodes that
471 // lead to it. But computation is a DAG, so we are double-counting nodes,
472 // which can lead to overflows for large programs.
473 // cumulative_total_size caps the size to prevent overflows.
474 // Same for total_hlos: it prevents overflows on very large and branchy
475 // models, where the number of paths is exponential to the number of nodes.
476 // NOTE(dimvar): this is quite ugly and should be changed. It's unclear
477 // why we care about transitive sizes; when scheduling a node, its input
478 // and output buffers should be all that matters, not its "history".
479 total_sizes[hlo] = std::min(total_sizes[hlo], cumulative_total_size);
480 extra_users[hlo] = std::min(extra_users[hlo], total_hlos);
481 }
482 CHECK_EQ(extra_users.size(), computation->instruction_count());
483 CHECK_EQ(total_sizes.size(), computation->instruction_count());
484
485 // Construct a total order based on DFS post-order, visiting operands in
486 // decreasing cumulative extra user order, and next by cumulative size, with a
487 // tiebreaker by name for determinism.
488 HloInstructionSequence sequence;
489 FunctionVisitor visitor([&sequence](HloInstruction* hlo) {
490 sequence.push_back(hlo);
491 return Status::OK();
492 });
493 visitor.ReserveVisitStates(computation->instruction_count());
494 TF_RETURN_IF_ERROR(computation->AcceptWithOperandOrder(
495 &visitor, [&extra_users, &total_sizes](const HloInstruction* a,
496 const HloInstruction* b) {
497 if (extra_users[a] != extra_users[b]) {
498 return extra_users[a] > extra_users[b];
499 }
500 if (total_sizes[a] != total_sizes[b]) {
501 return total_sizes[a] > total_sizes[b];
502 }
503 return a->name() < b->name();
504 }));
505 CHECK_EQ(sequence.size(), computation->instruction_count());
506 if (peak_memory) {
507 TF_ASSIGN_OR_RETURN(
508 *peak_memory, HeapSimulator::MinimumMemoryForComputation(
509 *computation, sequence, alias_analysis, size_function,
510 &memory_by_computation));
511 }
512 return sequence;
513 } // namespace xla
514
ComputationSchedulerToModuleScheduler(const MemorySchedulerAlgorithm & computation_scheduler)515 ModuleSchedulerAlgorithm ComputationSchedulerToModuleScheduler(
516 const MemorySchedulerAlgorithm& computation_scheduler) {
517 return [computation_scheduler](
518 HloModule* module, const TuplePointsToAnalysis& points_to_analysis,
519 const HloAliasAnalysis& alias_analysis,
520 const LogicalBuffer::SizeFunction& size_func,
521 int64* peak_memory) -> StatusOr<HloSchedule> {
522 HloSchedule schedule(module);
523 absl::flat_hash_map<const HloComputation*, int64> memory_by_computation;
524 for (auto* computation : module->MakeComputationPostOrder()) {
525 if (!computation->IsFusionComputation()) {
526 TF_ASSIGN_OR_RETURN(
527 HloInstructionSequence computation_sequence,
528 ScheduleComputationHelper(
529 computation, points_to_analysis, alias_analysis, size_func,
530 computation_scheduler, memory_by_computation, nullptr));
531 schedule.set_sequence(computation, std::move(computation_sequence));
532 }
533 }
534 if (peak_memory) {
535 TF_ASSIGN_OR_RETURN(*peak_memory, HeapSimulator::MinimumMemoryForModule(
536 schedule, size_func));
537 }
538 return std::move(schedule);
539 };
540 }
541
ListMemoryScheduler(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const HloAliasAnalysis & alias_analysis,const BufferValue::SizeFunction & size_function,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation,int64 * peak_memory)542 StatusOr<HloInstructionSequence> ListMemoryScheduler(
543 HloComputation* computation,
544 const TuplePointsToAnalysis& points_to_analysis,
545 const HloAliasAnalysis& alias_analysis,
546 const BufferValue::SizeFunction& size_function,
547 const absl::flat_hash_map<const HloComputation*, int64>&
548 memory_by_computation,
549 int64* peak_memory) {
550 TF_ASSIGN_OR_RETURN(HloInstructionSequence sequence,
551 ListScheduler::Run(computation, points_to_analysis,
552 size_function, memory_by_computation));
553 if (peak_memory) {
554 TF_ASSIGN_OR_RETURN(
555 *peak_memory, HeapSimulator::MinimumMemoryForComputation(
556 *computation, sequence, alias_analysis, size_function,
557 &memory_by_computation));
558 }
559 return sequence;
560 }
561
PostOrderMemoryScheduler(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const HloAliasAnalysis & alias_analysis,const BufferValue::SizeFunction & size_function,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation,int64 * peak_memory)562 StatusOr<HloInstructionSequence> PostOrderMemoryScheduler(
563 HloComputation* computation,
564 const TuplePointsToAnalysis& points_to_analysis,
565 const HloAliasAnalysis& alias_analysis,
566 const BufferValue::SizeFunction& size_function,
567 const absl::flat_hash_map<const HloComputation*, int64>&
568 memory_by_computation,
569 int64* peak_memory) {
570 HloInstructionSequence sequence(computation->MakeInstructionPostOrder());
571 if (peak_memory) {
572 TF_ASSIGN_OR_RETURN(
573 *peak_memory, HeapSimulator::MinimumMemoryForComputation(
574 *computation, sequence, alias_analysis, size_function,
575 &memory_by_computation));
576 }
577 return sequence;
578 }
579
DefaultMemoryScheduler(HloComputation * computation,const TuplePointsToAnalysis & points_to_analysis,const HloAliasAnalysis & alias_analysis,const BufferValue::SizeFunction & size_function,const absl::flat_hash_map<const HloComputation *,int64> & memory_by_computation,int64 * peak_memory)580 StatusOr<HloInstructionSequence> DefaultMemoryScheduler(
581 HloComputation* computation,
582 const TuplePointsToAnalysis& points_to_analysis,
583 const HloAliasAnalysis& alias_analysis,
584 const BufferValue::SizeFunction& size_function,
585 const absl::flat_hash_map<const HloComputation*, int64>&
586 memory_by_computation,
587 int64* peak_memory) {
588 // We try a few schedulers and choose whichever returns a lower min-memory,
589 // not accounting for fragmentation.
590 // - List is a scheduler that uses greedy heuristics.
591 // - DFS visits HLOs in postorder, with a heuristic to decide the order of
592 // children.
593 // - Postorder does not use any heuristics.
594 // List wins for most of our benchmarks; postorder-based schedulers win for
595 // some RNNs.
596 int64 list_memory;
597 TF_ASSIGN_OR_RETURN(
598 HloInstructionSequence list_sequence,
599 ListMemoryScheduler(computation, points_to_analysis, alias_analysis,
600 size_function, memory_by_computation, &list_memory));
601 VLOG(2) << "Min-memory list sequence: " << HumanReadableNumBytes(list_memory);
602
603 int64 dfs_memory;
604 TF_ASSIGN_OR_RETURN(
605 HloInstructionSequence dfs_sequence,
606 DFSMemoryScheduler(computation, points_to_analysis, alias_analysis,
607 size_function, memory_by_computation, &dfs_memory));
608 VLOG(2) << "Min-memory dfs sequence: " << HumanReadableNumBytes(dfs_memory);
609
610 int64 post_order_memory;
611 TF_ASSIGN_OR_RETURN(
612 HloInstructionSequence post_order_sequence,
613 PostOrderMemoryScheduler(computation, points_to_analysis, alias_analysis,
614 size_function, memory_by_computation,
615 &post_order_memory));
616 VLOG(2) << "Min-memory post order sequence: "
617 << HumanReadableNumBytes(post_order_memory);
618
619 auto min_memory = std::min({dfs_memory, post_order_memory, list_memory});
620 if (peak_memory) {
621 *peak_memory = min_memory;
622 }
623
624 if (min_memory == list_memory) {
625 VLOG(2) << "Chose min-memory list sequence: "
626 << HumanReadableNumBytes(list_memory);
627 return list_sequence;
628 } else if (min_memory == dfs_memory) {
629 VLOG(2) << "Chose min-memory dfs sequence: "
630 << HumanReadableNumBytes(dfs_memory);
631 return dfs_sequence;
632 } else {
633 VLOG(2) << "Chose min-memory post_order sequence: "
634 << HumanReadableNumBytes(post_order_memory);
635 return post_order_sequence;
636 }
637 }
638
DefaultModuleScheduler(HloModule * module,const TuplePointsToAnalysis & points_to_analysis,const HloAliasAnalysis & alias_analysis,const BufferValue::SizeFunction & size_function,int64 * peak_memory)639 StatusOr<HloSchedule> DefaultModuleScheduler(
640 HloModule* module, const TuplePointsToAnalysis& points_to_analysis,
641 const HloAliasAnalysis& alias_analysis,
642 const BufferValue::SizeFunction& size_function, int64* peak_memory) {
643 // We try a few schedulers and choose whichever returns a lower min-memory,
644 // not accounting for fragmentation.
645 // - List is a scheduler that uses greedy heuristics.
646 // - DFS visits HLOs in postorder, with a heuristic to decide the order of
647 // children.
648 // - Postorder does not use any heuristics.
649 // List wins for most of our benchmarks; postorder-based schedulers win for
650 // some RNNs.
651 int64 list_memory;
652 TF_ASSIGN_OR_RETURN(
653 HloSchedule list_sequence,
654 ComputationSchedulerToModuleScheduler(ListMemoryScheduler)(
655 module, points_to_analysis, alias_analysis, size_function,
656 &list_memory));
657
658 VLOG(2) << "Min-memory list sequence: " << HumanReadableNumBytes(list_memory);
659
660 int64 dfs_memory;
661 TF_ASSIGN_OR_RETURN(HloSchedule dfs_sequence,
662 ComputationSchedulerToModuleScheduler(DFSMemoryScheduler)(
663 module, points_to_analysis, alias_analysis,
664 size_function, &dfs_memory));
665 VLOG(2) << "Min-memory dfs sequence: " << HumanReadableNumBytes(dfs_memory);
666
667 int64 post_order_memory;
668 TF_ASSIGN_OR_RETURN(
669 HloSchedule post_order_sequence,
670 ComputationSchedulerToModuleScheduler(PostOrderMemoryScheduler)(
671 module, points_to_analysis, alias_analysis, size_function,
672 &post_order_memory));
673 VLOG(2) << "Min-memory post order sequence: "
674 << HumanReadableNumBytes(post_order_memory);
675
676 auto min_memory = std::min({dfs_memory, post_order_memory, list_memory});
677 if (peak_memory) {
678 *peak_memory = min_memory;
679 }
680
681 if (min_memory == list_memory) {
682 VLOG(2) << "Chose min-memory list sequence: "
683 << HumanReadableNumBytes(list_memory);
684 return list_sequence;
685 } else if (min_memory == dfs_memory) {
686 VLOG(2) << "Chose min-memory dfs sequence: "
687 << HumanReadableNumBytes(dfs_memory);
688 return dfs_sequence;
689 } else {
690 VLOG(2) << "Chose min-memory post_order sequence: "
691 << HumanReadableNumBytes(post_order_memory);
692 return post_order_sequence;
693 }
694 }
695
ScheduleModule(HloModule * module,const BufferValue::SizeFunction & size_function,const ModuleSchedulerAlgorithm & algorithm,int64 * peak_memory)696 StatusOr<HloSchedule> ScheduleModule(
697 HloModule* module, const BufferValue::SizeFunction& size_function,
698 const ModuleSchedulerAlgorithm& algorithm, int64* peak_memory) {
699 TF_ASSIGN_OR_RETURN(std::unique_ptr<TuplePointsToAnalysis> points_to_analysis,
700 TuplePointsToAnalysis::Run(module));
701 TF_ASSIGN_OR_RETURN(std::unique_ptr<HloAliasAnalysis> alias_analysis,
702 HloAliasAnalysis::Run(module));
703
704 TF_ASSIGN_OR_RETURN(HloSchedule schedule,
705 (algorithm ? algorithm : DefaultModuleScheduler)(
706 module, *points_to_analysis, *alias_analysis,
707 size_function, peak_memory));
708
709 TF_RETURN_IF_ERROR(schedule.Verify());
710
711 return std::move(schedule);
712 }
713
ScheduleComputation(HloComputation * computation,const BufferValue::SizeFunction & size_function)714 StatusOr<HloInstructionSequence> ScheduleComputation(
715 HloComputation* computation,
716 const BufferValue::SizeFunction& size_function) {
717 CHECK(!computation->IsFusionComputation());
718 TF_ASSIGN_OR_RETURN(std::unique_ptr<TuplePointsToAnalysis> points_to_analysis,
719 TuplePointsToAnalysis::Run(computation->parent()));
720 TF_ASSIGN_OR_RETURN(std::unique_ptr<HloAliasAnalysis> alias_analysis,
721 HloAliasAnalysis::Run(computation->parent()));
722 absl::flat_hash_map<const HloComputation*, int64> empty_map;
723 return ScheduleComputationHelper(computation, *points_to_analysis,
724 *alias_analysis, size_function, nullptr,
725 empty_map, nullptr);
726 }
727
HloMemoryScheduler(const BufferValue::SizeFunction & size_function,const ModuleSchedulerAlgorithm & algorithm)728 HloMemoryScheduler::HloMemoryScheduler(
729 const BufferValue::SizeFunction& size_function,
730 const ModuleSchedulerAlgorithm& algorithm)
731 : size_function_(size_function), algorithm_(algorithm) {}
732
Run(HloModule * module)733 StatusOr<bool> HloMemoryScheduler::Run(HloModule* module) {
734 TF_ASSIGN_OR_RETURN(HloSchedule schedule,
735 ScheduleModule(module, size_function_, algorithm_));
736 TF_RETURN_IF_ERROR(module->set_schedule(std::move(schedule)));
737 return true;
738 }
739
Run(HloModule * module)740 StatusOr<bool> HloTrivialScheduler::Run(HloModule* module) {
741 HloSchedule schedule(module);
742 for (HloComputation* computation : module->MakeComputationPostOrder()) {
743 if (!computation->IsFusionComputation()) {
744 HloInstructionSequence& computation_sequence =
745 schedule.GetOrCreateSequence(computation);
746 FunctionVisitor visitor(
747 [&computation_sequence](HloInstruction* instruction) {
748 computation_sequence.push_back(instruction);
749 return Status::OK();
750 });
751 visitor.ReserveVisitStates(computation->instruction_count());
752 TF_RETURN_IF_ERROR(computation->Accept(&visitor));
753 }
754 }
755 TF_RETURN_IF_ERROR(module->set_schedule(std::move(schedule)));
756 return true;
757 }
758
Run(HloModule * module)759 StatusOr<bool> HloDescheduler::Run(HloModule* module) {
760 bool changed = module->has_schedule();
761 module->clear_schedule();
762 return changed;
763 }
764
765 } // namespace xla
766