Files
NexQuant/rdagent/app/finetune/llm/README.md
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

6.7 KiB

LLM Fine-tuning (FT) 场景运行指南

本文档介绍如何运行 RD-Agent 的 LLM Fine-tuning 场景。

简介

FT 场景用于自动化优化大语言模型在特定 benchmark 上的表现。系统会自动:

  1. 生成数据处理和训练代码
  2. 执行模型微调
  3. 在目标 benchmark 上评估模型性能
  4. 根据反馈迭代改进

支持的 Benchmark

类别 Benchmark 数据集 描述
Math aime24, aime25 deepscaler AIME 数学竞赛
Patent panorama_par4pc panorama-par4pc 专利现有技术检索
Patent panorama_pi4pc panorama-pi4pc 专利段落识别
Patent panorama_noc4pc panorama-noc4pc 专利新颖性分类
Chemistry chemcotbench_mol_und chemcot-mol_und 分子理解
Chemistry chemcotbench_mol_edit chemcot-mol_edit 分子编辑
Chemistry chemcotbench_mol_opt chemcot-mol_opt 分子优化
Chemistry chemcotbench_reaction chemcot-rxn 化学反应预测

数据集配置位于 rdagent/scenarios/finetune/datasets/__init__.pyDATASETS 字典中。

运行时agent会查看所有数据集,根据target benchmark和scenario选出与之相关的。

环境配置

1. 运行环境

确保已安装 rdagent 主运行环境,其他需要的运行环境会自动创建

.env 配置文件中通过设置 FT_Coder_CoSTEER_env_type = conda/docker 来配置

2. .env 配置文件

在项目根目录创建 .env 文件,参考以下模板:

# ========== API Configuration ==========
BACKEND=rdagent.oai.backend.LiteLLMAPIBackend
CHAT_MODEL=gpt-5.2
CHAT_TEMPERATURE=1
CHAT_STREAM=True
OPENAI_API_KEY=sk-xxx
OPENAI_API_BASE=http://your-api-endpoint

EMBEDDING_MODEL=text-embedding-ada-002
EMBEDDING_USE_AZURE=True

# ========== Global Configs ==========
MAX_RETRY=12000
RETRY_WAIT_SECONDS=5
MULTI_PROC_N=16
STEP_SEMAPHORE=1

# ========== Cache Settings ==========
DUMP_CHAT_CACHE=False
USE_CHAT_CACHE=False
DUMP_EMBEDDING_CACHE=True
USE_EMBEDDING_CACHE=True
LOG_LLM_CHAT_CONTENT=True

CHAT_FREQUENCY_PENALTY=0.1
CHAT_PRESENCE_PENALTY=0.0

# ========== FT Scenario Specific ==========
FT_FILE_PATH=/path/to/your/finetune/workspace

# Environment type: docker or conda
# Set to "conda" when Docker is unavailable
FT_Coder_CoSTEER_env_type=conda

# Docker settings (only used when env_type=docker)
FT_DOCKER_ENABLE_CACHE=True
FT_UPDATE_LLAMA_FACTORY=False

# Data processing API concurrency (adjust based on target API capacity)
FT_API_MAX_WORKERS=1000

# Data processing Model
FT_STRONG_MODELS='["gpt-5", "gpt-5.1"]'
FT_WEAK_MODELS='["gpt-4o-mini"]'

# Benchmark and target (can be overridden in script)
FT_TARGET_BENCHMARK=aime25
FT_USER_TARGET_SCENARIO="I need to enhance the model's performance on math reasoning tasks."

# Timeout settings
FT_DATA_PROCESSING_TIMEOUT=28800

# Judge settings (optional)
# FT_JUDGE_MODEL=gpt-5.1
# FT_JUDGE_RETRY=10

REASONING_THINK_RM=True

# ========== Logging ==========
LOG_FORMAT_CONSOLE="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | <cyan>{process}</cyan> | {name}:{function}:{line} - {message}"

# ========== HuggingFace ==========
HF_TOKEN=hf_xxx

运行方法

基本命令

# 激活 conda 环境
conda activate rdagent

# 运行 FT 场景
dotenv run -- python rdagent/app/finetune/llm/loop.py --base-model <MODEL>

命令行参数

