Files
NexQuant/rdagent/core/proposal.py
T
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

470 lines
16 KiB
Python

# TODO: remove `self.scen` if traces will be passed into the instance.
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Generic, TypeVar
from rdagent.core.conf import RD_AGENT_SETTINGS
from rdagent.core.evaluation import Feedback
from rdagent.core.experiment import (
ASpecificExp,
ASpecificPlan,
Experiment,
ExperimentPlan,
)
from rdagent.core.knowledge_base import KnowledgeBase
from rdagent.core.scenario import Scenario
if TYPE_CHECKING:
from rdagent.utils.workflow.loop import LoopBase
class Hypothesis:
"""
TODO: We may have better name for it.
Name Candidates:
- Belief
"""
def __init__(
self,
hypothesis: str,
reason: str,
concise_reason: str,
concise_observation: str,
concise_justification: str,
concise_knowledge: str,
) -> None:
self.hypothesis: str = hypothesis
self.reason: str = reason
self.concise_reason: str = concise_reason
self.concise_observation: str = concise_observation
self.concise_justification: str = concise_justification
self.concise_knowledge: str = concise_knowledge
def __str__(self) -> str:
return f"""Hypothesis: {self.hypothesis}
Reason: {self.reason}"""
# source: data_ana | model_nan = None
# Origin(path of repo/data/feedback) => view/summarization => generated Hypothesis
class ExperimentFeedback(Feedback):
def __init__(
self,
reason: str,
*,
code_change_summary: str | None = None,
decision: bool,
eda_improvement: str | None = None,
exception: Exception | None = None,
) -> None:
self.decision = decision
self.eda_improvement = eda_improvement
self.reason = reason
# Exception is not None means failing to generate runnable experiments due to exception.
# Runable reuslts are not always good.
self.exception: Exception | None = (
exception # if the experiment raises exception, it will be integrated into part of the feedback.
)
self.code_change_summary = code_change_summary
def __bool__(self) -> bool:
return self.decision
def __str__(self) -> str:
res = f"Decision: {self.decision}\nReason: {self.reason}"
code_change_summary = getattr(self, "code_change_summary", None)
if code_change_summary is not None:
res += "\nCode Change Summary: " + code_change_summary
return res
@classmethod
def from_exception(cls, e: Exception) -> ExperimentFeedback:
"""
A convenient method to create Feedback from an exception.
"""
return cls(decision=False, reason=f"The experiment fails due to {e!s}", exception=e)
class HypothesisFeedback(ExperimentFeedback):
def __init__(
self,
reason: str,
decision: bool,
code_change_summary: str = "",
*,
observations: str | None = None,
hypothesis_evaluation: str | None = None,
new_hypothesis: str | None = None,
eda_improvement: str | None = None,
acceptable: bool | None = None,
) -> None:
super().__init__(
reason,
decision=decision,
code_change_summary=code_change_summary,
eda_improvement=eda_improvement,
)
self.observations = observations
self.hypothesis_evaluation = hypothesis_evaluation
self.new_hypothesis = new_hypothesis
self.acceptable = acceptable
def __str__(self) -> str:
upper_str = f"""{super().__str__()}"""
if self.observations is not None:
upper_str += f"\nObservations: {self.observations}"
if self.hypothesis_evaluation is not None:
upper_str += f"\nHypothesis Evaluation: {self.hypothesis_evaluation}"
if self.new_hypothesis is not None:
upper_str += f"\nNew Hypothesis: {self.new_hypothesis}"
if self.eda_improvement is not None:
upper_str += f"\nEDA Improvement: {self.eda_improvement}"
if self.acceptable is not None:
upper_str += f"\nOverall Acceptable: {self.acceptable}"
return upper_str
ASpecificScen = TypeVar("ASpecificScen", bound=Scenario)
ASpecificKB = TypeVar("ASpecificKB", bound=KnowledgeBase)
class Trace(Generic[ASpecificScen, ASpecificKB]):
NodeType = tuple[Experiment, ExperimentFeedback] # Define NodeType as a new type representing the tuple
NEW_ROOT: tuple = ()
SEL_LATEST_SOTA: tuple = (-1,) # select the SOTA experiment in latest node
def __init__(self, scen: ASpecificScen, knowledge_base: ASpecificKB | None = None) -> None:
self.scen: ASpecificScen = scen
# BEGIN: graph structure -------------------------
self.hist: list[Trace.NodeType] = (
[]
) # List of tuples containing experiments and their feedback, organized over time.
self.dag_parent: list[tuple[int, ...]] = [] # List of tuples representing parent indices in the DAG structure.
# Definition:
# - (,) represents no parent (root node in one tree);
# - (1,) presents one parent;
# - (1, 2) represents two parents (Multiple parent is not implemented yet).
# Syntax sugar for the parent relationship:
# - Only for selection:
# - (-1,) indicates that select the last record node as parent.
# NOTE: the sequence of hist and dag_parent is organized by the order to record the experiment.
# So it may be different from the order of the loop_id.
# So we need an extra mapping to map the enqueue id back to the loop id.
self.idx2loop_id: dict[int, int] = {}
# Design discussion:
# - If we unifiy the loop_id and the enqueue id, we will have less recognition burden.
# - If we use different id for loop and enqueue, we don't have to handle the placeholder logic.
# END: graph structure -------------------------
# TODO: self.hist is 2-tuple now, remove hypothesis from it, change old code for this later.
self.knowledge_base: ASpecificKB | None = knowledge_base
# The next expending point of the selection. Set it as a state of the trace will make
self.current_selection: tuple[int, ...] = self.SEL_LATEST_SOTA
def get_sota_hypothesis_and_experiment(self) -> tuple[Hypothesis | None, Experiment | None]:
"""Access the last experiment result, sub-task, and the corresponding hypothesis."""
# TODO: The return value does not align with the signature.
for experiment, feedback in self.hist[::-1]:
if feedback.decision:
return experiment.hypothesis, experiment
return None, None
def is_selection_new_tree(self, selection: tuple[int, ...] | None = None) -> bool:
"""
Check if the current trace is a new tree.
- selection maybe (-1,) when the dag_parent is empty.
"""
if selection is None:
selection = self.get_current_selection()
return selection == self.NEW_ROOT or len(self.dag_parent) == 0
def get_current_selection(self) -> tuple[int, ...]:
return self.current_selection
def set_current_selection(self, selection: tuple[int, ...]) -> None:
self.current_selection = selection
def get_parent_exps(
self,
selection: tuple[int, ...] | None = None,
) -> list[Trace.NodeType]:
"""
Collect all ancestors of the given selection.
The return list follows the order of [root->...->parent->current_node].
"""
if selection is None:
selection = self.get_current_selection()
if self.is_selection_new_tree(selection):
return []
return [self.hist[i] for i in self.get_parents(selection[0])]
def exp2idx(self, exp: Experiment | list[Experiment]) -> int | list[int] | None:
if isinstance(exp, list):
exps: list[Experiment] = exp
# keep the order
exp_to_index: dict[Experiment, int] = {_exp: i for i, (_exp, _) in enumerate(self.hist)}
return [exp_to_index[_exp] for _exp in exps]
for i, (_exp, _) in enumerate(self.hist):
if _exp == exp:
return i
return None
def idx2exp(self, idx: int | list[int]) -> Experiment | list[Experiment]:
if isinstance(idx, list):
idxs: list[int] = idx
return [self.hist[_idx][0] for _idx in idxs]
return self.hist[idx][0]
def is_parent(self, parent_idx: int, child_idx: int) -> bool:
ancestors = self.get_parents(child_idx)
return parent_idx in ancestors
def get_parents(self, child_idx: int) -> list[int]:
if self.is_selection_new_tree((child_idx,)):
return []
ancestors: list[int] = []
curr = child_idx
while True:
ancestors.insert(0, curr)
parent_tuple = self.dag_parent[curr]
if not parent_tuple or parent_tuple[0] == curr:
break
curr = parent_tuple[0]
return ancestors
def sync_dag_parent_and_hist(
self,
exp_and_fb: NodeType,
cur_loop_id: int,
) -> None:
"""
Adding corresponding parent index to the dag_parent when the hist is going to be changed.
Should be called when the hist is changed.
"""
# Prioritize local_selection from the experiment if available
exp = exp_and_fb[0]
selection = getattr(exp, "local_selection", None)
if selection is None:
selection = self.get_current_selection()
if len(self.hist) == 0 or len(selection) == 0:
# the node we are going to add is the first node of hist / root node of a new sub-trace
self.dag_parent.append(self.NEW_ROOT)
else:
current_node_idx = selection[0]
if current_node_idx == -1:
# the current selection is the latest one
current_node_idx = len(self.hist) - 1
self.dag_parent.append((current_node_idx,))
self.hist.append(exp_and_fb)
self.idx2loop_id[len(self.hist) - 1] = cur_loop_id
def get_children(self, parent_idx: int | None = None) -> list[NodeType]:
"""
Get all children nodes for a given parent index.
If parent_idx is None, returns the root nodes (experiments starting from scratch).
"""
target_parents = (parent_idx,) if parent_idx is not None else self.NEW_ROOT
children = []
for i, parents in enumerate(self.dag_parent):
if parents == target_parents and i < len(self.hist):
children.append(self.hist[i])
return children
def get_sota_experiment(self, node_id: int | None = None) -> Experiment | None:
"""
Get the SOTA experiment from the trace by traversing ancestors backwards from node_id.
"""
# NOTE: it is first used in the finetune scenario.
if node_id is None:
selection = self.get_current_selection()
if self.is_selection_new_tree(selection):
return None
node_id = selection[0]
if node_id == -1:
if not self.hist:
return None
node_id = len(self.hist) - 1
ancestors = self.get_parents(node_id)
for i in reversed(ancestors):
if self.hist[i][1].decision:
return self.hist[i][0]
return None
class CheckpointSelector:
"""
In the trace, we may start from any check point (we'll represent it as a variable `from_checkpoint_idx`)
"""
@abstractmethod
def get_selection(self, trace: Trace) -> tuple[int, ...] | None:
"""
checkpoint_idx represents the place where we want to create a new node.
the return value should be the idx of target node (the parent of the new generating node).
- `(-1, )` represents starting from the latest trial in the trace - default value
- NOTE: we don't encourage to use this option; It is confusing when we have multiple traces.
- `(idx, )` represents starting from the `idx`-th trial in the trace.
- `None` represents starting from scratch (start a new trace)
- More advanced selection strategies in `select.py`
"""
class SOTAexpSelector:
"""
Select the SOTA experiment from the trace to submit
"""
@abstractmethod
def get_sota_exp_to_submit(self, trace: Trace) -> Experiment | None:
"""
Select the SOTA experiment from the trace to submit
"""
class ExpPlanner(ABC, Generic[ASpecificPlan]):
"""
An abstract class for planning the experiment.
The planner should generate a plan for the experiment based on the trace.
"""
def __init__(self, scen: Scenario) -> None:
self.scen = scen
@abstractmethod
def plan(self, trace: Trace) -> ASpecificPlan:
"""
Generate a plan for the experiment based on the trace.
The plan should be a dictionary that contains the plan to each stage.
"""
class ExpGen(ABC):
def __init__(self, scen: Scenario) -> None:
self.scen = scen
@abstractmethod
def gen(self, trace: Trace) -> Experiment:
"""
Generate the experiment based on the trace.
Planning is part of gen, but since we may support multi-stage planning,
we need to pass plan as optional argument.
`ExpGen().gen()` play a role like
.. code-block:: python
# ExpGen().gen() ==
Hypothesis2Experiment().convert(
HypothesisGen().gen(trace)
)
"""
async def async_gen(self, trace: Trace, loop: LoopBase) -> Experiment:
"""
generate the experiment and decide whether to stop yield generation and give up control to other routines.
"""
# we give a default implementation here.
# The proposal is set to try best to generate the experiment in max-parallel level.
while True:
if loop.get_unfinished_loop_cnt(loop.loop_idx) < RD_AGENT_SETTINGS.get_max_parallel():
return self.gen(trace)
await asyncio.sleep(1)
def reset(self) -> None:
"""
Reset the proposal to the initial state.
Sometimes the main loop may want to reset the whole process to the initial state.
Default implementation does nothing; override in subclasses if needed.
"""
return
class HypothesisGen(ABC):
def __init__(self, scen: Scenario) -> None:
self.scen = scen
@abstractmethod
def gen(
self,
trace: Trace,
plan: ExperimentPlan | None = None,
) -> Hypothesis:
# def gen(self, scenario_desc: str, ) -> Hypothesis:
"""
Motivation of the variable `scenario_desc`:
- Mocking a data-scientist is observing the scenario.
scenario_desc may include:
- data observation:
- Original or derivative
- Task information:
"""
class Hypothesis2Experiment(ABC, Generic[ASpecificExp]):
"""
[Abstract description => concrete description] => Code implementation Card
"""
@abstractmethod
def convert(self, hypothesis: Hypothesis, trace: Trace) -> ASpecificExp:
"""Connect the idea proposal to implementation"""
...
# Boolean, Reason, Confidence, etc.
class Experiment2Feedback(ABC):
""" "Generated feedbacks on the hypothesis from **Executed** Implementations of different tasks
& their comparisons with previous performances"""
def __init__(self, scen: Scenario) -> None:
self.scen = scen
@abstractmethod
def generate_feedback(
self,
exp: Experiment,
trace: Trace,
exception: Exception | None = None,
) -> ExperimentFeedback:
"""
The `exp` should be executed and the results should be included, as well as the comparison
between previous results (done by LLM).
For example: `mlflow` of Qlib will be included.
"""
error_message = "generate_feedback method is not implemented."
raise NotImplementedError(error_message)