schedules.py 29 KB
Newer Older
Jared Casper's avatar
Jared Casper committed
1
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2

3
from contextlib import contextmanager
4
import torch
5
from torch.autograd.variable import Variable
6
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP
7
8

from megatron import get_args
9
from megatron import get_num_microbatches
10
from megatron import get_timers
11
from megatron import p2p_communication
12
from megatron.core import mpu
13
14
15
from megatron.utils import unwrap_model
from megatron.model import DistributedDataParallel as LocalDDP
from megatron.model import Float16Module
16
17
from megatron.model import ModelType

18

Jared Casper's avatar
Jared Casper committed
19
20
21
22
23
def get_forward_backward_func():
    args = get_args()
    if mpu.get_pipeline_model_parallel_world_size() > 1:
        if args.virtual_pipeline_model_parallel_size is not None:
            forward_backward_func = forward_backward_pipelining_with_interleaving
Lawrence McAfee's avatar
Lawrence McAfee committed
24
25
26
27
28
29
30
            assert get_num_microbatches() % \
                args.pipeline_model_parallel_size == 0, \
                'number of microbatches (%d) is not divisible by pipeline-' \
                'model-parallel-size (%d) when using interleaved schedule' % (
                    get_num_microbatches(),
                    args.pipeline_model_parallel_size,
                )
Jared Casper's avatar
Jared Casper committed
31
32
33
34
35
36
        else:
            forward_backward_func = forward_backward_pipelining_without_interleaving
    else:
        forward_backward_func = forward_backward_no_pipelining
    return forward_backward_func

37
38
def deallocate_output_tensor(out):
    '''Pseudo-deallocate (i.e., set to scalar) the output tensor's '.data' field.
39
40
41
42
43

    This method should be called right after the output tensor has been
    sent to the next pipeline stage. At this point, the output tensor is
    only useful for its '.grad_fn' field, and not its '.data'.
    '''
Lawrence McAfee's avatar
Lawrence McAfee committed
44
45
    if out is None:
        return
46
47
48
49
50
51
52
53
54
    assert isinstance(out, torch.Tensor), \
        "expected Tensor, found %s." % type(out).__name__
    assert out._base is None, \
        "counter-productive to free a view of another tensor."
    out.data = torch.empty(
        (1,),
        device = out.device,
        dtype = out.dtype,
    )
55
        
56
def custom_backward(output, grad_output):
57
58
    '''Directly call C++ autograd engine.

59
    To make the 'deallocate_output_tensor' (above) optimization work, the C++
60
61
62
63
    autograd engine must be called directly, bypassing Pytorch's
    torch.autograd.backward. Pytorch's 'backward' checks that the output and
    grad have the same shape, while C++'s 'backward' does not.
    '''
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

    assert output.numel() == 1, \
        "output should be pseudo-'freed' in schedule, to optimize memory"
    assert isinstance(output, torch.Tensor), \
        "output == '%s'." % type(output).__name__
    assert isinstance(grad_output, (torch.Tensor, type(None))), \
        "grad_output == '%s'." % type(grad_output).__name__

    # Handle scalar output
    if grad_output is None:
        assert output.numel() == 1, "implicit grad requires scalar output."
        grad_output = torch.ones_like(
            output,
            memory_format = torch.preserve_format,
        )

    # Call c++ engine [ see torch/csrc/autograd/python_engine.cpp ]
Lawrence McAfee's avatar
Lawrence McAfee committed
81
82
83
84
85
86
87
88
89
    Variable._execution_engine.run_backward(
        tensors = (output,),
        grad_tensors = (grad_output,),
        keep_graph = False,
        create_graph = False,
        inputs = tuple(),
        allow_unreachable=True,
        accumulate_grad=True,
    )
90
        
Jared Casper's avatar
Jared Casper committed
91

92
93
94
95
96
def forward_step(forward_step_func,
                 data_iterator,
                 model,
                 input_tensor,
                 forward_data_store,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
97
                 timers,
98
                 collect_non_loss_data=False):
99
100
101
102
103
104
    """Forward step for passed-in model.

    If first stage, input tensor is obtained from data_iterator, otherwise
    passed-in input_tensor is used.

    Returns output tensor."""
105
    args = get_args()
106

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
107
108
    if timers is not None:
        timers('forward-compute', log_level=2).start()
