# SPDX-License-Identifier: Apache-2.0 """Host token selection (torch, CPU): greedy / temperature / top-k / top-p / repetition penalty. Used for token 0 of every request (the prefill's logits) and for every token of the ttnn decode engine; the DEC megakernel samples on the device (tt/mk_dec/kernels/sampler.hpp: greedy, temperature, top-k <= 64, top-p, Philox seed; no repetition penalty).""" from __future__ import annotations from typing import Iterable, Optional import torch class HostSampler: def __init__(self, temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0, repetition_penalty: float = 1.0, seed: Optional[int] = None): self.t = float(temperature or 0.0) self.k = int(top_k or 0) self.p = float(top_p if top_p is not None else 1.0) self.rp = float(repetition_penalty or 1.0) self.gen = torch.Generator().manual_seed(int(seed) & 0x7FFFFFFFFFFFFFFF if seed is not None else 0) if seed is None: self.gen.seed() def __call__(self, logits: torch.Tensor, seen: Iterable[int] = ()) -> int: lg = logits.float().reshape(-1).clone() if self.rp != 1.0: idx = torch.tensor(sorted(set(int(i) for i in seen)), dtype=torch.long) if idx.numel(): v = lg[idx] lg[idx] = torch.where(v > 0, v / self.rp, v * self.rp) # HF RepetitionPenaltyLogitsProcessor if self.t <= 0: return int(lg.argmax()) lg = lg / self.t if self.k > 0: kth = torch.topk(lg, min(self.k, lg.numel())).values[-1] lg = torch.where(lg < kth, torch.full_like(lg, float("-inf")), lg) if self.p < 1.0: s, i = torch.sort(lg, descending=True) c = torch.softmax(s, -1).cumsum(-1) drop = c - torch.softmax(s, -1) > self.p # keep the smallest prefix with mass >= p s = s.masked_fill(drop, float("-inf")) lg = torch.full_like(lg, float("-inf")).scatter(0, i, s) pr = torch.softmax(lg, -1) return int(torch.multinomial(pr, 1, generator=self.gen))