Skip to content

Commit

Permalink
Make sampling with bias numerically stable (#90)
Browse files Browse the repository at this point in the history
* Update sampling.py

Remove a slow for loop on logit bias. Make the numpy re-softmax operation numerically stable.

* Update sampling.py
  • Loading branch information
Jmkernes committed Jun 13, 2023
1 parent c64009e commit bd65c97
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions rwkv/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ def sample_probs(probs: np.ndarray, temperature: float = 1.0, top_p: float = 0.8
if logit_bias is not None:
logits = np.log(probs)

for token in logit_bias.keys():
logits[token] += logit_bias[token]

if len(logit_bias) > 0:
ids, values = zip(*logit_bias.items())
logits[list(ids)] += values

logits -= logits.max(axis=-1, keepdims=True)
probs = np.exp(logits) / np.sum(np.exp(logits))

if temperature == 0.0:
Expand Down

0 comments on commit bd65c97

Please sign in to comment.