concept

Top-p nucleus selection

Select a descending-probability prefix, renormalize it, then sample. The illustrative integer-weight function specifies ties by index and does not perform sampling. Actual API semantics may differ.

Formal Syntax & Structure

artificial-intelligence syntaxartificial-intelligence
smallest sorted prefix with cumulative mass >= p

Working Example

Example Snippetartificial-intelligence
def nucleus(weights, percent):    if (not weights or any(type(w) is not int or w < 0 for w in weights)            or sum(weights) == 0 or type(percent) is not int            or not 1 <= percent <= 100):        raise ValueError("need positive total and percent from 1 to 100")    order = sorted(range(len(weights)), key=lambda i: (-weights[i], i))    total = sum(weights)    mass = 0    kept = []    for i in order:        kept.append(i)        mass += weights[i]        if 100 * mass >= percent * total:            break    return kept
print(nucleus([50, 30, 20], 80))print(nucleus([50, 30, 20], 81))print(nucleus([1, 1, 0], 50))