Files
NexQuant/rdagent/scenarios/kaggle/proposal/proposal.py
T
you-n-g 7f4c2d18c6 feat: refactor for general data science (#498)
* refine ds modal for more cases: eval and es

* update model template

* prompts for model and ensemble

* fix a bug

* fix a bug

* init: ds workflow evovingstrategy

* Adding ensemble (#505)

* Initial Draft

* Updating logic for init

* Revising

* Successful Testing

* Updating to use the latest & right class

* bug: bug-fixing for testing

* data science loop changes

* data science loop base

* ds loop feedback

* fix

* remove measure_time because it's duplicated (in LoopBase)

* add the knowledge query for data_loader & feature

* edit ds workflow evaluator

* data_loader bug fix

* stop evolving when all tasks completed

* llm app change

* fix break all complete strategy

* Adding queried knowledge (#508)

Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>

* fix loop bug

* ds workflow evaluator; test; refine prompts

* workflow spec

* fix ci

* feature task changes

* ds loop change

* fix a bug in feat

* add query knowledge for model and workflow

* llm_debug info(for show) using pickle instead of json

* remove NextLoopException

* loop change

* coder raise CoderError when all sub_tasks failed

* rename code_dict to file_dict in FBWorkspace

* add CoSTEER unittest

* now show self.version in Task.get_task_information(), simplify CoSTEER sub tasks definition

* remove some properties in ModelTask, add model_type in it.

* fix llm app bug

* llm web app bug fix

* ds loop bug fix

* fix: give component code to feature&ens eval

* loop catch error bug

* rename load_from_raw_data to load_data

* feat: Add debug data creation functionality for data science scenarios

* support local folder (#511)

* support local folder

* remove unnecessary random

* KaggleScen Subclass

* small fix

* use template for style description

* update default scen to kaggle

* update sample data script

* make sure frac < 1

* fix a bug

* feature spec changes

* fix

* changeimport order

* clear unnecessary std outputs

* fix a typo

* create sample folder after unzip kaggle data

* feature/model test script update

* Align the data types across modules.

* fix a bug in model eval

* show line number

* move sample entry point to app

* spec & model prompt changes

* Refine the competition specification to address the data type problem and the coherence issue.

* fix some bugs

* add file filter in FBworkspace.code property

* support non-binary prediction

* avoid too much warnings

* fix a bug in ensemble module

* filtered the knowledge query in all modules

* delete RAG in idea proposal

* refine the code in ensemble

* show exp workspace in llm_st

* exp_gen bug fix

* feedback bug fix

* use `feature` instead of `feat01`

* Trace & method of judging if exp is completed change

* fix a bug in package calling and execute ci

* fix code

* bug fix

* bug fix

* fix a bug

* fix some bugs

* fix a bug

* refactor: Enhance error handling and feedback in data science loop

* support different use_azure on chat and embedding models

* multi-model proposal logic

* fix a small syntax error

* loopBase and some changes

* ensemble scores change

* fbworkspace.code -> .all_codes

* use all model codes in workflow coder

* check scores.csv's keys(model_names)

* model name changes

* add a todo in  ensemble test

* sota_exp changes

* give model info in exp gen

* add runner time limit

* config using debug data or not in evals

* exp to feedback base

* add feature code when writing model task

* small problem

* copying during sampling

* update

* refactor: Simplify code handling and improve workspace management

* model part output fix

* print model's execution time

* bug fix

* ensemble test fix

* ens small change

* ens_test bug fix

* Refine partial expansion logic to display only a few subfolders when their structure is uniform, improving readability in nested directories.

* several update on prompts

* sample subfolders

* Filter the stdout after code execution to remove irrelevant information e.g. progress bars, whitespace characters, excessive line breaks.

* Add some more prompts and comments

* several update on the first init rounds

* model timeout as error

* fix pattern of getting model codes in workspace

* small bux fix on model prompts

* remove get_code_with_key since we have regex pattern

* fix: Correct tqdm progress bar update logic in LoopBase class

* feat: Add diff generation and enhance feedback mechanism in data science loop

* update some fix to model and workflow prompts

* refine the logic of progress bar filter

* add last_successful_exp in exp_gen

* fix a one line bug

* add a hint in prompt

* fix data sample for bms

* fix data sample for bms

* hypothesis small fix

* crawler readme update

* fix component gen

* fix bug

* annotation change

* load description.md if it exists

* refactor: Simplify SOTA description handling in feedback and prompts

* refactor: Use shared templates for feedback and experiment descriptions

* change webapp for model codes changes

* update proposal

* add timeout message for docker run output

* fix

* refine the code in docker time processing

* use .shape instead of len() when do shape eval

* won't change size during iteration

* support bson sample

* sample support jsonl and bson

* add former_code to coder prompts

* a little speed us in debug data creating

* filter progress bar when eval ens and main

* avoid costeer makes no change to former code

* fix several log error

* add timeout judge threshold

* fix some bugs in the evaluation of component output shapes

* File structure for supporting litellm (#517)

Co-authored-by: Young <afe.young@gmail.com>

* ignore submission and show processing

* ignore submission and show processing

* add efficiency notice

* refactor: Enhance error message with detailed feedback summary

* refactor: Simplify component handling in DSExpGen class

* refactor: Update code structure and add docstring for clarity

* reserve one sample to each label in data sampling

* add Evaluation info

* refine costeer code to avoid giving same code twice

* use raw_description as plain text

* add a prompt hint to avoid same dict key

* model task name bug in first model exp gen

* fix a typo

* add some debug info in costeer tests

* task init change

* enhance data sampling

* refine the code in data_loader

* more reasonable loop

* fix a bug in data folder description

* add error msg & traceback to execution feedback

* fix llm error msg detection

* add task information to costeer eval & add cache to docker run(use zipfile to store the whole workspace)

* fix CI first round

* fix CI second round

* use txt to store test script to avoid pytest

* remove zipfile in requirements

* add azure.identity to requirements

* ignore debug web page

* component test changes

* remove redundent task_desc in model coder

* feat: Add APE module and prompts for automated prompt engineering

* fix: Update .gitignore and improve text formatting in eval.py

* refactor: Update print output and improve code comments and imports

* style: Fix string formatting and import order in ape.py and fmt.py

* exclude ape

* add a data folder notice

* reduce unnecessary output to stdout

* refine the code of describe_data_folder

* fix ci

* style: streamlit style update (#522)

* streamlit style update

* fix import

* fix format

* fix llm_st loop progress bar

* debugapp small change

* fix model str

* refine some prompts

* fix model str

* fix CI

* refine the logic associated with the data_folder

* fix ci

* small change

* set filter_progress_bar as default in execute

* model proposal with workflow

* add submission check in workflow eval

* fix bug

* small change

* fix CI

* fix CI

* refactor: Move generate_diff to utils and update DSExpGen logic

* more reasonable prompt describing metric direction

* fix a minor jinja2 bug

* quick fix exp_gen bugs

* fix the following bug

* fix

* fix some bugs

* remove workflow from model

* add pending_tasks_list in data science to enable coding model and workflow

* refine the code for handling JSON-formatted data descriptions

* assert with information

* ensure correct csv file name

* add logging to help record the output

* log competition

* add log tag for debug llm app

* test: Test ds refactor ll (#523)

* fix bugs to former scenario

* fix a bug because coding in rdloop changed

* fix the bug when feedback gets no hypothesis

* fix trace structure

* change all trace hist when merging hypothesis to experiments

* ignore some error in ruff

* fix kaggle scenario bugs

* refine one line

* another bug

* another small bug

* fix ui bugs

* chage kaggle  train.py path

---------

Co-authored-by: Xu Yang <peteryang@vip.qq.com>

* fix CI

* Update rdagent/app/data_science/loop.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* add samplecsv into spec prompts

* fix CI

---------

Co-authored-by: TPLin22 <tplin2@163.com>
Co-authored-by: yuanteli <1957922024@qq.com>
Co-authored-by: Xisen Wang <118058822+xisen-w@users.noreply.github.com>
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
Co-authored-by: Tim <illking@foxmail.com>
Co-authored-by: 炼金术师华华 <37462254+YeewahChan@users.noreply.github.com>
Co-authored-by: Linlang <30293408+SunsetWolf@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-01-17 22:53:05 +08:00

438 lines
18 KiB
Python

import json
import math
from pathlib import Path
from typing import List, Tuple
from jinja2 import Environment, StrictUndefined
from rdagent.app.kaggle.conf import KAGGLE_IMPLEMENT_SETTING
from rdagent.components.coder.factor_coder.factor import FactorTask
from rdagent.components.coder.model_coder.model import ModelExperiment, ModelTask
from rdagent.components.knowledge_management.vector_base import VectorBase
from rdagent.components.proposal import (
FactorAndModelHypothesis2Experiment,
FactorAndModelHypothesisGen,
)
from rdagent.core.exception import ModelEmptyError
from rdagent.core.prompts import Prompts
from rdagent.core.proposal import Hypothesis, Scenario, Trace
from rdagent.scenarios.kaggle.experiment.kaggle_experiment import (
KG_MODEL_MAPPING,
KG_SELECT_MAPPING,
KGFactorExperiment,
KGModelExperiment,
)
from rdagent.scenarios.kaggle.experiment.scenario import KGScenario
from rdagent.scenarios.kaggle.knowledge_management.graph import KGKnowledgeGraph
from rdagent.scenarios.kaggle.knowledge_management.vector_base import (
KaggleExperienceBase,
)
prompt_dict = Prompts(file_path=Path(__file__).parent.parent / "prompts.yaml")
from rdagent.scenarios.kaggle.experiment.scenario import (
KG_ACTION_FEATURE_ENGINEERING,
KG_ACTION_FEATURE_PROCESSING,
KG_ACTION_LIST,
KG_ACTION_MODEL_FEATURE_SELECTION,
KG_ACTION_MODEL_TUNING,
)
class KGHypothesis(Hypothesis):
def __init__(
self,
hypothesis: str,
reason: str,
concise_reason: str,
concise_observation: str,
concise_justification: str,
concise_knowledge: str,
action: str,
) -> None:
super().__init__(
hypothesis, reason, concise_reason, concise_observation, concise_justification, concise_knowledge
)
self.action = action
def __str__(self) -> str:
return f"""Chosen Action: {self.action}
Hypothesis: {self.hypothesis}
Reason: {self.reason}
Concise Reason & Knowledge: {self.concise_reason}
Concise Observation: {self.concise_observation}
Concise Justification: {self.concise_justification}
Concise Knowledge: {self.concise_knowledge}
"""
def generate_RAG_content(
scen: KGScenario,
trace: Trace,
hypothesis_and_feedback: str,
target: str = None,
chosen_hypothesis: str = None,
chosen_hypothesis_type: str = None,
) -> str:
if scen.if_using_vector_rag:
if scen.mini_case:
rag_results, _ = scen.vector_base.search_experience(target, hypothesis_and_feedback, topk_k=1)
else:
rag_results, _ = scen.vector_base.search_experience(target, hypothesis_and_feedback, topk_k=5)
return "\n".join([doc.content for doc in rag_results])
if scen.if_using_graph_rag is False or trace.knowledge_base is None:
return None
same_competition_node = trace.knowledge_base.get_node_by_content(trace.scen.get_competition_full_desc())
if same_competition_node is not None:
related_hypothesis_nodes = []
for action in KG_ACTION_LIST:
related_hypothesis_nodes.extend(
trace.knowledge_base.get_nodes_within_steps(
start_node=same_competition_node,
steps=1,
constraint_labels=[action],
)[:1]
)
else:
related_hypothesis_nodes = []
experiences = []
for hypothesis_node in related_hypothesis_nodes:
experience = {"hypothesis": hypothesis_node.content}
experiment_node_list = trace.knowledge_base.get_nodes_within_steps(
start_node=hypothesis_node, steps=1, constraint_labels=["experiments"]
)
if len(experiment_node_list) > 0:
experience["experiments"] = experiment_node_list[0].content
else:
experience["experiments"] = "No experiment information available."
conclusion_node_list = trace.knowledge_base.get_nodes_within_steps(
start_node=hypothesis_node, steps=1, constraint_labels=["conclusion"]
)
if len(conclusion_node_list) > 0:
experience["conclusion"] = conclusion_node_list[0].content
else:
experience["conclusion"] = "No conclusion information available."
experiences.append(experience)
found_nodes = []
insights = []
if chosen_hypothesis is not None:
similar_nodes = trace.knowledge_base.semantic_search(
node=chosen_hypothesis,
topk_k=2,
)
for similar_node in similar_nodes:
hypothesis_nodes = trace.knowledge_base.get_nodes_within_steps(
start_node=similar_node,
steps=3,
constraint_labels=[chosen_hypothesis_type],
)
found_nodes.extend(hypothesis_nodes[:5])
found_nodes = sorted(list(set(found_nodes)), key=lambda x: len(x.content))
for exp_node in found_nodes[:5]:
insight = {"experiments": exp_node.content}
hypothesis_node_list = trace.knowledge_base.get_nodes_within_steps(
start_node=exp_node, steps=2, constraint_labels=KG_ACTION_LIST
)
if len(hypothesis_node_list) > 0:
insight["hypothesis"] = hypothesis_node_list[0].content
else:
insight["hypothesis"] = "No hypothesis information available."
conclusion_node_list = trace.knowledge_base.get_nodes_within_steps(
start_node=exp_node, steps=2, constraint_labels=["conclusion"]
)
if len(conclusion_node_list) > 0:
insight["conclusion"] = conclusion_node_list[0].content
else:
insight["conclusion"] = "No conclusion information available."
insights.append(insight)
else:
similar_nodes = trace.knowledge_base.semantic_search(
node=trace.scen.get_competition_full_desc(),
topk_k=2,
)
for similar_node in similar_nodes:
for hypothesis_type in KG_ACTION_LIST:
hypothesis_nodes = trace.knowledge_base.get_nodes_within_steps(
start_node=similar_node,
steps=3,
constraint_labels=[hypothesis_type],
)
found_nodes.extend(hypothesis_nodes[:2])
found_nodes = sorted(list(set(found_nodes)), key=lambda x: len(x.content))
for hypothesis_node in found_nodes[:5]:
if hypothesis_node in related_hypothesis_nodes:
continue
insight = {"hypothesis": hypothesis_node.content}
experiment_node_list = trace.knowledge_base.get_nodes_within_steps(
start_node=hypothesis_node, steps=2, constraint_labels=["experiments"]
)
if len(experiment_node_list) > 0:
insight["experiments"] = experiment_node_list[0].content
else:
insight["experiments"] = "No experiment information available."
conclusion_node_list = trace.knowledge_base.get_nodes_within_steps(
start_node=hypothesis_node, steps=2, constraint_labels=["conclusion"]
)
if len(conclusion_node_list) > 0:
insight["conclusion"] = conclusion_node_list[0].content
else:
insight["conclusion"] = "No conclusion information available."
insights.append(insight)
RAG_content = (
Environment(undefined=StrictUndefined)
.from_string(prompt_dict["KG_hypothesis_gen_RAG"])
.render(insights=insights, experiences=experiences)
)
return RAG_content
class KGHypothesisGen(FactorAndModelHypothesisGen):
"""
# NOTE: we can share this class across different data mining scenarios
# It may better to move the class into components folder like `rdagent/components/proposal/model_proposal.py`
# Here is the use case:
.. code-block:: python
class KGHypothesisGen(ModelHypothesisGen):
prompts: Prompts = a_specific_prompt_dict
"""
def __init__(self, scen: Scenario) -> Tuple[dict, bool]:
super().__init__(scen)
def update_reward_estimates(self, trace: Trace) -> None:
if len(trace.hist) > 0:
last_entry = trace.hist[-1]
last_action = last_entry[0].action
last_result = last_entry[1].result
# Extract performance_t
performance_t = last_result.get("performance", 0.0)
# Get performance_{t-1}
if len(trace.hist) > 1:
prev_entry = trace.hist[-2]
prev_result = prev_entry[1].result
performance_t_minus_1 = prev_result.get("performance", 0.0)
else:
performance_t_minus_1 = self.scen.initial_performance
if self.scen.evaluation_metric_direction:
reward = (performance_t - performance_t_minus_1) / max(performance_t_minus_1, 1e-8)
else:
reward = (performance_t_minus_1 - performance_t) / max(performance_t_minus_1, 1e-8)
reward = (performance_t - performance_t_minus_1) / performance_t_minus_1
n_o = self.scen.action_counts[last_action]
mu_o = self.scen.reward_estimates[last_action]
self.scen.reward_estimates[last_action] += (reward - mu_o) / n_o
else:
# First iteration, nothing to update
pass
def execute_next_action(self, trace: Trace) -> str:
actions = list(self.scen.action_counts.keys())
t = sum(self.scen.action_counts.values()) + 1
# If any action has not been tried yet, select it
for action in actions:
if self.scen.action_counts[action] == 0:
selected_action = action
return selected_action
c = self.scen.confidence_parameter
ucb_values = {}
for action in actions:
mu_o = self.scen.reward_estimates[action]
n_o = self.scen.action_counts[action]
ucb = mu_o + c * math.sqrt(math.log(t) / n_o)
ucb_values[action] = ucb
# Select action with highest UCB
selected_action = max(ucb_values, key=ucb_values.get)
return selected_action
def prepare_context(self, trace: Trace) -> Tuple[dict, bool]:
hypothesis_and_feedback = (
(
Environment(undefined=StrictUndefined)
.from_string(prompt_dict["hypothesis_and_feedback"])
.render(trace=trace)
)
if len(trace.hist) > 0
else "No previous hypothesis and feedback available since it's the first round."
)
if self.scen.if_action_choosing_based_on_UCB:
action = self.execute_next_action(trace)
hypothesis_specification = f"Hypothesis should avoid being too general and vague, and should be specific and actionable. For example, hypothesis like 'tune a model' is too general, while hypothesis like 'increase the learning rate to 0.1 of the lightgbm model will improve the performance' is specific and actionable."
if len(trace.hist) > 0:
sota_features = str(trace.hist[-1][0].based_experiments[-1].experiment_workspace.data_description)
sota_models = json.dumps(
trace.hist[-1][0].based_experiments[-1].experiment_workspace.model_description, indent=2
)
sota_result = trace.hist[-1][0].based_experiments[-1].result
hypothesis_specification += f"\nYour hypothesis should based on current SOTA solution. The user will conduct experiments based on the SOTA solution to test whether your hypothesis is right on this specific ecompetition. \n\nSOTA Features: {sota_features}\n\nSOTA Models: {sota_models}\n\nSOTA Result: {sota_result}"
if self.scen.if_action_choosing_based_on_UCB:
hypothesis_specification += (
"\n\nNext experiment action is "
+ action
+ "\nspecification: "
+ prompt_dict["hypothesis_specification"][action]
)
context_dict = {
"hypothesis_and_feedback": hypothesis_and_feedback,
"RAG": generate_RAG_content(
scen=self.scen,
trace=trace,
hypothesis_and_feedback=hypothesis_and_feedback,
target=action if self.scen.if_action_choosing_based_on_UCB else None,
),
"hypothesis_output_format": prompt_dict["hypothesis_output_format"],
"hypothesis_specification": hypothesis_specification,
}
return context_dict, True
def convert_response(self, response: str) -> Hypothesis:
response_dict = json.loads(response)
hypothesis = KGHypothesis(
hypothesis=response_dict.get("hypothesis", "Hypothesis not provided"),
reason=response_dict.get("reason", "Reason not provided"),
concise_reason=response_dict.get("concise_reason", "Concise reason not provided"),
concise_observation=response_dict.get("concise_observation", "Concise observation not provided"),
concise_justification=response_dict.get("concise_justification", "Concise justification not provided"),
concise_knowledge=response_dict.get("concise_knowledge", "Concise knowledge not provided"),
action=response_dict.get("action", "Action not provided"),
)
return hypothesis
class KGHypothesis2Experiment(FactorAndModelHypothesis2Experiment):
def prepare_context(self, hypothesis: Hypothesis, trace: Trace) -> Tuple[dict, bool]:
scenario = trace.scen.get_scenario_all_desc(filtered_tag="hypothesis_and_experiment")
assert isinstance(hypothesis, KGHypothesis)
experiment_output_format = (
prompt_dict["feature_experiment_output_format"]
if hypothesis.action in [KG_ACTION_FEATURE_ENGINEERING, KG_ACTION_FEATURE_PROCESSING]
else prompt_dict["model_experiment_output_format"]
)
self.current_action = hypothesis.action
hypothesis_and_feedback = (
(
Environment(undefined=StrictUndefined)
.from_string(prompt_dict["hypothesis_and_feedback"])
.render(trace=trace)
)
if len(trace.hist) > 0
else "No previous hypothesis and feedback available since it's the first round."
)
experiment_list: List[ModelExperiment] = [t[0] for t in trace.hist]
model_list = []
for experiment in experiment_list:
for sub_task in experiment.sub_tasks:
model_list.extend(sub_task.get_task_information())
return {
"target_hypothesis": str(hypothesis),
"scenario": scenario,
"hypothesis_and_feedback": hypothesis_and_feedback,
"experiment_output_format": experiment_output_format,
"target_list": model_list,
"RAG": generate_RAG_content(
trace.scen,
trace,
hypothesis_and_feedback,
chosen_hypothesis=hypothesis.hypothesis,
chosen_hypothesis_type=hypothesis.action,
),
}, True
def convert_feature_experiment(self, response: str, hypothesis: Hypothesis, trace: Trace) -> KGFactorExperiment:
response_dict = json.loads(response)
tasks = []
for factor_name in response_dict:
description = (response_dict[factor_name].get("description", "Factor description not provided"),)
formulation = (response_dict[factor_name].get("formulation", "Factor formulation not provided"),)
variables = (response_dict[factor_name].get("variables", "Variables not provided"),)
tasks.append(
FactorTask(
factor_name=factor_name,
factor_description=description,
factor_formulation=formulation,
variables=variables,
version=2,
)
)
exp = KGFactorExperiment(
sub_tasks=tasks,
based_experiments=(
[KGFactorExperiment(sub_tasks=[], source_feature_size=trace.scen.input_shape[-1])]
+ [t[0] for t in trace.hist if t[1]]
),
hypothesis=hypothesis,
)
return exp
def convert_model_experiment(self, response: str, hypothesis: Hypothesis, trace: Trace) -> KGModelExperiment:
response_dict = json.loads(response)
tasks = []
model_type = response_dict.get("model_type", "Model type not provided")
if not isinstance(model_type, str) or model_type not in KG_SELECT_MAPPING:
raise ModelEmptyError(
f"Invalid model type '{model_type}'. Allowed model types are: {', '.join(KG_SELECT_MAPPING)}."
)
based_experiments = [KGModelExperiment(sub_tasks=[], source_feature_size=trace.scen.input_shape[-1])] + [
t[0] for t in trace.hist if t[1]
]
model_type = response_dict.get("model_type", "Model type not provided")
if model_type in KG_MODEL_MAPPING:
base_code = based_experiments[-1].experiment_workspace.file_dict.get(KG_MODEL_MAPPING[model_type], None)
else:
base_code = None
tasks.append(
ModelTask(
name=response_dict.get("model_name", "Model name not provided"),
description=response_dict.get("description", "Description not provided"),
architecture=response_dict.get("architecture", "Architecture not provided"),
hyperparameters=response_dict.get("hyperparameters", "Hyperparameters not provided"),
model_type=model_type,
version=2,
base_code=base_code,
)
)
exp = KGModelExperiment(
sub_tasks=tasks,
based_experiments=based_experiments,
hypothesis=hypothesis,
)
return exp
def convert_response(self, response: str, hypothesis: Hypothesis, trace: Trace) -> ModelExperiment:
if self.current_action in [KG_ACTION_FEATURE_ENGINEERING, KG_ACTION_FEATURE_PROCESSING]:
return self.convert_feature_experiment(response, hypothesis, trace)
elif self.current_action in [KG_ACTION_MODEL_FEATURE_SELECTION, KG_ACTION_MODEL_TUNING]:
return self.convert_model_experiment(response, hypothesis, trace)
class KGTrace(Trace[KGScenario, KGKnowledgeGraph]):
pass