BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving34 of 36 in topic

807. Find the largest batch size that fits in memory

EasyLLM inference and serving

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.

Functiondef 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_fn up 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.

Worked example

memory 1000 + 100 b with budget 2000 fits up to b = 10.

if mem(mid) fits, record it and search right; else search left
Topics
LLM inference and serving
Similar questions
  • Trim a chat history to fit the context windowEasy
  • Work out how many tokens fit in GPU memory for the KV cacheEasy
  • Compute TTFT, TPOT and throughput from request timestampsEasy
  • Price an API request with cached input tokensEasy
All LLM inference and serving problems
Report
807 / 903
Python 3solution.pyPython idle
1
2
3
4
def max_batch(mem_fn, budget, hi):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS