-
Notifications
You must be signed in to change notification settings - Fork 93
/
eval.py
165 lines (127 loc) · 5.13 KB
/
eval.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# Import necessary modules
import time
import torch
import torch.nn as nn
# Import get_loaders function from data module within the same directory
from .data import get_loaders
from collections import defaultdict
import fnmatch
# Function to evaluate perplexity (ppl) on a specified model and tokenizer
def eval_ppl(args, model, tokenizer, device=torch.device("cuda:0")):
# Set dataset
dataset = "wikitext2"
# Print status
print(f"evaluating on {dataset}")
# Get the test loader
_, testloader = get_loaders(
dataset, seed=0, seqlen=model.seqlen, tokenizer=tokenizer
)
# Evaluate ppl in no grad context to avoid updating the model
with torch.no_grad():
ppl_test = eval_ppl_wikitext(model, testloader, 1, device)
return ppl_test
# Function to evaluate perplexity (ppl) specifically on the wikitext dataset
def eval_ppl_wikitext_train(model, trainloader, bs=1, device=None):
# Get input IDs
# testenc = testenc.input_ids
# Calculate number of samples
# nsamples = testenc.numel() // model.seqlen
nsamples = len(trainloader)
# List to store negative log likelihoods
nlls = []
print(f"nsamples {nsamples}")
# Loop through each batch
for i in range(0,nsamples,bs):
if i % 50 == 0:
print(f"sample {i}")
# Calculate end index
j = min(i+bs, nsamples)
# Prepare inputs and move to device
# inputs = testenc[:,(i * model.seqlen):(j * model.seqlen)].to(device)
inputs = trainloader[i][0].to(device)
inputs = inputs.reshape(j-i, model.seqlen)
# Forward pass through the model
lm_logits = model(inputs).logits
# Shift logits and labels for next token prediction
shift_logits = lm_logits[:, :-1, :].contiguous()
shift_labels = inputs[:, 1:]
# Compute loss
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
# Calculate negative log likelihood
neg_log_likelihood = loss.float() * model.seqlen * (j-i)
# Append to list of negative log likelihoods
nlls.append(neg_log_likelihood)
# Compute perplexity
ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
# Empty CUDA cache to save memory
torch.cuda.empty_cache()
return ppl.item()
# Function to evaluate perplexity (ppl) specifically on the wikitext dataset
def eval_ppl_wikitext(model, testenc, bs=1, device=None):
# Get input IDs
testenc = testenc.input_ids
# Calculate number of samples
nsamples = testenc.numel() // model.seqlen
# List to store negative log likelihoods
nlls = []
print(f"nsamples {nsamples}")
# Loop through each batch
for i in range(0,nsamples,bs):
if i % 50 == 0:
print(f"sample {i}")
# Calculate end index
j = min(i+bs, nsamples)
# Prepare inputs and move to device
inputs = testenc[:,(i * model.seqlen):(j * model.seqlen)].to(device)
inputs = inputs.reshape(j-i, model.seqlen)
# Forward pass through the model
lm_logits = model(inputs).logits
# Shift logits and labels for next token prediction
shift_logits = lm_logits[:, :-1, :].contiguous()
shift_labels = inputs[:, 1:]
# Compute loss
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
# Calculate negative log likelihood
neg_log_likelihood = loss.float() * model.seqlen * (j-i)
# Append to list of negative log likelihoods
nlls.append(neg_log_likelihood)
# Compute perplexity
ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
# Empty CUDA cache to save memory
torch.cuda.empty_cache()
return ppl.item()
def eval_zero_shot(model_name, model, tokenizer, task_list=["boolq","rte","hellaswag","winogrande","arc_challenge","arc_easy","openbookqa"],
num_fewshot=0, use_accelerate=False, add_special_tokens=False):
from lm_eval import tasks, evaluator
def pattern_match(patterns, source_list):
task_names = set()
for pattern in patterns:
for matching in fnmatch.filter(source_list, pattern):
task_names.add(matching)
return list(task_names)
task_names = pattern_match(task_list, tasks.ALL_TASKS)
model_args = f"pretrained={model_name},cache_dir=./llm_weights"
limit = None
if "70b" in model_name or "65b" in model_name:
limit = 2000
if use_accelerate:
model_args = f"pretrained={model_name},cache_dir=./llm_weights,use_accelerate=True"
results = evaluator.simple_evaluate(
model="hf-causal-experimental",
model_args=model_args,
tasks=task_names,
num_fewshot=num_fewshot,
batch_size=None,
device=None,
no_cache=True,
limit=limit,
description_dict={},
decontamination_ngrams_path=None,
check_integrity=False,
pretrained_model=model,
tokenizer=tokenizer,
add_special_tokens=add_special_tokens
)
return results