strands-isaaclab-reach-franka / examples /agent_rl_research_lead.py
cagataydev's picture
Polished dataset card: agent-driven training via strands isaaclab provider, recording, results, license; add playback + examples
adfb214 verified
Raw History Blame Contribute Delete
3.92 kB
"""An agent as RL research lead: one prompt -> an Isaac Lab hyper-parameter sweep.
A Strands Agent gets strands-robots' ``train_policy`` tool (provider ``isaaclab``)
plus three small helpers: ``gpu_status`` (nvidia-smi), ``wait_minutes`` and
``stop_job`` (train_policy has no cancel action yet, see FINDINGS IL-X-004).
From ONE natural-language request it launches a learning-rate x seed sweep,
keeps at most MAX_CONCURRENT runs on the GPU, polls, early-stops losers, picks
a winner and writes a comparison table.
Env: ISAACLAB_PYTHON, OMNI_KIT_ACCEPT_EULA=YES, STRANDS_MODEL_ID (Bedrock).
Usage: python agent_rl_research_lead.py [out_dir] [task]
"""
import json, os, subprocess, sys, time
from pathlib import Path
from strands import Agent, tool
from strands.models import BedrockModel
from strands_robots.tools.train_policy import train_policy
from strands_robots.training import _isaaclab_runtime as runtime
from strands_robots.training.isaaclab import IsaacLabTrainer
OUT = Path(sys.argv[1] if len(sys.argv) > 1 else "runs/agent_sweep").resolve()
TASK = sys.argv[2] if len(sys.argv) > 2 else "Isaac-Reach-Franka"
MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))
OUT.mkdir(parents=True, exist_ok=True)
@tool
def gpu_status() -> str:
"""GPU memory used/total (MiB) and utilization."""
q = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,memory.total,utilization.gpu", "--format=csv,noheader"],
capture_output=True, text=True).stdout.strip()
return f"gpu memory.used, memory.total, util: {q}"
@tool
def wait_minutes(minutes: float) -> str:
"""Sleep for up to 5 minutes while training runs progress."""
m = max(0.1, min(float(minutes), 5.0)); time.sleep(m * 60); return f"waited {m} min"
@tool
def stop_job(job_id: str) -> str:
"""Stop a running Isaac Lab job (early-stopping a losing run). Returns its final status."""
t = IsaacLabTrainer()
rec = json.loads((t._jobs_dir / job_id / "job.json").read_text())
runtime.terminate(int(rec["pid"]))
r = t.status(job_id)
return f"{job_id}: {r.status} at iteration {r.metrics.get('latest_iteration')} reward {r.metrics.get('latest_reward')}"
PROMPT = f"""You are the RL research lead on a single shared L40S GPU. Using train_policy with provider='isaaclab'
(it needs no dataset), run a hyper-parameter sweep on the Isaac Lab task {TASK}:
learning rates [3e-4, 1e-3, 3e-3] x seeds [1, 2] = 6 runs, each steps=300 PPO iterations,
extra={{'task': '{TASK}', 'num_envs': 4096, 'timeout_s': 1800}}, output_dir='{OUT}/<lr>_s<seed>'.
Rules: keep at most {MAX_CONCURRENT} runs alive at once (check gpu_status before launching, keep >= 8 GB free);
never pass extra['wait']; poll every run with train_policy(action='status', provider='isaaclab', job_id=...),
using wait_minutes between polls. Early stopping: once all runs of a learning rate have reached iteration >= 100,
if that learning rate's best mean reward is clearly worse than the current leader's, stop_job its remaining
running jobs and do not launch its remaining seeds. When everything finished or was stopped, pick the best
(lr, seed) by final mean reward, and answer with a markdown table: lr | seed | job_id | status | iterations |
final reward | best reward | steps/s | stopped early? | checkpoint, then a 3-line recommendation."""
if __name__ == "__main__":
model = BedrockModel(model_id=os.environ.get("STRANDS_MODEL_ID", "global.anthropic.claude-sonnet-4-6"))
agent = Agent(model=model, tools=[train_policy, gpu_status, wait_minutes, stop_job],
system_prompt="You operate robot-learning tools carefully and report honestly.")
t0 = time.time()
res = agent(PROMPT)
(OUT / "answer.md").write_text(str(res))
(OUT / "transcript.json").write_text(json.dumps(agent.messages, indent=1, default=str))
print(f"\n[wall {time.time() - t0:.0f}s] answer saved to {OUT / 'answer.md'}")