Generate a 1F1B pipeline schedule
Why it matters Megatron-LM and DeepSpeed pipeline engines run 1F1B for large model training.
In pipeline parallelism, the 1F1B schedule warms up with forwards, then alternates one forward and one backward to limit memory.
Write one_f_one_b(stage, n_stages, n_micro). For a given stage (0-based), warmup = min(n_stages - stage - 1, n_micro) forwards. Then while forwards remain, do one forward then one backward. Then do the remaining backwards. Microbatches are numbered from 0 in order for both forwards and backwards. Return the list of ops like "F0", "B0". Also report peak in-flight activations as the max over time of (forwards done - backwards done). Return (ops, peak).
def one_f_one_b(stage, n_stages, n_micro)Example
one_f_one_b(1, 2, 3) is (["F0", "B0", "F1", "B1", "F2", "B2"], 1) and the first stage of 2 is (["F0", "F1", "B0", "F2", "B1", "B2"], 2).
Understand the idea
Pipeline parallelism splits a model's layers into stages on different GPUs and feeds microbatches through. GPipe runs all forwards first, so every stage stores activations for all microbatches. 1F1B is smarter: each stage does a few warmup forwards, then alternates one forward with one backward, and backwards free memory as they go. Earlier stages need more warmup so later stages always have work. Worked example: stage 0 of 3, 4 microbatches. warmup = min(3 - 0 - 1, 4) = 2, so F0, F1. Then alternate while forwards remain: F2, B0, F3, B1. Then drain: B2, B3. Ops [F0, F1, F2, B0, F3, B1, B2, B3]. In-flight activations peak at 3 (after F2 and again after F3), which is warmup + 1. The last stage has warmup 0, so it runs F0, B0, F1, B1 and so on with peak 1. Rule: warmup = min(n_stages - stage - 1, n_micro); emit warmup forwards; while forwards remain emit one F then one B; then emit the remaining Bs; number both sequences from 0; peak = max over time of forwards done minus backwards done. Used in: Megatron-LM and DeepSpeed pipeline schedules.
Shapes and data flow
stage s of p: warmup p - s - 1 forwards steady: F, B, F, B ... cooldown: remaining B peak activations = warmup + 1