783. Split model layers into pipeline stages to minimize the slowest stage
In pipeline parallel training, each GPU runs a contiguous block of layers, and the whole pipeline moves at the speed of its slowest stage. So you want to cut the layer list into stages that keep the largest stage cost as small as possible.
Write min_max_stage_load(layer_costs, k). layer_costs is a non-empty list of positive integers, the cost of each layer in order. Split it into at most k contiguous, non-empty stages (layers cannot be reordered). Return the smallest possible value of the largest stage sum.
If k is larger than the number of layers, every layer can get its own stage.
def min_max_stage_load(layer_costs, k)Example 1
Input: min_max_stage_load([4, 2, 7, 1, 5], 2)
Output: 13, from the split [4, 2, 7] and [1, 5]
Example 2
Input: min_max_stage_load([1, 2, 3, 4, 5], 3)
Output: 6, from [1, 2, 3], [4] and [5]
Constraints
- 1 <=
len(layer_costs)<= 100,000 - Each cost is a positive integer up to 10^6
- 1 <= k <= 100,000
Hint 1
The answer is between max(layer_costs) and sum(layer_costs).
Hint 2
Write a function that counts stages needed for a given limit.
Hint 3
Use lo < hi and move hi to mid when feasible.
Common mistakes
- Starting the search at 0 or 1 instead of the largest layer, which lets the greedy check pass impossible limits.
- Reordering layers or sorting the list, which breaks the contiguous rule.
- Off by one in the binary search that returns a value one too high.
Understand the idea
Binary search on the answer is a pattern for problems where you cannot easily compute the best value directly, but you can quickly check whether a given value is good enough. Here the check is: with a stage limit of L, how many stages does a greedy pass need? For [4, 2, 7, 1, 5] and L = 13, the greedy pass makes [4, 2, 7] then [1, 5], which is 2 stages, so 13 works. L = 12 forces [4, 2], [7, 1], [5], which is 3 stages, so it fails for k = 2. The same idea sizes pipeline stages, picks the smallest batch that fits a latency budget, and shards data so no worker gets too much.