(
weights: torch.Tensor, # [V, D] (may be a TP shard over dim V)
hidden_states: torch.Tensor, # [n_hidden_states, D]
num_samples: int,
temperature: torch.Tensor, # scalar (0-d)
return_probs: bool = False,
seed: int = None,
tl_matmul: bool = False,
top_k: int | None = None,
top_p: float | None = None,
use_qitra: bool = False,
tp: "TPInfo" = TP1,
)
| 27 | # gather_dim != 0), breaking torch.compile(fullgraph=True) on _sample_compiled |
| 28 | # / greedy_sample_compiled. Upstream fix is in flight (PRs #180389, #182435); |
| 29 | # patch the rule map until it lands. |
| 30 | manual_torch_name_rule_map.setdefault("torch._utils._maybe_view_chunk_cat", UserFunctionVariable) |
| 31 | |
| 32 | |
| 33 | def sample( |
| 34 | weights: torch.Tensor, # [V, D] (may be a TP shard over dim V) |
| 35 | hidden_states: torch.Tensor, # [n_hidden_states, D] |
| 36 | num_samples: int, |
| 37 | temperature: torch.Tensor, # scalar (0-d) |
| 38 | return_probs: bool = False, |
| 39 | seed: int = None, |
| 40 | tl_matmul: bool = False, |
| 41 | top_k: int | None = None, |
| 42 | top_p: float | None = None, |
| 43 | use_qitra: bool = False, |
| 44 | tp: "TPInfo" = TP1, |
| 45 | ): |
| 46 | if seed is not None: |
| 47 | torch.manual_seed(seed) |
| 48 | if tl_matmul: |
| 49 | logits = matmul(hidden_states, weights) # [n_hidden_states, V] |
| 50 | else: |
| 51 | logits = hidden_states @ weights.T # [n_hidden_states, V] |
| 52 | if tp.size > 1: |
| 53 | logits = _allgather_logits(logits) # shape [H, V_local] -> [H, V] |
| 54 | # Upcast to float32 before temperature scaling: Qitra asserts float32, and |
| 55 | # torch.multinomial produces imprecise distributions with bfloat16. |
| 56 | # See findings/upcasting-before-softmax.md. |
| 57 | logits = logits.float() / temperature |
| 58 | if use_qitra: |
| 59 | probs = apply_top_k_top_p_qitra(logits, top_k, top_p) |
| 60 | else: |
| 61 | probs = apply_top_k_top_p(logits, top_k, top_p) |
| 62 | samples = torch.multinomial(probs, num_samples, replacement=True) |
| 63 | if return_probs: |
| 64 | return samples, probs |
no test coverage detected