Spaces:
Runtime error
Runtime error
Update grpo_train.py
Browse files- grpo_train.py +75 -31
grpo_train.py
CHANGED
|
@@ -1,12 +1,29 @@
|
|
| 1 |
# grpo_train.py
|
| 2 |
|
| 3 |
import os
|
|
|
|
| 4 |
os.environ.setdefault("USER", "user")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
import time
|
| 7 |
import json
|
| 8 |
import random
|
| 9 |
import requests
|
|
|
|
|
|
|
| 10 |
import torch
|
| 11 |
|
| 12 |
from datasets import Dataset
|
|
@@ -19,6 +36,8 @@ PatchFastRL("GRPO", FastLanguageModel)
|
|
| 19 |
# CONFIG
|
| 20 |
# =========================
|
| 21 |
|
|
|
|
|
|
|
| 22 |
ENV_URL = os.getenv("ENV_URL", "https://parth-1-metaguard.hf.space")
|
| 23 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 24 |
HF_REPO = os.getenv("HF_REPO", "")
|
|
@@ -34,46 +53,57 @@ ALLOWED_ACTIONS = [
|
|
| 34 |
# =========================
|
| 35 |
|
| 36 |
def ensure_env_ready():
|
| 37 |
-
for i in range(
|
| 38 |
try:
|
| 39 |
r = requests.post(
|
| 40 |
f"{ENV_URL}/reset",
|
| 41 |
json={"task_id": "task_1_healthcare"},
|
| 42 |
-
timeout=
|
| 43 |
)
|
| 44 |
if r.status_code == 200:
|
| 45 |
-
print("Environment ready")
|
| 46 |
return
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# =========================
|
| 53 |
# ENV CLIENT
|
| 54 |
# =========================
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
class EnvClient:
|
| 57 |
def __init__(self, url):
|
| 58 |
self.url = url
|
|
|
|
| 59 |
|
| 60 |
def reset(self, task_id):
|
| 61 |
-
return
|
| 62 |
-
f"{self.url}/reset", json={"task_id": task_id}, timeout=
|
| 63 |
).json()
|
| 64 |
|
| 65 |
def step(self, action):
|
| 66 |
-
return
|
| 67 |
-
f"{self.url}/step", json={"action": action}, timeout=
|
| 68 |
).json()
|
| 69 |
|
| 70 |
def safe_step(client, action):
|
| 71 |
-
for
|
| 72 |
try:
|
| 73 |
return client.step(action)
|
| 74 |
except Exception:
|
| 75 |
-
time.sleep(
|
| 76 |
-
return {"reward": -0.3}
|
| 77 |
|
| 78 |
def extract_json(text):
|
| 79 |
try:
|
|
@@ -631,7 +661,7 @@ trainer = GRPOTrainer(
|
|
| 631 |
model=model,
|
| 632 |
reward_funcs=[reward_environment],
|
| 633 |
args=GRPOConfig(
|
| 634 |
-
output_dir=
|
| 635 |
learning_rate=5e-6,
|
| 636 |
num_train_epochs=3,
|
| 637 |
per_device_train_batch_size=4,
|
|
@@ -656,35 +686,49 @@ trainer = GRPOTrainer(
|
|
| 656 |
if __name__ == "__main__":
|
| 657 |
ensure_env_ready()
|
| 658 |
|
| 659 |
-
|
| 660 |
-
|
| 661 |
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
|
| 666 |
print("Merging adapter into base model...")
|
| 667 |
merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(
|
| 668 |
-
model_name=
|
| 669 |
load_in_4bit=False,
|
| 670 |
max_seq_length=2048,
|
| 671 |
)
|
| 672 |
merged_model.save_pretrained_merged(
|
| 673 |
-
|
| 674 |
merged_tokenizer,
|
| 675 |
save_method="merged_16bit",
|
| 676 |
)
|
| 677 |
-
print("Merged model saved to
|
| 678 |
|
| 679 |
if HF_REPO:
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 688 |
else:
|
| 689 |
print("Set HF_REPO env var to auto-push to Hub (skipped).")
|
| 690 |
|
|
|
|
| 1 |
# grpo_train.py
|
| 2 |
|
| 3 |
import os
|
| 4 |
+
|
| 5 |
os.environ.setdefault("USER", "user")
|
| 6 |
+
os.environ.setdefault("HOME", "/tmp/home")
|
| 7 |
+
os.environ.setdefault("HF_HOME", "/tmp/hf_home")
|
| 8 |
+
os.environ.setdefault("TRANSFORMERS_CACHE", "/tmp/hf_home/transformers")
|
| 9 |
+
os.environ.setdefault("TRITON_CACHE_DIR", "/tmp/triton_cache")
|
| 10 |
+
os.environ.setdefault("TORCH_EXTENSIONS_DIR", "/tmp/torch_ext")
|
| 11 |
+
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/cache")
|
| 12 |
+
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
|
| 13 |
+
|
| 14 |
+
for _d in [
|
| 15 |
+
"/tmp/home", "/tmp/hf_home", "/tmp/hf_home/transformers",
|
| 16 |
+
"/tmp/triton_cache", "/tmp/torch_ext", "/tmp/cache",
|
| 17 |
+
"/tmp/mpl", "/tmp/outputs",
|
| 18 |
+
]:
|
| 19 |
+
os.makedirs(_d, exist_ok=True)
|
| 20 |
|
| 21 |
import time
|
| 22 |
import json
|
| 23 |
import random
|
| 24 |
import requests
|
| 25 |
+
from requests.adapters import HTTPAdapter
|
| 26 |
+
from urllib3.util.retry import Retry
|
| 27 |
import torch
|
| 28 |
|
| 29 |
from datasets import Dataset
|
|
|
|
| 36 |
# CONFIG
|
| 37 |
# =========================
|
| 38 |
|
| 39 |
+
OUTPUT_DIR = "/tmp/outputs"
|
| 40 |
+
|
| 41 |
ENV_URL = os.getenv("ENV_URL", "https://parth-1-metaguard.hf.space")
|
| 42 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 43 |
HF_REPO = os.getenv("HF_REPO", "")
|
|
|
|
| 53 |
# =========================
|
| 54 |
|
| 55 |
def ensure_env_ready():
|
| 56 |
+
for i in range(60):
|
| 57 |
try:
|
| 58 |
r = requests.post(
|
| 59 |
f"{ENV_URL}/reset",
|
| 60 |
json={"task_id": "task_1_healthcare"},
|
| 61 |
+
timeout=15,
|
| 62 |
)
|
| 63 |
if r.status_code == 200:
|
| 64 |
+
print(f"Environment ready (attempt {i+1})")
|
| 65 |
return
|
| 66 |
+
print(f"Env returned {r.status_code}, retrying...")
|
| 67 |
+
except Exception as e:
|
| 68 |
+
if i % 10 == 0:
|
| 69 |
+
print(f"Env not ready (attempt {i+1}): {e}")
|
| 70 |
+
time.sleep(2)
|
| 71 |
+
raise RuntimeError("ENV not reachable after 60 attempts")
|
| 72 |
|
| 73 |
# =========================
|
| 74 |
# ENV CLIENT
|
| 75 |
# =========================
|
| 76 |
|
| 77 |
+
def _build_session():
|
| 78 |
+
s = requests.Session()
|
| 79 |
+
retries = Retry(total=3, backoff_factor=0.5,
|
| 80 |
+
status_forcelist=[500, 502, 503, 504])
|
| 81 |
+
s.mount("https://", HTTPAdapter(max_retries=retries))
|
| 82 |
+
s.mount("http://", HTTPAdapter(max_retries=retries))
|
| 83 |
+
return s
|
| 84 |
+
|
| 85 |
class EnvClient:
|
| 86 |
def __init__(self, url):
|
| 87 |
self.url = url
|
| 88 |
+
self.session = _build_session()
|
| 89 |
|
| 90 |
def reset(self, task_id):
|
| 91 |
+
return self.session.post(
|
| 92 |
+
f"{self.url}/reset", json={"task_id": task_id}, timeout=15,
|
| 93 |
).json()
|
| 94 |
|
| 95 |
def step(self, action):
|
| 96 |
+
return self.session.post(
|
| 97 |
+
f"{self.url}/step", json={"action": action}, timeout=15,
|
| 98 |
).json()
|
| 99 |
|
| 100 |
def safe_step(client, action):
|
| 101 |
+
for attempt in range(5):
|
| 102 |
try:
|
| 103 |
return client.step(action)
|
| 104 |
except Exception:
|
| 105 |
+
time.sleep(1.0 * (attempt + 1))
|
| 106 |
+
return {"reward": -0.3, "status_message": "timeout"}
|
| 107 |
|
| 108 |
def extract_json(text):
|
| 109 |
try:
|
|
|
|
| 661 |
model=model,
|
| 662 |
reward_funcs=[reward_environment],
|
| 663 |
args=GRPOConfig(
|
| 664 |
+
output_dir=OUTPUT_DIR,
|
| 665 |
learning_rate=5e-6,
|
| 666 |
num_train_epochs=3,
|
| 667 |
per_device_train_batch_size=4,
|
|
|
|
| 686 |
if __name__ == "__main__":
|
| 687 |
ensure_env_ready()
|
| 688 |
|
| 689 |
+
LORA_DIR = os.path.join(OUTPUT_DIR, "lora_adapter")
|
| 690 |
+
MERGED_DIR = os.path.join(OUTPUT_DIR, "merged")
|
| 691 |
|
| 692 |
+
print("Starting GRPO training...")
|
| 693 |
+
try:
|
| 694 |
+
trainer.train()
|
| 695 |
+
except torch.cuda.OutOfMemoryError:
|
| 696 |
+
print("OOM detected! Clearing cache and retrying with batch_size=2, num_generations=4...")
|
| 697 |
+
torch.cuda.empty_cache()
|
| 698 |
+
trainer.args.per_device_train_batch_size = 2
|
| 699 |
+
trainer.args.num_generations = 4
|
| 700 |
+
trainer.train()
|
| 701 |
+
|
| 702 |
+
model.save_pretrained(LORA_DIR)
|
| 703 |
+
tokenizer.save_pretrained(LORA_DIR)
|
| 704 |
+
print(f"LoRA adapter saved to {LORA_DIR}")
|
| 705 |
|
| 706 |
print("Merging adapter into base model...")
|
| 707 |
merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(
|
| 708 |
+
model_name=LORA_DIR,
|
| 709 |
load_in_4bit=False,
|
| 710 |
max_seq_length=2048,
|
| 711 |
)
|
| 712 |
merged_model.save_pretrained_merged(
|
| 713 |
+
MERGED_DIR,
|
| 714 |
merged_tokenizer,
|
| 715 |
save_method="merged_16bit",
|
| 716 |
)
|
| 717 |
+
print(f"Merged model saved to {MERGED_DIR}")
|
| 718 |
|
| 719 |
if HF_REPO:
|
| 720 |
+
try:
|
| 721 |
+
print(f"Pushing merged model to {HF_REPO}...")
|
| 722 |
+
merged_model.push_to_hub_merged(
|
| 723 |
+
HF_REPO,
|
| 724 |
+
merged_tokenizer,
|
| 725 |
+
save_method="merged_16bit",
|
| 726 |
+
token=HF_TOKEN,
|
| 727 |
+
)
|
| 728 |
+
print(f"Model live at https://huggingface.co/{HF_REPO}")
|
| 729 |
+
except Exception as e:
|
| 730 |
+
print(f"Hub push failed: {e}")
|
| 731 |
+
print(f"Model is still saved locally at {MERGED_DIR}")
|
| 732 |
else:
|
| 733 |
print("Set HF_REPO env var to auto-push to Hub (skipped).")
|
| 734 |
|