File size: 10,493 Bytes
43235e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
LLM 评分脚本:评估 LLaVA 模型在 K线分析任务上的表现
使用 NVIDIA NIM API (Llama-3.2-90b) 作为评分 LLM
"""
import json
import os
import requests
from pathlib import Path
from tqdm import tqdm
from datetime import datetime

# ========= 配置 =========
NIM_API_KEY = "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"
NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"

# 评分模型选择(使用与数据生成不同的模型,避免偏差)
# 可选: "meta/llama-4-scout-17b-16e-instruct", "openai/gpt-oss-120b"
SCORING_MODEL = "meta/llama-4-scout-17b-16e-instruct"  # Llama 4 Scout

# 数据路径
TEST_DATA_PATH = Path("/workspace/data/finmultitime_hf/finmultitime_kline_llavaplus_kimi_k2_test.json")
MODEL_PREDICTIONS_PATH = Path("/workspace/output/model_predictions_v3.json")
SCORING_OUTPUT_PATH = Path("/workspace/output/llm_scoring_results_v3.json")

# ========= 评分提示模板 =========
SCORING_PROMPT_TEMPLATE = """你是一名专业的金融技术分析评审专家。请对以下 K线图技术分析回答进行评分。

## 评分任务
用户提出了一个关于股票K线图的技术分析问题,模型给出了回答。请根据以下5个维度进行评分,每个维度0-20分,总分100分。

## 评分维度
1. **完整性** (0-20分): 回答是否覆盖了问题要求的所有分析维度(如趋势划分、波动分析、强度评估、转折点、未来预判等)
2. **准确性** (0-20分): 技术分析描述是否合理准确,数据引用和形态描述是否符合常识
3. **专业性** (0-20分): 金融术语使用是否恰当(如均线、MACD、支撑位、阻力位、量价关系等)
4. **逻辑性** (0-20分): 分析推理是否有条理,因果关系是否清晰,论证是否充分
5. **实用性** (0-20分): 交易建议是否具体可操作,风险提示是否到位

## 问题
{question}

## 模型回答
{model_answer}

## 参考答案(仅供参考,不必完全一致)
{reference_answer}

