Files
NexQuant/rdagent/app/finetune/llm/ui/data_loader.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

456 lines
16 KiB
Python

"""
FT UI Data Loader
Load pkl logs and convert to hierarchical timeline structure
"""
import re
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any
import streamlit as st
from rdagent.app.finetune.llm.ui.config import EVALUATOR_CONFIG, EventType
from rdagent.log.storage import FileStorage
@dataclass
class Event:
"""Timeline event"""
type: EventType
timestamp: datetime
tag: str
title: str
content: Any
loop_id: int | None = None
evo_id: int | None = None
stage: str = ""
duration: float | None = None
success: bool | None = None
@property
def time_str(self) -> str:
return self.timestamp.strftime("%H:%M:%S")
@dataclass
class EvoLoop:
"""Evolution loop containing events"""
evo_id: int
events: list[Event] = field(default_factory=list)
success: bool | None = None
@dataclass
class Loop:
"""Main loop containing stages"""
loop_id: int
exp_gen: list[Event] = field(default_factory=list)
coding: dict[int, EvoLoop] = field(default_factory=dict) # evo_id -> EvoLoop
runner: list[Event] = field(default_factory=list)
feedback: list[Event] = field(default_factory=list)
@dataclass
class Session:
"""Session containing init events and loops"""
init_events: list[Event] = field(default_factory=list)
loops: dict[int, Loop] = field(default_factory=dict) # loop_id -> Loop
def extract_loop_id(tag: str) -> int | None:
match = re.search(r"Loop_(\d+)", tag)
return int(match.group(1)) if match else None
def extract_evo_id(tag: str) -> int | None:
match = re.search(r"evo_loop_(\d+)", tag)
return int(match.group(1)) if match else None
def extract_stage(tag: str) -> str:
if "direct_exp_gen" in tag:
return "exp_gen"
if "coding" in tag:
return "coding"
if "running" in tag: # Note: tag uses "running", not "runner"
return "runner"
if "feedback" in tag:
return "feedback"
return ""
def get_valid_sessions(log_folder: Path) -> list[str]:
if not log_folder.exists():
return []
sessions = []
for d in log_folder.iterdir():
if d.is_dir() and d.joinpath("__session__").exists():
sessions.append(d.name)
return sorted(sessions, reverse=True)
def parse_event(tag: str, content: Any, timestamp: datetime) -> Event | None:
loop_id = extract_loop_id(tag)
evo_id = extract_evo_id(tag)
stage = extract_stage(tag)
# Scenario
if tag == "scenario":
model = getattr(content, "base_model", "Unknown")
return Event(type="scenario", timestamp=timestamp, tag=tag, title=f"Scenario: {model}", content=content)
# Dataset selection
if "dataset_selection" in tag:
selected = content.get("selected_datasets", []) if isinstance(content, dict) else []
total = content.get("total_datasets", 0) if isinstance(content, dict) else 0
return Event(
type="dataset_selection",
timestamp=timestamp,
tag=tag,
title=f"Dataset Selection: {len(selected)}/{total}",
content=content,
)
# Settings
if "SETTINGS" in tag:
name = tag.replace("_SETTINGS", "").replace("SETTINGS", "")
return Event(type="settings", timestamp=timestamp, tag=tag, title=f"Settings: {name}", content=content)
# Hypothesis
if tag == "hypothesis" or (loop_id is not None and "hypothesis" in tag):
return Event(
type="hypothesis",
timestamp=timestamp,
tag=tag,
title="Hypothesis",
content=content,
loop_id=loop_id,
stage="exp_gen",
)
# LLM Call
if "debug_llm" in tag:
if isinstance(content, dict) and ("user" in content or "system" in content):
duration = None
if content.get("start") and content.get("end"):
duration = (content["end"] - content["start"]).total_seconds()
return Event(
type="llm_call",
timestamp=timestamp,
tag=tag,
title="LLM Call",
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage,
duration=duration,
)
# Template
if "debug_tpl" in tag:
if isinstance(content, dict) and "uri" in content:
uri = content.get("uri", "")
tpl_name = uri.split(":")[-1] if ":" in uri else uri
return Event(
type="template",
timestamp=timestamp,
tag=tag,
title=f"Template: {tpl_name}",
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage,
)
# Experiment generation
if "experiment generation" in tag:
task_count = len(content) if isinstance(content, list) else 1
return Event(
type="experiment",
timestamp=timestamp,
tag=tag,
title=f"Experiment ({task_count} task)",
content=content,
loop_id=loop_id,
stage=stage,
)
# Evolving code
if "evolving code" in tag:
file_count = 0
if isinstance(content, list):
for ws in content:
if hasattr(ws, "file_dict"):
file_count += len(ws.file_dict)
return Event(
type="code",
timestamp=timestamp,
tag=tag,
title=f"Code ({file_count} files)",
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage or "coding",
)
# Benchmark execution (Docker or Conda) - must check before generic docker_run/conda_run
if "docker_run.Benchmark" in tag or "conda_run.Benchmark" in tag:
benchmark_name = content.get("benchmark_name", "Unknown") if isinstance(content, dict) else "Unknown"
exit_code = content.get("exit_code") if isinstance(content, dict) else None
success = exit_code == 0 if exit_code is not None else None
env_type = "Docker" if "docker_run" in tag else "Conda"
return Event(
type="docker_exec",
timestamp=timestamp,
tag=tag,
title=f"Benchmark ({benchmark_name}) [{env_type}] {'✓' if success else '✗' if success is False else ''}",
content=content,
loop_id=loop_id,
stage="runner",
success=success,
)
# Environment run (Docker or Conda, raw execution logged before LLM evaluation)
if "docker_run." in tag or "conda_run." in tag:
is_docker = "docker_run." in tag
tag_prefix = "docker_run." if is_docker else "conda_run."
class_name = tag.split(tag_prefix)[-1].split(".")[0]
# FTWorkspace unified logging - determine type from entry command
if class_name == "FTWorkspace":
entry = content.get("entry", "") if isinstance(content, dict) else ""
if "llamafactory-cli train" in entry:
# Distinguish by yaml file name: debug_train.yaml for micro-batch, train.yaml for full training
if "debug_train.yaml" in entry:
evaluator_name, default_stage = "Micro-batch Test", "coding"
else:
evaluator_name, default_stage = "Full Train", "runner"
elif "process_data" in entry.lower():
evaluator_name, default_stage = "Data Processing", "coding"
elif entry.startswith("rm "):
evaluator_name, default_stage = "Cleanup", "runner"
else:
evaluator_name, default_stage = "Env Run", "coding"
else:
evaluator_name, default_stage = EVALUATOR_CONFIG.get(class_name, (class_name, "coding"))
exit_code = content.get("exit_code") if isinstance(content, dict) else None
success = exit_code == 0 if exit_code is not None else content.get("success")
env_label = "Docker" if is_docker else "Conda"
title = f"{env_label} ({evaluator_name}) {'✓' if success else '✗' if success is False else ''}"
return Event(
type="docker_exec",
timestamp=timestamp,
tag=tag,
title=title,
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage or default_stage,
success=success,
)
# Docker execution (individual evaluator feedback, logged after LLM evaluation)
if "docker_exec." in tag:
class_name = tag.split("docker_exec.")[-1].split(".")[0]
evaluator_name, default_stage = EVALUATOR_CONFIG.get(class_name, (class_name, "coding"))
success = getattr(content, "final_decision", None)
title = f"Eval ({evaluator_name}) {'✓' if success else '✗' if success is False else '?'}"
return Event(
type="docker_exec",
timestamp=timestamp,
tag=tag,
title=title,
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage or default_stage,
success=success,
)
# Evaluator feedback (logged from FT evaluators with final_decision)
if "evaluator_feedback." in tag:
class_name = tag.split("evaluator_feedback.")[-1].split(".")[0]
evaluator_name, default_stage = EVALUATOR_CONFIG.get(class_name, (class_name, "coding"))
success = getattr(content, "final_decision", None)
title = f"Eval ({evaluator_name}) {'✓' if success else '✗' if success is False else '?'}"
return Event(
type="evaluator", # Use dedicated evaluator type with 📝 icon
timestamp=timestamp,
tag=tag,
title=title,
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage or default_stage,
success=success,
)
# Final feedback
if "feedback.feedback" in tag or (tag.endswith(".feedback") and "evo_loop" not in tag):
decision = getattr(content, "decision", None)
return Event(
type="feedback",
timestamp=timestamp,
tag=tag,
title=f"Feedback: {'Accept' if decision else 'Reject'}",
content=content,
loop_id=loop_id,
stage="feedback",
success=decision,
)
# Benchmark result (supports benchmark_result, benchmark_result.validation, benchmark_result.test)
if "benchmark_result" in tag:
benchmark_name = content.get("benchmark_name", "Unknown") if isinstance(content, dict) else "Unknown"
accuracy = content.get("accuracy_summary", {}) if isinstance(content, dict) else {}
# Extract split from tag or content
split = content.get("split", "") if isinstance(content, dict) else ""
if not split and "." in tag:
split = tag.split(".")[-1] # e.g., "validation" or "test" from "benchmark_result.validation"
split_label = f" [{split.title()}]" if split and split != "default" else ""
return Event(
type="feedback",
timestamp=timestamp,
tag=tag,
title=f"Benchmark Result{split_label} ({benchmark_name}: {len(accuracy)} datasets)",
content=content,
loop_id=loop_id,
stage="runner",
)
# Runner result
if "runner result" in tag:
return Event(
type="docker_exec",
timestamp=timestamp,
tag=tag,
title="Full Train",
content=content,
loop_id=loop_id,
stage="runner",
)
# Token cost
if "token_cost" in tag:
if isinstance(content, dict):
total = content.get("total_tokens", 0)
return Event(
type="token",
timestamp=timestamp,
tag=tag,
title=f"Token: {total}",
content=content,
loop_id=loop_id,
evo_id=evo_id,
stage=stage,
)
# Time info
if "time_info" in tag:
return Event(
type="time", timestamp=timestamp, tag=tag, title="Time Info", content=content, loop_id=loop_id, stage=stage
)
return None
@st.cache_data(ttl=300, hash_funcs={Path: str})
def load_ft_session(log_path: Path) -> Session:
"""Load events into hierarchical session structure"""
session = Session()
storage = FileStorage(log_path)
events = []
for msg in storage.iter_msg():
if not msg.tag:
continue
event = parse_event(msg.tag, msg.content, msg.timestamp)
if event:
events.append(event)
# Sort by timestamp
events.sort(key=lambda e: e.timestamp)
# Organize into hierarchy
for event in events:
if event.loop_id is None:
session.init_events.append(event)
continue
# Ensure loop exists
if event.loop_id not in session.loops:
session.loops[event.loop_id] = Loop(loop_id=event.loop_id)
loop = session.loops[event.loop_id]
# Place event in appropriate stage
if event.stage == "exp_gen":
loop.exp_gen.append(event)
elif event.stage == "coding":
if event.evo_id is not None:
if event.evo_id not in loop.coding:
loop.coding[event.evo_id] = EvoLoop(evo_id=event.evo_id)
evo = loop.coding[event.evo_id]
evo.events.append(event)
# Use evaluator feedback (final_decision) for evo success, fallback to docker_exec
if event.type in ("evaluator", "docker_exec") and event.success is not None:
if evo.success is None:
evo.success = event.success
else:
evo.success = evo.success and event.success # AND logic: all evaluators must pass
else:
# Coding events without evo_id go to evo 0
if 0 not in loop.coding:
loop.coding[0] = EvoLoop(evo_id=0)
loop.coding[0].events.append(event)
elif event.stage == "runner":
loop.runner.append(event)
elif event.stage == "feedback":
loop.feedback.append(event)
else:
# Unknown stage - put in exp_gen
loop.exp_gen.append(event)
return session
def get_summary(session: Session) -> dict:
"""Get summary statistics"""
llm_calls = []
docker_execs = []
# Collect from init
for e in session.init_events:
if e.type == "llm_call":
llm_calls.append(e)
elif e.type == "docker_exec":
docker_execs.append(e)
# Collect from loops
for loop in session.loops.values():
for e in loop.exp_gen + loop.runner + loop.feedback:
if e.type == "llm_call":
llm_calls.append(e)
elif e.type == "docker_exec":
docker_execs.append(e)
for evo in loop.coding.values():
for e in evo.events:
if e.type == "llm_call":
llm_calls.append(e)
elif e.type == "docker_exec":
docker_execs.append(e)
return {
"loop_count": len(session.loops),
"llm_call_count": len(llm_calls),
"llm_total_time": sum(e.duration or 0 for e in llm_calls),
"docker_success": sum(1 for e in docker_execs if e.success is True),
"docker_fail": sum(1 for e in docker_execs if e.success is False),
}