-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_ppl.py
81 lines (53 loc) · 2.34 KB
/
evaluate_ppl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import time
import torch
import torch.nn as nn
from data import get_loaders
def eval_ppl(model, tokenizer, dataset, device = torch.device("cuda:0")):
ppl_dict = {}
trainloader, testloader = get_loaders(dataset, seed=0, nsamples=128, seqlen=model.seqlen, tokenizer=tokenizer)
with torch.no_grad():
print("Evaluating done on ", dataset)
ppl_dict[dataset + "_ppl_test"] = eval_ppl_test(model, testloader, 1, device)
ppl_dict[dataset + "_ppl_train"] = eval_ppl_train(model, trainloader, 1, device)
return ppl_dict
def eval_ppl_train(model, trainloader, bs = 1, device = None):
nsamples = len(trainloader)
nlls = []
print(f"nsamples {nsamples}")
for i in range(0,nsamples,bs):
if i % 50 == 0:
print(f"sample {i}")
j = min(i+bs, nsamples)
inputs = trainloader[i][0].to(device)
inputs = inputs.reshape(j-i, model.seqlen)
lm_logits = model(inputs).logits
shift_logits = lm_logits[:, :-1, :].contiguous()
shift_labels = inputs[:, 1:]
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
neg_log_likelihood = loss.float() * model.seqlen * (j-i)
nlls.append(neg_log_likelihood)
ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
torch.cuda.empty_cache()
return ppl.item()
def eval_ppl_test(model, testenc, bs=1, device=None):
testenc = testenc.input_ids
nsamples = testenc.numel() // model.seqlen
nlls = []
print(f"nsamples {nsamples}")
for i in range(0,nsamples,bs):
if i % 50 == 0:
print(f"sample {i}")
j = min(i+bs, nsamples)
inputs = testenc[:,(i * model.seqlen):(j * model.seqlen)].to(device)
inputs = inputs.reshape(j-i, model.seqlen)
lm_logits = model(inputs).logits
shift_logits = lm_logits[:, :-1, :].contiguous()
shift_labels = inputs[:, 1:]
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
neg_log_likelihood = loss.float() * model.seqlen * (j-i)
nlls.append(neg_log_likelihood)
ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
torch.cuda.empty_cache()
return ppl.item()