你说得对,不仅界面需要修改,evaluation.py 中的实际评估逻辑也需要调整,以确保级联评估模式下正确处理推理策略和校准选项。
以下是需要修改的地方:
1. 修改 evaluate 函数
在级联评估模式下,evaluate 函数需要支持推理策略(直接评估/思维链)和校准选项。以下是具体修改:
python
def evaluate(instruction, answer1, answer2, mode, state=None, model_name=None, proprietary_model=None, calibration_mode=False):
# 创建 prompt
conversation = create_prompt(instruction, answer1, answer2, mode, model_name)
if not proprietary_model:
# 使用微调裁判模型
model = state.get("model")
tokenizer = state.get("tokenizer")
if model_name is None:
return "请先加载模型", "", []
# 检查 tokenizer 是否支持 chat_template
if tokenizer.chat_template is None:
inputs = tokenizer(conversation, return_tensors="pt").to(model.device)
input_ids = inputs["input_ids"]
full_prompt = conversation
else:
if not isinstance(conversation, list) or not all(isinstance(msg, dict) for msg in conversation):
raise ValueError("Conversation must be a list of dictionaries with 'role' and 'content' keys.")
full_prompt = "\n".join([msg["content"] for msg in create_prompt(instruction, answer1, answer2, mode)])
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(model.device)
inputs = {"input_ids": input_ids}
# 生成模型输出
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=2048,
return_dict_in_generate=True,
output_scores=True
)
generated_token_ids = outputs.sequences[0]
input_length = input_ids.shape[1]
output_token_ids = generated_token_ids[input_length:]
result = tokenizer.decode(output_token_ids, skip_special_tokens=True)
logprobs = []
for scores in outputs.scores:
logits = scores.log_softmax(dim=-1)
logprobs.append(logits)
confidence = calculate_confidence(logprobs)
print(f"置信度: {confidence}")
else:
# 使用专有模型
full_prompt = "\n".join([msg["content"] for msg in create_prompt(instruction, answer1, answer2, mode)])
result = call_model(conversation, proprietary_model)
logprobs = None
try:
scores = extract_scores(result, mode)
except ValueError as e:
scores = ""
if [Redacted Person](scores) == 2:
score1, score2 = scores
verdict = "大模型 1 更好 " if score1 > score2 else ("大模型 2 更好 " if score2 > score1 else "两个大模型表现相当!")
else:
verdict = "解析分数失败。请检查评估模型的输出。"
details = f"""
<div class=\"details-section\">
<h3>👨🏽💻 用户</h3>
<pre>{full_prompt.replace('>', '>').replace('<', '<').replace('\\n', '<br>')}</pre>
<h3>🧑⚖️ 裁判模型</h3>
<pre>{result.replace('\\n', '<br>')}</pre>
</div>
"""
return verdict, details, logprobs
2. 修改 manual_evaluate 函数
manual_evaluate 是手动评估的核心逻辑函数,需要确保在级联评估模式下正确处理推理策略和校准选项。以下是修改:
python
def manual_evaluate(instruction, answer1, answer2, mode, state, calibration_mode=False):
finetuned_model_name = state.get("finetuned_model_name")
model_type = state.get("model_type")
proprietary_model_name = state.get("proprietary_model_name")
eval_mode = state.get("eval_mode") # 从 state 中获取 eval_mode
if eval_mode == "级联评估":
# 级联评估模式下,先使用微调裁判模型评估并计算置信度
llm = state.get("model")
tokenizer = state.get("tokenizer")
if llm is None:
return "请先加载模型", "", gr.update(visible=False)
# 使用微调裁判模型进行评估
verdict, details, logprobs = evaluate(instruction, answer1, answer2, mode, state, finetuned_model_name)
# 计算置信度
confidence = calculate_confidence(logprobs)
# 如果置信度低于阈值,调用专有模型重新评估
threshold = state.get("confidence_threshold", 0.5) # 默认阈值为 0.5
if confidence < threshold:
proprietary_model_name = state.get("proprietary_model_name")
if proprietary_model_name:
# 调用专有模型重新评估
proprietary_verdict, proprietary_details, _ = evaluate(
instruction, answer1, answer2, mode, state=state, proprietary_model=proprietary_model_name
)
details += f"""
<p>置信度低于阈值 ({confidence:.4f} < {threshold:.4f}),已调用专有模型重新评估。</p>
<h3>🧑⚖️ 专有模型评估结果</h3>
<pre>{proprietary_details.replace('\\n', '<br>')}</pre>
"""
verdict = proprietary_verdict # 使用专有模型的评估结果
else:
details += f"\n<p>置信度低于阈值 ({confidence:.4f} < {threshold:.4f}),但未加载专有模型。</p>"
else:
details += f"\n<p>置信度: {confidence:.4f} (高于阈值 {threshold:.4f})</p>"
return verdict, details, gr.update(visible=True)
else:
# 单模型评估模式
if model_type == "专有模型":
if not proprietary_model_name:
return "请先加载模型", "", gr.update(visible=False)
if calibration_mode:
return calibrated_evaluation(instruction, answer1, answer2, mode, model_name=proprietary_model_name)
return evaluate(instruction, answer1, answer2, mode, state=state, proprietary_model=proprietary_model_name)
llm = state.get("model")
tokenizer = state.get("tokenizer")
if llm is None or tokenizer is None:
return "请先加载模型", "", gr.update(visible=False)
if calibration_mode:
return "校准模式只能用于专有模型。", "", gr.update(visible=False)
return evaluate(instruction, answer1, answer2, mode, state=state, model_name=state.get("finetuned_model_name"))
3. 修改 evaluate_batch_with_api 函数
批量评估时也需要支持推理策略和校准选项。以下是修改:
python
def evaluate_batch_with_api(file, output_path, mode, model_name, calibration_mode=False):
"""
批量执行评估,仅支持通过 API 调用模型。
"""
if file is None:
return "请上传文件"
try:
if file.name.endswith('.csv'):
df = pd.read_csv(file.name)
elif file.name.endswith('.json'):
with open(file.name, 'r', encoding='utf-8') as f:
data = json.load(f)
df = pd.DataFrame(data)
else:
return "仅支持 CSV 或 JSON 格式的文件"
except (pd.errors.ParserError, json.JSONDecodeError) as e:
return f"文件解析错误:{e}"
except Exception as e:
return f"读取文件时出错:{e}"
results = []
details_list = []
for _, row in df.iterrows():
instruction = row.get('instruction', '')
answer1 = row.get('answer1', '')
answer2 = row.get('answer2', '')
if not instruction or not answer1 or not answer2:
results.append("Invalid row: Missing data")
details_list.append("")
continue
try:
# 使用 API 模型进行评估
if calibration_mode:
verdict, details = calibrated_evaluation(instruction, answer1, answer2, mode, model_name=model_name)
else:
verdict, details, _ = evaluate(instruction, answer1, answer2, mode, proprietary_model=model_name)
results.append(verdict)
details_list.append(details)
except Exception as e:
results.append(f"Error: {str(e)}")
details_list.append(f"<pre>Details: {str(e)}</pre>")
output_df = pd.DataFrame({
'指令': df.get('instruction', []),
'答案 1': df.get('