807. Find the largest batch size that fits in memory
Why it matters Capacity planning for vLLM-style servers and finding the largest training micro-batch both come down to this search.
Memory use grows with batch size, so serving teams binary search for the largest batch that still fits instead of trying every size.
Write max_batch(mem_fn, budget, hi). mem_fn(b) returns the bytes needed for batch size b and never decreases as b grows. Return the largest b in [1, hi] with mem_fn(b) <= budget, or 0 if even b = 1 does not fit. Call mem_fn at most about log2(hi) + 2 times.
def max_batch(mem_fn, budget, hi)Example 1
Input: max_batch(lambda b: 1000 + 100 * b, 2000, 64)
Output: 10
Example 2
Input: mem_fn = lambda b: 10 * b, budget = 5, hi = 100
Output: 0
Example 3
Input: mem_fn = lambda b: b * b, budget = 10 ** 6, hi = 5000
Output: 1000
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
The answer is the last b where mem_fn(b) <= budget.
Hint 2
Keep lo and hi, test the middle, and move one end each time.
Common mistakes
- Linear search, which calls
mem_fnup to hi times. - Returning lo instead of the last size that fit, an off-by-one.
Understand the idea
Because memory never decreases with b, the sizes that fit form a prefix 1..B. Binary search keeps an interval that must contain B and halves it with each call.
memory 1000 + 100 b with budget 2000 fits up to b = 10.
if mem(mid) fits, record it and search right; else search left