Files
NexQuant/rdagent/scenarios/finetune/scen/scenario.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

305 lines
13 KiB
Python

import json
import os
import shutil
from pathlib import Path
from rdagent.app.finetune.llm.conf import FT_RD_SETTING
from rdagent.components.coder.finetune.conf import get_ft_env
from rdagent.core.utils import cache_with_pickle
from rdagent.log import rdagent_logger as logger
from rdagent.oai.llm_utils import APIBackend
from rdagent.scenarios.data_science.scen import DataScienceScen
from rdagent.scenarios.finetune.benchmark import get_benchmark_ranges, run_benchmark
from rdagent.scenarios.finetune.datasets import prepare_all
from rdagent.scenarios.finetune.experiment.workspace import FTWorkspace
from rdagent.scenarios.finetune.scen.llama_factory_manager import LLaMAFactory_manager
from rdagent.scenarios.finetune.scen.memory_estimator import MemoryEstimator
from rdagent.scenarios.finetune.scen.utils import (
FinetuneDatasetDescriptor,
generate_dataset_info_config,
)
from rdagent.scenarios.finetune.utils import ensure_ft_assets_exist
from rdagent.scenarios.shared.get_runtime_info import get_runtime_environment_by_env
from rdagent.utils.agent.tpl import T
class LLMFinetuneScen(DataScienceScen):
"""LLMFinetuneScen Scenario"""
def __init__(self) -> None:
"""Initialize LLM finetune scenario using configuration from FT_RD_SETTING."""
logger.info("Initializing LLM Fine-tune scenario")
# Basic attributes
self.user_target_scenario = FT_RD_SETTING.user_target_scenario
self.target_benchmark = FT_RD_SETTING.target_benchmark
self.benchmark_description = FT_RD_SETTING.benchmark_description
self.dataset = FT_RD_SETTING.dataset
self.base_model = FT_RD_SETTING.base_model
# Validate and prepare environment
self._validate_and_prepare_environment()
# Initialize LLaMA Factory manager
self._initialize_llama_factory()
# Generate dataset configuration for all datasets first
self.dataset_config = self._prepare_dataset_config()
# Select relevant datasets based on user target scenario (using full config info)
self.selected_datasets = self._select_relevant_datasets()
# Filter dataset_config to only include selected datasets
self.dataset_config = {k: v for k, v in self.dataset_config.items() if k in self.selected_datasets}
# timeout tracking
self.timeout_increase_count = 0
# NOTE: we disable the cache for environment. in case of changing cuda config
self.device_info = get_runtime_environment_by_env(get_ft_env(enable_cache=False))
self.gpu_count = json.loads(self.device_info).get("gpu_count", 0)
self.model_info = FinetuneDatasetDescriptor().describe_model(self.base_model)
# Initialize memory estimator
self.memory_report = self._generate_memory_report()
baseline_result = self.run_baseline_model_evaluation(
model_name=self.base_model, benchmark_name=self.target_benchmark
)
# Agent only sees validation score
self.baseline_benchmark_score = baseline_result.get("benchmark", {})
# Test score is for frontend display only
self.baseline_benchmark_score_test = baseline_result.get("benchmark_test", {})
def benchmark_hash(self, model_name, benchmark_name) -> str:
return f"llm_finetune_baseline_eval_{model_name}_{benchmark_name}"
@cache_with_pickle(benchmark_hash)
def run_baseline_model_evaluation(self, model_name, benchmark_name) -> dict:
ws = FTWorkspace()
shutil.copytree(
Path(FT_RD_SETTING.file_path) / "models" / model_name,
ws.workspace_path / "models" / model_name,
dirs_exist_ok=True,
)
val_range, test_range = get_benchmark_ranges()
# Validation set - visible to agent
validation_result = run_benchmark(
workspace_path=str(ws.workspace_path),
model_path=ws.workspace_path / "models" / model_name,
model_name=model_name,
benchmark_name=benchmark_name,
gpu_count=self.gpu_count,
test_range=val_range,
result_subdir="validation",
)
# Test set - NOT visible to agent, frontend only
test_result = run_benchmark(
workspace_path=str(ws.workspace_path),
model_path=ws.workspace_path / "models" / model_name,
model_name=model_name,
benchmark_name=benchmark_name,
gpu_count=self.gpu_count,
test_range=test_range,
result_subdir="test",
)
return {
"benchmark": validation_result, # Agent sees this
"benchmark_test": test_result, # Agent does NOT see this
}
def real_full_timeout(self):
return FT_RD_SETTING.full_timeout
def _generate_memory_report(self) -> str:
"""Generate memory estimation report based on hardware and model."""
try:
# Parse device info
device_info = json.loads(self.device_info) if isinstance(self.device_info, str) else self.device_info
gpu_info = device_info.get("gpu", {})
# Extract GPU info based on source
if gpu_info.get("source") == "pytorch":
# PyTorch format: gpu_count at top level, total_memory_gb in summary
num_gpus = gpu_info.get("gpu_count")
gpu_mem = gpu_info.get("summary", {}).get("total_memory_gb")
else:
# nvidia-smi format: has gpus array with memory_total_gb
gpus = gpu_info.get("gpus", [])
num_gpus = len(gpus) if gpus else None
gpu_mem = gpus[0].get("memory_total_gb", 0) if gpus else None
# Skip if GPU info not available
if not num_gpus or not gpu_mem:
logger.warning("GPU info not available, skipping memory report")
return ""
# Create estimator from model name (pass model_specs for max_position_embeddings)
estimator = MemoryEstimator.from_model_name(
name=self.base_model,
gpu_mem=gpu_mem,
num_gpus=num_gpus,
model_specs=self.model_info.get("specs", ""),
)
return estimator.format()
except Exception as e:
logger.warning(f"Failed to generate memory report: {e}")
return ""
def _validate_and_prepare_environment(self):
"""Validate FT_FILE_PATH and prepare all registered datasets"""
ft_root = Path(FT_RD_SETTING.file_path)
if not ft_root.exists():
os.makedirs(ft_root, mode=0o777, exist_ok=True)
logger.info(f"FT_FILE_PATH not exists, created FT_FILE_PATH directory: {ft_root}")
# Prepare all registered datasets
prepare_all()
# Ensure model assets exist
if self.base_model:
ensure_ft_assets_exist(model=self.base_model, check_model=True)
def _initialize_llama_factory(self):
"""Initialize LLaMA Factory information manager"""
# Extract LLaMA Factory information (pulls latest code automatically)
info = LLaMAFactory_manager.get_info()
# Log extracted information
methods_count = len(info.get("methods", []))
params_count = sum(len(p) if isinstance(p, dict) else 0 for p in info.get("parameters", {}).values())
logger.info(f"LLaMA Factory initialized: {methods_count} methods, {params_count} parameters")
def _select_relevant_datasets(self) -> list[str]:
"""Select relevant datasets based on user target scenario using LLM.
Uses self.dataset_config which contains full information (stats, description, samples).
"""
total = len(self.dataset_config)
# If user specified a dataset, use it directly
if self.dataset:
selected, reasoning = [self.dataset], "User specified dataset directly"
elif not self.dataset_config:
logger.warning("No datasets found for selection")
return []
else:
# Use LLM to select relevant datasets
logger.info(f"Found {total} datasets, selecting relevant ones...")
selected, reasoning = self._llm_select_datasets()
# Log results
logger.info(f"Dataset selection: {len(selected)}/{total} - {selected}")
logger.log_object(
{"selected_datasets": selected, "total_datasets": total, "reasoning": reasoning},
tag="dataset_selection",
)
return selected
def _llm_select_datasets(self) -> tuple[list[str], str]:
"""Use LLM to select relevant datasets."""
# Pass dataset_config directly - it already has the unified tasks structure
dataset_summaries = [
{
"name": ds_name,
"total_samples": ds_config.get("total_samples"),
"total_size_mb": ds_config.get("total_size_mb"),
"tasks": ds_config.get("tasks", {}),
"readme": ds_config.get("readme"),
}
for ds_name, ds_config in self.dataset_config.items()
]
system_prompt = T(".prompts:dataset_selection.system").r(
user_target_scenario=self.user_target_scenario,
target_benchmark=self.target_benchmark,
benchmark_description=self.benchmark_description,
)
user_prompt = T(".prompts:dataset_selection.user").r(datasets=dataset_summaries)
response = APIBackend().build_messages_and_create_chat_completion(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_mode=True,
)
result = json.loads(response)
return result.get("selected_datasets", []), result.get("reasoning", "")
def _prepare_dataset_config(self) -> dict:
"""Generate dataset_info.json configuration.
This is the single source of truth for dataset information, containing:
- LlamaFactory compatible fields (file_name, formatting, columns)
- Auto-computed statistics (stats.column_stats)
- Data samples (truncated)
- AI-generated description
Returns:
dict: Complete dataset configuration
"""
datasets_dir = Path(FT_RD_SETTING.file_path) / "datasets"
dataset_info_path = datasets_dir / "dataset_info.json"
# Check if already configured
existing_config = {}
if dataset_info_path.exists():
try:
with open(dataset_info_path, "r", encoding="utf-8") as f:
existing_config = json.load(f)
# Only keep entries that have corresponding local directories
local_datasets = {d.name for d in datasets_dir.iterdir() if d.is_dir() and not d.name.startswith(".")}
existing_config = {k: v for k, v in existing_config.items() if k in local_datasets}
except Exception as e:
logger.warning(f"Failed to load existing dataset_info.json: {e}")
# Generate config for all datasets (will be filtered later by _select_relevant_datasets)
target_dataset_list = [] if self.dataset is None else [self.dataset]
logger.info(
f"Generating dataset_info.json configuration for: {target_dataset_list if target_dataset_list else 'all datasets'}"
)
generated_config = generate_dataset_info_config(target_dataset_list, FT_RD_SETTING.file_path, existing_config)
for dataset_name, config in generated_config.items():
existing_config[dataset_name] = config
try:
os.makedirs(datasets_dir, mode=0o777, exist_ok=True)
with open(dataset_info_path, "w", encoding="utf-8") as f:
json.dump(existing_config, f, indent=2, ensure_ascii=False)
logger.info(f"Successfully updated dataset_info.json with configuration for: {target_dataset_list}")
except Exception as e:
raise RuntimeError(f"Failed to write dataset_info.json: {e}")
return existing_config
@property
def metric_direction(self) -> bool:
"""Metric direction for LLM fine-tuning (higher is better)"""
return True
def get_scenario_all_desc(self, enable_dataset_description: bool = False) -> str:
"""Get complete scenario description for LLM fine-tuning.
Uses dataset_config as the single source of truth for dataset information.
The prompt template renders tasks with their statistics and samples.
"""
return T(".prompts:scenario_description").r(
user_target_scenario=self.user_target_scenario,
target_benchmark=self.target_benchmark,
benchmark_description=self.benchmark_description,
device_info=self.device_info,
memory_report=self.memory_report,
chosen_model=FT_RD_SETTING.base_model is not None,
base_model=FT_RD_SETTING.base_model,
dataset_config=self.dataset_config,
model_info=self.model_info,
full_timeout=f"{self.real_full_timeout() / 60 / 60:.2f} hours",
data_processing_timeout=f"{FT_RD_SETTING.data_processing_timeout / 60:.0f} minutes",
enable_dataset_description=enable_dataset_description,
upper_data_size_limit=FT_RD_SETTING.upper_data_size_limit,
)