Simulate a GPipe-style schedule with uneven stage times

Real pipeline stages are never perfectly balanced, and the slowest stage sets the pace. Simulating the schedule shows the true step time and how idle each GPU is, which is how you decide where to cut the layers. This is a timing simulation in Python, not a real run.

Schedule (all forward, then all backward), p stages, m micro-batches, per-stage forward times tf[s] and backward times tb[s]:
- F(s, j) is the forward of micro-batch j on stage s. It starts when both F(s - 1, j) has finished and stage s has finished F(s, j - 1).
- Backward runs micro-batches in order j = 0..m-1 and stages from last to first. B(s, j) starts when B(s + 1, j) has finished, stage s has finished B(s, j - 1), and stage s has finished all its forwards. For the last stage, B(p - 1, j) also needs F(p - 1, m - 1) done (all forwards finished there).
- Each stage runs one op at a time. Time starts at 0.

Write pipeline_schedule(tf, tb, m). Return (makespan, idle) where makespan is the finish time of the last op (B(0, m - 1)) and idle is a list with 1 - busy_s / makespan for every stage, busy_s = m * (tf[s] + tb[s]).

Signaturedef pipeline_schedule(tf, tb, m)

Example

tf = [1, 1], tb = [2, 2], m = 1. F(0)=0..1, F(1)=1..2, B(1)=2..4, B(0)=4..6. makespan 6, idle [0.5, 0.5].

Understand the idea

Real pipeline stages are not equally fast, and the slowest one sets the pace. Simulate it: every operation starts only when its input is ready AND its own GPU is free, so its start time is the later of the two. Worked example: tf = [1, 2], tb = [1, 2], m = 2. Forwards: F(0, 0) runs 0 to 1, F(0, 1) 1 to 2. F(1, 0) starts at max(1, 0) = 1 and ends 3. F(1, 1) starts at max(2, 3) = 3 and ends 5. Backwards: the last stage waits for all its forwards, so B(1, 0) runs 5 to 7 and B(1, 1) 7 to 9. B(0, 0) starts at max(7, 2) = 7, ends 8. B(0, 1) starts at max(9, 8) = 9, ends 10. Makespan 10. Busy time: stage 0 = 2 * (1 + 1) = 4, idle 0.6; stage 1 = 2 * (2 + 2) = 8, idle 0.2. Rule: start = max(finish of the data it needs, finish of this stage's previous op, and for backward all of this stage's forwards); idle_s = 1 - busy_s / makespan. Used to decide where to cut layers across GPUs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: worked examplepipeline_schedule([1, 1], [2, 2], 1)
  • Sample 2: balanced 4 stages, 8 micro-batchespipeline_schedule([1, 1, 1, 1], [2, 2, 2, 2], 8)