55. 使用逆 CDF 从固定均匀分布中进行类别采样
生产环境中的采样器通常使用固定的随机采样值进行测试。逆 CDF 采样将一个均匀分布的数字转换为一个类别。
编写 categorical_sample(probs, u)。probs 是一个总和为 1 的 1D array,u 是一个在 [0, 1) 范围内的均匀分布 1D array。对于每个 u,返回满足 cumsum(probs)[i] > u 的最小索引 i。返回一个 int array。
def categorical_sample(probs, u)示例 1
输入: categorical_sample([0.2, 0.5, 0.3], [0.1, 0.2, 0.95])
输出: [0, 1, 2]
示例 2
输入: probs = [0.5, 0.5], u = [0.5, 0.0]
输出: [1, 0]
示例 3
输入: probs = [0.3, 0.0, 0.7], u = [0.3, 0.29, 0.31]
输出: [2, 0, 2]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
The cumulative sum splits [0, 1) into consecutive intervals whose widths are the probabilities, so each u falls into exactly one category's interval.
提示 2
Compute np.cumsum(probs), then for every u find the first position whose cumulative value is strictly greater than u, using a binary search instead of a loop.
提示 3
np.searchsorted(c, u, side="right") returns the first index with c[i] > u. Clamp the result with np.minimum(idx, len(c) - 1) in case floating point makes the last cumsum slightly below 1.
理解思路
逆 CDF 采样将一个均匀分布的随机数转换为一个类别。将概率像尺子上的线段一样,从 0 到 1 首尾相连地排列;采样值 u 正好落在其中一个线段内,该线段的索引即为采样结果。
probs = [0.1, 0.6, 0.3],因此累加和为 [0.1, 0.7, 1.0]。u = 0.05 小于 0.1,所以索引为 0。u = 0.1 正好落在边界上;
规则选择满足 cumsum > u 的最小 i,由于 0.1 > 0.1 为假,因此它进入索引 1。u = 0.69 得到 1,u = 0.7 得到 2。对于 [0.05, 0.1, 0.69, 0.7] 的答案是: [0, 1, 1, 2]。
c = probs 的累加和;对于每个 u,返回第一个满足 c > u(严格大于)的索引。通过排序搜索,这是一个 "right side" 插入点。使用大于等于(greater-or-equal)会将边界采样值交给前一个类别,甚至可能选中概率为零的类别。这就是在已知 next-token 概率后 token sampling 的工作方式,而固定采样值使得采样器变得可测试。
公司2
- Google a candidate reported this question Google AI/ML, RAG and agentic AI interview (AI Engineering Insider)
- Uber the topic appears in interview reports Uber Machine Learning Engineer Interview Process
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。