Junior interview questionAsked at Cohere, Mistral AI · interview write-up
Given logits from a toy language model, implement greedy, top-k and top-p decoding in NumPy.
Model answer
Greedy takes the argmax. Both samplers sort the probabilities, keep a prefix, renormalise it and sample.
import numpy as np
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def pick(logits, rng, mode="greedy", k=5, p=0.9,
temp=1.0):
if mode == "greedy":
return int(np.argmax(logits))
probs = softmax(logits / temp)
order = np.argsort(probs)[::-1] # high to low
if mode == "top_k":
keep = order[:k]
else: # top_p
cum = np.cumsum(probs[order])
keep = order[:np.searchsorted(cum, p) + 1]
q = probs[keep] / probs[keep].sum()
return int(rng.choice(keep, p=q))
Interviewers check the max subtracted in softmax, that top-p keeps the token that crosses p, and the renormalisation before sampling.
Practise the rest
9 Sampling questions, 492 in all, each with a model answer. Free.
More from Cohere interview questions, Mistral AI interview questions.
More Sampling interview questions
- What are logits, and how does a model go from them to a whole sentence of output?
- Explain temperature, top-k and top-p. Why would you usually reach for top-p rather than a fixed k?
- Greedy decoding on a small model gives fluent text that soon repeats itself word for word. Why does that happen?
- Your integration tests call a hosted model at temperature 0 and compare the output with an exact string. They fail now and then. What's going on, and what do you change?
- A PM wants to show users a 'confidence' percentage computed from the answer's token probabilities. What's your position, and what would you build instead?
- Write beam search that returns each sentence with its probability. How does it differ from greedy decoding?