Files
NexQuant/rdagent/core/experiment.py
T

185 lines
5.7 KiB
Python
Raw Normal View History

2024-07-17 15:00:13 +08:00
from __future__ import annotations
import shutil
import uuid
2024-06-14 12:59:44 +08:00
from abc import ABC, abstractmethod
2024-07-17 15:00:13 +08:00
from copy import deepcopy
from pathlib import Path
2024-07-18 22:36:04 +08:00
from typing import Any, Generic, Sequence, TypeVar
2024-07-17 15:00:13 +08:00
from rdagent.core.conf import RD_AGENT_SETTINGS
"""
This file contains the all the class about organizing the task in RD-Agent.
"""
class Task(ABC):
@abstractmethod
2024-07-18 22:36:04 +08:00
def get_task_information(self) -> str:
"""
Get the task information string to build the unique key
"""
2024-06-14 12:59:44 +08:00
ASpecificTask = TypeVar("ASpecificTask", bound=Task)
2024-07-17 15:00:13 +08:00
class Workspace(ABC, Generic[ASpecificTask]):
"""
A workspace is a place to store the task implementation. It evolves as the developer implements the task.
To get a snapshot of the workspace, make sure call `copy` to get a copy of the workspace.
"""
2024-07-25 15:20:04 +08:00
def __init__(self, target_task: ASpecificTask | None = None) -> None:
self.target_task: ASpecificTask | None = target_task
2024-06-14 12:59:44 +08:00
@abstractmethod
2024-07-25 15:20:04 +08:00
def execute(self, *args: Any, **kwargs: Any) -> object | None:
2024-07-18 22:36:04 +08:00
error_message = "execute method is not implemented."
raise NotImplementedError(error_message)
2024-07-17 15:00:13 +08:00
@abstractmethod
def copy(self) -> Workspace:
2024-07-18 22:36:04 +08:00
error_message = "copy method is not implemented."
raise NotImplementedError(error_message)
2024-07-17 15:00:13 +08:00
ASpecificWS = TypeVar("ASpecificWS", bound=Workspace)
2024-07-17 15:00:13 +08:00
class WsLoader(ABC, Generic[ASpecificTask, ASpecificWS]):
@abstractmethod
2024-07-17 15:00:13 +08:00
def load(self, task: ASpecificTask) -> ASpecificWS:
2024-07-18 22:36:04 +08:00
error_message = "load method is not implemented."
raise NotImplementedError(error_message)
2024-07-17 15:00:13 +08:00
class FBWorkspace(Workspace):
"""
2024-07-17 15:00:13 +08:00
File-based task workspace
The implemented task will be a folder which contains related elements.
- Data
2024-07-17 15:00:13 +08:00
- Code Workspace
- Output
- After execution, it will generate the final output as file.
2024-07-18 22:36:04 +08:00
A typical way to run the pipeline of FBWorkspace will be:
(We didn't add it as a method due to that we may pass arguments into
`prepare` or `execute` based on our requirements.)
.. code-block:: python
def run_pipeline(self, **files: str):
self.prepare()
self.inject_code(**files)
self.execute()
"""
2024-07-18 22:36:04 +08:00
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
2024-07-25 15:20:04 +08:00
self.code_dict: dict[str, Any] = {}
2024-07-17 15:00:13 +08:00
self.code_dict = (
{}
) # The code injected into the folder, store them in the variable to reproduce the former result
self.workspace_path: Path = RD_AGENT_SETTINGS.workspace_path / uuid.uuid4().hex
@property
def code(self) -> str:
code_string = ""
for file_name, code in self.code_dict.items():
code_string += f"File: {file_name}\n{code}\n"
return code_string
2024-07-18 22:36:04 +08:00
def prepare(self) -> None:
"""
2024-07-17 15:00:13 +08:00
Prepare the workspace except the injected code
- Data
- Documentation
typical usage of `*args, **kwargs`:
Different methods shares the same data. The data are passed by the arguments.
"""
2024-07-17 15:00:13 +08:00
self.workspace_path.mkdir(parents=True, exist_ok=True)
2024-07-18 22:36:04 +08:00
def inject_code(self, **files: str) -> None:
"""
Inject the code into the folder.
{
2024-07-17 15:00:13 +08:00
<file name>: <code>
}
"""
2024-07-17 15:00:13 +08:00
self.prepare()
for k, v in files.items():
2024-07-17 15:00:13 +08:00
self.code_dict[k] = v
2024-07-18 22:36:04 +08:00
with Path.open(self.workspace_path / k, "w") as f:
f.write(v)
def get_files(self) -> list[Path]:
"""
Get the environment description.
To be general, we only return a list of filenames.
2024-07-17 15:00:13 +08:00
How to summarize the environment is the responsibility of the Developer.
"""
return list(self.workspace_path.iterdir())
2024-06-14 12:59:44 +08:00
2024-07-18 22:36:04 +08:00
def inject_code_from_folder(self, folder_path: Path) -> None:
2024-07-17 15:00:13 +08:00
"""
Load the workspace from the folder
"""
for file_path in folder_path.iterdir():
2024-07-18 22:36:04 +08:00
if file_path.suffix in {".py", ".yaml"}:
2024-07-17 15:00:13 +08:00
self.inject_code(**{file_path.name: file_path.read_text()})
def copy(self) -> FBWorkspace:
"""
copy the workspace from the original one
"""
return deepcopy(self)
def clear(self) -> None:
"""
Clear the workspace
"""
shutil.rmtree(self.workspace_path)
self.code_dict = {}
2024-07-25 15:20:04 +08:00
def execute(self) -> object | None:
2024-07-17 15:00:13 +08:00
"""
Before each execution, make sure to prepare and inject code
"""
self.prepare()
self.inject_code(**self.code_dict)
2024-07-25 15:20:04 +08:00
return None
2024-07-17 15:00:13 +08:00
ASpecificWSForExperiment = TypeVar("ASpecificWSForExperiment", bound=Workspace)
ASpecificWSForSubTasks = TypeVar("ASpecificWSForSubTasks", bound=Workspace)
2024-07-17 15:00:13 +08:00
class Experiment(ABC, Generic[ASpecificTask, ASpecificWSForExperiment, ASpecificWSForSubTasks]):
"""
2024-07-17 15:00:13 +08:00
The experiment is a sequence of tasks and the implementations of the tasks after generated by the Developer.
"""
2024-07-04 15:56:14 +08:00
def __init__(self, sub_tasks: Sequence[ASpecificTask]) -> None:
self.sub_tasks = sub_tasks
2024-07-25 15:20:04 +08:00
self.sub_workspace_list: list[ASpecificWSForSubTasks | None] = [None] * len(self.sub_tasks)
2024-07-17 15:00:13 +08:00
self.based_experiments: Sequence[ASpecificWSForExperiment] = []
self.result: object = None # The result of the experiment, can be different types in different scenarios.
2024-07-25 15:20:04 +08:00
self.experiment_workspace: ASpecificWSForExperiment | None = None
ASpecificExp = TypeVar("ASpecificExp", bound=Experiment)
TaskOrExperiment = TypeVar("TaskOrExperiment", Task, Experiment)
2024-06-14 12:59:44 +08:00
class Loader(ABC, Generic[TaskOrExperiment]):
@abstractmethod
2024-07-18 22:36:04 +08:00
def load(self, *args: Any, **kwargs: Any) -> TaskOrExperiment:
err_msg = "load method is not implemented."
raise NotImplementedError(err_msg)