File size: 797 Bytes
7b6f2cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""Response-token-weighted teacher-forced loss; not a translation quality score."""
import torch
@torch.no_grad()
def evaluate_nll(model,examples,device):
    was_training=model.training
    model.eval()
    total=0.0; count=0
    try:
        for ids,labels in examples:
            tokens=int((labels[:,1:]!=-100).sum())
            if not tokens: continue
            loss=model(ids.to(device),labels=labels.to(device),use_cache=False).loss
            if not torch.isfinite(loss): raise RuntimeError('Nonfinite validation loss')
            total+=loss.item()*tokens; count+=tokens
    finally:
        model.train(was_training)
    if count==0: raise ValueError('No supervised validation tokens')
    return {'nll':total/count,'tokens':count,'precision':'model parameter dtype; no autocast'}