File size: 632 Bytes
a46f4fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | """Sign-aware token repetition penalty, excluding document-control token IDs."""
import math
import torch
def penalize_repetition(logits,token_ids,penalty=1.1,first_text_id=6):
if not math.isfinite(penalty) or penalty<1:raise ValueError('repetition penalty must be finite and >= 1')
if penalty==1:return logits
seen=sorted({n for n in token_ids if first_text_id<=n<logits.shape[-1]})
if not seen:return logits
ids=torch.tensor(seen,device=logits.device,dtype=torch.long)
values=logits.index_select(-1,ids)
logits.index_copy_(-1,ids,torch.where(values<0,values*penalty,values/penalty))
return logits
|