Files
NexQuant/rdagent/scenarios/finetune/train/eval.py
XianBW 6e19c9e632 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

331 lines
13 KiB
Python

import json
from typing import Any, Dict, List, 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.exp import FTTask
from rdagent.components.coder.finetune.unified_validator import LLMConfigValidator
from rdagent.core.evolving_framework import QueriedKnowledge
from rdagent.core.experiment import FBWorkspace
from rdagent.log import rdagent_logger as logger
from rdagent.scenarios.finetune.benchmark import get_benchmark_ranges, run_benchmark
from rdagent.utils.agent.tpl import T
from rdagent.utils.agent.workflow import build_cls_from_json_with_retry
def extract_loss_history(output_path) -> Dict[str, List[Dict[str, Any]]]:
"""
Extract training and evaluation loss history from LlamaFactory's trainer_state.json.
Args:
output_path: Path to the training output directory
Returns:
Dict with 'train' and 'eval' keys, each containing a list of loss entries.
"""
trainer_state_path = output_path / "trainer_state.json"
result = {"train": [], "eval": []}
if not trainer_state_path.exists():
logger.warning(f"trainer_state.json not found at {trainer_state_path}")
return result
try:
with open(trainer_state_path) as f:
trainer_state = json.load(f)
log_history = trainer_state.get("log_history", [])
for entry in log_history:
if "loss" in entry:
result["train"].append(
{
"step": entry.get("step"),
"epoch": entry.get("epoch"),
"loss": entry.get("loss"),
}
)
if "eval_loss" in entry:
result["eval"].append(
{
"step": entry.get("step"),
"epoch": entry.get("epoch"),
"eval_loss": entry.get("eval_loss"),
}
)
logger.info(f"Extracted {len(result['train'])} train + {len(result['eval'])} eval entries")
except (json.JSONDecodeError, OSError) as e:
logger.warning(f"Failed to parse trainer_state.json: {e}")
return result
class FTRunnerEvaluator(CoSTEEREvaluator):
"""LLM Fine-tuning specific evaluator that uses LLM Docker environment."""
def evaluate(
self,
target_task: FTTask,
implementation: FBWorkspace,
gt_implementation: FBWorkspace,
queried_knowledge: Optional[QueriedKnowledge] = None,
**kwargs,
) -> CoSTEERSingleFeedback:
"""Evaluate LLM fine-tuning implementation using dedicated LLM environment.
This evaluator performs three stages:
0. Clean workspace (remove old training outputs)
1. Full data processing (without --debug flag) to generate complete data.json
2. Full training with the complete dataset
"""
# Check if FT_YAML_FILE_NAME exists
if FT_YAML_FILE_NAME not in implementation.file_dict:
fb = CoSTEERSingleFeedback(
execution=f"No {FT_YAML_FILE_NAME} found in workspace",
return_checking="Config file missing",
code="No valid configuration file",
final_decision=False,
)
implementation.feedback = fb
logger.log_object(fb, tag="evaluator_feedback.FTRunnerEvaluator")
return fb
# Use LLM-specific environment with appropriate timeout for training
env = get_ft_env(operation="full_training")
# ========== Stage 0: Clean Workspace ==========
# Clean old training outputs before data processing and training
clear_workspace(implementation, env)
# ========== Stage 1: Full Data Processing ==========
# Execute data processing WITHOUT --debug flag to generate complete data.json
data_result = self._run_full_data_processing(implementation)
data_stdout = data_result.stdout or ""
if data_result.exit_code != 0:
# Data processing failed, return feedback to enter next loop
logger.error(f"Full data processing failed with exit_code={data_result.exit_code}")
return self._generate_llm_feedback(
target_task=target_task,
implementation=implementation,
raw_stdout=data_stdout,
exit_code=data_result.exit_code,
model_files_exist=False,
benchmark_result=None,
loss_history=None,
failed_stage="data_processing",
)
logger.info("Full data processing completed successfully")
# Update data_stats.json with full dataset statistics
# This ensures feedback sees the correct sample count, not debug mode count
data_json_path = implementation.workspace_path / FT_DATA_FILE_NAME
if data_json_path.exists():
with open(data_json_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list) and len(data) > 0:
inject_data_stats(implementation, data, data_stdout)
# ========== Stage 2: Full Training ==========
# Execute LlamaFactory training
train_result = implementation.run(
env=env,
entry=f"llamafactory-cli train {FT_YAML_FILE_NAME}",
)
# Combine data processing and training stdout for comprehensive feedback
combined_stdout = (
f"=== DATA PROCESSING OUTPUT ===\n{data_stdout}\n\n=== TRAINING OUTPUT ===\n{train_result.stdout or ''}"
)
implementation.running_info.running_time = train_result.running_time
# NOTE: Docker execution is logged by FTWorkspace.run() automatically
# Simple success check: exit code
training_success = train_result.exit_code == 0
# Check for model output files
workspace_path = implementation.workspace_path
output_path = workspace_path / "output"
model_output_files = (
list(output_path.glob("*.safetensors"))
+ list(output_path.glob("*.bin"))
+ list(output_path.glob("adapter_*"))
if output_path.exists()
else []
)
# Early return if training failed
if not training_success or len(model_output_files) == 0:
return self._generate_llm_feedback(
target_task=target_task,
implementation=implementation,
raw_stdout=combined_stdout,
exit_code=train_result.exit_code,
model_files_exist=len(model_output_files) > 0,
benchmark_result=None,
loss_history=None,
failed_stage="training",
)
# Extract loss history from training output
loss_history = extract_loss_history(output_path)
val_range, test_range = get_benchmark_ranges()
# Validation set - used for SOTA judgment, visible to agent
validation_result = run_benchmark(
workspace_path=str(workspace_path),
model_path=output_path,
model_name=target_task.base_model,
benchmark_name=target_task.benchmark,
gpu_count=self.scen.gpu_count,
test_range=val_range,
result_subdir="validation",
)
# Test set - only for frontend display, not visible to agent
test_result = run_benchmark(
workspace_path=str(workspace_path),
model_path=output_path,
model_name=target_task.base_model,
benchmark_name=target_task.benchmark,
gpu_count=self.scen.gpu_count,
test_range=test_range,
result_subdir="test",
)
# Build comprehensive result with training metrics and benchmark results
# Note: "benchmark" is for agent (SOTA judgment), "benchmark_test" is for frontend only
train_history = loss_history.get("train", []) if loss_history else []
implementation.running_info.result = {
"benchmark": validation_result, # Agent visible - used for SOTA judgment
"benchmark_test": test_result, # Agent invisible - frontend display only
"training_metrics": {
"loss_history": loss_history,
"final_loss": train_history[-1]["loss"] if train_history else None,
"initial_loss": train_history[0]["loss"] if train_history else None,
},
}
benchmark_result = validation_result # For backward compatibility with feedback
# Call LLM for feedback analysis - LLM will determine final_decision
return self._generate_llm_feedback(
target_task=target_task,
implementation=implementation,
raw_stdout=combined_stdout,
exit_code=train_result.exit_code,
model_files_exist=len(model_output_files) > 0,
benchmark_result=benchmark_result,
loss_history=loss_history,
)
def _generate_llm_feedback(
self,
target_task: FTTask,
implementation: FBWorkspace,
raw_stdout: str,
exit_code: int,
model_files_exist: bool,
benchmark_result: Optional[Dict] = None,
loss_history: Optional[Dict[str, List[Dict]]] = None,
failed_stage: Optional[str] = None,
) -> CoSTEERSingleFeedback:
"""Generate LLM-based feedback for runner evaluation.
LLM will determine final_decision based on all provided information.
Args:
failed_stage: Which stage failed - "data_processing" or "training"
"""
# Parse execution log to extract structured info (reuse unified_validator's method)
# Reduces ~36k tokens to ~500 tokens by extracting: status, errors, metrics, warnings
parsed_stdout = LLMConfigValidator()._parse_execution_log(raw_stdout, exit_code, failed_stage)
# Get timeout config for the failed stage
timeout_seconds = None
if failed_stage == "data_processing":
timeout_seconds = FT_RD_SETTING.data_processing_timeout
elif failed_stage == "training":
timeout_seconds = FT_RD_SETTING.full_timeout
# Pass loss_history directly (simpler and preserves full information)
# Sample train entries if too many to avoid token bloat
if loss_history and len(loss_history.get("train", [])) > 60:
loss_history["train"] = loss_history["train"][:30] + loss_history["train"][-30:]
system_prompt = T("rdagent.components.coder.finetune.prompts:runner_eval.system").r()
user_prompt = T("rdagent.components.coder.finetune.prompts:runner_eval.user").r(
task_desc=target_task.get_task_information(),
config_yaml=implementation.file_dict.get(FT_YAML_FILE_NAME, ""),
exit_code=exit_code,
model_files_status="Found" if model_files_exist else "Not found",
stdout=parsed_stdout, # Structured JSON instead of raw truncated log
benchmark_result=(
json.dumps(benchmark_result, indent=2) if benchmark_result else "N/A (not executed or failed)"
),
loss_history=(
json.dumps(loss_history, indent=2)
if (loss_history and (loss_history.get("train") or loss_history.get("eval")))
else "N/A"
),
failed_stage=failed_stage,
timeout_seconds=timeout_seconds,
)
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,
)
feedback.raw_execution = raw_stdout
implementation.feedback = feedback
logger.log_object(feedback, tag="evaluator_feedback.FTRunnerEvaluator")
return feedback
def _run_full_data_processing(self, implementation: FBWorkspace):
"""Execute full data processing (without --debug flag) to generate complete data.json.
This is called at the beginning of the running stage to regenerate data.json
with all samples instead of the debug subset created during coding stage.
Args:
implementation: The workspace containing process_data.py
Returns:
EnvResult with exit_code, stdout, etc.
"""
# Get data processing environment with LLM API access
env, env_vars = get_data_processing_env()
ws_prefix = get_workspace_prefix(env)
logger.info("Starting full data processing (without --debug flag)")
# Execute WITHOUT --debug flag to generate all samples
result = implementation.run(
env=env,
entry=f"python {ws_prefix}/{FT_DATA_SCRIPT_NAME}", # No --debug flag
env_vars=env_vars,
cache_key_extra_func=get_data_processing_cache_key,
cache_files_to_extract=[FT_DATA_FILE_NAME],
)
return result