mirror of
https://github.com/NicolasBohn/NexQuant.git
synced 2026-07-28 16:07:46 +00:00
6e19c9e632
* 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>
563 lines
24 KiB
Python
563 lines
24 KiB
Python
"""
|
|
This is a class that try to store/resume/traceback the workflow session
|
|
|
|
|
|
Postscripts:
|
|
- Originally, I want to implement it in a more general way with python generator.
|
|
However, Python generator is not picklable (dill does not support pickle as well)
|
|
|
|
"""
|
|
|
|
import asyncio
|
|
import concurrent.futures
|
|
import copy
|
|
import os
|
|
import pickle
|
|
from collections import defaultdict
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Any, Callable, Optional, Union, cast
|
|
|
|
import psutil
|
|
from tqdm.auto import tqdm
|
|
|
|
from rdagent.core.conf import RD_AGENT_SETTINGS
|
|
from rdagent.log import rdagent_logger as logger
|
|
from rdagent.log.conf import LOG_SETTINGS
|
|
from rdagent.log.timer import RD_Agent_TIMER_wrapper, RDAgentTimer
|
|
from rdagent.utils.workflow.tracking import WorkflowTracker
|
|
|
|
|
|
class LoopMeta(type):
|
|
|
|
@staticmethod
|
|
def _get_steps(bases: tuple[type, ...]) -> list[str]:
|
|
"""
|
|
Recursively get all the `steps` from the base classes and combine them into a single list.
|
|
|
|
Args:
|
|
bases (tuple): A tuple of base classes.
|
|
|
|
Returns:
|
|
List[Callable]: A list of steps combined from all base classes.
|
|
"""
|
|
steps = []
|
|
for base in bases:
|
|
for step in LoopMeta._get_steps(base.__bases__) + getattr(base, "steps", []):
|
|
if step not in steps and step not in ["load", "dump"]: # incase user override the load/dump method
|
|
steps.append(step)
|
|
return steps
|
|
|
|
def __new__(mcs, clsname: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> Any:
|
|
"""
|
|
Create a new class with combined steps from base classes and current class.
|
|
|
|
Args:
|
|
clsname (str): Name of the new class.
|
|
bases (tuple): Base classes.
|
|
attrs (dict): Attributes of the new class.
|
|
|
|
Returns:
|
|
LoopMeta: A new instance of LoopMeta.
|
|
"""
|
|
steps = LoopMeta._get_steps(bases) # all the base classes of parents
|
|
for name, attr in attrs.items():
|
|
if not name.startswith("_") and callable(attr) and not isinstance(attr, type):
|
|
# NOTE: `not isinstance(attr, type)` is trying to exclude class type attribute
|
|
if name not in steps and name not in ["load", "dump"]: # incase user override the load/dump method
|
|
# NOTE: if we override the step in the subclass
|
|
# Then it is not the new step. So we skip it.
|
|
steps.append(name)
|
|
attrs["steps"] = steps
|
|
return super().__new__(mcs, clsname, bases, attrs)
|
|
|
|
|
|
@dataclass
|
|
class LoopTrace:
|
|
start: datetime # the start time of the trace
|
|
end: datetime # the end time of the trace
|
|
step_idx: int
|
|
# TODO: more information about the trace
|
|
|
|
|
|
class LoopBase:
|
|
"""
|
|
Assumption:
|
|
- The last step is responsible for recording information!!!!
|
|
|
|
Unsolved problem:
|
|
- Global variable synchronization when `force_subproc` is True
|
|
- Timer
|
|
"""
|
|
|
|
steps: list[str] # a list of steps to work on
|
|
loop_trace: dict[int, list[LoopTrace]]
|
|
|
|
skip_loop_error: tuple[type[BaseException], ...] = () # you can define a list of error that will skip current loop
|
|
skip_loop_error_stepname: str | None = None # if skip_loop_error exception happens, what's the next step to work on
|
|
withdraw_loop_error: tuple[
|
|
type[BaseException], ...
|
|
] = () # you can define a list of error that will withdraw current loop
|
|
|
|
EXCEPTION_KEY = "_EXCEPTION"
|
|
LOOP_IDX_KEY = "_LOOP_IDX"
|
|
SENTINEL = -1
|
|
|
|
_pbar: tqdm # progress bar instance
|
|
|
|
class LoopTerminationError(Exception):
|
|
"""Exception raised when loop conditions indicate the loop should terminate"""
|
|
|
|
class LoopResumeError(Exception):
|
|
"""Exception raised when loop conditions indicate the loop should stop all coroutines and resume"""
|
|
|
|
def __init__(self) -> None:
|
|
# progress control
|
|
self.loop_idx: int = 0 # current loop index / next loop index to kickoff
|
|
self.step_idx: defaultdict[int, int] = defaultdict(int) # dict from loop index to next step index
|
|
self.queue: asyncio.Queue[Any] = asyncio.Queue()
|
|
|
|
# Store step results for all loops in a nested dictionary, following information will be stored:
|
|
# - loop_prev_out[loop_index][step_name]: the output of the step function
|
|
# - loop_prev_out[loop_index][<special keys like LOOP_IDX_KEY or EXCEPTION_KEY>]: the special keys
|
|
self.loop_prev_out: dict[int, dict[str, Any]] = defaultdict(dict)
|
|
self.loop_trace = defaultdict(list[LoopTrace]) # the key is the number of loop
|
|
self.session_folder = Path(LOG_SETTINGS.trace_path) / "__session__"
|
|
self.timer: RDAgentTimer = RD_Agent_TIMER_wrapper.timer
|
|
self.tracker = WorkflowTracker(self) # Initialize tracker with this LoopBase instance
|
|
|
|
# progress control
|
|
self.loop_n: Optional[int] = None # remain loop count
|
|
self.step_n: Optional[int] = None # remain step count
|
|
|
|
self.semaphores: dict[str, asyncio.Semaphore] = {}
|
|
|
|
def get_unfinished_loop_cnt(self, next_loop: int) -> int:
|
|
n = 0
|
|
for li in range(next_loop):
|
|
if self.step_idx[li] < len(self.steps): # unfinished loop
|
|
n += 1
|
|
return n
|
|
|
|
def get_semaphore(self, step_name: str) -> asyncio.Semaphore:
|
|
if isinstance(limit := RD_AGENT_SETTINGS.step_semaphore, dict):
|
|
limit = limit.get(step_name, 1) # default to 1 if not specified
|
|
|
|
# NOTE:
|
|
# (1) we assume the record step is always the last step to modify the global environment,
|
|
# so we set the limit to 1 to avoid race condition
|
|
# (2) Because we support (-1,) as local selection; So it is hard to align a) the comparision target in `feedbck`
|
|
# and b) parent node in `record`; So we prevent parallelism in `feedback` and `record` to avoid inconsistency
|
|
if step_name in ("record", "feedback"):
|
|
limit = 1
|
|
|
|
if step_name not in self.semaphores:
|
|
self.semaphores[step_name] = asyncio.Semaphore(limit)
|
|
return self.semaphores[step_name]
|
|
|
|
@property
|
|
def pbar(self) -> tqdm:
|
|
"""Progress bar property that initializes itself if it doesn't exist."""
|
|
if getattr(self, "_pbar", None) is None:
|
|
self._pbar = tqdm(total=len(self.steps), desc="Workflow Progress", unit="step")
|
|
return self._pbar
|
|
|
|
def close_pbar(self) -> None:
|
|
if getattr(self, "_pbar", None) is not None:
|
|
self._pbar.close()
|
|
del self._pbar
|
|
|
|
def _check_exit_conditions_on_step(self, loop_id: Optional[int] = None, step_id: Optional[int] = None) -> None:
|
|
"""Check if the loop should continue or terminate.
|
|
|
|
Raises
|
|
------
|
|
LoopTerminationException
|
|
When conditions indicate that the loop should terminate
|
|
"""
|
|
# Check step count limitation
|
|
if self.step_n is not None:
|
|
if self.step_n <= 0:
|
|
raise self.LoopTerminationError("Step count reached")
|
|
self.step_n -= 1
|
|
|
|
# Check timer timeout
|
|
if self.timer.started:
|
|
if self.timer.is_timeout():
|
|
logger.warning("Timeout, exiting the loop.")
|
|
raise self.LoopTerminationError("Timer timeout")
|
|
else:
|
|
logger.info(f"Timer remaining time: {self.timer.remain_time()}")
|
|
|
|
async def _run_step(self, li: int, force_subproc: bool = False) -> None:
|
|
"""Execute a single step (next unrun step) in the workflow (async version with force_subproc option).
|
|
|
|
Parameters
|
|
----------
|
|
li : int
|
|
Loop index
|
|
|
|
force_subproc : bool
|
|
Whether to force the step to run in a subprocess in asyncio
|
|
|
|
Returns
|
|
-------
|
|
Any
|
|
The result of the step function
|
|
"""
|
|
si = self.step_idx[li]
|
|
name = self.steps[si]
|
|
|
|
async with self.get_semaphore(name):
|
|
|
|
logger.info(f"Start Loop {li}, Step {si}: {name}")
|
|
self.tracker.log_workflow_state()
|
|
|
|
with logger.tag(f"Loop_{li}.{name}"):
|
|
start = datetime.now(timezone.utc)
|
|
func: Callable[..., Any] = cast(Callable[..., Any], getattr(self, name))
|
|
|
|
next_step_idx = si + 1
|
|
step_forward = True
|
|
# NOTE: each step are aware are of current loop index
|
|
# It is very important to set it before calling the step function!
|
|
self.loop_prev_out[li][self.LOOP_IDX_KEY] = li
|
|
|
|
try:
|
|
# Call function with current loop's output, await if coroutine or use ProcessPoolExecutor for sync if required
|
|
if force_subproc:
|
|
curr_loop = asyncio.get_running_loop()
|
|
with concurrent.futures.ProcessPoolExecutor() as pool:
|
|
# Using deepcopy is to avoid triggering errors like "RuntimeError: dictionary changed size during iteration"
|
|
# GUESS: Some content in self.loop_prev_out[li] may be in the middle of being changed.
|
|
result = await curr_loop.run_in_executor(
|
|
pool, copy.deepcopy(func), copy.deepcopy(self.loop_prev_out[li])
|
|
)
|
|
else:
|
|
# auto determine whether to run async or sync
|
|
if asyncio.iscoroutinefunction(func):
|
|
result = await func(self.loop_prev_out[li])
|
|
else:
|
|
# Default: run sync function directly
|
|
result = func(self.loop_prev_out[li])
|
|
# Store result in the nested dictionary
|
|
self.loop_prev_out[li][name] = result
|
|
except Exception as e:
|
|
if isinstance(e, self.skip_loop_error):
|
|
logger.warning(f"Skip loop {li} due to {e}")
|
|
if self.skip_loop_error_stepname:
|
|
next_step_idx = self.steps.index(self.skip_loop_error_stepname)
|
|
if next_step_idx <= si:
|
|
raise RuntimeError(
|
|
f"Cannot skip backwards or to same step. Current: {si} ({name}), Target: {next_step_idx} ({self.skip_loop_error_stepname})"
|
|
) from e
|
|
else:
|
|
# Default: jump to feedback step if exists, otherwise jump to the last step (record)
|
|
if "feedback" in self.steps:
|
|
next_step_idx = self.steps.index("feedback")
|
|
else:
|
|
next_step_idx = len(self.steps) - 1
|
|
self.loop_prev_out[li][name] = None
|
|
self.loop_prev_out[li][self.EXCEPTION_KEY] = e
|
|
elif isinstance(e, self.withdraw_loop_error):
|
|
logger.warning(f"Withdraw loop {li} due to {e}")
|
|
# Back to previous loop
|
|
self.withdraw_loop(li)
|
|
step_forward = False
|
|
|
|
msg = "We have reset the loop instance, stop all the routines and resume."
|
|
raise self.LoopResumeError(msg) from e
|
|
else:
|
|
raise # re-raise unhandled exceptions
|
|
finally:
|
|
# No matter the execution succeed or not, we have to finish the following steps
|
|
|
|
# Record the trace
|
|
end = datetime.now(timezone.utc)
|
|
self.loop_trace[li].append(LoopTrace(start, end, step_idx=si))
|
|
logger.log_object(
|
|
{
|
|
"start_time": start,
|
|
"end_time": end,
|
|
},
|
|
tag="time_info",
|
|
)
|
|
if step_forward:
|
|
# Increment step index
|
|
self.step_idx[li] = next_step_idx
|
|
|
|
# Update progress bar
|
|
current_step = self.step_idx[li]
|
|
self.pbar.n = current_step
|
|
next_step = self.step_idx[li] % len(self.steps)
|
|
self.pbar.set_postfix(
|
|
loop_index=li + next_step_idx // len(self.steps),
|
|
step_index=next_step,
|
|
step_name=self.steps[next_step],
|
|
)
|
|
|
|
# Save snapshot after completing the step;
|
|
# 1) It has to be after the step_idx is updated, so loading the snapshot will be on the right step.
|
|
# 2) Only save it when the step forward, withdraw does not worth saving.
|
|
if name in self.loop_prev_out[li]:
|
|
# 3) Only dump the step if (so we don't have to redo the step when we load the session again)
|
|
# it has been executed successfully
|
|
self.dump(self.session_folder / f"{li}" / f"{si}_{name}")
|
|
|
|
self._check_exit_conditions_on_step(loop_id=li, step_id=si)
|
|
else:
|
|
logger.warning(f"Step forward {si} of loop {li} is skipped.")
|
|
|
|
async def kickoff_loop(self) -> None:
|
|
while True:
|
|
li = self.loop_idx
|
|
|
|
# exit on loop limitation
|
|
if self.loop_n is not None:
|
|
if self.loop_n <= 0:
|
|
for _ in range(RD_AGENT_SETTINGS.get_max_parallel()):
|
|
self.queue.put_nowait(self.SENTINEL)
|
|
break
|
|
self.loop_n -= 1
|
|
|
|
# NOTE:
|
|
# Try best to kick off the first step; the first step is always the ExpGen;
|
|
# it have the right to decide when to stop yield new Experiment
|
|
if self.step_idx[li] == 0:
|
|
# Assume the first step is ExpGen
|
|
# Only kick off ExpGen when it is never kicked off before
|
|
await self._run_step(li)
|
|
self.queue.put_nowait(li) # the loop `li` has been kicked off, waiting for workers to pick it up
|
|
self.loop_idx += 1
|
|
await asyncio.sleep(0)
|
|
|
|
async def execute_loop(self) -> None:
|
|
while True:
|
|
# 1) get the tasks to goon loop `li`
|
|
li = await self.queue.get()
|
|
if li == self.SENTINEL:
|
|
break
|
|
# 2) run the unfinished steps
|
|
while self.step_idx[li] < len(self.steps):
|
|
if self.step_idx[li] == len(self.steps) - 1:
|
|
# NOTE: assume the last step is record, it will be fast and affect the global environment
|
|
# if it is the last step, run it directly ()
|
|
await self._run_step(li)
|
|
else:
|
|
# await the step; parallel running happens here!
|
|
# Only trigger subprocess if we have more than one process.
|
|
await self._run_step(li, force_subproc=RD_AGENT_SETTINGS.is_force_subproc())
|
|
|
|
async def run(self, step_n: int | None = None, loop_n: int | None = None, all_duration: str | None = None) -> None:
|
|
"""Run the workflow loop.
|
|
|
|
Parameters
|
|
----------
|
|
loop_n: int | None
|
|
How many loops to run; if current loop is incomplete, it will be counted as the first loop for completion
|
|
`None` indicates to run forever until error or KeyboardInterrupt
|
|
all_duration : str | None
|
|
Maximum duration to run, in format accepted by the timer
|
|
"""
|
|
# Initialize timer if duration is provided
|
|
if all_duration is not None and not self.timer.started:
|
|
self.timer.reset(all_duration=all_duration)
|
|
|
|
if step_n is not None:
|
|
self.step_n = step_n
|
|
if loop_n is not None:
|
|
self.loop_n = loop_n
|
|
|
|
# empty the queue when restarting
|
|
while not self.queue.empty():
|
|
self.queue.get_nowait()
|
|
self.loop_idx = (
|
|
0 # if we rerun the loop, we should revert the loop index to 0 to make sure every loop is correctly kicked
|
|
)
|
|
|
|
tasks: list[asyncio.Task] = []
|
|
while True:
|
|
try:
|
|
# run one kickoff_loop and execute_loop
|
|
tasks = [
|
|
asyncio.create_task(t)
|
|
for t in [
|
|
self.kickoff_loop(),
|
|
*[self.execute_loop() for _ in range(RD_AGENT_SETTINGS.get_max_parallel())],
|
|
]
|
|
]
|
|
await asyncio.gather(*tasks)
|
|
break
|
|
except self.LoopResumeError as e:
|
|
logger.warning(f"Stop all the routines and resume loop: {e}")
|
|
self.loop_idx = 0
|
|
except self.LoopTerminationError as e:
|
|
logger.warning(f"Reach stop criterion and stop loop: {e}")
|
|
kill_subprocesses() # NOTE: coroutine-based workflow can't automatically stop subprocesses.
|
|
break
|
|
finally:
|
|
# cancel all previous tasks before resuming all loops or exit
|
|
for t in tasks:
|
|
t.cancel()
|
|
self.close_pbar()
|
|
|
|
def withdraw_loop(self, loop_idx: int) -> None:
|
|
prev_session_dir = self.session_folder / str(loop_idx - 1)
|
|
prev_path = min(
|
|
(p for p in prev_session_dir.glob("*_*") if p.is_file()),
|
|
key=lambda item: int(item.name.split("_", 1)[0]),
|
|
default=None,
|
|
)
|
|
if prev_path:
|
|
loaded = type(self).load(
|
|
prev_path,
|
|
checkout=True,
|
|
replace_timer=True,
|
|
)
|
|
logger.info(f"Load previous session from {prev_path}")
|
|
# Overwrite current instance state
|
|
self.__dict__ = loaded.__dict__
|
|
else:
|
|
logger.error(f"No previous dump found at {prev_session_dir}, cannot withdraw loop {loop_idx}")
|
|
raise
|
|
|
|
def dump(self, path: str | Path) -> None:
|
|
if RD_Agent_TIMER_wrapper.timer.started:
|
|
RD_Agent_TIMER_wrapper.timer.update_remain_time()
|
|
path = Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open("wb") as f:
|
|
pickle.dump(self, f)
|
|
|
|
def truncate_session_folder(self, li: int, si: int) -> None:
|
|
"""
|
|
Clear the session folder by removing all session objects after the given loop index (li) and step index (si).
|
|
"""
|
|
# clear session folders after the li
|
|
for sf in self.session_folder.iterdir():
|
|
if sf.is_dir() and int(sf.name) > li:
|
|
for file in sf.iterdir():
|
|
file.unlink()
|
|
sf.rmdir()
|
|
|
|
# clear step session objects in the li
|
|
final_loop_session_folder = self.session_folder / str(li)
|
|
for step_session in final_loop_session_folder.glob("*_*"):
|
|
if step_session.is_file():
|
|
step_id = int(step_session.name.split("_", 1)[0])
|
|
if step_id > si:
|
|
step_session.unlink()
|
|
|
|
@classmethod
|
|
def load(
|
|
cls,
|
|
path: str | Path,
|
|
checkout: bool | Path | str = False,
|
|
replace_timer: bool = True,
|
|
) -> "LoopBase":
|
|
"""
|
|
Load a session from a given path.
|
|
Parameters
|
|
----------
|
|
path : str | Path
|
|
The path to the session file.
|
|
checkout : bool | Path | str
|
|
If True, the new loop will use the existing folder and clear logs for sessions after the one corresponding to the given path.
|
|
If False, the new loop will use the existing folder but keep the logs for sessions after the one corresponding to the given path.
|
|
If a path (or a str like Path) is provided, the new loop will be saved to that path, leaving the original path unchanged.
|
|
replace_timer : bool
|
|
If a session is loaded, determines whether to replace the timer with session.timer.
|
|
Default is True, which means the session timer will be replaced with the current timer.
|
|
If False, the session timer will not be replaced.
|
|
Returns
|
|
-------
|
|
LoopBase
|
|
An instance of LoopBase with the loaded session.
|
|
"""
|
|
path = Path(path)
|
|
session_folder = None
|
|
# if the path is a directory, load the latest session
|
|
if path.is_dir():
|
|
if path.name != "__session__":
|
|
session_folder = path / "__session__"
|
|
else:
|
|
session_folder = path
|
|
|
|
if not session_folder.exists():
|
|
raise FileNotFoundError(f"No session file found in {path}")
|
|
|
|
# iterate the dump steps in increasing order
|
|
files = sorted(session_folder.glob("*/*_*"), key=lambda f: (int(f.parent.name), int(f.name.split("_")[0])))
|
|
path = files[-1]
|
|
logger.info(f"Loading latest session from {path}")
|
|
else:
|
|
session_folder = path.parent.parent
|
|
|
|
with path.open("rb") as f:
|
|
session = cast(LoopBase, pickle.load(f))
|
|
|
|
# set session folder
|
|
if checkout:
|
|
if checkout is True:
|
|
session.session_folder = session_folder
|
|
logger.set_storages_path(session.session_folder.parent)
|
|
|
|
# truncate log storages after the max loop
|
|
max_loop = max(session.loop_trace.keys())
|
|
session.truncate_session_folder(max_loop, len(session.loop_trace[max_loop]) - 1)
|
|
logger.truncate_storages(session.loop_trace[max_loop][-1].end)
|
|
else:
|
|
checkout = Path(checkout)
|
|
checkout.mkdir(parents=True, exist_ok=True)
|
|
session.session_folder = checkout / "__session__"
|
|
logger.set_storages_path(checkout)
|
|
|
|
logger.info(f"Checkout session to {session.session_folder.parent}")
|
|
|
|
if session.timer.started:
|
|
if replace_timer:
|
|
RD_Agent_TIMER_wrapper.replace_timer(session.timer)
|
|
RD_Agent_TIMER_wrapper.timer.restart_by_remain_time()
|
|
else:
|
|
# Use the default timer to replace the session timer
|
|
session.timer = RD_Agent_TIMER_wrapper.timer
|
|
|
|
return session
|
|
|
|
def __getstate__(self) -> dict[str, Any]:
|
|
res = {}
|
|
for k, v in self.__dict__.items():
|
|
if k not in ["queue", "semaphores", "_pbar"]:
|
|
res[k] = v
|
|
return res
|
|
|
|
def __setstate__(self, state: dict[str, Any]) -> None:
|
|
self.__dict__.update(state)
|
|
self.queue = asyncio.Queue()
|
|
self.semaphores = {}
|
|
|
|
|
|
def kill_subprocesses() -> None:
|
|
"""
|
|
Due to the coroutine-based nature of the workflow, the event loop of the main process can't
|
|
stop all the subprocesses start by `curr_loop.run_in_executor`. So we need to kill them manually.
|
|
Otherwise, the subprocesses will keep running in the background and the the main process keeps waiting.
|
|
"""
|
|
current_proc = psutil.Process(os.getpid())
|
|
for child in current_proc.children(recursive=True):
|
|
try:
|
|
print(f"Terminating subprocess PID {child.pid} ({child.name()})")
|
|
child.terminate()
|
|
except Exception as ex:
|
|
print(f"Could not terminate subprocess {child.pid}: {ex}")
|
|
print("Finished terminating subprocesses. Then force killing still alive subprocesses.")
|
|
_, alive = psutil.wait_procs(current_proc.children(recursive=True), timeout=3)
|
|
for p in alive:
|
|
try:
|
|
print(f"Killing still alive subprocess PID {p.pid} ({p.name()})")
|
|
p.kill()
|
|
except Exception as ex:
|
|
print(f"Could not kill subprocess {p.pid}: {ex}")
|
|
print("Finished killing subprocesses.")
|