sampling.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import numpy as np
  2. import torch
  3. from typing import Dict
  4. from torch.nn import functional as F
  5. def sample_logits(out: torch.Tensor, temperature: float = 1.0, top_p: float = 0.8, logit_bias: Dict[int, float] = None) -> int:
  6. probs = F.softmax(out.cpu(), dim=-1).numpy()
  7. return sample_probs(probs, temperature, top_p, logit_bias)
  8. def sample_probs(probs: np.ndarray, temperature: float = 1.0, top_p: float = 0.8, logit_bias: Dict[int, float] = None) -> int:
  9. assert 0.0 <= temperature, 'temperature'
  10. assert 0.0 <= top_p <= 1.0, 'top_p'
  11. if top_p == 0.0:
  12. top_p = 1.0
  13. if logit_bias is not None:
  14. logits = np.log(probs)
  15. for token in logit_bias.keys():
  16. logits[token] += logit_bias[token]
  17. probs = np.exp(logits) / np.sum(np.exp(logits))
  18. if temperature == 0.0:
  19. return np.argmax(probs).item()
  20. if top_p < 1.0:
  21. sorted_probs = np.sort(probs)[::-1]
  22. cumulative_probs = np.cumsum(sorted_probs)
  23. cutoff = float(sorted_probs[np.argmax(cumulative_probs > top_p)])
  24. probs[probs < cutoff] = 0
  25. if temperature != 1.0:
  26. probs = np.power(probs, 1.0 / temperature)
  27. probs = probs / np.sum(probs)
  28. return np.random.choice(a=len(probs), p=probs)
粤ICP备19079148号