Files
NexQuant/rdagent/components/coder/CoSTEER/evaluators.py
T
XianBW 342d78e234 feat: add LLM-finetune scenario (#1314)
* refine prompt

* small update

* fix a small bug

* remove debug config after execution

* fix: only remove <think> at start

* feat: support creating dataset & multi-eval frame (#1302)

* feat: add iterative evolve and evaluation support with partial chain stop

* feat: add FTDataEvaluator and support multiple implement functions in finetune

* feat: data implement for pre-proposal and proposal and add datasets (#1303)

* feat:(1) support for multi layer dataset extraction (2) add category.json for dataset in datasets/

* fix: fix bug for generate category.json

* feat: add get_dataset_folder_desc

* init data proposal and merge qzli/ft

* update data proposal prompts and add max_position_embeddings and resolve confilcts

* remove sample counts in data proposal

* turn data and train to unified hypo_gen

* refine prompts

* remove category.json and add it to dataset_info

* fix jinja problem and proposal done

* lint

* add ai-generated description and raw readme into dataset_info.json

* update prompt for description

* add datasets

* initial fix for proposal of data

* final version for data proposal

* lint

* feat: add stats in dataset_info, and enable data coder (#1306)

* refactor(dataset): add stats into dataset_info.json, and remove dataset from gitignore_folder

* feat: enable data coder and run data process

* feat: Merge data coder (#1307)

* feat: implement finetune data coding, evaluation, and config improvements

* fix: deepspeed config path

* fix: dataset info columns

---------

Co-authored-by: Young <afe.young@gmail.com>

* replace str length with token_limit

* add readme to dataset_info and remove useless blank lines in scenario description

* feat: dataset prepare

* fix: extract prams script name

* feat: add loss&predictions samples to feedback

* remove duplicate envs and and add llm_api_preferences and enhance reasoning token limits

* feat: network for ft_env

* fix: remove gpt-4o, which has low quota

* feat: a simple ui

* feat: merge data and train task type (#1309)

* feat: filter redundant prams of lf

* fix: ui bug caused by removing task_type

* fix: force agent to use high concurrency, and remove redundant prompt

* feat: extract info from llama factory log, and check data exists before download

* fix: add compatibility rules

* feat: llm evaluator for data coder

* feat: openai package in ft docker, and refine prompt

* feat: refine ft ui, add more info

* feat: add raw logs

* refine data coder prompt(for feedback debug)

* feat: select dataset in scen init

* fix: ui for docker log seperately

* feat: sync log through blob

* improve ui, and add llm feedback in Runner&Exp2FB (#1312)

* fix: ui bug to visualize docker log, and lint

* feat: unified docker log for ft env, and some refactor

* fix bugs and improve ui

* feat: save log of evaluator(single feedback)

* feat: add evaluator, set cleanup docker log

* feat: call llm in RunnerEvaluator and Feedback

* fix: extract structured error message in RunnerEvaluator

* feat: feedback improve, and fix some bugs

* feat: feedback improve when runner fails

* small update

* feat(UI): add running info and benchmark metric in loop expander

* feat(UI): add render markdown toggle

* feat: refine prompts and add error type in exp2fb

* feat: add filterd params reason, set default benchmark timeout to infinite, and refine train loss express

* recover dataset deepscaler

* feat: set timeout in .env

* refactor: unifiied ft_env timeout

* feat: debug mode for data coder

* feat: deliver data_stats after generate debug_data

* feat: use gpt-5.1 as judge model, set judge_retry, and refine debug mode prompt

* refine prompt

* refactor: llama factory manager logic, and refine data processing prompt

* feat(DockerEnv): support GPU selection via CUDA_VISIBLE_DEVICES

* feat: set api concurrency via .env

* fix: ft env timeout bug

* feat: enable CondaEnv run

* fix: can't update bin path in first run, and path bug in lf manager

* feat(ui): set log path through .env

* refactor(ui): wrap_lines, remove css

* feat(coder): retry when parse code-block fail

* fix: refine single-fb in ui, and fix path bug(not allow proposal to decide path)

* fix: opencompass CondaEnv torch compatible with vllm

* fix: refine error text in coding

* feat: deepspeed config for CondaEnv

* feat: memory estimator

* fix: deepspeed package for condaenv

* fix: use `client.chat.completions.create()` only

* feat: flash attention for condaenv

* feat: strong and weak models interface

* fix: condaenv package dependency

* use multi round conversation in llm finetune proposal

* refine prompt for data processing

* enable evolving in data coder

* maximize output token size

* fix: refine ui

* fix: optional packages for llama factory

* fix: torch denpendency for b200

* fix: opencompass dependency

* update cot prompts

* skip the sub implement

* skip conda preparation if env exists

* update chemcot datasets

* fix: unify docker to use litellm

* update readme and instructions

* fix: set CUDA_VISIBLE_DEVICES for CondaEnv

* feat: add panorama dataset, refactor dataset interface

* feat: calculate token using tiktoken, and ndarray bug

* fix: download subtasks of chemcotdataset seperately

* feat: customized prepare func for datasets

* feat: update new benchmarks

* add datasets package

* docs: readme for llm finetune

* feat: download raw data directly, with post-process function

* feat: analyze raw dataset

* suppress litellm debug info

* feat(ui): summary page

* feat: run multi-jobs

* feat: improve ui

* feat: add path and checkout options to LLM finetune loop entrypoint

* feat: add FinanceIQ_ppl benchmark with auto-download and dataset desc rendering

* refactor: remove unused imports and dead code, fix session folder logging

* feat: enable tablebench and tableInstruct dataset

* refine dataset readme, and coder prompt

* refine proposal and coder prompt

* fix: ui path (default log path)

* feat: add automatic LoRA model merging for benchmarking with vLLM

* refactor: reorganize finetune benchmark and merge modules under benchmark dir

* refactor: modularize benchmark config and error extraction for finetune scenario

* fix: update benchmark import paths and disable env cache for device info

* refactor docke&conda env and fix import bugs

* modify init python file

* feat: add FinanceIQ dataset split utility and integrate with pipeline

* feat: set weak and strong model by env, distribute workload across models

* feat: sample dataset and rm params for tensorboard, wandb

* update script to run jobs

* refine proposal prompt, remove specific dataset name

* fix(ui): auto switch log folder

* fix: estimate the processed full data after sample

* feat: filter raw data more aggressively, and lower data_eval standard

* feat: sync workspace to blob

* feat: rdkit for chemcotbench

* update qwen2.5&llama3.1 context

* fix: force failure on validation error and remove try/except in validator

* feat: unified error sample extraction (with test scripts)

* feat: set conda cache with .env

* feat: skip data eval if data pass in last evo

* fix: rm redundant param

* fix ui bug

* refactor: centralize assign_code_list_to_evo in MultiProcessEvolvingStrategy

* feat: add test_params.yaml generation and workspace cleanup improvements for finetune

* refactor: replace get_clear_ws_cmd with clear_workspace and update prompts for hard check criteria

* add bioprobench dataset

* fix: handle commas in training config extraction and refactor prompt includes

* bioprobench description

* add bioprobench readme

* feat: merge lora adapter for blackwell gpu

* feat: support for multi benchmarks in one job

* change dfficult aware content for training

* update difficulty-aware and logging principles

* fix: resolve variable name conflict in FTRunnerEvaluator

* set job id accuracy to minute

* feat(ui): display one selected metric per benchmark

* feat: store sota exp, and fix ws_ckp bug

* fix: truncate data.json in feedback

* fix: opencompass data for conda env

* fix: save only the last model

* feat: set log path and ws path

* fix: set overwrite_cache to avoid lock contention(through injecting params)

* feat: redirect stdout to file in localenv

* add pickle cache to dataset desc

* fix CI

* fix: remove redundant wrapper

* feat: set python_unbuffered

* move redirect stdout to env run

* fix a small bug

* move model folder

* feat(ui): display benchmark baseline

* fix: enrich scenario and benchmark description

* fix: rewrite runner eval to accept easier

* feat: compare with baseline when no SOTA

* update tablebench readme

* fix: switch back to single benchmark (for baseline)

* feat(ui): add ws path in ui

* refactor: update SOTA tracking to use DAG traversal and parent selection

* fix: prioritize local_selection in trace and refactor sibling retrieval logic

* refactor: unify error handling in feedback generation and update workspace injection

* feat: add skip_loop_error_stepname to control error skip step in LoopBase

* fix: set local_selection to NEW_ROOT for experiments without parent

* feat: set different ports for jobs

* feat: set different ports for jobs

* feat: add upper data size limit for LLM fine-tuning and update related prompts

* fix: replace get_truncated_stdout() with stdout for consistent output handling

* refactor: remove data.json from cache and workspace logic, focus on script-based reuse

* fix: rm target_scenario

* feat: add selective cache extraction and custom cache key for data processing

* fix(ui): bug when displaying tablebench

* fix: filter config in dataset_info.json

* feat: add test set, set valid set

* feat(ui): update test score, and set color for final decision

* feat: add test score for baseline and update ui

* fix: use [-100:] as test range

* feat: update data_stats in runner

* feat: wait for opencompass init when run multi jobs

* fix: adjust test&valid split

* feat: force to generate COT(with <think> token), and add answer format in scenarios.json

* feat: improve ui

* fix: unify benchmark volume mounts and set extra_volumes for conda env

* fix(ui): number color

* fix: update GPU memory handling to use total memory in GB and streamline code

* fix: set use_cot_postprocessor

* feat: add env_dict to config classes and merge env vars in Env run

* fix: let coder obey proposal

* fix(ui): direction bug and update chemcot core metirc

* fix: set consistent benchmark mount points and env vars for docker and conda

* fix: addintional target for LoRA

* feat: workspace dir log for benchmark running

* fix: tableInstruct path bug and update benchmark description

* feat: timeout for whole job

* fix: align FinanceIQ import to opencompass

* feat: use llm_judge for FinanceIQ

* feat: switch to turn on <think> or not

* feat: using scripts to redirect stdout, and run in different windows

* feat: sync litellm log

* fix: gpu memory format

* fix: escape special characters in benchmark desc

* fix: set data processing timeout to 1h

* feat: set valid_loss and save_best_model

* fix: inject timeout and stage

* fix: loss history extract logic

* feat: inject output dir

* feat: inject eval batch size

* feat: inject save_total_limit

* feat: update data prompt

* fix:  escape shell special characters

* fix: tablebench visualization UI

* fix: move implementation validation to coder, and ignore injected params

* feat: README for FinanceIQ dataset

* fix: bioprobench desc error

* fix: remove task alignment when coder eval

* fix: FinanceIQ now extracts last capital as answer

* fix: stdout contains binary data

* feat: recover estimate full output and set eval setting automatically

* fix(ui): precision for summary table

* fix(ui): import error

* feat: try to use lora

* fix(api): fix litellm bug for code block

* fix: refine prompts to give agent more decision space

* chore(ci): fix mypy typing issues

* chore(ci): format code with black

* chore(ci): fix ruff lint violations

* chore(ci): sort imports with isort

* chore(ci): format code with black

* test: temporarily skip extract_parameters imports due to numpy pin

* fix: compatibility issues for qlib scenarios on finetune branch

* fix(fin_factor): skip to fb for coder error

* fix(loop): default skip to feedback step on skip_loop_error

When skip_loop_error exception happens and skip_loop_error_stepname is not
explicitly set, default to jumping to 'feedback' step if it exists,
otherwise fall back to the last step (record).

This prevents KeyError when record step tries to access feedback data that
doesn't exist because we skipped the feedback phase.

Also removed redundant skip_loop_error_stepname from finetune loop since
it's now the default behavior.

* add 'skip to record' to DS scenario like other scenarios

* fix 2 scenarios bug about rd_loop class

* fix: lint(mypy, ruff, black) error

* fix: mypy lint error

* fix data science scenario bug

---------

Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: Qizheng Li <jenssenlee@163.com>
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: amstrongzyf <201840057@smail.nju.edu.cn>
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: amstrongzyf <amstrongzyf@126.com>
Co-authored-by: chelsea97 <zhuowbrown@gmail.com>
Co-authored-by: SunsetWolf <Lv.Linlang@hotmail.com>
2026-03-02 19:04:10 +08:00

334 lines
14 KiB
Python

import json
from abc import abstractmethod
from copy import deepcopy
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Dict, Generator, List
from rdagent.components.coder.CoSTEER.evolvable_subjects import EvolvingItem
from rdagent.core.conf import RD_AGENT_SETTINGS
from rdagent.core.evaluation import Evaluator, Feedback
from rdagent.core.evolving_agent import RAGEvaluator
from rdagent.core.evolving_framework import QueriedKnowledge
from rdagent.core.experiment import Task, Workspace
from rdagent.core.utils import multiprocessing_wrapper
from rdagent.log import rdagent_logger as logger
if TYPE_CHECKING:
from rdagent.core.scenario import Scenario
# TODO:
# 1. It seems logically sound, but we currently lack a scenario to apply it.
# 2. If it proves to be useful, relocate it to a more general location.
#
# class FBWorkspaceExeFeedback(Feedback):
# """
# It pairs with FBWorkspace in the abstract level.
# """
# # ws: FBWorkspace # potential
# stdout: str
@dataclass
class CoSTEERSingleFeedback(Feedback):
# TODO: (xiao)
# it should be more general class for FBWorkspaceExeFeedback
# A better name of it may be NormalFeedback
# TODO: It should be a general feeddback for CoSTEERR
"""
The feedback for the data loader evaluation.
It is design align the phases of the implemented code
- Execution -> Return Value -> Code -> Final Decision
"""
execution: str # Summarized execution feedback
# execution_feedback
return_checking: str | None # including every check in the testing (constraints about the generated value)
# value_feedback, shape_feedback, value_generated_flag
code: str
final_decision: bool | None = None
raw_execution: str = "" # Full raw stdout for UI display
source_feedback: Dict[str, bool] = field(
default_factory=dict
) # Record the source of the feedback since it might be merged from multiple feedbacks, stores the mapping from source tag to its final_decision, this dict also includes the feedback source of itself
@staticmethod
def val_and_update_init_dict(data: dict) -> dict:
# TODO: (bowen) use a more general method to validate and update the data dictionary before init, like pydantic
"""
Validates and converts the 'final_decision' field in the given data dictionary.
Args:
data (dict): The data dictionary containing the 'final_decision' field.
Returns:
dict: The updated data dictionary with 'final_decision' as a boolean.
Raises:
ValueError: If 'final_decision' is not present or not a boolean.
"""
if "final_decision" not in data:
raise ValueError("'final_decision' is required")
if isinstance(data["final_decision"], str):
if data["final_decision"] == "false" or data["final_decision"] == "False":
data["final_decision"] = False
elif data["final_decision"] == "true" or data["final_decision"] == "True":
data["final_decision"] = True
if not isinstance(data["final_decision"], bool):
raise ValueError(f"'final_decision' must be a boolean, not {type(data['final_decision'])}")
for attr in "execution", "return_checking", "code":
if data.get(attr) is not None and not isinstance(data[attr], str):
data[attr] = json.dumps(data[attr], indent=2, ensure_ascii=False)
return data
@classmethod
def merge(cls, feedback_li: list["CoSTEERSingleFeedback"]) -> "CoSTEERSingleFeedback":
# NOTE:
# Here we don't know the detailed design of each feedback, we just know they are CoSTEERSingleFeedback
# So we merge them only based on CoSTEERSingleFeedback's attributes
# **So some information may be lost when we have different types of feedbacks**
# If you have more sophisticated sub class of CoSTEERSingleFeedback, you should override this method
# to avoid the loss of information.
fb = deepcopy(feedback_li[0])
# for all the evaluators, aggregate the final_decision from `task_id`
fb.final_decision = all(fb.final_decision for fb in feedback_li)
for attr in "execution", "return_checking", "code":
setattr(
fb,
attr,
"\n\n".join([getattr(_fb, attr) for _fb in feedback_li if getattr(_fb, attr) is not None]),
)
fb.source_feedback = {}
for _fb in feedback_li:
for tag, decision in _fb.source_feedback.items():
fb.source_feedback[tag] = decision
return fb
def __str__(self) -> str:
return f"""------------------Execution------------------
{self.execution}
------------------Return Checking------------------
{self.return_checking if self.return_checking is not None else 'No return checking'}
------------------Code------------------
{self.code}
------------------Final Decision------------------
This implementation is {'SUCCESS' if self.final_decision else 'FAIL'}.
"""
def __bool__(self):
return self.final_decision
class CoSTEERSingleFeedbackDeprecated(CoSTEERSingleFeedback):
"""This class is a base class for all code generator feedback to single implementation"""
def __init__(
self,
execution_feedback: str = None,
shape_feedback: str = None,
code_feedback: str = None,
value_feedback: str = None,
final_decision: bool = None,
final_feedback: str = None,
value_generated_flag: bool = None,
final_decision_based_on_gt: bool = None,
source_feedback: dict = None,
) -> None:
self.execution_feedback = execution_feedback
self.code_feedback = code_feedback
self.value_feedback = value_feedback
self.final_decision = final_decision
self.final_feedback = final_feedback
self.value_generated_flag = value_generated_flag
self.final_decision_based_on_gt = final_decision_based_on_gt
self.source_feedback = source_feedback if source_feedback is not None else {}
# TODO:
# Not general enough. So we should not put them in the general costeer feedback
# Instead, we should create subclass for it.
self.shape_feedback = shape_feedback # Not general enough. So
@property
def execution(self):
return self.execution_feedback
@execution.setter
def execution(self, value):
self.execution_feedback = value
@property
def return_checking(self):
if self.value_generated_flag:
return f"value feedback: {self.value_feedback}\n\nshape feedback: {self.shape_feedback}"
return None
@return_checking.setter
def return_checking(self, value):
# Since return_checking is derived from value_feedback and shape_feedback,
# we don't need to do anything here
self.value_feedback = value
self.shape_feedback = value
@property
def code(self):
return self.code_feedback
@code.setter
def code(self, value):
self.code_feedback = value
def __str__(self) -> str:
return f"""------------------Execution Feedback------------------
{self.execution_feedback if self.execution_feedback is not None else 'No execution feedback'}
------------------Shape Feedback------------------
{self.shape_feedback if self.shape_feedback is not None else 'No shape feedback'}
------------------Code Feedback------------------
{self.code_feedback if self.code_feedback is not None else 'No code feedback'}
------------------Value Feedback------------------
{self.value_feedback if self.value_feedback is not None else 'No value feedback'}
------------------Final Feedback------------------
{self.final_feedback if self.final_feedback is not None else 'No final feedback'}
------------------Final Decision------------------
This implementation is {'SUCCESS' if self.final_decision else 'FAIL'}.
"""
class CoSTEERMultiFeedback(Feedback):
"""Feedback contains a list, each element is the corresponding feedback for each factor implementation."""
def __init__(self, feedback_list: List[CoSTEERSingleFeedback]) -> None:
self.feedback_list = feedback_list
def __getitem__(self, index: int) -> CoSTEERSingleFeedback:
return self.feedback_list[index]
def __len__(self) -> int:
return len(self.feedback_list)
def append(self, feedback: CoSTEERSingleFeedback) -> None:
self.feedback_list.append(feedback)
def __iter__(self):
return iter(self.feedback_list)
def is_acceptable(self) -> bool:
return all(feedback.is_acceptable() for feedback in self.feedback_list)
def finished(self) -> bool:
"""
In some implementations, tasks may fail multiple times, leading agents to skip the implementation.
This results in None feedback. However, we want to accept the correct parts and ignore None feedback.
"""
return all(feedback.final_decision for feedback in self.feedback_list if feedback is not None)
def __bool__(self) -> bool:
return all(feedback.final_decision for feedback in self.feedback_list)
class CoSTEEREvaluator(Evaluator):
def __init__(
self,
scen: "Scenario",
) -> None:
self.scen = scen
# TODO:
# I think we should have unified interface for all evaluates, for examples.
# So we should adjust the interface of other factors
# Based on the implementation, I think a better name is some name like task-implement evaluator
@abstractmethod
def evaluate(
self,
target_task: Task,
implementation: Workspace,
gt_implementation: Workspace,
**kwargs,
) -> CoSTEERSingleFeedback:
raise NotImplementedError("Please implement the `evaluator` method")
class CoSTEERMultiEvaluator(RAGEvaluator):
"""This is for evaluation of experiment. Due to we have multiple tasks, so we will return a list of evaluation feebacks"""
def __init__(self, single_evaluator: CoSTEEREvaluator | list[CoSTEEREvaluator], scen: "Scenario") -> None:
super().__init__()
self.scen = scen
self.single_evaluator = single_evaluator
def evaluate_iter(
self,
queried_knowledge: QueriedKnowledge = None,
**kwargs,
) -> Generator[CoSTEERMultiFeedback, EvolvingItem | None, CoSTEERMultiFeedback]:
evo = yield CoSTEERMultiFeedback(
[]
) # it will receive the evo first, so the first yield is for get the sent evo instead of generate useful feedback
eval_l = self.single_evaluator if isinstance(self.single_evaluator, list) else [self.single_evaluator]
# 1) Evaluate each sub_task
task_li_feedback_li = []
# task_li_feedback_li: List[List[CoSTEERSingleFeedback]]
# Example:
# If there are 2 evaluators and 3 sub_tasks in evo, and each evaluator's evaluate returns a list of 3 CoSTEERSingleFeedbacks,
# Then task_li_feedback_li will be:
# [
# [feedback_1_1, feedback_1_2, feedback_1_3], # results from the 1st evaluator for all sub_tasks
# [feedback_2_1, feedback_2_2, feedback_2_3], # results from the 2nd evaluator for all sub_tasks
# ]
# Where feedback_i_j is the feedback from the i-th evaluator for the j-th sub_task.
for ev in eval_l:
multi_implementation_feedback = multiprocessing_wrapper(
[
(
ev.evaluate,
(
evo.sub_tasks[index],
evo.sub_workspace_list[index],
evo.sub_gt_implementations[index] if evo.sub_gt_implementations is not None else None,
queried_knowledge,
),
)
for index in range(len(evo.sub_tasks))
],
n=RD_AGENT_SETTINGS.multi_proc_n,
)
# None received, we skip the rest and return the overall feedback directly
evo_next_iter = yield CoSTEERMultiFeedback(multi_implementation_feedback)
task_li_feedback_li.append(multi_implementation_feedback)
if evo_next_iter is None:
break
evo = evo_next_iter
# 2) merge the feedbacks along the sub_tasks to aggregate the multiple evaluation feedbacks
merged_task_feedback = []
# task_li_feedback_li[0] is a list of feedbacks of different tasks for the 1st evaluator
for task_id, fb in enumerate(task_li_feedback_li[0]):
fb = fb.merge([fb_li[task_id] for fb_li in task_li_feedback_li])
merged_task_feedback.append(fb)
# merged_task_feedback: List[CoSTEERSingleFeedback]
# Example:
# [
# CoSTEERSingleFeedback(final_decision=True, execution="...", return_checking="...", code="..."),
# CoSTEERSingleFeedback(final_decision=False, execution="...", return_checking="...", code="..."),
# ...
# ]
# Each element corresponds to the merged feedback for one sub-task across all evaluators.
# merged_task_feedback[i] is the merged feedback for the i-th sub_task
final_decision = [
None if single_feedback is None else single_feedback.final_decision
for single_feedback in merged_task_feedback
]
logger.info(f"Final decisions: {final_decision} True count: {final_decision.count(True)}")
# TODO: this is to be compatible with factor_implementation;
for index in range(len(evo.sub_tasks)):
if final_decision[index]:
evo.sub_tasks[index].factor_implementation = True
return CoSTEERMultiFeedback(merged_task_feedback)