372 lines
11 KiB
Python
372 lines
11 KiB
Python
"""
|
||||
|
|
Parallel execution module for RAG evaluation
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from typing import List, Dict, Any, Optional, Callable
|
|||
|
|
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
|
|||
|
|
import threading
|
|||
|
|
from dataclasses import dataclass
|
|||
|
|
import time
|
|||
|
|
|
|||
|
|
|
|||
|
|
@dataclass
|
|||
|
|
class ParallelConfig:
|
|||
|
|
"""并行执行配置"""
|
|||
|
|
max_workers: int = 5 # 最大工作线程数
|
|||
|
|
use_processes: bool = False # 是否使用进程池(默认使用线程池)
|
|||
|
|
chunk_size: int = 1 # 每个任务处理的问题数量
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ParallelExecutor:
|
|||
|
|
"""并行执行器,用于加速RAG评估"""
|
|||
|
|
|
|||
|
|
def __init__(self, config: ParallelConfig):
|
|||
|
|
"""
|
|||
|
|
初始化并行执行器
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
config: 并行配置
|
|||
|
|
"""
|
|||
|
|
self.config = config
|
|||
|
|
self._lock = threading.Lock()
|
|||
|
|
self._results = []
|
|||
|
|
self._errors = []
|
|||
|
|
|
|||
|
|
def execute_tasks(
|
|||
|
|
self,
|
|||
|
|
tasks: List[Any],
|
|||
|
|
task_func: Callable,
|
|||
|
|
task_desc: str = "task"
|
|||
|
|
) -> List[Any]:
|
|||
|
|
"""
|
|||
|
|
并行执行任务列表
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
tasks: 任务列表
|
|||
|
|
task_func: 任务执行函数,接收单个任务作为参数
|
|||
|
|
task_desc: 任务描述(用于日志)
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
结果列表
|
|||
|
|
"""
|
|||
|
|
if not tasks:
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
results = []
|
|||
|
|
errors = []
|
|||
|
|
|
|||
|
|
# 选择执行器类型
|
|||
|
|
executor_class = ProcessPoolExecutor if self.config.use_processes else ThreadPoolExecutor
|
|||
|
|
|
|||
|
|
with executor_class(max_workers=self.config.max_workers) as executor:
|
|||
|
|
# 提交所有任务
|
|||
|
|
future_to_task = {
|
|||
|
|
executor.submit(task_func, task): task
|
|||
|
|
for task in tasks
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# 收集结果
|
|||
|
|
for future in as_completed(future_to_task):
|
|||
|
|
task = future_to_task[future]
|
|||
|
|
try:
|
|||
|
|
result = future.result()
|
|||
|
|
results.append(result)
|
|||
|
|
except Exception as e:
|
|||
|
|
error_msg = f"Error processing {task_desc}: {str(e)}"
|
|||
|
|
errors.append({
|
|||
|
|
'task': task,
|
|||
|
|
'error': error_msg
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
if errors:
|
|||
|
|
# 记录错误但不中断执行
|
|||
|
|
print(f"Warnings: {len(errors)} tasks failed:")
|
|||
|
|
for error in errors[:3]: # 只显示前3个错误
|
|||
|
|
print(f" - {error['error']}")
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
def execute_evaluation_batch(
|
|||
|
|
self,
|
|||
|
|
evaluation_items: List[Dict[str, Any]],
|
|||
|
|
evaluate_func: Callable
|
|||
|
|
) -> List[Dict[str, Any]]:
|
|||
|
|
"""
|
|||
|
|
批量并行执行评估任务
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
evaluation_items: 评估项目列表,每个项目包含问题索引和问题数据
|
|||
|
|
evaluate_func: 评估函数
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
评估结果列表
|
|||
|
|
"""
|
|||
|
|
if not evaluation_items:
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
# 如果任务数量较少,使用串行执行
|
|||
|
|
if len(evaluation_items) <= 3:
|
|||
|
|
return [evaluate_func(item) for item in evaluation_items]
|
|||
|
|
|
|||
|
|
# 并行执行
|
|||
|
|
return self.execute_tasks(
|
|||
|
|
tasks=evaluation_items,
|
|||
|
|
task_func=evaluate_func,
|
|||
|
|
task_desc="evaluation"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def execute_with_progress(
|
|||
|
|
self,
|
|||
|
|
tasks: List[Any],
|
|||
|
|
task_func: Callable,
|
|||
|
|
task_desc: str = "task",
|
|||
|
|
progress_callback: Optional[Callable] = None
|
|||
|
|
) -> List[Any]:
|
|||
|
|
"""
|
|||
|
|
带进度回调的并行执行
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
tasks: 任务列表
|
|||
|
|
task_func: 任务执行函数
|
|||
|
|
task_desc: 任务描述
|
|||
|
|
progress_callback: 进度回调函数(current, total)
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
结果列表
|
|||
|
|
"""
|
|||
|
|
if not tasks:
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
total = len(tasks)
|
|||
|
|
completed = 0
|
|||
|
|
results = []
|
|||
|
|
errors = []
|
|||
|
|
|
|||
|
|
executor_class = ProcessPoolExecutor if self.config.use_processes else ThreadPoolExecutor
|
|||
|
|
|
|||
|
|
with executor_class(max_workers=self.config.max_workers) as executor:
|
|||
|
|
future_to_index = {
|
|||
|
|
executor.submit(task_func, task): idx
|
|||
|
|
for idx, task in enumerate(tasks)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
for future in as_completed(future_to_index):
|
|||
|
|
try:
|
|||
|
|
result = future.result()
|
|||
|
|
results.append(result)
|
|||
|
|
completed += 1
|
|||
|
|
|
|||
|
|
# 调用进度回调
|
|||
|
|
if progress_callback:
|
|||
|
|
progress_callback(completed, total)
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
errors.append(str(e))
|
|||
|
|
completed += 1
|
|||
|
|
|
|||
|
|
if progress_callback:
|
|||
|
|
progress_callback(completed, total)
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
|
|||
|
|
class BatchEvaluator:
|
|||
|
|
"""批量评估器,优化大量评估任务的执行"""
|
|||
|
|
|
|||
|
|
def __init__(self, parallel_config: Optional[ParallelConfig] = None):
|
|||
|
|
"""
|
|||
|
|
初始化批量评估器
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
parallel_config: 并行配置(可选)
|
|||
|
|
"""
|
|||
|
|
self.config = parallel_config or ParallelConfig()
|
|||
|
|
self.executor = ParallelExecutor(self.config)
|
|||
|
|
|
|||
|
|
def evaluate_questions_batch(
|
|||
|
|
self,
|
|||
|
|
questions: List[Dict[str, Any]],
|
|||
|
|
evaluation_func: Callable,
|
|||
|
|
batch_size: Optional[int] = None
|
|||
|
|
) -> List[Dict[str, Any]]:
|
|||
|
|
"""
|
|||
|
|
批量评估问题
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
questions: 问题列表
|
|||
|
|
evaluation_func: 单个问题的评估函数
|
|||
|
|
batch_size: 批次大小(如果为None,使用配置中的chunk_size)
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
评估结果列表
|
|||
|
|
"""
|
|||
|
|
if not questions:
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
batch_size = batch_size or self.config.chunk_size
|
|||
|
|
|
|||
|
|
# 如果问题数量小于等于批次大小,直接并行执行
|
|||
|
|
if len(questions) <= batch_size:
|
|||
|
|
results = self.executor.execute_tasks(
|
|||
|
|
tasks=questions,
|
|||
|
|
task_func=evaluation_func,
|
|||
|
|
task_desc="question evaluation"
|
|||
|
|
)
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
# 分批执行
|
|||
|
|
all_results = []
|
|||
|
|
for i in range(0, len(questions), batch_size):
|
|||
|
|
batch = questions[i:i + batch_size]
|
|||
|
|
batch_results = self.executor.execute_tasks(
|
|||
|
|
tasks=batch,
|
|||
|
|
task_func=evaluation_func,
|
|||
|
|
task_desc=f"batch {i // batch_size + 1}"
|
|||
|
|
)
|
|||
|
|
all_results.extend(batch_results)
|
|||
|
|
|
|||
|
|
return all_results
|
|||
|
|
|
|||
|
|
def evaluate_with_retry(
|
|||
|
|
self,
|
|||
|
|
questions: List[Dict[str, Any]],
|
|||
|
|
evaluation_func: Callable,
|
|||
|
|
max_retries: int = 3
|
|||
|
|
) -> List[Dict[str, Any]]:
|
|||
|
|
"""
|
|||
|
|
带重试机制的批量评估
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
questions: 问题列表
|
|||
|
|
evaluation_func: 评估函数
|
|||
|
|
max_retries: 最大重试次数
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
评估结果列表
|
|||
|
|
"""
|
|||
|
|
results = []
|
|||
|
|
failed_items = []
|
|||
|
|
|
|||
|
|
# 首次尝试
|
|||
|
|
for question in questions:
|
|||
|
|
try:
|
|||
|
|
result = evaluation_func(question)
|
|||
|
|
results.append(result)
|
|||
|
|
except Exception as e:
|
|||
|
|
failed_items.append((question, e))
|
|||
|
|
|
|||
|
|
# 重试失败的项目
|
|||
|
|
for attempt in range(max_retries):
|
|||
|
|
if not failed_items:
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
next_failed = []
|
|||
|
|
for question, original_error in failed_items:
|
|||
|
|
try:
|
|||
|
|
result = evaluation_func(question)
|
|||
|
|
results.append(result)
|
|||
|
|
except Exception as e:
|
|||
|
|
next_failed.append((question, e))
|
|||
|
|
|
|||
|
|
failed_items = next_failed
|
|||
|
|
|
|||
|
|
# 记录仍然失败的项目
|
|||
|
|
if failed_items:
|
|||
|
|
print(f"Warning: {len(failed_items)} items failed after {max_retries} retries")
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
|
|||
|
|
def parallel_evaluator_wrapper(evaluation_id: str, question_data: Dict[str, Any],
|
|||
|
|
rag_adapter, metrics_calculator, db_manager):
|
|||
|
|
"""
|
|||
|
|
包装函数,用于进程池执行单个问题的评估
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
evaluation_id: 评估ID
|
|||
|
|
question_data: 问题数据
|
|||
|
|
rag_adapter: RAG适配器
|
|||
|
|
metrics_calculator: 指标计算器
|
|||
|
|
db_manager: 数据库管理器
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
评估结果
|
|||
|
|
"""
|
|||
|
|
try:
|
|||
|
|
question_text = question_data['question']
|
|||
|
|
question_index = question_data['index']
|
|||
|
|
ground_truth = question_data.get('ground_truth', {})
|
|||
|
|
|
|||
|
|
# 执行RAG查询
|
|||
|
|
rag_result = rag_adapter.evaluate_question(question_text)
|
|||
|
|
|
|||
|
|
# 提取ground truth
|
|||
|
|
ground_truth_answer = ground_truth.get('answer', '')
|
|||
|
|
ground_truth_contexts = ground_truth.get('context', [])
|
|||
|
|
|
|||
|
|
# 计算指标
|
|||
|
|
retrieved_context_texts = rag_result['context_texts']
|
|||
|
|
generated_answer = rag_result['generated_answer']
|
|||
|
|
|
|||
|
|
metrics = metrics_calculator.calculate_all(
|
|||
|
|
question=question_text,
|
|||
|
|
retrieved_contexts=retrieved_context_texts,
|
|||
|
|
generated_answer=generated_answer,
|
|||
|
|
ground_truth_contexts=ground_truth_contexts,
|
|||
|
|
ground_truth_answer=ground_truth_answer
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 保存到数据库
|
|||
|
|
from ..utils.helpers import generate_id, generate_biz_seq, generate_sys_seq
|
|||
|
|
result_id = generate_id("result")
|
|||
|
|
biz_seq = generate_biz_seq("RESULT")
|
|||
|
|
sys_seq = generate_sys_seq("RESULT")
|
|||
|
|
|
|||
|
|
sql = """
|
|||
|
|
INSERT INTO evaluation_results (
|
|||
|
|
id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
|||
|
|
context_recall, context_precision, mrr, ndcg,
|
|||
|
|
faithfulness, answer_relevancy, correctness,
|
|||
|
|
retrieved_contexts, generated_answer, ground_truth_answer, ground_truth_context,
|
|||
|
|
retrieval_time_ms, generation_time_ms, create_time
|
|||
|
|
) VALUES (
|
|||
|
|
%s, %s, %s, %s, %s, %s,
|
|||
|
|
%s, %s, %s, %s,
|
|||
|
|
%s, %s, %s,
|
|||
|
|
%s, %s, %s, %s,
|
|||
|
|
%s, %s, %s
|
|||
|
|
)
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
import json
|
|||
|
|
from datetime import datetime
|
|||
|
|
|
|||
|
|
now = datetime.now()
|
|||
|
|
db_manager.execute_update(
|
|||
|
|
sql,
|
|||
|
|
(
|
|||
|
|
result_id, biz_seq, sys_seq, evaluation_id, question_index, question_text,
|
|||
|
|
metrics['context_recall'], metrics['context_precision'],
|
|||
|
|
metrics['mrr'], metrics['ndcg'],
|
|||
|
|
metrics['faithfulness'], metrics['answer_relevancy'], metrics['correctness'],
|
|||
|
|
json.dumps(rag_result['retrieved_contexts']),
|
|||
|
|
generated_answer, ground_truth_answer,
|
|||
|
|
json.dumps(ground_truth_contexts),
|
|||
|
|
rag_result['retrieval_time_ms'], rag_result['generation_time_ms'],
|
|||
|
|
now
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
'result_id': result_id,
|
|||
|
|
'question_index': question_index,
|
|||
|
|
'metrics': metrics
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
# 返回错误信息
|
|||
|
|
return {
|
|||
|
|
'question_index': question_data.get('index', -1),
|
|||
|
|
'error': str(e),
|
|||
|
|
'metrics': None
|
|||
|
|
}
|