Example 1
Arguments: [
[
0.5,
0.3,
0.2
],
0.6
]
Expected result: {
"ids": [
0,
1
],
"probabilities": [
0.625,
0.375
]
}Mass 0.5 is below 0.6; adding 0.3 crosses the threshold. Normalize [0.5,0.3] by 0.8.
Decoding and sampling · Medium
Problem 25 of 50 · Python and NumPy
Given a normalized vocabulary distribution, sort token IDs by descending probability, breaking ties by smaller ID. Retain the shortest nonempty prefix whose cumulative probability is at least p, then renormalize that prefix. Return {"ids": ranked retained IDs, "probabilities": their normalized probabilities}.
At p=0 retain one token. Compare cumulative mass to p using a 1e-12 absolute boundary allowance to avoid including an extra token because of decimal summation error. Zero-probability tails are excluded once the threshold is reached.
def nucleus_candidates(probabilities, p):Arguments: [
[
0.5,
0.3,
0.2
],
0.6
]
Expected result: {
"ids": [
0,
1
],
"probabilities": [
0.625,
0.375
]
}Mass 0.5 is below 0.6; adding 0.3 crosses the threshold. Normalize [0.5,0.3] by 0.8.
Arguments: [
[
0.5,
0.3,
0.2
],
0.5
]
Expected result: {
"ids": [
0
],
"probabilities": [
1
]
}The first token reaches mass 0.5 exactly, so it alone is retained.