mirror of
https://github.com/NicolasBohn/NexQuant.git
synced 2026-07-28 07:57:44 +00:00
6e19c9e632
* 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>
400 lines
16 KiB
Python
400 lines
16 KiB
Python
"""
|
|
LLM Fine-tuning Evaluation Components
|
|
|
|
Provides simplified evaluation: parameter filtering + micro-batch testing.
|
|
No redundant LLM feedback generation - test results speak for themselves.
|
|
"""
|
|
|
|
import json
|
|
import random
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
from rdagent.app.finetune.llm.conf import FT_RD_SETTING
|
|
from rdagent.components.coder.CoSTEER.evaluators import (
|
|
CoSTEEREvaluator,
|
|
CoSTEERSingleFeedback,
|
|
)
|
|
from rdagent.components.coder.finetune.conf import (
|
|
FT_DATA_FILE_NAME,
|
|
FT_DATA_SCRIPT_NAME,
|
|
FT_YAML_FILE_NAME,
|
|
clear_workspace,
|
|
get_data_processing_cache_key,
|
|
get_data_processing_env,
|
|
get_ft_env,
|
|
get_workspace_prefix,
|
|
inject_data_stats,
|
|
)
|
|
from rdagent.components.coder.finetune.unified_validator import (
|
|
SYSTEM_MANAGED_PARAMS,
|
|
LLMConfigValidator,
|
|
)
|
|
from rdagent.core.evolving_framework import QueriedKnowledge
|
|
from rdagent.core.experiment import FBWorkspace, Task
|
|
from rdagent.log import rdagent_logger as logger
|
|
from rdagent.utils.agent.tpl import T
|
|
from rdagent.utils.agent.workflow import build_cls_from_json_with_retry
|
|
|
|
DIRNAME = Path(__file__).absolute().resolve().parent
|
|
|
|
|
|
class FTDataEvaluator(CoSTEEREvaluator):
|
|
"""Evaluator for data processing results.
|
|
|
|
This evaluator:
|
|
1. Executes the process_data.py script in Docker
|
|
2. Validates the output data.json file
|
|
3. Generates dataset_info.json for LlamaFactory
|
|
"""
|
|
|
|
def evaluate(
|
|
self,
|
|
target_task: Task,
|
|
implementation: FBWorkspace,
|
|
gt_implementation: FBWorkspace,
|
|
queried_knowledge: Optional[QueriedKnowledge] = None,
|
|
**kwargs,
|
|
) -> CoSTEERSingleFeedback:
|
|
"""Evaluate data processing implementation with LLM feedback."""
|
|
|
|
script_code = implementation.file_dict.get(FT_DATA_SCRIPT_NAME, "")
|
|
data_json_path = implementation.workspace_path / FT_DATA_FILE_NAME
|
|
execution_output = ""
|
|
exit_code = 0
|
|
data = None
|
|
error_msg = None
|
|
|
|
# Step 1: Check script exists
|
|
if not script_code:
|
|
feedback = CoSTEERSingleFeedback(
|
|
execution=f"No {FT_DATA_SCRIPT_NAME} found",
|
|
return_checking="Data processing script missing",
|
|
code="Please generate a data processing script first.",
|
|
final_decision=False,
|
|
)
|
|
logger.log_object(feedback, tag="evaluator_feedback.FTDataEvaluator")
|
|
return feedback
|
|
|
|
# NOTE: we depends cache for speeding up the process of data generation.
|
|
# So we clear the workspace every time.
|
|
|
|
# Step 3: Execute script in DEBUG mode (generates ~10 samples for fast validation)
|
|
env, env_vars = get_data_processing_env(is_debug=True)
|
|
|
|
# Clear workspace (except logs and file_dict items) before data processing
|
|
clear_workspace(implementation, env=env)
|
|
ws_prefix = get_workspace_prefix(env)
|
|
|
|
# Use FTWorkspace.run() for unified Docker logging
|
|
# --debug flag tells the script to generate only ~10 samples
|
|
result = implementation.run(
|
|
env=env,
|
|
entry=f"python {ws_prefix}/{FT_DATA_SCRIPT_NAME} --debug",
|
|
env_vars=env_vars,
|
|
cache_key_extra_func=get_data_processing_cache_key,
|
|
cache_files_to_extract=[FT_DATA_FILE_NAME],
|
|
)
|
|
execution_output = result.stdout if hasattr(result, "stdout") else str(result)
|
|
exit_code = result.exit_code if hasattr(result, "exit_code") else -1
|
|
|
|
# Step 4: Validate output
|
|
if not data_json_path.exists():
|
|
error_msg = f"{FT_DATA_FILE_NAME} not generated"
|
|
else:
|
|
validation_result = self._validate_data_json(data_json_path)
|
|
if not validation_result["valid"]:
|
|
error_msg = validation_result["error"]
|
|
else:
|
|
self._update_dataset_info(implementation, validation_result["sample_count"])
|
|
|
|
# Step 5: Load data if valid
|
|
if error_msg is None and data_json_path.exists():
|
|
with open(data_json_path, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
# Step 5.5: Compute token stats and inject data_stats for yaml coder
|
|
if data is not None and error_msg is None:
|
|
inject_data_stats(implementation, data, execution_output)
|
|
|
|
# Step 6: Generate LLM feedback
|
|
# Truncate stdout from end for LLM (summary at the end is more useful)
|
|
stdout_summary = execution_output[-1500:] if execution_output else ""
|
|
return self._generate_llm_feedback(
|
|
target_task=target_task,
|
|
script_code=script_code if error_msg else "", # Only show script on error
|
|
stdout=stdout_summary, # Always show summary (truncated from end)
|
|
exit_code=exit_code,
|
|
data=data,
|
|
error_msg=error_msg,
|
|
queried_knowledge=queried_knowledge,
|
|
raw_stdout=execution_output, # Full log for UI
|
|
)
|
|
|
|
def _generate_llm_feedback(
|
|
self,
|
|
target_task: Task,
|
|
script_code: str,
|
|
stdout: str,
|
|
exit_code: int,
|
|
data: Optional[list],
|
|
error_msg: Optional[str],
|
|
queried_knowledge: Optional[QueriedKnowledge],
|
|
raw_stdout: str = "",
|
|
) -> CoSTEERSingleFeedback:
|
|
"""Generate LLM-based feedback for data processing evaluation."""
|
|
|
|
# Prepare data statistics and samples
|
|
if data:
|
|
stats = self._analyze_data_quality(data)
|
|
data_stats = json.dumps(stats, indent=2)
|
|
sampled_data = self._sample_data(data)
|
|
data_samples = json.dumps(sampled_data, indent=2, ensure_ascii=False)
|
|
sample_count = len(sampled_data)
|
|
total_samples = len(data)
|
|
else:
|
|
data_stats = json.dumps({"error": error_msg or "No data generated"})
|
|
data_samples = "[]"
|
|
sample_count = 0
|
|
total_samples = 0
|
|
|
|
# Extract similar successful knowledge
|
|
queried_similar_successful_knowledge = []
|
|
if queried_knowledge is not None:
|
|
task_info = target_task.get_task_information()
|
|
queried_similar_successful_knowledge = queried_knowledge.task_to_similar_task_successful_knowledge.get(
|
|
task_info, []
|
|
)
|
|
|
|
# Build prompts
|
|
system_prompt = T(".prompts:data_eval.system").r(
|
|
scenario=self.scen.get_scenario_all_desc(),
|
|
queried_similar_successful_knowledge=queried_similar_successful_knowledge,
|
|
upper_data_size_limit=FT_RD_SETTING.upper_data_size_limit,
|
|
force_think_token=FT_RD_SETTING.force_think_token,
|
|
)
|
|
user_prompt = T(".prompts:data_eval.user").r(
|
|
task_desc=target_task.get_task_information(),
|
|
script_code=script_code,
|
|
exit_code=exit_code,
|
|
stdout=stdout[:3000] if stdout else "", # Empty string triggers {% if stdout %} = false
|
|
data_stats=data_stats,
|
|
sample_count=sample_count,
|
|
total_samples=total_samples,
|
|
data_samples=data_samples,
|
|
)
|
|
|
|
logger.info(
|
|
f"Generating LLM feedback for data evaluation (samples: {total_samples}, has_error: {bool(error_msg)})"
|
|
)
|
|
|
|
feedback = build_cls_from_json_with_retry(
|
|
CoSTEERSingleFeedback,
|
|
system_prompt=system_prompt,
|
|
user_prompt=user_prompt,
|
|
init_kwargs_update_func=CoSTEERSingleFeedback.val_and_update_init_dict,
|
|
)
|
|
|
|
# NOTE: 0 exit code is a hard criteria for success
|
|
if exit_code != 0:
|
|
feedback.final_decision = False
|
|
|
|
feedback.raw_execution = raw_stdout
|
|
feedback.source_feedback[self.__class__.__name__] = feedback.final_decision
|
|
logger.log_object(feedback, tag="evaluator_feedback.FTDataEvaluator")
|
|
return feedback
|
|
|
|
def _validate_data_json(self, data_json_path: Path) -> dict:
|
|
"""Validate data.json file format and content."""
|
|
try:
|
|
with open(data_json_path, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
# Must be a non-empty list
|
|
if not isinstance(data, list):
|
|
return {"valid": False, "error": "data.json must be a JSON array", "sample_count": 0}
|
|
|
|
if len(data) == 0:
|
|
return {"valid": False, "error": "data.json is empty", "sample_count": 0}
|
|
|
|
# Check required fields in samples
|
|
required_fields = ["instruction", "output"]
|
|
for i, sample in enumerate(data[:10]): # Check first 10 samples
|
|
if not isinstance(sample, dict):
|
|
return {"valid": False, "error": f"Sample {i} is not a dict", "sample_count": 0}
|
|
|
|
missing = [f for f in required_fields if f not in sample]
|
|
if missing:
|
|
return {"valid": False, "error": f"Sample {i} missing fields: {missing}", "sample_count": 0}
|
|
|
|
# Check for empty required fields
|
|
for field in required_fields:
|
|
if not sample.get(field):
|
|
return {
|
|
"valid": False,
|
|
"error": f"Sample {i} has empty '{field}' field",
|
|
"sample_count": 0,
|
|
}
|
|
|
|
return {"valid": True, "error": None, "sample_count": len(data)}
|
|
|
|
except json.JSONDecodeError as e:
|
|
return {"valid": False, "error": f"Invalid JSON: {e}", "sample_count": 0}
|
|
except Exception as e:
|
|
return {"valid": False, "error": f"Error reading file: {e}", "sample_count": 0}
|
|
|
|
def _update_dataset_info(self, implementation: FBWorkspace, sample_count: int):
|
|
"""Generate dataset_info.json for LlamaFactory to use the processed data.
|
|
|
|
Note: LlamaFactory's columns mapping uses internal names (prompt, query, response)
|
|
that map to the actual column names in the data file (instruction, input, output).
|
|
See: https://github.com/hiyouga/LLaMA-Factory/blob/main/src/llamafactory/data/parser.py
|
|
"""
|
|
dataset_info = {
|
|
"processed_data": {
|
|
"file_name": FT_DATA_FILE_NAME,
|
|
"formatting": "alpaca",
|
|
"columns": {
|
|
"prompt": "instruction",
|
|
"query": "input",
|
|
"response": "output",
|
|
},
|
|
}
|
|
}
|
|
|
|
try:
|
|
implementation.inject_files(**{"dataset_info.json": json.dumps(dataset_info, indent=2)})
|
|
logger.info(f"Updated dataset_info.json with processed_data ({sample_count} samples)")
|
|
except Exception as e:
|
|
logger.warning(f"Failed to update dataset_info.json: {e}")
|
|
|
|
def _sample_data(self, data: list, n: int = 5) -> list:
|
|
"""Random sampling for LLM evaluation."""
|
|
if len(data) <= n:
|
|
return data
|
|
return random.sample(data, n)
|
|
|
|
def _analyze_data_quality(self, data: list) -> dict:
|
|
"""Analyze data quality statistics for all fields."""
|
|
if not data:
|
|
return {"total_samples": 0, "error": "Empty data"}
|
|
|
|
# Analyze length stats for all standard fields
|
|
fields = ["instruction", "input", "output"]
|
|
stats = {"total_samples": len(data)}
|
|
|
|
for field in fields:
|
|
lens = [len(str(d.get(field, ""))) for d in data]
|
|
empty_count = sum(1 for d in data if not d.get(field))
|
|
stats[f"{field}_len"] = {
|
|
"min": min(lens),
|
|
"max": max(lens),
|
|
"avg": round(sum(lens) / len(lens), 1),
|
|
}
|
|
stats[f"{field}_empty_ratio"] = round(empty_count / len(data) * 100, 1)
|
|
|
|
# Detect duplicates by full record (instruction + input + output)
|
|
record_set = set(
|
|
(str(d.get("instruction", "")), str(d.get("input", "")), str(d.get("output", ""))) for d in data
|
|
)
|
|
duplicate_count = len(data) - len(record_set)
|
|
stats["duplicate_count"] = duplicate_count
|
|
stats["duplicate_ratio"] = round(duplicate_count / len(data) * 100, 1)
|
|
|
|
return stats
|
|
|
|
|
|
class FTCoderEvaluator(CoSTEEREvaluator):
|
|
"""Evaluator for LLM fine-tuning implementations with simplified validation"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
|
|
def evaluate(
|
|
self,
|
|
target_task: Task,
|
|
implementation: FBWorkspace,
|
|
gt_implementation: FBWorkspace,
|
|
queried_knowledge: QueriedKnowledge = None,
|
|
**kwargs,
|
|
) -> CoSTEERSingleFeedback:
|
|
"""Evaluate LLM fine-tuning implementation with two-step validation"""
|
|
|
|
task_info = target_task.get_task_information()
|
|
|
|
# Check task history
|
|
if queried_knowledge is not None:
|
|
if task_info in queried_knowledge.success_task_to_knowledge_dict:
|
|
return queried_knowledge.success_task_to_knowledge_dict[task_info].feedback
|
|
elif task_info in queried_knowledge.failed_task_info_set:
|
|
feedback = CoSTEERSingleFeedback(
|
|
execution="Task failed too many times, skipping.",
|
|
return_checking="Task failed too many times, skipping.",
|
|
code="Task failed too many times, skipping.",
|
|
final_decision=False,
|
|
)
|
|
logger.log_object(feedback, tag="evaluator_feedback.FTCoderEvaluator")
|
|
return feedback
|
|
|
|
env = get_ft_env(operation="micro_batch")
|
|
config_yaml = implementation.file_dict.get(FT_YAML_FILE_NAME, "")
|
|
if not config_yaml:
|
|
feedback = CoSTEERSingleFeedback(
|
|
execution=f"No {FT_YAML_FILE_NAME} found",
|
|
return_checking="Configuration file missing",
|
|
code="No valid configuration file",
|
|
final_decision=False,
|
|
)
|
|
logger.log_object(feedback, tag="evaluator_feedback.FTCoderEvaluator")
|
|
return feedback
|
|
|
|
# Two-step validation: parameter filtering + micro-batch test
|
|
validation_result = LLMConfigValidator().validate_and_test(
|
|
config_yaml=config_yaml, workspace=implementation, env=env
|
|
)
|
|
# NOTE: Docker execution is logged by FTWorkspace.run() automatically
|
|
|
|
# Update config with filtered version
|
|
if validation_result.filtered_config != config_yaml:
|
|
implementation.inject_files(**{FT_YAML_FILE_NAME: validation_result.filtered_config})
|
|
|
|
queried_similar_successful_knowledge = (
|
|
queried_knowledge.task_to_similar_task_successful_knowledge[target_task.get_task_information()]
|
|
if queried_knowledge is not None
|
|
else []
|
|
)
|
|
|
|
system_prompt = T(".prompts:finetune_eval.system").r(
|
|
queried_similar_successful_knowledge=queried_similar_successful_knowledge,
|
|
system_managed_params=SYSTEM_MANAGED_PARAMS,
|
|
)
|
|
user_prompt = T(".prompts:finetune_eval.user").r(
|
|
scenario=self.scen.get_scenario_all_desc(),
|
|
task_desc=target_task.get_task_information(),
|
|
stdout=validation_result.execution_output or "No output",
|
|
code_yaml=implementation.file_dict[FT_YAML_FILE_NAME],
|
|
workspace_files="\n".join(
|
|
[
|
|
f"- {file.name} ({file.stat().st_size} bytes)"
|
|
for file in implementation.workspace_path.rglob("*")
|
|
if file.is_file() and "checkpoint" not in file.absolute().as_posix()
|
|
]
|
|
),
|
|
)
|
|
feedback = build_cls_from_json_with_retry(
|
|
CoSTEERSingleFeedback,
|
|
system_prompt=system_prompt,
|
|
user_prompt=user_prompt,
|
|
init_kwargs_update_func=CoSTEERSingleFeedback.val_and_update_init_dict,
|
|
)
|
|
|
|
# Force failure if validation failed programmatically
|
|
if not validation_result.success:
|
|
feedback.final_decision = False
|
|
logger.warning("FTCoderEvaluator: Forced final_decision=False due to validation failure")
|
|
|
|
feedback.raw_execution = validation_result.raw_stdout or ""
|
|
feedback.source_feedback[self.__class__.__name__] = feedback.final_decision
|
|
logger.log_object(feedback, tag="evaluator_feedback.FTCoderEvaluator")
|
|
return feedback
|