-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.py
76 lines (61 loc) · 2.12 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
import argparse
import torch
import torch
import numpy as np
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
from ppl_data import get_loaders
from torch.amp import autocast
def PPLMetric(model,
tokenizer,
datasets,
seq_len=128,
batch_size=4,
device="cuda"):
metric = {}
for dataset in datasets:
_, test_loader = get_loaders(dataset,
tokenizer,
seq_len=seq_len,
batch_size=batch_size)
ppl = llama_eval(model, test_loader, device)
metric[dataset] = ppl
print(metric)
return metric
@torch.no_grad()
def llama_eval(model, test_lodaer, device):
nlls = []
n_samples = 0
for batch in tqdm(test_lodaer):
batch = batch.to(device)
output = model(batch)
lm_logits = output.logits
shift_logits = lm_logits[:, :-1, :].contiguous()
shift_labels = batch[:, 1:].contiguous()
loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)),
shift_labels.view(-1))
nlls.append(loss)
#print(torch.cat(nlls, dim=-1).mean())
ppl = np.exp(torch.cat(nlls, dim=-1).mean().item())
return ppl.item()
def main(args):
device = 'cuda:0'
model = AutoModelForCausalLM.from_pretrained(args.model)
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=False)
model = model.to(device)
with autocast('cuda'):
ppl = PPLMetric(model,
tokenizer, ['wikitext2', 'ptb'],
seq_len=2048,
device=device)
print(ppl)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Tuning Pruned LLM')
# Model Type&Path
parser.add_argument('--model',
type=str,
default="decapoda-research/llama-7b-hf",
help='base model name')
args = parser.parse_args()
main(args)