874. Count token frequencies fast
Why it matters Counting tokens is the first step of BPE training, vocabulary pruning and data mix analysis. np.bincount is the tool.
token_counts(ids, vocab_size) returns how many times each token id appears.
Inputs: ids is a list or ndarray of ints in [0, vocab_size). It can be empty. vocab_size is an int >= 1.
Return an ndarray of ints with shape (vocab_size,).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 15 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def token_counts(ids, vocab_size)Example 1
Input: token_counts([0, 2, 2, 3], 5)
Output: [1, 0, 2, 1, 0]
Example 2
Input: ids = [], vocab_size = 3
Output: [0, 0, 0]
Example 3
Input: ids = [1, 1, 1], vocab_size = 2
Output: [0, 3]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
np.bincount counts non-negative ints.
Hint 2
Pass minlength=vocab_size.
Hint 3
Convert an empty list with dtype=int so bincount accepts it.
Common mistakes
- Using
np.uniqueand forgetting the missing ids. np.histogramwith float bins, which is slower and has edge rules.- Converting to a Python Counter, which is still a loop.
Understand the idea
Each loop iteration touches one NumPy scalar, which costs far more than the addition itself. np.bincount does the whole count in C. minlength makes sure ids that never appear still get a 0, so the output always has vocab_size entries.
Shapes and data flow
ids: (n,). Output: (vocab_size,).