参数 说明 示例
--base-model 基础模型名称(必需,其他都可以不填) Qwen/Qwen2.5-7B-Instruct
--benchmark 目标 benchmark aime25
--benchmark-description Benchmark 描述 -
--dataset 指定数据集 -
--step-n 步数限制 10
--loop-n 循环次数限制 5
--timeout 总时间限制 -

运行示例

# 在 AIME25 上微调 Qwen2.5-7B
dotenv run -- python rdagent/app/finetune/llm/loop.py \
    --base-model Qwen/Qwen2.5-7B-Instruct

# 指定 GPU 运行
CUDA_VISIBLE_DEVICES=0,1 dotenv run -- python rdagent/app/finetune/llm/loop.py \
    --base-model Qwen/Qwen2.5-7B-Instruct

# 限制循环次数
dotenv run -- python rdagent/app/finetune/llm/loop.py \
    --base-model Qwen/Qwen2.5-7B-Instruct \
    --loop-n 3

多任务并行运行

创建 tasks.json 配置文件:

{
  "tasks": [
    {"model": "Qwen/Qwen2.5-7B-Instruct", "benchmark": "aime25", "gpus": "0,1"},
    {"model": "Qwen/Qwen2.5-7B-Instruct", "benchmark": "gsm8k", "gpus": "2,3"}
  ]
}

使用 run_ft_deploy.sh 脚本运行:

./run_ft_deploy.sh tasks.json           # 正常运行
./run_ft_deploy.sh tasks.json --dry-run # 仅预览配置
./run_ft_deploy.sh tasks.json --no-sync # 禁用 blob 同步
run_ft_deploy.sh 脚本参考
#!/bin/bash
# 多任务并行部署脚本(简化版)

RDAGENT_DIR="$HOME/RD-Agent"
ENV_TEMPLATE=".env.ft"
STAGGER_DELAY=60

cd "$RDAGENT_DIR"
source ~/miniconda3/etc/profile.d/conda.sh
conda activate rdagent

CONFIG_FILE="${1:-tasks.json}"
NUM_TASKS=$(jq '.tasks | length' "$CONFIG_FILE")

for ((i=0; i<NUM_TASKS; i++)); do
    model=$(jq -r ".tasks[$i].model" "$CONFIG_FILE")
    benchmark=$(jq -r ".tasks[$i].benchmark" "$CONFIG_FILE")
    gpus=$(jq -r ".tasks[$i].gpus" "$CONFIG_FILE")

    # 更新 .env 中的 benchmark
    cp "$ENV_TEMPLATE" .env
    sed -i "s|^FT_TARGET_BENCHMARK=.*|FT_TARGET_BENCHMARK=$benchmark|" .env

    CUDA_VISIBLE_DEVICES=$gpus \
    dotenv run -- python rdagent/app/finetune/llm/loop.py --base-model "$model" &

    # 首个任务等待环境创建,后续任务错开启动
    [[ $i -eq 0 ]] && sleep 120 || sleep $STAGGER_DELAY
done

wait

Blob 日志同步

使用 Azure Blob 在多台机器间同步日志文件。

1. 生成 SAS Token

# 首先登录 Azure CLI
az login

# 生成 Token(默认有效期 7 天)
bash rdagent/utils/blob/gen_token.sh

# 或指定过期时间
bash rdagent/utils/blob/gen_token.sh 2025-01-31T00:00Z

Token 会保存到 git_ignore_folder/.az_sas_token

2. 同步日志

同步路径:log/blob://epeastus/rdagent/FinetuneAgenticLLM/FT_qizheng/logs

# 上传本地日志到 Blob
bash rdagent/utils/blob/azsync.sh up

# 从 Blob 下载日志到本地
bash rdagent/utils/blob/azsync.sh down

如需修改远程路径,编辑 rdagent/utils/blob/azsync.sh 中的 REMOTE_PATH 变量。

日志查看

运行日志保存在 log/ 目录下:

log/
└── 2025-01-01_12-00-00-123456/
    ├── Loop_0/
    │   ├── direct_exp_gen/   # 假设生成
    │   ├── coding/           # 代码生成
    │   ├── running/          # 训练执行
    │   └── feedback/         # 反馈总结
    └── Loop_1/
        └── ...