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

398 lines
15 KiB
Python

"""
Benchmark Evaluation using OpenCompass
Evaluator that runs OpenCompass in Docker to evaluate fine-tuned models on standard benchmarks.
Configure benchmark behavior via editting .env to cover default settings in conf.py:
```
FT_BENCHMARK_DATASETS='["aime25", "gsm8k"]'
FT_BENCHMARK_NUM_RUNS=4
FT_JUDGE_MODEL="gpt-4"
FT_JUDGE_API_KEY="sk-xxx"
FT_JUDGE_API_BASE="https://api.openai.com/v1"
```
"""
import json
import random
import shutil
import subprocess
from pathlib import Path
from typing import Any, Dict, List, Optional
import pandas as pd
import yaml
from rdagent.app.finetune.llm.conf import FT_RD_SETTING
from rdagent.components.coder.finetune.conf import (
FT_MODEL_PATH,
get_benchmark_env,
get_ft_env,
get_workspace_prefix,
is_docker_env,
)
from rdagent.core.experiment import FBWorkspace, Task
from rdagent.log import rdagent_logger as logger
from rdagent.oai.llm_conf import LLM_SETTINGS
from rdagent.scenarios.finetune.benchmark.data.adaptor import (
BENCHMARK_CONFIG_DICT,
BenchmarkConfig,
)
from rdagent.scenarios.finetune.benchmark.data.default import extract_error_samples
from rdagent.scenarios.finetune.benchmark.merge.merge import (
check_if_merging_needed,
merge_model,
)
from rdagent.utils.agent.tpl import T
def get_model_inference_config(base_model_name: str, gpu_count: int) -> dict:
"""
Load model inference configuration from YAML file.
Args:
base_model_name: HuggingFace model name (e.g., "Qwen/Qwen3-8B")
gpu_count: GPU count for tensor_parallel_size (from scenario.device_info)
Returns:
dict: Merged configuration (model-specific overrides default)
Uses exact match first, then longest prefix match, finally default only.
"""
config_data = yaml.safe_load(open(Path(__file__).parent / "configs" / "models.yaml", "r"))
default_config = config_data.get("default", {})
models_config = config_data.get("models", {})
# 1. Exact match
if base_model_name in models_config:
model_specific = models_config[base_model_name]
else:
# 2. Prefix match - find longest matching prefix
model_specific = {}
best_match_len = 5
for configured_model in models_config:
if base_model_name.startswith(configured_model) and len(configured_model) > best_match_len:
model_specific = models_config[configured_model]
best_match_len = len(configured_model)
final_config = {**default_config, **model_specific}
# Handle auto tensor_parallel_size
if final_config.get("tensor_parallel_size") == "auto":
if gpu_count <= 0:
final_config["tensor_parallel_size"] = 1
else:
# Round down to nearest power of 2
power = 0
while (1 << (power + 1)) <= gpu_count:
power += 1
final_config["tensor_parallel_size"] = 1 << power
return final_config
def detect_model_type(model_path: str) -> bool:
"""
Detect whether the given model path corresponds to a LoRA adapter.
Returns:
True if LoRA adapter, False otherwise.
"""
model_dir = Path(model_path)
# LoRA (llama-factory style)
if (model_dir / "adapter_config.json").exists():
return True
# Alternate LoRA file indicators
for fname in ("adapter_model.bin", "adapter_model.safetensors"):
if (model_dir / fname).exists():
return True
return False
def run_benchmark(
workspace_path: str,
model_path: str,
model_name: str,
benchmark_name: str,
gpu_count: int,
test_range: Optional[str] = "[:100]",
num_runs: int = 1,
pass_k: Optional[List[int]] = None,
max_error_samples: int = 10,
result_subdir: str = "",
) -> Dict[str, Any]:
"""
Run benchmark evaluation on a fine-tuned model.
Args:
workspace_path: Path to workspace directory
model_path: Path to fine-tuned model (supports full/LoRA auto-detection)
model_name: HuggingFace model name
benchmark_name: Benchmark dataset name (e.g., "aime25", "gsm8k")
gpu_count: GPU count for tensor_parallel_size (from scenario.device_info)
test_range: Python slice string for dataset sampling (e.g., "[:100]", "[-100:]").
Negative indexing allows automatic adaptation to varying subset sizes.
num_runs: Number of times to run each sample (default: 1)
pass_k: Optional list of k values for pass@k evaluation (e.g., [1, 5, 10])
max_error_samples: Maximum number of error samples to extract for feedback
result_subdir: Subdirectory for results (e.g., "validation", "test")
Returns:
Dict containing:
- accuracy_summary: Dict mapping dataset -> {metric: value}, grouped by dataset
- error_samples: List of error samples for feedback analysis
"""
# Load configurations
benchmark_cfg: BenchmarkConfig = BENCHMARK_CONFIG_DICT[benchmark_name]
dataset_imports = benchmark_cfg.dataset
# Auto download dependent data if configured on this benchmark
if benchmark_cfg.download is not None:
benchmark_cfg.download()
model_is_lora = detect_model_type(model_path)
inference_config = get_model_inference_config(model_name, gpu_count)
workspace_path = Path(workspace_path)
# Get environment first to determine path prefix
env = get_benchmark_env()
ws_prefix = get_workspace_prefix(env)
is_docker = is_docker_env(env)
# Determine model paths based on environment type
model_rel_path = Path(model_path).relative_to(workspace_path)
adapter_path_in_env = Path(ws_prefix) / model_rel_path
if model_is_lora:
if is_docker:
# Docker: use /assets/models mount
model_path_in_env = Path(FT_MODEL_PATH) / model_name
else:
# Conda: use actual file path
model_path_in_env = Path(FT_RD_SETTING.file_path) / "models" / model_name
lora_path_in_env = adapter_path_in_env
# Check if we need to merge the model (e.g. vLLM doesn't support LoRA with modules_to_save)
if check_if_merging_needed(model_path):
merged_model_dir_inside_env = Path(ws_prefix) / "merged_model"
# Create a temporary environment for merging (use FT env as it has peft/transformers)
merge_env = get_ft_env()
merge_model(
env=merge_env,
workspace_path=workspace_path,
base_model_path=str(model_path_in_env),
adapter_path=str(lora_path_in_env),
output_path=str(merged_model_dir_inside_env),
)
# Switch to using the merged model
model_path_in_env = merged_model_dir_inside_env
model_is_lora = False
lora_path_in_env = ""
adapter_path_in_env = merged_model_dir_inside_env
else:
model_path_in_env = adapter_path_in_env
lora_path_in_env = ""
# Prepare template variables (merge inference config from models.yaml)
template_vars = {
# Model configuration
"model_abbr": f"ft-{benchmark_name}",
"model_path": model_path_in_env,
"is_lora": model_is_lora,
"lora_path": lora_path_in_env,
# Dataset configuration
"dataset_imports": [dataset_imports],
"test_range": test_range,
"num_runs": num_runs,
"pass_k": pass_k,
"work_dir": adapter_path_in_env,
# Merge all inference parameters from models.yaml (default + model-specific)
**inference_config,
}
# Override use_cot_postprocessor based on force_think_token setting
# When force_think_token=false, we don't need the CoT postprocessor to extract answers
if not FT_RD_SETTING.force_think_token:
template_vars["use_cot_postprocessor"] = False
# Render Jinja2 template
config_content = T("rdagent.scenarios.finetune.benchmark.configs.opencompass_template:template").r(**template_vars)
# Note: env was already created above via get_benchmark_env()
(workspace_path / "config.py").write_text(config_content)
# Use result_subdir for validation/test separation
if result_subdir:
benchmark_work_dir = f"{ws_prefix}/benchmark_results/{result_subdir}"
else:
benchmark_work_dir = f"{ws_prefix}/benchmark_results"
# Logging
logger.info(f"Running benchmark '{benchmark_name}' on model: {model_path}")
logger.info(f"Base model: {model_name}, LoRA?: {model_is_lora}")
logger.info(f"Workspace: {workspace_path}")
logger.info(f"Benchmark work_dir: {benchmark_work_dir}")
if test_range:
logger.info(f"Dataset range: {test_range}")
# Environment variables
env_vars = {
"OC_JUDGE_MODEL": FT_RD_SETTING.judge_model or LLM_SETTINGS.chat_model,
"OC_JUDGE_API_KEY": FT_RD_SETTING.judge_api_key or LLM_SETTINGS.openai_api_key,
"OC_JUDGE_API_BASE": FT_RD_SETTING.judge_api_base or LLM_SETTINGS.openai_api_base,
"OC_JUDGE_RETRY": str(FT_RD_SETTING.judge_retry),
}
# Check if results already exist (skip re-running if cached)
results_base = workspace_path / "benchmark_results"
if result_subdir:
results_base = results_base / result_subdir
timestamped_dirs = sorted([d for d in results_base.glob("202*_*") if d.is_dir()], reverse=True)
if timestamped_dirs:
logger.info(f"Found existing results in {timestamped_dirs[0].name}, skipping benchmark execution")
else:
# Run OpenCompass
entry_cmd = f"opencompass {ws_prefix}/config.py --work-dir {benchmark_work_dir}"
result = env.run(
entry=entry_cmd,
local_path=str(workspace_path),
env=env_vars,
)
# Log execution immediately (for UI display)
tag_prefix = "docker_run" if is_docker else "conda_run"
logger.log_object(
{
"exit_code": result.exit_code,
"stdout": (result.stdout or ""),
"benchmark_name": benchmark_name,
"model_path": str(model_path),
"workspace_path": str(workspace_path),
},
tag=f"{tag_prefix}.Benchmark",
)
# Check execution status
if result.exit_code != 0:
error_msg = result.stdout[-2000:] if result.stdout else "No output"
raise RuntimeError(f"Benchmark execution failed (exit_code={result.exit_code})\n{error_msg}")
# Re-scan for timestamped directories after execution
timestamped_dirs = sorted([d for d in results_base.glob("202*_*") if d.is_dir()], reverse=True)
# OpenCompass stores results in results/<model_name>/<dataset>.json
results_subdir = timestamped_dirs[0] / "summary"
results_csv_path = sorted([f for f in results_subdir.rglob("*.csv")], reverse=True)[0]
logger.info(f"Detailed results CSV: {results_csv_path.relative_to(results_base)}")
# Read CSV content for accuracy summary (grouped by dataset)
df = pd.read_csv(results_csv_path)
# Get score column (the model name column, e.g., 'api-chemcotbench')
score_col = [c for c in df.columns if c not in ["dataset", "version", "metric", "mode"]][0]
# Pivot to group by dataset, with metrics as columns (use pivot_table to handle duplicates)
pivoted = df.pivot_table(index="dataset", columns="metric", values=score_col, aggfunc="first").to_dict("index")
# Filter out NaN values (different datasets have different metrics)
accuracy_summary = {ds: {k: v for k, v in metrics.items() if pd.notna(v)} for ds, metrics in pivoted.items()}
# Extract error samples for feedback
error_samples = extract_error_samples(
timestamped_dirs[0],
max_samples=max_error_samples,
)
# Log benchmark result for UI display
# Use result_subdir to distinguish validation vs test in tag
log_tag = f"benchmark_result.{result_subdir}" if result_subdir else "benchmark_result"
logger.log_object(
{
"accuracy_summary": accuracy_summary,
"error_samples": error_samples,
"benchmark_name": benchmark_name,
"split": result_subdir or "default", # validation, test, or default
},
tag=log_tag,
)
return {
"accuracy_summary": accuracy_summary,
"error_samples": error_samples,
}
def get_benchmark_ranges() -> tuple[str, str]:
"""Get validation and test range strings for benchmark evaluation.
Uses dynamic expressions that adapt to any dataset size:
- For small datasets (<200): splits 50/50 to avoid overlap
- For large datasets (>=200): takes 100 samples each
The expressions use OpenCompass's eval mechanism with index_list variable.
Returns:
Tuple of (validation_range, test_range) - guaranteed non-overlapping:
- validation: first min(100, 50%) samples
- test: last min(100, 50%) samples
"""
return "[:min(100, len(index_list)//2)]", "[-min(100, len(index_list)//2):]"
if __name__ == "__main__":
"""Test benchmark evaluation on Qwen3-1.7B with LoRA adapter."""
# Configuration - Fill in your LoRA adapter path and model name
LORA_ADAPTER_PATH = "/home/v-qizhengli/workspace/FT_workspace/gitignore_folder/B200/B200_FT_workspace/limo/train/b200_sweep_yamls/saves/qwen3-1.7b/lora_b200_lr1e-4_acc4/checkpoint-100"
MODEL_NAME = "Qwen/Qwen3-1.7B"
BENCHMARK = "aime25"
GPU_COUNT = 1
print("=" * 80)
print("Benchmark Evaluation Test")
print("=" * 80)
print(f"\nEnvironment: FT_JUDGE_API_KEY={'Set' if FT_RD_SETTING.judge_api_key else 'Not Set'}")
print(f"Judge API Base: {FT_RD_SETTING.judge_api_base or 'Not Set'}")
if not Path(LORA_ADAPTER_PATH).exists():
print(f"\nPlease set LORA_ADAPTER_PATH to a valid checkpoint directory")
print(f"Current path does not exist: {LORA_ADAPTER_PATH}")
exit(1)
print(f"\nModel: {MODEL_NAME}")
print(f"Adapter: {LORA_ADAPTER_PATH}")
print(f"Benchmark: {BENCHMARK}")
print("-" * 80)
try:
# Create FBWorkspace for test (auto-generates UUID workspace)
test_task = Task(name=f"benchmark_test_{BENCHMARK}")
test_workspace = FBWorkspace(target_task=test_task)
test_workspace.prepare()
print(f"\nWorkspace: {test_workspace.workspace_path}")
result = run_benchmark(
workspace_path=str(test_workspace.workspace_path),
model_path=LORA_ADAPTER_PATH,
model_name=MODEL_NAME,
benchmark_name=BENCHMARK,
gpu_count=GPU_COUNT,
)
print("\nEvaluation completed!")
print(f"Accuracy Summary: {result['accuracy_summary']}")
print(f"Error Samples: {len(result['error_samples'])} samples")
print(f"\nResults saved to: {test_workspace.workspace_path / 'benchmark_results'}")
except Exception as e:
print(f"\nEvaluation failed: {e}")
import traceback
traceback.print_exc()