MCPcopy Create free account
hub / github.com/microsoft/BitNet / top_p

Function top_p

gpu/sample_utils.py:9–31  ·  view source on GitHub ↗

Perform top-p (nucleus) sampling on a probability distribution. Args: probs (torch.Tensor): probability distribution tensor. p (float): probability threshold for top-p sampling. Returns: torch.Tensor: sampled token indices. Note: Top-p s

(probs: torch.Tensor, p: float)

Source from the content-addressed store, hash-verified

7
8@torch.compile
9def top_p(probs: torch.Tensor, p: float) -> torch.Tensor:
10 """
11 Perform top-p (nucleus) sampling on a probability distribution.
12
13 Args:
14 probs (torch.Tensor): probability distribution tensor.
15 p (float): probability threshold for top-p sampling.
16
17 Returns:
18 torch.Tensor: sampled token indices.
19
20 Note:
21 Top-p sampling selects the smallest set of tokens whose cumulative
22 probability mass exceeds the threshold p. The distribution is
23 renormalized based on the selected tokens.
24 """
25 probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
26 probs_sum = torch.cumsum(probs_sort, dim=-1)
27 mask = probs_sum - probs_sort > p
28 probs_sort[mask] = 0.0
29 next_token = torch.multinomial(probs_sort, num_samples=1)
30 next_token = torch.gather(probs_idx, -1, next_token)
31 return next_token

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected