| 1 | import mlx.core as mx |
| 2 | |
| 3 | |
| 4 | def top_p_sampling(logits: mx.array, top_p: float, temperature: float) -> mx.array: |
| 5 | """ |
| 6 | Apply top-p (nucleus) sampling to logits. |
| 7 | |
| 8 | Args: |
| 9 | logits: The logits from the model's output. |
| 10 | top_p: The cumulative probability threshold for top-p filtering. |
| 11 | temperature: Temperature parameter for softmax distribution reshaping. |
| 12 | Returns: |
| 13 | token selected based on the top-p criterion. |
| 14 | """ |
| 15 | if ( |
| 16 | logits.dtype == mx.bfloat16 |
| 17 | ): # workaround for unable to load kernel contiguous_scan_inclusive_sum_bfloat16_bfloat16 |
| 18 | logits = logits.astype(mx.float32) |
| 19 | |
| 20 | # referenced implementation from https://github.com/huggingface/transformers/blob/main/src/transformers/generation/logits_process.py#L449-L460 |
| 21 | probs = mx.softmax(logits / temperature, axis=-1) |
| 22 | |
| 23 | # sort probs in ascending order |
| 24 | sorted_indices = mx.argsort(probs, axis=-1) |
| 25 | sorted_probs = probs[..., sorted_indices.squeeze(0)] |
| 26 | |
| 27 | cumulative_probs = mx.cumsum(sorted_probs, axis=-1) |
| 28 | |
| 29 | # select tokens with cumulative probs below threshold |
| 30 | top_probs = mx.where( |
| 31 | cumulative_probs > 1 - top_p, |
| 32 | sorted_probs, |
| 33 | mx.zeros_like(sorted_probs), |
| 34 | ) |
| 35 | |
| 36 | sorted_token = mx.random.categorical(mx.log(top_probs)) |
| 37 | token = sorted_indices.squeeze(0)[sorted_token] |
| 38 | |
| 39 | return token |