109
110
    unwrapped_model = unwrap_model(
        model, (torchDDP, LocalDDP, Float16Module))
111
112
113
114
115
116

    unwrap_output_tensor = False
    if not isinstance(input_tensor, list):
        input_tensor = [input_tensor]
        unwrap_output_tensor = True

117
    unwrapped_model.set_input_tensor(input_tensor)
118
    output_tensor, loss_func = forward_step_func(data_iterator, model)
119
    if mpu.is_pipeline_last_stage():
120
121
122
123
124
125
126
127
128
        if not collect_non_loss_data:
            output_tensor = loss_func(output_tensor)
            loss, loss_reduced = output_tensor
            output_tensor = loss / get_num_microbatches()
            forward_data_store.append(loss_reduced)
        else:
            data = loss_func(output_tensor, non_loss_data=True)
            forward_data_store.append(data)

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
129
130
    if timers is not None:
        timers('forward-compute').stop()
131

132
133
134
    # If T5 model (or other model with encoder and decoder)
    # and in decoder stack, then send encoder_hidden_state
    # downstream as well.
135
136
137
138
139
140
    if mpu.is_pipeline_stage_after_split() and \
            args.model_type == ModelType.encoder_and_decoder:
        return [output_tensor, input_tensor[-1]]
    if unwrap_output_tensor:
        return output_tensor
    return [output_tensor]
141
142


Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
143
144
def backward_step(optimizer, input_tensor, output_tensor,
                  output_tensor_grad, timers):
145
146
147
148
149
150
151
    """Backward step through passed-in output tensor.

    If last stage, output_tensor_grad is None, otherwise gradient of loss
    with respect to stage's output tensor.

    Returns gradient of loss with respect to input tensor (None if first
    stage)."""
152
153
154
155

    # NOTE: This code currently can handle at most one skip connection. It
    # needs to be modified slightly to support arbitrary numbers of skip
    # connections.
156
157
    args = get_args()

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
158
159
    if timers is not None:
        timers('backward-compute', log_level=2).start()
160
161

    # Retain the grad on the input_tensor.
162
163
164
165
166
167
168
169
170
171
172
173
    unwrap_input_tensor_grad = False
    if not isinstance(input_tensor, list):
        input_tensor = [input_tensor]
        unwrap_input_tensor_grad = True
    for x in input_tensor:
        if x is not None:
            x.retain_grad()

    if not isinstance(output_tensor, list):
        output_tensor = [output_tensor]
    if not isinstance(output_tensor_grad, list):
        output_tensor_grad = [output_tensor_grad]
174
175

    # Backward pass.
176
177
    if output_tensor_grad[0] is None:
        output_tensor = optimizer.scale_loss(output_tensor[0])
178
    custom_backward(output_tensor[0], output_tensor_grad[0])
179
180

    # Collect the grad of the input_tensor.
181
    input_tensor_grad = [None]
182
    if input_tensor is not None:
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        input_tensor_grad = []
        for x in input_tensor:
            if x is None:
                input_tensor_grad.append(None)
            else:
                input_tensor_grad.append(x.grad)

    # Handle single skip connection if it exists (encoder_hidden_state in
    # model with encoder and decoder).
    if mpu.get_pipeline_model_parallel_world_size() > 1 and \
            mpu.is_pipeline_stage_after_split() and \
            args.model_type == ModelType.encoder_and_decoder:
        if output_tensor_grad[1] is not None:
            input_tensor_grad[-1].add_(output_tensor_grad[1])
    if unwrap_input_tensor_grad:
        input_tensor_grad = input_tensor_grad[0]
199

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
200
201
    if timers is not None:
        timers('backward-compute').stop()
202
203
204
205

    return input_tensor_grad


206
207
208
209
210
211
212
213
@contextmanager
def dummy_handler():
    try:
        yield
    finally:
        pass


214
215
216
217
218
219
def forward_backward_no_pipelining(forward_step_func,
                                   data_iterator, model,
                                   optimizer,
                                   timers,
                                   forward_only,
                                   collect_non_loss_data=False):
220
221
222
223
    """Run forward and backward passes with no pipeline parallelism
    (no inter-stage communication).

    Returns dictionary with losses."""
224
225
226
    assert len(model) == 1
    model = model[0]

227
228
229
230
    context_handler = dummy_handler
    if isinstance(model, torchDDP):
        context_handler = model.no_sync

231
    forward_data_store = []
232
233
234
    input_tensor, output_tensor_grad = None, None
    with context_handler():
        for i in range(get_num_microbatches() - 1):
235
236
            output_tensor = forward_step(forward_step_func, data_iterator,
                                         model, input_tensor, forward_data_store,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
237
                                         timers, collect_non_loss_data)
238
239
            if not forward_only:
                backward_step(optimizer, input_tensor, output_tensor,
240
                              output_tensor_grad, timers)
241
242
243

    # Run computation for last microbatch out of context handler (want to
    # synchronize gradients).
244
245
    output_tensor = forward_step(forward_step_func, data_iterator,
                                 model, input_tensor, forward_data_store,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
246
                                 timers, collect_non_loss_data)
Lawrence McAfee's avatar
Retro  
Lawrence McAfee committed
247

248
    if not forward_only:
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
249
250
        backward_step(optimizer, input_tensor, output_tensor,
                      output_tensor_grad, timers)
251

252
    return forward_data_store
253
254


255
256
257
258
259
260
def forward_backward_pipelining_with_interleaving(forward_step_func,
                                                  data_iterator, model,
                                                  optimizer,
                                                  timers,
                                                  forward_only, 
                                                  collect_non_loss_data=False):
