-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathtest_ppl.py
More file actions
63 lines (50 loc) · 2.11 KB
/
test_ppl.py
File metadata and controls
63 lines (50 loc) · 2.11 KB
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
import math
import requests
from datasets import load_dataset
from tqdm import tqdm
from transformers import AutoTokenizer
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model-path", type=str, required=True)
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--endpoint", type=str, default="/completions")
parser.add_argument("--chunk", type=int, default=512)
args = parser.parse_args()
API_URL = "http://localhost:" + str(args.port) + args.endpoint
CHUNK_SIZE = args.chunk
dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
# Local tokenizer used for chunking
tokenizer = AutoTokenizer.from_pretrained(args.model_path)
total_neg_log_likelihood = 0.0
total_tokens = 0
for example in tqdm(dataset, desc="Evaluating PPL"):
text = example["text"].strip()
if not text:
continue
# endcode, chunk and decode
tokens = tokenizer.encode(text, add_special_tokens=False)
# 使用与jiuge_ppl.py相同的分割逻辑,只处理完整的chunk
for i in range(0, len(tokens) - CHUNK_SIZE + 1, CHUNK_SIZE):
chunk_tokens = tokens[i : i + CHUNK_SIZE]
chunk_text = tokenizer.decode(chunk_tokens)
resp = requests.post(
API_URL,
headers={"Content-Type": "application/json"},
json={
"model": "",
"prompt": chunk_text,
"max_tokens": 0,
"temperature": 1.0,
"echo": True,
"logprobs": 0,
},
).json()
logprobs = resp["choices"][0]["logprobs"]["token_logprobs"]
# skip first token's None
valid_logprobs = [lp for lp in logprobs[1:] if lp is not None]
total_neg_log_likelihood += -sum(valid_logprobs)
total_tokens += len(valid_logprobs)
# ==== Compute final PPL ====
ppl = math.exp(total_neg_log_likelihood / total_tokens)
print(f"Perplexity: {ppl:.4f}")