Spaces:
Running
Running
Commit ·
2c70945
1
Parent(s): 7208b31
feat: add persistent training logging and organize real graph artifacts
Browse filesAutomate saving TRL training logs, metrics, and loss/reward plots after each run, and reorganize repository graph evidence into dedicated Colab and HF folders while removing synthetic graph artifacts.
Made-with: Cursor
Files changed (10)
- README.md+28-4
- colab_graphs/baseline_comparison.pngAdded
- colab_graphs/loss_curve_run2.pngAdded
- colab_graphs/reward_curve_run2.pngAdded
- training_plot.png → colab_graphs/training_plot_run1.pngRenamed
- colab_qlora_grpo_fleet.py+16-39
- hf_graphs/.gitkeepAdded+1
- plot_run2.pyAdded+23
- training_logging.pyAdded+176
- training_results.json+81-6
24 unmodified lines25262728293031323334353637383924 unmodified lines## Hackathon Submission Links- **Hugging Face Space**: [https://huggingface.co/spaces/SnippyCodes/Libratio](https://huggingface.co/spaces/SnippyCodes/Libratio)- **2-Minute Demo Video**: [Insert YouTube URL Here]- **Training Script (Colab)**: [Run in Google Colab](https://colab.research.google.com/drive/1O74FkE8YCkren_sJHmx_p0i3hLAQ9Ylv)---## Training Evidence*Figure 1: GRPO training log from Colab showing the Llama-3.1-8B model's reward steadily increasing as it learns to statelessly detect precision-induced NaN crashes and format valid JSON actions.*---24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626324 unmodified lines## Hackathon Submission Links- **Hugging Face Space**: [https://huggingface.co/spaces/SnippyCodes/Libratio](https://huggingface.co/spaces/SnippyCodes/Libratio)- **Environment Manifest**: [`openenv.yaml`](./openenv.yaml)- **Training Script (Colab, Unsloth + TRL/GRPO)**: [Run in Google Colab](https://colab.research.google.com/drive/1O74FkE8YCkren_sJHmx_p0i3hLAQ9Ylv)- **Standalone Colab Script (single-cell)**: [`colab_qlora_grpo_fleet.py`](./colab_qlora_grpo_fleet.py)- **Training Results JSON (real run artifact)**: [`training_results.json`](./training_results.json)- **Writeup / Video / Slides**: _Add your public URL here before final submission_---## Training Evidence*Figure 1: GRPO reward curve from a real training run (`run2`), with reward tracked against training step.**Figure 2: GRPO loss curve from the same run, showing optimization behavior over steps.**Figure 3: Baseline comparison plot used to contrast trained policy behavior against baseline performance.*- **Colab graphs folder**: [`colab_graphs/`](./colab_graphs)- **HF graphs folder**: [`hf_graphs/`](./hf_graphs)---## Submission Checklist (Minimum Requirements)- [x] Built on **OpenEnv** with valid manifest: [`openenv.yaml`](./openenv.yaml)- [x] Working training pipeline using **Unsloth + Hugging Face TRL (GRPO)**: [`colab_qlora_grpo_fleet.py`](./colab_qlora_grpo_fleet.py) and [Colab notebook](https://colab.research.google.com/drive/1O74FkE8YCkren_sJHmx_p0i3hLAQ9Ylv)- [x] Evidence of training committed: `reward`/`loss` plots + [`training_results.json`](./training_results.json)- [x] Environment published on Hugging Face Space: [SnippyCodes/Libratio](https://huggingface.co/spaces/SnippyCodes/Libratio)- [x] README explains problem, environment design, and results- [ ] Add final writeup asset link (HF blog post, <2 min YouTube video, or slides)- [ ] Ensure final writeup/video/slides URL is linked in this README before submission---
25 unmodified lines262728293031213 unmodified lines24524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628714 unmodified lines30230330430530625 unmodified lines# ── Step 2: Clone your repo ────────────────────────────────import osimport subprocessREPO_URL = "https://github.com/SnippyCodes/Libratio.git" # <-- UPDATE THIS to your actual GitHub repo URLREPO_DIR = "./Libratio"213 unmodified linestrainer.train()# ── Step 7.5: Plot Training Curves ─────────────────────────import matplotlib.pyplot as plthistory = trainer.state.log_historysteps = []rewards = []losses = []for log in history:if "step" in log:if "reward" in log:steps.append(log["step"])rewards.append(log["reward"])if "loss" in log:losses.append(log["loss"])if steps and rewards:plt.figure(figsize=(10, 5))plt.plot(steps, rewards, marker='o', color='g', label='Mean Reward')plt.title('GRPO Training: Mean Fleet Reward')plt.xlabel('Steps')plt.ylabel('Reward')plt.grid(True)plt.savefig('reward_curve.png')plt.show()if losses:# Match the steps length to the losses length for plottingloss_steps = [log["step"] for log in history if "loss" in log]plt.figure(figsize=(10, 5))plt.plot(loss_steps, losses, marker='o', color='r', label='Training Loss')plt.title('GRPO Training: Loss')plt.xlabel('Steps')plt.ylabel('Loss')plt.grid(True)plt.savefig('loss_curve.png')plt.show()# ── Step 8: Save results ───────────────────────────────────trainer.save_model(OUT_DIR)14 unmodified linesprint(" from google.colab import files")print(" !zip -r fleet_model.zip ./results")print(" files.download('fleet_model.zip')")print(" files.download('reward_curve.png')")print(" files.download('loss_curve.png')")25 unmodified lines26272829303132213 unmodified lines24624724824925025125225325425525625725825926026126226326414 unmodified lines27928028128228325 unmodified lines# ── Step 2: Clone your repo ────────────────────────────────import osimport subprocessfrom datetime import datetimeREPO_URL = "https://github.com/SnippyCodes/Libratio.git" # <-- UPDATE THIS to your actual GitHub repo URLREPO_DIR = "./Libratio"213 unmodified linestrainer.train()# ── Step 7.5: Persist logs + auto-generate plots ───────────from training_logging import save_trl_training_artifactsrun_id = datetime.utcnow().strftime("%Y%m%d_%H%M%S")artifact_paths = save_trl_training_artifacts(log_history=trainer.state.log_history,output_dir="./results/training_logs",run_name=f"grpo_fleet_{run_id}",)print("\nSaved training artifacts:")for key, value in artifact_paths.items():if value:print(f" - {key}: {value}")# ── Step 8: Save results ───────────────────────────────────trainer.save_model(OUT_DIR)14 unmodified linesprint(" from google.colab import files")print(" !zip -r fleet_model.zip ./results")print(" files.download('fleet_model.zip')")print(" files.download('<path-from-artifact_paths.reward_curve_png>')")print(" files.download('<path-from-artifact_paths.loss_curve_png>')")
1
1234567891011121314151617181920212223import matplotlib.pyplot as plt
steps = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]losses = [0.000000, 0.000000, 0.000002, 0.000007, 0.000016, 0.000021, 0.000034, 0.000040, 0.000049, 0.000057]rewards = [0.185827, 0.351165, 0.489893, 0.609637, 0.611199, 0.757431, 0.778288, 0.742079, 0.846850, 0.824075]
plt.figure(figsize=(10, 5))plt.plot(steps, rewards, marker='o', color='g', label='Mean Reward')plt.title('GRPO Training Run 2: Mean Fleet Reward')plt.xlabel('Steps')plt.ylabel('Reward')plt.grid(True)plt.savefig('reward_curve_run2.png')print("Saved reward_curve_run2.png")
plt.figure(figsize=(10, 5))plt.plot(steps, losses, marker='o', color='r', label='Training Loss')plt.title('GRPO Training Run 2: Loss')plt.xlabel('Steps')plt.ylabel('Loss')plt.grid(True)plt.savefig('loss_curve_run2.png')print("Saved loss_curve_run2.png")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""Utility helpers to persist training artifacts after every run.
Designed for TRL/Hugging Face trainer logs (`trainer.state.log_history`)."""
from __future__ import annotations
import csvimport jsonfrom datetime import datetimefrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence, Tuple
import matplotlib.pyplot as plt
def _as_float(value) -> Optional[float]: try: return float(value) except (TypeError, ValueError): return None
def _extract_series( log_history: Sequence[Dict], candidate_keys: Sequence[str],) -> Tuple[List[float], List[float], Optional[str]]: steps: List[float] = [] values: List[float] = [] key_used: Optional[str] = None
for entry in log_history: if "step" not in entry: continue
step = _as_float(entry.get("step")) if step is None: continue
for key in candidate_keys: val = _as_float(entry.get(key)) if val is None: continue steps.append(step) values.append(val) key_used = key break
return steps, values, key_used
def _save_plot( x: Sequence[float], y: Sequence[float], *, title: str, xlabel: str, ylabel: str, output_path: Path, color: str,) -> None: plt.figure(figsize=(10, 5)) plt.plot(x, y, marker="o", linewidth=1.8, markersize=3, color=color) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.grid(True, linestyle="--", alpha=0.5) plt.tight_layout() plt.savefig(output_path, dpi=220) plt.close()
def save_trl_training_artifacts( *, log_history: Sequence[Dict], output_dir: str = "results/training_logs", run_name: str = "run",) -> Dict[str, str]: """ Persist TRL training artifacts for reproducibility and README evidence.
Saves: - <run_name>_log_history.json - <run_name>_log_history.csv - <run_name>_loss_curve.png (if loss exists) - <run_name>_reward_curve.png (if reward exists) - <run_name>_metrics_summary.json """ out_dir = Path(output_dir) out_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.utcnow().isoformat(timespec="seconds") + "Z" base = run_name.strip().replace(" ", "_") or "run"
log_json_path = out_dir / f"{base}_log_history.json" log_csv_path = out_dir / f"{base}_log_history.csv" loss_plot_path = out_dir / f"{base}_loss_curve.png" reward_plot_path = out_dir / f"{base}_reward_curve.png" summary_path = out_dir / f"{base}_metrics_summary.json"
# 1) Raw JSON history with log_json_path.open("w", encoding="utf-8") as f: json.dump(list(log_history), f, indent=2, ensure_ascii=True)
# 2) Flat CSV history all_keys = sorted({k for row in log_history for k in row.keys()}) with log_csv_path.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=all_keys) writer.writeheader() for row in log_history: writer.writerow(row)
# 3) Extract common loss/reward keys from TRL logs loss_steps, losses, loss_key = _extract_series(log_history, ["loss", "train/loss"]) reward_steps, rewards, reward_key = _extract_series( log_history, [ "reward", "rewards/mean", "objective/rlhf_reward", "train/reward", ], )
if losses: _save_plot( loss_steps, losses, title=f"Training Loss ({base})", xlabel="Training Step", ylabel="Loss", output_path=loss_plot_path, color="#d62728", )
if rewards: _save_plot( reward_steps, rewards, title=f"Training Reward ({base})", xlabel="Training Step", ylabel="Reward", output_path=reward_plot_path, color="#2ca02c", )
# 4) Summary metrics summary = { "run_name": base, "timestamp_utc": timestamp, "num_log_entries": len(log_history), "loss_key_used": loss_key, "reward_key_used": reward_key, "final_loss": losses[-1] if losses else None, "best_loss": min(losses) if losses else None, "final_reward": rewards[-1] if rewards else None, "best_reward": max(rewards) if rewards else None, "outputs": { "log_history_json": str(log_json_path), "log_history_csv": str(log_csv_path), "loss_curve_png": str(loss_plot_path) if losses else None, "reward_curve_png": str(reward_plot_path) if rewards else None, }, }
with summary_path.open("w", encoding="utf-8") as f: json.dump(summary, f, indent=2, ensure_ascii=True)
return { "log_history_json": str(log_json_path), "log_history_csv": str(log_csv_path), "loss_curve_png": str(loss_plot_path) if losses else "", "reward_curve_png": str(reward_plot_path) if rewards else "", "metrics_summary_json": str(summary_path), }3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738393 unmodified lines1,2,3,4],"rewards": [1.7713999999999999,2.60783515625,3.44827109375,2.6079265625,1.7713999999999999],"avg_step_rewards": [0.8856999999999999,0.8692783854166667,0.8620677734375,0.8693088541666666,0.8856999999999999],"final_step_rewards": [0.8956999999999999,0.89504375,0.894850390625,0.9004015625,0.8956999999999999],"num_steps": [2,3,4,3,2],"best_reward": 3.44827109375,"successes": 5}3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131143 unmodified lines1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],"rewards": [2.63123125,1.76586875,1.7713999999999999,1.7713999999999999,1.7713999999999999,2.60783515625,2.6079265625,2.6079265625,2.6066416666666665,3.44827109375,3.44827109375,2.6079265625,2.60783515625,2.6066416666666665,2.6079265625,1.7713999999999999,2.6079265625,3.44827109375,1.7713999999999999,2.63123125],"avg_step_rewards": [0.8770770833333333,0.882934375,0.8856999999999999,0.8856999999999999,0.8856999999999999,0.8692783854166667,0.8693088541666666,0.8693088541666666,0.8688805555555555,0.8620677734375,0.8620677734375,0.8693088541666666,0.8692783854166667,0.8688805555555555,0.8693088541666666,0.8856999999999999,0.8693088541666666,0.8620677734375,0.8856999999999999,0.8770770833333333],"final_step_rewards": [0.908065625,0.907803125,0.8956999999999999,0.8956999999999999,0.8956999999999999,0.89504375,0.9004015625,0.9004015625,0.9063916666666667,0.894850390625,0.894850390625,0.9004015625,0.89504375,0.9063916666666667,0.9004015625,0.8956999999999999,0.9004015625,0.894850390625,0.8956999999999999,0.908065625],"num_steps": [3,2,2,2,2,3,3,3,3,4,4,3,3,3,3,2,3,4,2,3],"best_reward": 3.44827109375,"successes": 20}
README.md+28-4
colab_graphs/baseline_comparison.pngAdded

Large File Pointer Details
- SHA256: 8e879efafe0906bb4a83ad5905aed62f6cc5a63167577e550920c61b500d2a48
- Pointer size: 131 Bytes
- Size of remote file: 113 kB
colab_graphs/loss_curve_run2.pngAdded

Large File Pointer Details
- SHA256: a05816d541cbb98cdf8f5dcc21e8d4f46dcab3385325f1b319a2a486f2262423
- Pointer size: 130 Bytes
- Size of remote file: 22 kB
colab_graphs/reward_curve_run2.pngAdded

Large File Pointer Details
- SHA256: 382946a21b855ea5a65808e225fe72bbd33425fdff031dcc00d3656d477a7e5a
- Pointer size: 130 Bytes
- Size of remote file: 28.6 kB
training_plot.png → colab_graphs/training_plot_run1.pngRenamed

Large File Pointer Details
- SHA256: 8baa911781da93915fa2d45328ec07cc7a8687496d126c3b5bcc3a628dbf782e
- Pointer size: 131 Bytes
- Size of remote file: 219 kB

Large File Pointer Details
- SHA256: 8baa911781da93915fa2d45328ec07cc7a8687496d126c3b5bcc3a628dbf782e
- Pointer size: 131 Bytes
- Size of remote file: 219 kB
colab_qlora_grpo_fleet.py+16-39
hf_graphs/.gitkeepAdded+1
plot_run2.pyAdded+23
training_logging.pyAdded+176
training_results.json+81-6