261
262
263
264
    """Run interleaved 1F1B schedule (model split into model chunks), with
    communication between pipeline stages as needed.

    Returns dictionary with losses if the last stage, empty dict otherwise."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
265
266
267

    args = get_args()

268
269
    input_tensors = [[] for _ in range(len(model))]
    output_tensors = [[] for _ in range(len(model))]
270
    forward_data_store = []
271
272
273
274
    if not forward_only:
        output_tensor_grads = [[] for _ in range(len(model))]

    pipeline_parallel_size = mpu.get_pipeline_model_parallel_world_size()
275
    pipeline_parallel_rank = mpu.get_pipeline_model_parallel_rank()
276

Vijay Korthikanti's avatar
Vijay Korthikanti committed
277
    if args.sequence_parallel:
278
279
280
281
282
        seq_length = args.seq_length // mpu.get_tensor_model_parallel_world_size()
    else:
        seq_length = args.seq_length
    tensor_shape = (seq_length, args.micro_batch_size, args.hidden_size)
    
283
284
285
286
287
288
289
    # Compute number of warmup and remaining microbatches.
    num_model_chunks = len(model)
    num_microbatches = get_num_microbatches() * num_model_chunks
    all_warmup_microbatches = False
    if forward_only:
        num_warmup_microbatches = num_microbatches
    else:
290
291
292
293
294
295
        # Run all forward passes and then all backward passes if number of
        # microbatches is just the number of pipeline stages.
        # Otherwise, perform (num_model_chunks-1)*pipeline_parallel_size on
        # all workers, followed by more microbatches after depending on
        # stage ID (more forward passes for earlier stages, later stages can
        # immediately start with 1F1B).
296
297
298
299
300
        if get_num_microbatches() == pipeline_parallel_size:
            num_warmup_microbatches = num_microbatches
            all_warmup_microbatches = True
        else:
            num_warmup_microbatches = \
301
                (pipeline_parallel_size - pipeline_parallel_rank - 1) * 2
302
303
304
305
            num_warmup_microbatches += (
                num_model_chunks - 1) * pipeline_parallel_size
            num_warmup_microbatches = min(num_warmup_microbatches,
                                          num_microbatches)
306
307
308
    num_microbatches_remaining = \
        num_microbatches - num_warmup_microbatches

309
    def get_model_chunk_id(microbatch_id, forward):
310
        """Helper method to get the model chunk ID given the iteration number."""
311
312
        microbatch_id_in_group = microbatch_id % (pipeline_parallel_size * num_model_chunks)
        model_chunk_id = microbatch_id_in_group // pipeline_parallel_size
313
        if not forward:
314
315
            model_chunk_id = (num_model_chunks - model_chunk_id - 1)
        return model_chunk_id
316

317
    def forward_step_helper(microbatch_id):
318
319
320
        """Helper method to run forward step with model split into chunks
        (run set_virtual_pipeline_model_parallel_rank() before calling
        forward_step())."""
321
        model_chunk_id = get_model_chunk_id(microbatch_id, forward=True)
322
323
        mpu.set_virtual_pipeline_model_parallel_rank(model_chunk_id)

324
        # forward step
325
        if mpu.is_pipeline_first_stage():
326
327
            if len(input_tensors[model_chunk_id]) == \
                    len(output_tensors[model_chunk_id]):
328
329
                input_tensors[model_chunk_id].append(None)
        input_tensor = input_tensors[model_chunk_id][-1]
330
331
        output_tensor = forward_step(forward_step_func,
                                     data_iterator[model_chunk_id],
332
                                     model[model_chunk_id],
333
334
                                     input_tensor, 
                                     forward_data_store,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
335
                                     timers,
336
                                     collect_non_loss_data)
337
338
        output_tensors[model_chunk_id].append(output_tensor)

339
340
341
342
343
        # if forward-only, no need to save tensors for a backward pass
        if forward_only:
            input_tensors[model_chunk_id].pop()
            output_tensors[model_chunk_id].pop()

344
345
        return output_tensor

346
    def backward_step_helper(microbatch_id):
347
348
349
        """Helper method to run backward step with model split into chunks
        (run set_virtual_pipeline_model_parallel_rank() before calling
        backward_step())."""
350
        model_chunk_id = get_model_chunk_id(microbatch_id, forward=False)
351
352
353
354
355
356
357
358
359
        mpu.set_virtual_pipeline_model_parallel_rank(model_chunk_id)

        if mpu.is_pipeline_last_stage():
            if len(output_tensor_grads[model_chunk_id]) == 0:
                output_tensor_grads[model_chunk_id].append(None)
        input_tensor = input_tensors[model_chunk_id].pop(0)
        output_tensor = output_tensors[model_chunk_id].pop(0)
        output_tensor_grad = output_tensor_grads[model_chunk_id].pop(0)
        input_tensor_grad = \
360
361
362
            backward_step(optimizer,
                          input_tensor,
                          output_tensor,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
363
364
                          output_tensor_grad,
                          timers)
365
366
367
368
369

        return input_tensor_grad

    # Run warmup forward passes.
    mpu.set_virtual_pipeline_model_parallel_rank(0)
370
    input_tensors[0].append(
371
        p2p_communication.recv_forward(tensor_shape, timers=timers))
372
373
    for k in range(num_warmup_microbatches):
        output_tensor = forward_step_helper(k)
374
375

        # Determine if tensor should be received from previous stage.
376
377
378
379
380
381
382
        next_forward_model_chunk_id = get_model_chunk_id(k+1, forward=True)
        recv_prev = True
        if mpu.is_pipeline_first_stage(ignore_virtual=True):
            if next_forward_model_chunk_id == 0:
                recv_prev = False
        if k == (num_microbatches - 1):
            recv_prev = False
383
384

        # Don't send tensor downstream if on last stage.
385
386
        if mpu.is_pipeline_last_stage():
            output_tensor = None
387
388
389

        # Send and receive tensors as appropriate (send tensors computed
        # in this iteration; receive tensors for next iteration).
390
391
392
393
394
395
396
        if k == (num_warmup_microbatches - 1) and not forward_only and \
                not all_warmup_microbatches:
            input_tensor_grad = None
            recv_next = True
            if mpu.is_pipeline_last_stage(ignore_virtual=True):
                recv_next = False
            input_tensor, output_tensor_grad = \
397
                p2p_communication.send_forward_backward_recv_forward_backward(
398
399
                        output_tensor, input_tensor_grad,
                        recv_prev=recv_prev, recv_next=recv_next,
400
                        tensor_shape=tensor_shape,
401
402
403
                        timers=timers)
            output_tensor_grads[num_model_chunks-1].append(output_tensor_grad)
        else:
404
            input_tensor = \
405
                p2p_communication.send_forward_recv_forward(
406
407
408
                    output_tensor, recv_prev=recv_prev,
                    tensor_shape=tensor_shape,
                    timers=timers)
409
        input_tensors[next_forward_model_chunk_id].append(input_tensor)
410
        deallocate_output_tensor(output_tensor)
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

    # Run 1F1B in steady state.
    for k in range(num_microbatches_remaining):
        # Forward pass.
        forward_k = k + num_warmup_microbatches
        output_tensor = forward_step_helper(forward_k)

        # Backward pass.
        backward_k = k
        input_tensor_grad = backward_step_helper(backward_k)

        # Send output_tensor and input_tensor_grad, receive input_tensor
        # and output_tensor_grad.

        # Determine if current stage has anything to send in either direction,
        # otherwise set tensor to None.
        forward_model_chunk_id = get_model_chunk_id(forward_k, forward=True)
        mpu.set_virtual_pipeline_model_parallel_rank(forward_model_chunk_id)
        if mpu.is_pipeline_last_stage():
            output_tensor = None

        backward_model_chunk_id = get_model_chunk_id(backward_k, forward=False)
        mpu.set_virtual_pipeline_model_parallel_rank(backward_model_chunk_id)
        if mpu.is_pipeline_first_stage():
            input_tensor_grad = None

        # Determine if peers are sending, and where in data structure to put
        # received tensors.
        recv_prev = True
        if mpu.is_pipeline_first_stage(ignore_virtual=True):
            # First stage is ahead of last stage by (pipeline_parallel_size - 1).
            next_forward_model_chunk_id = get_model_chunk_id(
                forward_k - (pipeline_parallel_size - 1), forward=True)
            if next_forward_model_chunk_id == (num_model_chunks - 1):
                recv_prev = False
            next_forward_model_chunk_id += 1
        else:
448
449
            next_forward_model_chunk_id = get_model_chunk_id(forward_k + 1,
                                                             forward=True)
450
451
452
453
454
455
456
457
458
459

        recv_next = True
        if mpu.is_pipeline_last_stage(ignore_virtual=True):
            # Last stage is ahead of first stage by (pipeline_parallel_size - 1).
            next_backward_model_chunk_id = get_model_chunk_id(
                backward_k - (pipeline_parallel_size - 1), forward=False)
            if next_backward_model_chunk_id == 0:
                recv_next = False
            next_backward_model_chunk_id -= 1
        else:
460
461
            next_backward_model_chunk_id = get_model_chunk_id(backward_k + 1,
                                                              forward=False)
462

463
464
        # If last iteration, don't receive; we already received one extra
        # before the start of the for loop.
465
466
467
468
469
        if k == (num_microbatches_remaining - 1):
            recv_prev = False

        # Communicate tensors.
        input_tensor, output_tensor_grad = \
470
            p2p_communication.send_forward_backward_recv_forward_backward(
471
472
                    output_tensor, input_tensor_grad,
                    recv_prev=recv_prev, recv_next=recv_next,
473
                    tensor_shape=tensor_shape, timers=timers)
474
        deallocate_output_tensor(output_tensor)
475

476
477
        # Put input_tensor and output_tensor_grad in data structures in the
        # right location.
478
479
480
        if recv_prev:
            input_tensors[next_forward_model_chunk_id].append(input_tensor)
        if recv_next:
481
482
            output_tensor_grads[next_backward_model_chunk_id].append(
                output_tensor_grad)
483

484
    # Run cooldown backward passes (flush out pipeline).
485
486
487
    if not forward_only:
        if all_warmup_microbatches:
            output_tensor_grads[num_model_chunks-1].append(
488
                p2p_communication.recv_backward(tensor_shape, timers=timers))
489
490
491
492
493
494
495
496
497
498
        for k in range(num_microbatches_remaining, num_microbatches):
            input_tensor_grad = backward_step_helper(k)
            next_backward_model_chunk_id = get_model_chunk_id(k+1, forward=False)
            recv_next = True
            if mpu.is_pipeline_last_stage(ignore_virtual=True):
                if next_backward_model_chunk_id == (num_model_chunks - 1):
                    recv_next = False
            if k == (num_microbatches - 1):
                recv_next = False
            output_tensor_grads[next_backward_model_chunk_id].append(
499
                p2p_communication.send_backward_recv_backward(
500
501
502
                    input_tensor_grad, recv_next=recv_next,
                    tensor_shape=tensor_shape,
                    timers=timers))
503

504
    return forward_data_store
505
506


507
508
509
510
511
512
513
514
515
516
517
def get_tensor_shapes(rank, model_type):
    # Determine right tensor sizes (based on position of rank with respect to split
    # rank) and model size.
    # Send two tensors if model is T5 and rank is in decoder stage:
    #     first tensor is decoder (pre-transpose),
    #     second tensor is encoder (post-transpose).
    # If model is T5 and rank is at the boundary:
    #     send one tensor (post-transpose from encoder).
    # Otherwise, send one tensor (pre-transpose).
    args = get_args()
    tensor_shapes = []
518

Vijay Korthikanti's avatar
Vijay Korthikanti committed
519
    if args.sequence_parallel:
520
        seq_length = args.seq_length // mpu.get_tensor_model_parallel_world_size()
521
522
523
524
    else:
        seq_length = args.seq_length

    if model_type == ModelType.encoder_and_decoder:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
525
        if args.sequence_parallel:
526
527
            decoder_seq_length = args.decoder_seq_length // mpu.get_tensor_model_parallel_world_size()
        else:
528
            decoder_seq_length = args.decoder_seq_length
529

530
        if mpu.is_pipeline_stage_before_split(rank):
531
            tensor_shapes.append((seq_length, args.micro_batch_size, args.hidden_size))
532
        else:
533
534
            tensor_shapes.append((decoder_seq_length, args.micro_batch_size, args.hidden_size))
            tensor_shapes.append((seq_length, args.micro_batch_size, args.hidden_size))
535
    else:
536
        tensor_shapes.append((seq_length, args.micro_batch_size, args.hidden_size))
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
    return tensor_shapes


def recv_forward(tensor_shapes, timers):
    input_tensors = []
    for tensor_shape in tensor_shapes:
        if tensor_shape is None:
            input_tensors.append(None)
        else:
            input_tensors.append(p2p_communication.recv_forward(tensor_shape,
                                                                timers=timers))
    return input_tensors


def recv_backward(tensor_shapes, timers):
    output_tensor_grads = []
    for tensor_shape in tensor_shapes:
        if tensor_shape is None:
            output_tensor_grads.append(None)
        else:
            output_tensor_grads.append(p2p_communication.recv_backward(tensor_shape,
                                                                       timers=timers))
    return output_tensor_grads


def send_forward(output_tensors, tensor_shapes, timers):
    if not isinstance(output_tensors, list):
        output_tensors = [output_tensors]
    for (output_tensor, tensor_shape) in zip(output_tensors, tensor_shapes):
        if tensor_shape is None:
            continue
        p2p_communication.send_forward(output_tensor, tensor_shape, timers=timers)


def send_backward(input_tensor_grads, tensor_shapes, timers):
    if not isinstance(input_tensor_grads, list):
        input_tensor_grads = [input_tensor_grads]
    for (input_tensor_grad, tensor_shape) in zip(input_tensor_grads, tensor_shapes):
        if tensor_shape is None:
            continue
        p2p_communication.send_backward(input_tensor_grad, tensor_shape, timers=timers)


def send_forward_recv_backward(output_tensors, tensor_shapes, timers):
    if not isinstance(output_tensors, list):
        output_tensors = [output_tensors]
    output_tensor_grads = []
    for (output_tensor, tensor_shape) in zip(output_tensors, tensor_shapes):
        if tensor_shape is None:
            output_tensor_grads.append(None)
            continue
        output_tensor_grad = p2p_communication.send_forward_recv_backward(
                output_tensor, tensor_shape, timers=timers)
        output_tensor_grads.append(output_tensor_grad)
    return output_tensor_grads


def send_backward_recv_forward(input_tensor_grads, tensor_shapes, timers):
    if not isinstance(input_tensor_grads, list):
        input_tensor_grads = [input_tensor_grads]
    input_tensors = []
    for (input_tensor_grad, tensor_shape) in zip(input_tensor_grads, tensor_shapes):
        if tensor_shape is None:
            input_tensors.append(None)
            continue
        input_tensor = p2p_communication.send_backward_recv_forward(
                input_tensor_grad, tensor_shape, timers=timers)
        input_tensors.append(input_tensor)
    return input_tensors


608
609
610
611
612
613
614
def forward_backward_pipelining_without_interleaving(forward_step_func,
                                                     data_iterator,
                                                     model,
                                                     optimizer,
                                                     timers,
                                                     forward_only,
                                                     collect_non_loss_data=False):
615
616
617
618
    """Run non-interleaved 1F1B schedule, with communication between pipeline
    stages.

    Returns dictionary with losses if the last stage, empty dict otherwise."""
619
    args = get_args()
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
620
    
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    assert len(model) == 1
    model = model[0]

    # Compute number of warmup microbatches.
    num_microbatches = get_num_microbatches()
    num_warmup_microbatches = \
        (mpu.get_pipeline_model_parallel_world_size() -
         mpu.get_pipeline_model_parallel_rank() - 1)
    num_warmup_microbatches = min(
        num_warmup_microbatches,
        num_microbatches)
    num_microbatches_remaining = \
        num_microbatches - num_warmup_microbatches

635
636
637
638
639
640
641
    unwrapped_model = unwrap_model(
        model, (torchDDP, LocalDDP, Float16Module))
    model_type = unwrapped_model.model_type
    rank = mpu.get_pipeline_model_parallel_rank()
    recv_tensor_shapes = get_tensor_shapes(rank-1, model_type)
    send_tensor_shapes = get_tensor_shapes(rank, model_type)

642
643
644
645
646
647
    # Input, output tensors only need to be saved when doing backward passes
    input_tensors = None
    output_tensors = None
    if not forward_only:
        input_tensors = []
        output_tensors = []
648
    forward_data_store = []
649
650
651

    # Run warmup forward passes.
    for i in range(num_warmup_microbatches):
652
        input_tensor = recv_forward(recv_tensor_shapes, timers=timers)
653
        output_tensor = forward_step(forward_step_func, data_iterator, model,
654
                                     input_tensor, forward_data_store,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
655
                                     timers, collect_non_loss_data)
656
        send_forward(output_tensor, send_tensor_shapes, timers=timers)
657

658
659
660
        if not forward_only:
            input_tensors.append(input_tensor)
            output_tensors.append(output_tensor)
661
            deallocate_output_tensor(output_tensor[0])
662
663
664
665
666

    # Before running 1F1B, need to receive first forward tensor.
    # If all microbatches are run in warmup / cooldown phase, then no need to
    # receive this tensor here.
    if num_microbatches_remaining > 0:
667
        input_tensor = recv_forward(recv_tensor_shapes, timers=timers)
668
669
670
671
672
673

    # Run 1F1B in steady state.
    for i in range(num_microbatches_remaining):
        last_iteration = (i == (num_microbatches_remaining - 1))

        output_tensor = forward_step(forward_step_func, data_iterator, model,
674
                                     input_tensor, forward_data_store,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
675
                                     timers, collect_non_loss_data)
676
        if forward_only:
677
            send_forward(output_tensor, send_tensor_shapes, timers=timers)
678
679

            if not last_iteration:
680
                input_tensor = recv_forward(recv_tensor_shapes, timers=timers)
681

682
        else:
683
            output_tensor_grad = \
684
685
686
                send_forward_recv_backward(output_tensor,
                                           send_tensor_shapes,
                                           timers=timers)
687

688
689
690
            # Add input_tensor and output_tensor to end of list.
            input_tensors.append(input_tensor)
            output_tensors.append(output_tensor)
691
            deallocate_output_tensor(output_tensor[0])
692

693
694
695
696
            # Pop input_tensor and output_tensor from the start of the list for
            # the backward pass.
            input_tensor = input_tensors.pop(0)
            output_tensor = output_tensors.pop(0)
697
698
699

            input_tensor_grad = \
                backward_step(optimizer, input_tensor, output_tensor,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
700
                              output_tensor_grad, timers)
701
702
703

            if last_iteration:
                input_tensor = None
704
                send_backward(input_tensor_grad, recv_tensor_shapes, timers=timers)
705
            else:
706
                input_tensor = \
707
708
                    send_backward_recv_forward(
                        input_tensor_grad, recv_tensor_shapes, timers=timers)
709
710
711
712
713
714
715

    # Run cooldown backward passes.
    if not forward_only:
        for i in range(num_warmup_microbatches):
            input_tensor = input_tensors.pop(0)
            output_tensor = output_tensors.pop(0)

716
            output_tensor_grad = recv_backward(send_tensor_shapes, timers=timers)
717
718
719

            input_tensor_grad = \
                backward_step(optimizer, input_tensor, output_tensor,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
720
                              output_tensor_grad, timers)
721

722
            send_backward(input_tensor_grad, recv_tensor_shapes, timers=timers)
723

724
    return forward_data_store