Siddh12334 commited on
Commit
9bd2d99
Β·
verified Β·
1 Parent(s): 30bfe4c

fix: space_runner installs unsloth at click-time on live GPU

Browse files
Files changed (1) hide show
  1. training/space_runner.py +74 -62
training/space_runner.py CHANGED
@@ -1,8 +1,10 @@
1
  """
2
- Gradio UI for the training Space.
3
  Training does NOT start automatically β€” user must click "Start Training".
 
4
  """
5
  import os
 
6
  import sys
7
  import threading
8
  import time
@@ -14,7 +16,7 @@ from dotenv import load_dotenv
14
  load_dotenv()
15
 
16
  _log_lines: list[str] = []
17
- _training_status = "idle" # idle | running | complete | failed
18
 
19
 
20
  def _append_log(msg: str):
@@ -22,78 +24,91 @@ def _append_log(msg: str):
22
  _log_lines.append(f"[{ts}] {msg}")
23
 
24
 
25
- def _run_training():
26
- global _training_status
27
- _training_status = "running"
28
- _append_log("Training started.")
29
- try:
30
- # Redirect stdout so log lines appear in the UI
31
- import io
32
- import contextlib
33
 
34
- sys.path.insert(0, str(Path(__file__).parent.parent))
35
- from training.train_grpo import main
36
-
37
- # Capture print output
38
- old_stdout = sys.stdout
39
- old_stderr = sys.stderr
40
 
41
- class Tee:
42
- def __init__(self, orig):
43
- self._orig = orig
44
 
45
- def write(self, msg):
46
- if msg.strip():
47
- _append_log(msg.rstrip())
48
- self._orig.write(msg)
49
 
50
- def flush(self):
51
- self._orig.flush()
52
-
53
- sys.stdout = Tee(old_stdout)
54
- sys.stderr = Tee(old_stderr)
55
 
56
- try:
57
- main()
58
- finally:
59
- sys.stdout = old_stdout
60
- sys.stderr = old_stderr
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
62
  _training_status = "complete"
63
- _append_log("βœ… Training complete. Check WandB for curves.")
64
  except Exception as e:
65
  _training_status = "failed"
66
  _append_log(f"❌ Training failed: {e}")
 
 
 
67
 
68
 
69
  def start_training():
70
  global _training_status
71
- if _training_status == "running":
72
- return "⚠️ Training is already running.", _get_logs()
73
  if _training_status == "complete":
74
  return "βœ… Training already complete.", _get_logs()
75
 
76
- missing = []
77
- if not os.getenv("WANDB_API_KEY"):
78
- missing.append("WANDB_API_KEY")
79
- if not os.getenv("HF_TOKEN"):
80
- missing.append("HF_TOKEN")
81
- if not os.getenv("HF_HUB_MODEL_ID"):
82
- missing.append("HF_HUB_MODEL_ID")
83
  if missing:
84
- return f"❌ Missing secrets: {', '.join(missing)}. Set them in Space Settings β†’ Variables and secrets.", _get_logs()
85
 
 
 
 
 
 
 
86
  threading.Thread(target=_run_training, daemon=True).start()
87
- return "πŸš€ Training started! Logs updating below...", _get_logs()
88
 
89
 
90
  def _get_logs() -> str:
91
- return "\n".join(_log_lines[-80:]) if _log_lines else "No logs yet."
92
 
93
 
94
  def get_status() -> str:
95
- icons = {"idle": "⏸️ Idle", "running": "πŸ”„ Training in progress...",
96
- "complete": "βœ… Complete", "failed": "❌ Failed"}
 
 
 
 
 
97
  return icons.get(_training_status, _training_status)
98
 
99
 
@@ -106,32 +121,29 @@ def refresh():
106
  with gr.Blocks(title="ContextCorruption Training") as demo:
107
  gr.Markdown("""
108
  # ContextCorruption-Env β€” GRPO Training
109
- **Qwen2-1.5B-Instruct** fine-tuned to identify corrupted documents and resist misleading context.
110
 
111
- Before starting, ensure these secrets are set in **Space Settings β†’ Variables and secrets**:
112
- - `WANDB_API_KEY`
113
- - `HF_TOKEN`
114
- - `HF_HUB_MODEL_ID` (e.g. `Siddh12334/qwen-1.5b-context-corruption`)
115
  """)
116
 
117
- status_box = gr.Textbox(label="Status", value="⏸️ Idle", interactive=False)
118
- log_box = gr.Textbox(label="Training Logs", lines=20, interactive=False,
119
- value="Waiting to start...")
120
- msg_box = gr.Textbox(label="Message", interactive=False)
121
 
122
  with gr.Row():
123
- start_btn = gr.Button("πŸš€ Start Training", variant="primary", scale=2)
124
- refresh_btn = gr.Button("πŸ”„ Refresh Logs", scale=1)
125
 
126
  gr.Markdown("""
127
  ---
128
- **Config:** 500 episodes Β· 3 epochs Β· Qwen2-1.5B Β· LoRA r=16 Β· A10G ~1.5 hrs Β· ~$2
 
129
  """)
130
 
131
  start_btn.click(fn=start_training, outputs=[msg_box, log_box])
132
  refresh_btn.click(fn=refresh, outputs=[status_box, log_box])
133
-
134
- # Auto-refresh every 10s while running
135
  demo.load(fn=refresh, outputs=[status_box, log_box], every=10)
136
 
137
 
 
1
  """
2
+ Gradio UI for the HF training Space.
3
  Training does NOT start automatically β€” user must click "Start Training".
4
+ Unsloth is installed at click-time so it picks up the A100's CUDA correctly.
5
  """
6
  import os
7
+ import subprocess
8
  import sys
9
  import threading
10
  import time
 
16
  load_dotenv()
17
 
18
  _log_lines: list[str] = []
19
+ _training_status = "idle" # idle | installing | running | complete | failed
20
 
21
 
22
  def _append_log(msg: str):
 
24
  _log_lines.append(f"[{ts}] {msg}")
25
 
26
 
27
+ class _Tee:
28
+ def __init__(self, orig):
29
+ self._orig = orig
 
 
 
 
 
30
 
31
+ def write(self, msg):
32
+ if msg.strip():
33
+ _append_log(msg.rstrip())
34
+ self._orig.write(msg)
 
 
35
 
36
+ def flush(self):
37
+ self._orig.flush()
 
38
 
 
 
 
 
39
 
40
+ def _run_training():
41
+ global _training_status
 
 
 
42
 
43
+ # Step 1 β€” install unsloth on the live GPU
44
+ _training_status = "installing"
45
+ _append_log("Installing unsloth on GPU hardware...")
46
+ try:
47
+ subprocess.check_call(
48
+ [sys.executable, "-m", "pip", "install", "--quiet",
49
+ "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"],
50
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
51
+ )
52
+ _append_log("unsloth installed successfully.")
53
+ except subprocess.CalledProcessError as e:
54
+ _training_status = "failed"
55
+ _append_log(f"❌ unsloth install failed: {e}")
56
+ return
57
 
58
+ # Step 2 β€” run training
59
+ _training_status = "running"
60
+ _append_log("Starting GRPO training...")
61
+ old_out, old_err = sys.stdout, sys.stderr
62
+ sys.stdout = _Tee(old_out)
63
+ sys.stderr = _Tee(old_err)
64
+ try:
65
+ sys.path.insert(0, str(Path(__file__).parent.parent))
66
+ from training.train_grpo import main
67
+ main()
68
  _training_status = "complete"
69
+ _append_log("βœ… Training complete! Model pushed to HF Hub. Check WandB for curves.")
70
  except Exception as e:
71
  _training_status = "failed"
72
  _append_log(f"❌ Training failed: {e}")
73
+ finally:
74
+ sys.stdout = old_out
75
+ sys.stderr = old_err
76
 
77
 
78
  def start_training():
79
  global _training_status
80
+ if _training_status in ("installing", "running"):
81
+ return "⚠️ Already in progress.", _get_logs()
82
  if _training_status == "complete":
83
  return "βœ… Training already complete.", _get_logs()
84
 
85
+ missing = [k for k in ("WANDB_API_KEY", "HF_TOKEN", "HF_HUB_MODEL_ID")
86
+ if not os.getenv(k)]
 
 
 
 
 
87
  if missing:
88
+ return f"❌ Missing secrets: {', '.join(missing)}", _get_logs()
89
 
90
+ import torch
91
+ if not torch.cuda.is_available():
92
+ return "❌ No GPU detected. Upgrade Space hardware to A100 first.", _get_logs()
93
+
94
+ gpu = torch.cuda.get_device_name(0)
95
+ _append_log(f"GPU detected: {gpu}")
96
  threading.Thread(target=_run_training, daemon=True).start()
97
+ return f"πŸš€ Started on {gpu}. Installing unsloth...", _get_logs()
98
 
99
 
100
  def _get_logs() -> str:
101
+ return "\n".join(_log_lines[-100:]) if _log_lines else "No logs yet."
102
 
103
 
104
  def get_status() -> str:
105
+ icons = {
106
+ "idle": "⏸️ Idle β€” ready to start",
107
+ "installing": "βš™οΈ Installing unsloth on GPU...",
108
+ "running": "πŸ”„ Training in progress...",
109
+ "complete": "βœ… Training complete",
110
+ "failed": "❌ Failed β€” check logs",
111
+ }
112
  return icons.get(_training_status, _training_status)
113
 
114
 
 
121
  with gr.Blocks(title="ContextCorruption Training") as demo:
122
  gr.Markdown("""
123
  # ContextCorruption-Env β€” GRPO Training
124
+ Fine-tuning **Qwen2-1.5B-Instruct** to identify corrupted documents.
125
 
126
+ **Before clicking Start, confirm:**
127
+ - Space hardware is set to **A100 Large** (Settings β†’ Space hardware)
128
+ - Secrets are set: `WANDB_API_KEY` Β· `HF_TOKEN` Β· `HF_HUB_MODEL_ID`
 
129
  """)
130
 
131
+ status_box = gr.Textbox(label="Status", value=get_status(), interactive=False)
132
+ log_box = gr.Textbox(label="Live Logs", lines=25, interactive=False, value="Waiting...")
133
+ msg_box = gr.Textbox(label="", interactive=False)
 
134
 
135
  with gr.Row():
136
+ start_btn = gr.Button("πŸš€ Start Training", variant="primary", scale=2)
137
+ refresh_btn = gr.Button("πŸ”„ Refresh", scale=1)
138
 
139
  gr.Markdown("""
140
  ---
141
+ **Estimated time on A100:** ~30–45 min Β· **Cost:** ~$3–5 from your HF credits
142
+ After training, model is pushed to HF Hub and WandB has the reward/loss curves.
143
  """)
144
 
145
  start_btn.click(fn=start_training, outputs=[msg_box, log_box])
146
  refresh_btn.click(fn=refresh, outputs=[status_box, log_box])
 
 
147
  demo.load(fn=refresh, outputs=[status_box, log_box], every=10)
148
 
149