Implement dynamic batching for token decoding
Company: xAI
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates dynamic batching, per-request state management, and sequence-decoding correctness for language-model inference, including handling stop conditions, max-token limits, and maintaining a correct slot-to-request mapping.
Constraints
- 1 <= batch_size <= 1000
- 0 <= len(requests) <= 10000
- 0 <= request['max_tokens'] <= 10000
- Exactly one of request['stop_token'] or request['stop_sequence'] is non-None
- If present, request['stop_sequence'] is non-empty
- All tokens are integers
- The sum of all generated tokens actually produced across all requests is at most 100000
- Every prefix your engine queries exists in next_token_map
Examples
Input: (2, [{'prompt_tokens': [1], 'max_tokens': 4, 'stop_token': 4, 'stop_sequence': None}, {'prompt_tokens': [5], 'max_tokens': 5, 'stop_token': None, 'stop_sequence': [7, 8]}, {'prompt_tokens': [9], 'max_tokens': 2, 'stop_token': 99, 'stop_sequence': None}], {(1,): 2, (1, 2): 3, (1, 2, 3): 4, (5,): 6, (5, 6): 7, (5, 6, 7): 8, (9,): 10, (9, 10): 11})
Expected Output: [[2, 3, 4], [6, 7, 8], [10, 11]]
Explanation: Requests 0 and 1 start first. Both finish after the third model call, freeing slots. Request 2 is then inserted and runs alone. The stop token 4 and stop sequence [7, 8] are included in the outputs.
Input: (3, [{'prompt_tokens': [4], 'max_tokens': 0, 'stop_token': 9, 'stop_sequence': None}, {'prompt_tokens': [], 'max_tokens': 3, 'stop_token': None, 'stop_sequence': [7, 8]}, {'prompt_tokens': [2], 'max_tokens': 1, 'stop_token': 5, 'stop_sequence': None}], {(): 7, (7,): 8, (2,): 3})
Expected Output: [[], [7, 8], [3]]
Explanation: The first request finishes immediately because max_tokens is 0. The batch is partially filled. The second request stops when its generated suffix becomes [7, 8], and the third request stops after one token because of max_tokens.
Hints
- Use a fixed-size array for batch slots, where each slot stores the request ID currently occupying that slot.
- For a stop sequence, you only need to compare the end of the generated output after appending the newest token.