## 输出格式
请严格按以下 JSON 格式输出评分结果,不要添加任何其他内容:
```json
{{
  "completeness": <0-20>,
  "accuracy": <0-20>,
  "professionalism": <0-20>,
  "logic": <0-20>,
  "practicality": <0-20>,
  "total": <0-100>,
  "brief_comment": "<一句话点评>"
}}
```
"""


def call_nim_scoring(prompt: str, max_retries: int = 3) -> dict:
    """调用 NIM API 进行评分"""
    headers = {
        "Authorization": f"Bearer {NIM_API_KEY}",
        "Content-Type": "application/json",
    }
    payload = {
        "model": SCORING_MODEL,
        "messages": [
            {
                "role": "system",
                "content": "你是一名专业的金融技术分析评审专家,请严格按照JSON格式输出评分结果。"
            },
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.1,
        "max_tokens": 512,
    }
    
    for attempt in range(max_retries):
        try:
            resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=120)
            resp.raise_for_status()
            content = resp.json()["choices"][0]["message"]["content"].strip()
            
            # 解析 JSON
            # 尝试从回复中提取 JSON
            if "```json" in content:
                json_str = content.split("```json")[1].split("```")[0].strip()
            elif "```" in content:
                json_str = content.split("```")[1].split("```")[0].strip()
            else:
                json_str = content
            
            scores = json.loads(json_str)
            return scores
            
        except Exception as e:
            print(f"  Attempt {attempt + 1} failed: {e}")
            if attempt == max_retries - 1:
                return {
                    "completeness": 0,
                    "accuracy": 0, 
                    "professionalism": 0,
                    "logic": 0,
                    "practicality": 0,
                    "total": 0,
                    "brief_comment": f"评分失败: {str(e)}",
                    "error": True
                }
    return None


def score_single_sample(sample: dict, model_prediction: str) -> dict:
    """对单个样本进行评分"""
    question = sample["conversations"][0]["value"]
    reference_answer = sample["conversations"][1]["value"]
    
    prompt = SCORING_PROMPT_TEMPLATE.format(
        question=question,
        model_answer=model_prediction,
        reference_answer=reference_answer
    )
    
    scores = call_nim_scoring(prompt)
    scores["sample_id"] = sample["id"]
    scores["task_type"] = sample.get("task_type", "unknown")
    scores["difficulty"] = sample.get("difficulty", "unknown")
    
    return scores


def run_scoring(predictions: dict, test_data: list, resume_from: dict = None):
    """运行评分流程"""
    results = resume_from if resume_from else {"scores": [], "summary": {}}
    scored_ids = {s["sample_id"] for s in results["scores"]}
    
    pending_samples = [s for s in test_data if s["id"] not in scored_ids]
    print(f"\n已评分: {len(scored_ids)}, 待评分: {len(pending_samples)}")
    
    for sample in tqdm(pending_samples, desc="LLM Scoring"):
        sample_id = sample["id"]
        
        if sample_id not in predictions:
            print(f"\n  Warning: No prediction for {sample_id}, skipping")
            continue
        
        model_pred = predictions[sample_id]
        scores = score_single_sample(sample, model_pred)
        results["scores"].append(scores)
        
        # 每10个样本保存一次
        if len(results["scores"]) % 10 == 0:
            save_results(results)
    
    # 计算汇总统计
    calculate_summary(results)
    save_results(results)
    
    return results


def calculate_summary(results: dict):
    """计算评分汇总"""
    scores = [s for s in results["scores"] if not s.get("error")]
    
    if not scores:
        results["summary"] = {"error": "No valid scores"}
        return
    
    # 总体统计
    total_scores = [s["total"] for s in scores]
    results["summary"] = {
        "total_samples": len(scores),
        "avg_total": sum(total_scores) / len(total_scores),
        "min_total": min(total_scores),
        "max_total": max(total_scores),
        "dimensions": {}
    }
    
    # 各维度统计
    for dim in ["completeness", "accuracy", "professionalism", "logic", "practicality"]:
        dim_scores = [s[dim] for s in scores]
        results["summary"]["dimensions"][dim] = {
            "avg": sum(dim_scores) / len(dim_scores),
            "min": min(dim_scores),
            "max": max(dim_scores)
        }
    
    # 按任务类型统计
    results["summary"]["by_task_type"] = {}
    for task_type in set(s["task_type"] for s in scores):
        task_scores = [s["total"] for s in scores if s["task_type"] == task_type]
        results["summary"]["by_task_type"][task_type] = {
            "count": len(task_scores),
            "avg": sum(task_scores) / len(task_scores)
        }
    
    # 按难度统计
    results["summary"]["by_difficulty"] = {}
    for diff in set(s["difficulty"] for s in scores):
        diff_scores = [s["total"] for s in scores if s["difficulty"] == diff]
        results["summary"]["by_difficulty"][diff] = {
            "count": len(diff_scores),
            "avg": sum(diff_scores) / len(diff_scores)
        }


def save_results(results: dict):
    """保存评分结果"""
    SCORING_OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    with open(SCORING_OUTPUT_PATH, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)


def print_summary(results: dict):
    """打印评分汇总"""
    summary = results.get("summary", {})
    
    print("\n" + "=" * 60)
    print("📊 LLM 评分结果汇总")
    print("=" * 60)
    
    print(f"\n📈 总体评分:")
    print(f"  样本数: {summary.get('total_samples', 0)}")
    print(f"  平均分: {summary.get('avg_total', 0):.2f} / 100")
    print(f"  最高分: {summary.get('max_total', 0)}")
    print(f"  最低分: {summary.get('min_total', 0)}")
    
    print(f"\n📋 各维度平均分 (满分20):")
    dims = summary.get("dimensions", {})
    for dim, stats in dims.items():
        dim_cn = {
            "completeness": "完整性",
            "accuracy": "准确性",
            "professionalism": "专业性",
            "logic": "逻辑性",
            "practicality": "实用性"
        }.get(dim, dim)
        print(f"  {dim_cn}: {stats['avg']:.2f}")
    
    print(f"\n📂 按任务类型:")
    for task, stats in summary.get("by_task_type", {}).items():
        print(f"  {task}: {stats['avg']:.2f} (n={stats['count']})")
    
    print(f"\n🎯 按难度:")
    for diff, stats in summary.get("by_difficulty", {}).items():
        print(f"  {diff}: {stats['avg']:.2f} (n={stats['count']})")
    
    print("\n" + "=" * 60)


def main():
    print("=" * 60)
    print("🚀 LLM 评分脚本启动")
    print(f"⏰ 时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)
    
    # 1. 加载测试数据
    print(f"\n📂 加载测试数据: {TEST_DATA_PATH}")
    with open(TEST_DATA_PATH, "r", encoding="utf-8") as f:
        test_data = json.load(f)
    print(f"  测试样本数: {len(test_data)}")
    
    # 2. 加载模型预测结果
    print(f"\n📂 加载模型预测: {MODEL_PREDICTIONS_PATH}")
    if not MODEL_PREDICTIONS_PATH.exists():
        print("  ❌ 预测文件不存在!请先运行模型推理生成预测结果。")
        print("  提示: 使用 generate_predictions.py 生成预测")
        return
    
    with open(MODEL_PREDICTIONS_PATH, "r", encoding="utf-8") as f:
        predictions = json.load(f)
    print(f"  预测样本数: {len(predictions)}")
    
    # 3. 加载已有评分结果(断点续跑)
    resume_from = None
    if SCORING_OUTPUT_PATH.exists():
        with open(SCORING_OUTPUT_PATH, "r", encoding="utf-8") as f:
            resume_from = json.load(f)
        print(f"\n📂 发现已有评分结果: {len(resume_from.get('scores', []))} 条")
    
    # 4. 运行评分
    print("\n🔄 开始 LLM 评分...")
    results = run_scoring(predictions, test_data, resume_from)
    
    # 5. 打印汇总
    print_summary(results)
    
    print(f"\n✅ 评分完成!结果已保存到: {SCORING_OUTPUT_PATH}")


if __name__ == "__main__":
    main()