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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Agent Zero Orchestrator — Gradio Space App
|
| 4 |
+
===========================================
|
| 5 |
+
Fully autonomous self-healing training on FREE CPU tier.
|
| 6 |
+
Auto-resume across Space sleeps. Live dashboard.
|
| 7 |
+
"""
|
| 8 |
+
import os, sys, json, time, threading, traceback
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from typing import Optional, Dict, Any
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import plotly.graph_objects as go
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 17 |
+
from self_healing import SelfHealingTrainer, HealingConfig
|
| 18 |
+
|
| 19 |
+
# Globals
|
| 20 |
+
training_thread: Optional[threading.Thread] = None
|
| 21 |
+
stop_event = threading.Event()
|
| 22 |
+
state: Dict[str, Any] = {"running": False, "step": 0, "loss": None,
|
| 23 |
+
"recoveries": 0, "zclip_clips": 0, "start_time": None,
|
| 24 |
+
"logs": [], "recovery_history": [], "status": "idle"}
|
| 25 |
+
STATE_FILE = Path("/app/training_state.json")
|
| 26 |
+
CKPT_DIR = Path("/app/checkpoints")
|
| 27 |
+
|
| 28 |
+
def _log(msg: str):
|
| 29 |
+
ts = datetime.now().strftime("%H:%M:%S")
|
| 30 |
+
entry = f"[{ts}] {msg}"
|
| 31 |
+
state["logs"].append(entry)
|
| 32 |
+
print(entry, flush=True)
|
| 33 |
+
if len(state["logs"]) > 500: state["logs"] = state["logs"][-500:]
|
| 34 |
+
|
| 35 |
+
def save_state():
|
| 36 |
+
try:
|
| 37 |
+
with open(STATE_FILE, "w") as f:
|
| 38 |
+
json.dump({k: v for k, v in state.items() if k != "logs"}, f, default=str)
|
| 39 |
+
except: pass
|
| 40 |
+
|
| 41 |
+
def load_state():
|
| 42 |
+
if STATE_FILE.exists():
|
| 43 |
+
try:
|
| 44 |
+
with open(STATE_FILE) as f: state.update(json.load(f))
|
| 45 |
+
except: pass
|
| 46 |
+
load_state()
|
| 47 |
+
|
| 48 |
+
def worker(model_id: str, dataset_id: str, max_steps: int, lr: float,
|
| 49 |
+
batch_size: int, hub_user: str, push_hub: bool):
|
| 50 |
+
import torch
|
| 51 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 52 |
+
from datasets import load_dataset
|
| 53 |
+
from trl import SFTConfig, SFTTrainer
|
| 54 |
+
|
| 55 |
+
state["running"] = True; state["status"] = "loading"
|
| 56 |
+
state["start_time"] = time.time(); stop_event.clear()
|
| 57 |
+
state["logs"] = []; state["step"] = 0
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
_log(f"Loading {model_id}...")
|
| 61 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 62 |
+
model_id, torch_dtype=torch.float32, device_map="cpu", low_cpu_mem_usage=True)
|
| 63 |
+
tok = AutoTokenizer.from_pretrained(model_id)
|
| 64 |
+
if tok.pad_token is None: tok.pad_token = tok.eos_token
|
| 65 |
+
|
| 66 |
+
_log(f"Loading dataset {dataset_id}...")
|
| 67 |
+
ds = load_dataset(dataset_id, split="train[:500]")
|
| 68 |
+
|
| 69 |
+
state["status"] = "training"
|
| 70 |
+
args = SFTConfig(
|
| 71 |
+
output_dir=str(CKPT_DIR), per_device_train_batch_size=batch_size,
|
| 72 |
+
gradient_accumulation_steps=4, learning_rate=lr, max_steps=max_steps,
|
| 73 |
+
logging_steps=1, logging_strategy="steps", logging_first_step=True,
|
| 74 |
+
save_steps=10, save_total_limit=5, use_cpu=True,
|
| 75 |
+
report_to="none", disable_tqdm=True,
|
| 76 |
+
push_to_hub=push_hub,
|
| 77 |
+
hub_model_id=f"{hub_user}/agent-zero-model" if push_hub else None)
|
| 78 |
+
|
| 79 |
+
trainer = SFTTrainer(model=model, args=args, train_dataset=ds, tokenizer=tok)
|
| 80 |
+
|
| 81 |
+
hcfg = HealingConfig(nan_patience=2, loss_spike_factor=5.0,
|
| 82 |
+
divergence_patience=30, grad_explosion_threshold=50.0,
|
| 83 |
+
zclip_enabled=True, zclip_z_threshold=3.0,
|
| 84 |
+
max_recovery_attempts=5, max_lr_reductions=3,
|
| 85 |
+
max_batch_reductions=2, postmortem_path="/app/postmortem.json")
|
| 86 |
+
sh = SelfHealingTrainer(trainer, hcfg)
|
| 87 |
+
|
| 88 |
+
resume = None
|
| 89 |
+
if CKPT_DIR.exists():
|
| 90 |
+
cks = sorted(CKPT_DIR.glob("checkpoint-*"))
|
| 91 |
+
if cks: resume = str(cks[-1]); _log(f"Resuming from {resume}")
|
| 92 |
+
|
| 93 |
+
_log("Dry-run...")
|
| 94 |
+
sh.dry_run(num_steps=2)
|
| 95 |
+
_log("Starting training!")
|
| 96 |
+
|
| 97 |
+
sh.train(resume_from_checkpoint=resume)
|
| 98 |
+
state["status"] = "completed"
|
| 99 |
+
rpt = sh.get_report()
|
| 100 |
+
state["recoveries"] = rpt["total_recoveries"]
|
| 101 |
+
state["zclip_clips"] = rpt["zclip_total_clips"]
|
| 102 |
+
_log(f"Done! Recoveries: {rpt['total_recoveries']}")
|
| 103 |
+
if push_hub: _log(f"Pushed to {hub_user}/agent-zero-model")
|
| 104 |
+
except Exception as e:
|
| 105 |
+
state["status"] = f"error: {type(e).__name__}"
|
| 106 |
+
_log(f"ERROR: {e}"); traceback.print_exc()
|
| 107 |
+
finally:
|
| 108 |
+
state["running"] = False; save_state()
|
| 109 |
+
_log("Thread ended.")
|
| 110 |
+
|
| 111 |
+
def start(model_id, dataset_id, max_steps, lr, batch_size, hub_user, push_hub):
|
| 112 |
+
global training_thread
|
| 113 |
+
if state["running"]: return "Already running!", ""
|
| 114 |
+
state["logs"] = []; state["step"] = 0; state["recoveries"] = 0; state["zclip_clips"] = 0
|
| 115 |
+
training_thread = threading.Thread(target=worker, daemon=True,
|
| 116 |
+
args=(model_id, dataset_id, int(max_steps), float(lr), int(batch_size), hub_user, push_hub))
|
| 117 |
+
training_thread.start()
|
| 118 |
+
return "Training started!", ""
|
| 119 |
+
|
| 120 |
+
def stop():
|
| 121 |
+
stop_event.set(); state["running"] = False; state["status"] = "stopped"
|
| 122 |
+
save_state(); return "Stop signal sent.", ""
|
| 123 |
+
|
| 124 |
+
def get_logs(): return "\n".join(state["logs"][-50:])
|
| 125 |
+
|
| 126 |
+
def get_status():
|
| 127 |
+
el = f" | {int(time.time()-state['start_time'])}s" if state["start_time"] else ""
|
| 128 |
+
return f"Status: {state['status']} | Step: {state['step']} | Rec: {state['recoveries']} | ZClip: {state['zclip_clips']}{el}"
|
| 129 |
+
|
| 130 |
+
def get_pm():
|
| 131 |
+
p = Path("/app/postmortem.json")
|
| 132 |
+
return json.dumps(json.load(open(p)), indent=2) if p.exists() else "No postmortem yet."
|
| 133 |
+
|
| 134 |
+
def get_plot():
|
| 135 |
+
try:
|
| 136 |
+
p = CKPT_DIR / "trainer_state.json"
|
| 137 |
+
if p.exists():
|
| 138 |
+
with open(p) as f: data = json.load(f)
|
| 139 |
+
hist = [e for e in data.get("log_history", []) if "loss" in e]
|
| 140 |
+
if hist:
|
| 141 |
+
fig = go.Figure()
|
| 142 |
+
fig.add_trace(go.Scatter(x=[e.get("step", i) for i, e in enumerate(hist)],
|
| 143 |
+
y=[e["loss"] for e in hist], mode="lines", name="Loss"))
|
| 144 |
+
fig.update_layout(title="Training Loss", xaxis_title="Step", yaxis_title="Loss", template="plotly_dark")
|
| 145 |
+
return fig
|
| 146 |
+
except: pass
|
| 147 |
+
fig = go.Figure(); fig.update_layout(title="Loss (no data)", template="plotly_dark")
|
| 148 |
+
return fig
|
| 149 |
+
|
| 150 |
+
with gr.Blocks(title="Agent Zero Orchestrator", theme=gr.themes.Soft()) as demo:
|
| 151 |
+
gr.Markdown("# 🔄 Agent Zero Orchestrator\n**Self-healing ML training. Free CPU. Auto-resume. Zero credits.**")
|
| 152 |
+
with gr.Row():
|
| 153 |
+
with gr.Column(scale=1):
|
| 154 |
+
gr.Markdown("### Config")
|
| 155 |
+
m = gr.Textbox(value="HuggingFaceTB/SmolLM2-135M", label="Model")
|
| 156 |
+
d = gr.Textbox(value="trl-lib/Capybara", label="Dataset")
|
| 157 |
+
s = gr.Number(value=100, label="Max Steps", minimum=10)
|
| 158 |
+
l = gr.Number(value=2e-5, label="LR", format=".2e")
|
| 159 |
+
b = gr.Number(value=1, label="Batch Size", minimum=1)
|
| 160 |
+
u = gr.Textbox(value="ScottzillaSystems", label="Hub User")
|
| 161 |
+
p = gr.Checkbox(value=False, label="Push to Hub")
|
| 162 |
+
with gr.Row():
|
| 163 |
+
gr.Button("🚀 Start", variant="primary").click(start, [m,d,s,l,b,u,p], [gr.Textbox(label="Status"), gr.Textbox(label="Logs")])
|
| 164 |
+
gr.Button("⏹ Stop", variant="stop").click(stop, outputs=[gr.Textbox(label="Status"), gr.Textbox(label="Logs")])
|
| 165 |
+
with gr.Column(scale=2):
|
| 166 |
+
gr.Markdown("### Dashboard")
|
| 167 |
+
gr.Textbox(value=get_status, label="Status", every=2, interactive=False)
|
| 168 |
+
gr.Plot(value=get_plot, label="Loss", every=5)
|
| 169 |
+
with gr.Row():
|
| 170 |
+
gr.Textbox(value=get_logs, label="Logs", lines=20, every=2, interactive=False)
|
| 171 |
+
gr.Textbox(value=get_pm, label="Postmortem", lines=20, every=10, interactive=False)
|
| 172 |
+
gr.Markdown("Papers: Unicron arxiv:2401.00134 | ZClip arxiv:2504.02507 | Pioneer Agent arxiv:2604.09791")
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|