File size: 6,745 Bytes
74b7543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
import torch
from tqdm import tqdm
import json
import os
import re
import random
from transformers import GPTJForCausalLM, GPT2TokenizerFast, GPT2Tokenizer, AutoModelForCausalLM
from datasets import load_dataset
from torch.utils.data import DataLoader
from utils.eval.exact_match_acc import calc_acc
random.seed(0)

def extract_answer(text: str) -> str:
    if "Answer:" in text:
        text = text.split("Answer:", 1)[1]
    text = text.strip()
    return text.split("\n", 1)[0].strip()

def evaluate(model_path: str, data_path: str, batch_size: int = 64):
    # Load the fine-tuned model and tokenizer
    from transformers import AutoConfig
    
    # Explicitly load the config to ensure correct architecture (e.g., number of layers)
    try:
        config_path = model_path
        # If config.json doesn't exist in model_path, try parent directory
        if not os.path.exists(os.path.join(model_path, "config.json")):
            parent_dir = os.path.dirname(os.path.normpath(model_path))
            if os.path.exists(os.path.join(parent_dir, "config.json")):
                config_path = parent_dir
                print(f"Using config from parent directory: {config_path}")
        
        config = AutoConfig.from_pretrained(config_path)
    except Exception as e:
        print(f"Could not load config from {model_path} or parent, using default. Error: {e}")
        config = None

    try:
        from safetensors.torch import load_file
        # Try manual loading to handle torch.compile prefix (_orig_mod.)
        weights_path = os.path.join(model_path, "model.safetensors")
        if not os.path.exists(weights_path):
            weights_path = os.path.join(model_path, "pytorch_model.bin")

        if os.path.exists(weights_path):
            if weights_path.endswith(".safetensors"):
                state_dict = load_file(weights_path)
            else:
                state_dict = torch.load(weights_path, map_location="cpu")
            
            # Remove "_orig_mod." prefix added by torch.compile
            new_state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
            model = GPTJForCausalLM(config=config)
            model.load_state_dict(new_state_dict)
            print(f"Successfully loaded model from {weights_path} (cleaned prefixes)")
        else:
            model = GPTJForCausalLM.from_pretrained(model_path, config=config)
    except Exception as e:
        print(f"Manual load failed: {e}. Trying AutoModel fallback...")
        try:
            model = AutoModelForCausalLM.from_pretrained(model_path, config=config)
        except:
            model = GPTJForCausalLM.from_pretrained(model_path, config=config)
    # if the last subdfolder is "checkpoint-...", load tokenizer from the parent folder
    if os.path.basename(os.path.normpath(model_path)).startswith("checkpoint-"):
        tokenizer_path = os.path.dirname(os.path.normpath(model_path))
    else:
        tokenizer_path = model_path
    tokenizer = GPT2TokenizerFast.from_pretrained(f"{tokenizer_path}")
    # tokenizer.pad_token = tokenizer.eos_token
    tokenizer.padding_side = "left"

    # Load data
    test_data = load_dataset("json", data_files=data_path)["train"]

    def tokenize_function(example):
        tok = tokenizer(example["text"], padding="max_length", truncation=True,
                         max_length=512)
        return tok

    tokenized_test_data = test_data.map(tokenize_function, batched=True)
    tokenized_test_data.set_format("torch",
                                      columns=["input_ids", "attention_mask", "answer", "q_type"])

    # Create DataLoader for test dataset
    test_dataloader = DataLoader(
        tokenized_test_data,
        batch_size=batch_size,
        shuffle=True
    )

    all_preds = []
    all_labels = []
    all_types = []
    # Move model to GPU if available
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.to(device)

    model.eval()  # Set model to evaluation mode
    with torch.no_grad():
        for batch in tqdm(test_dataloader):
            input_ids = batch["input_ids"].to(device)
            attention_mask = batch["attention_mask"].to(device)

            # Generate predictions with greedy decoding
            generated_ids = model.generate(
                input_ids=input_ids,
                attention_mask=attention_mask,
                max_new_tokens=16,
                pad_token_id=tokenizer.pad_token_id,
                eos_token_id=tokenizer.eos_token_id,
                do_sample=False,
                num_beams=1,
            )

            # Decode predictions and labels
            gen_only = generated_ids[:, input_ids.shape[1]:]
            preds = tokenizer.batch_decode(gen_only, skip_special_tokens=True)
            preds = [extract_answer(pred) for pred in preds]
            refs = batch["answer"]

            all_preds.extend(preds)
            all_labels.extend(refs)
            all_types.extend(batch["q_type"])

    print(f"Generated {len(all_preds)} predictions")
    # Print some examples
    for pred, label, q_type in zip(all_preds[:10], all_labels[:10], all_types[:10]):
        print(f"Prediction: {pred}")
        print(f"Label: {label}")
        print(f"Type: {q_type}")
        print()

    # Calculate accuracy
    metrics = calc_acc(all_preds, all_labels, all_types)
    # only maintain the first 20 keys and "exact_match" key
    keys = list(metrics.keys())
    keys.sort()
    keys = ["exact_match"] + keys
    metrics = {k: metrics[k] for k in keys[:21]}

    # 获取当前 checkpoint 的名称 (e.g., checkpoint-1000)
    ckpt_name = os.path.basename(os.path.normpath(model_path))
    # 获取测试集的文件名 (e.g., eval_test)
    data_name = data_path.split('/')[-1].split('.')[0]
    
    save_prefix = f"{ckpt_name}_{data_name}"

    os.makedirs(f"{model_path}/output", exist_ok=True)
    with open(f"{model_path}/output/{save_prefix}_metrics.json", "w") as f:
        json.dump(metrics, f, indent=2)

    # Save predictions to a file
    jsonlist = []
    for pred, label, q_type in zip(all_preds, all_labels, all_types):
        jsonlist.append({"pred_answer": pred, "label_answer": label, "q_type": q_type})

    with open(f"{model_path}/output/{save_prefix}_predictions.json", "w") as f:
        json.dump(jsonlist, f, indent=2)



if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_path", type=str, required=True)
    parser.add_argument("--data_path", type=str, required=True)
    parser.add_argument("--batch_size", type=int, default=64)
    args = parser.parse_args()
    evaluate(args.model_path, args.data_path, batch_size=args.batch_size)