Update train.py
Browse files
train.py
CHANGED
|
@@ -1,21 +1,58 @@
|
|
| 1 |
# ==========================================
|
| 2 |
-
#
|
| 3 |
# ==========================================
|
| 4 |
import os
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
# os.system('pip install "torch>=2.4.0,<2.11.0" torchvision torchaudio')
|
| 7 |
# os.system('pip install unsloth unsloth_zoo')
|
| 8 |
-
# os.system('pip install "trl==0.22.0" peft accelerate bitsandbytes openenv-core datasets')
|
| 9 |
|
| 10 |
import re
|
| 11 |
import json
|
| 12 |
import torch
|
|
|
|
| 13 |
from tqdm import tqdm
|
| 14 |
from datasets import Dataset
|
| 15 |
from unsloth import FastLanguageModel
|
| 16 |
from trl import SFTTrainer
|
| 17 |
from transformers import TrainingArguments
|
| 18 |
|
|
|
|
| 19 |
from env import EnterpriseEmailEnv
|
| 20 |
|
| 21 |
# ==========================================
|
|
@@ -27,6 +64,7 @@ model, tokenizer = FastLanguageModel.from_pretrained(
|
|
| 27 |
max_seq_length = 512,
|
| 28 |
dtype = None,
|
| 29 |
load_in_4bit = True,
|
|
|
|
| 30 |
)
|
| 31 |
|
| 32 |
# Apply LoRA adapters
|
|
@@ -48,7 +86,6 @@ print("Initializing OpenEnv...")
|
|
| 48 |
env = EnterpriseEmailEnv()
|
| 49 |
|
| 50 |
def format_observation_to_prompt(obs):
|
| 51 |
-
"""Refined prompt that uses high-authority instructions for 3B model stability."""
|
| 52 |
current_email = obs.get('current_email', {})
|
| 53 |
email_id = current_email.get('email_id', 'UNKNOWN_ID')
|
| 54 |
sender = current_email.get('sender', 'Unknown')
|
|
@@ -57,24 +94,18 @@ def format_observation_to_prompt(obs):
|
|
| 57 |
|
| 58 |
prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
|
| 59 |
You are a Corporate Email Triage Agent. You must respond ONLY with a JSON object.
|
| 60 |
-
|
| 61 |
### AVAILABLE TOOLS:
|
| 62 |
1. {{"tool": "route_to_human", "arguments": {{"email_id": "{email_id}", "department": "IT/Support/HR"}}}}
|
| 63 |
*RULE: Use this for VIPs, Angry customers, Server Outages, or Sensitive HR issues.*
|
| 64 |
-
|
| 65 |
2. {{"tool": "auto_reply", "arguments": {{"email_id": "{email_id}", "message": "REPLY_TEXT"}}}}
|
| 66 |
*RULE: Use this for routine tasks like password resets or feature requests.*
|
| 67 |
-
|
| 68 |
3. {{"tool": "ask_for_clarification", "arguments": {{"email_id": "{email_id}"}}}}
|
| 69 |
*RULE: Use this only if the email is confusing or missing data.*
|
| 70 |
-
|
| 71 |
-
Always use the correct Email ID: {email_id}
|
| 72 |
-
<|eot_id|><|start_header_id|>user<|end_header_id|>
|
| 73 |
Email ID: {email_id}
|
| 74 |
From: {sender}
|
| 75 |
Subject: {subject}
|
| 76 |
-
Body: {body}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
| 77 |
-
"""
|
| 78 |
return prompt
|
| 79 |
|
| 80 |
def collect_rollouts(env, model, tokenizer, num_episodes=30):
|
|
@@ -182,5 +213,45 @@ sft_trainer.train()
|
|
| 182 |
print("Training completed! Saving LoRA adapters...")
|
| 183 |
model.save_pretrained("email-triage-lora-final")
|
| 184 |
tokenizer.save_pretrained("email-triage-lora-final")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
print("
|
|
|
|
| 1 |
# ==========================================
|
| 2 |
+
# 0. JUDGE-PROOF SETUP & AUTHENTICATION
|
| 3 |
# ==========================================
|
| 4 |
import os
|
| 5 |
+
import sys
|
| 6 |
+
import urllib.request
|
| 7 |
+
|
| 8 |
+
# β οΈ IMPORTANT: Change these to your exact Hugging Face username and Space name!
|
| 9 |
+
HF_USERNAME = "your-username"
|
| 10 |
+
SPACE_NAME = "enterprise-email-triage"
|
| 11 |
+
|
| 12 |
+
print("Checking for required environment files...")
|
| 13 |
+
files_to_download = ["env.py", "dataset.json", "reward_system.py"]
|
| 14 |
+
base_url = f"https://huggingface.co/spaces/{HF_USERNAME}/{SPACE_NAME}/resolve/main/"
|
| 15 |
+
|
| 16 |
+
for file in files_to_download:
|
| 17 |
+
if not os.path.exists(file):
|
| 18 |
+
print(f"Downloading {file} from repository...")
|
| 19 |
+
try:
|
| 20 |
+
urllib.request.urlretrieve(base_url + file, file)
|
| 21 |
+
print(f"β
{file} successfully downloaded.")
|
| 22 |
+
except Exception as e:
|
| 23 |
+
print(f"β Failed to download {file}. Is your Space Public?")
|
| 24 |
+
else:
|
| 25 |
+
print(f"β
{file} is already present.")
|
| 26 |
+
|
| 27 |
+
from huggingface_hub import login
|
| 28 |
+
|
| 29 |
+
hf_token = os.environ.get("HF_TOKEN")
|
| 30 |
+
if hf_token is None:
|
| 31 |
+
print("β CRITICAL ERROR: HF_TOKEN not found in environment variables!")
|
| 32 |
+
sys.exit(1)
|
| 33 |
+
else:
|
| 34 |
+
print("β
Secure token found. Logging in...")
|
| 35 |
+
login(token=hf_token)
|
| 36 |
+
|
| 37 |
+
# ==========================================
|
| 38 |
+
# 1. THE STABLE ENVIRONMENT INSTALL
|
| 39 |
+
# ==========================================
|
| 40 |
+
# (Commented out for local runs, judges will run these if necessary)
|
| 41 |
# os.system('pip install "torch>=2.4.0,<2.11.0" torchvision torchaudio')
|
| 42 |
# os.system('pip install unsloth unsloth_zoo')
|
| 43 |
+
# os.system('pip install "trl==0.22.0" peft accelerate bitsandbytes openenv-core datasets matplotlib pandas')
|
| 44 |
|
| 45 |
import re
|
| 46 |
import json
|
| 47 |
import torch
|
| 48 |
+
import matplotlib.pyplot as plt
|
| 49 |
from tqdm import tqdm
|
| 50 |
from datasets import Dataset
|
| 51 |
from unsloth import FastLanguageModel
|
| 52 |
from trl import SFTTrainer
|
| 53 |
from transformers import TrainingArguments
|
| 54 |
|
| 55 |
+
# Import the environment we just ensured exists
|
| 56 |
from env import EnterpriseEmailEnv
|
| 57 |
|
| 58 |
# ==========================================
|
|
|
|
| 64 |
max_seq_length = 512,
|
| 65 |
dtype = None,
|
| 66 |
load_in_4bit = True,
|
| 67 |
+
token = hf_token, # Explicitly passing the token here
|
| 68 |
)
|
| 69 |
|
| 70 |
# Apply LoRA adapters
|
|
|
|
| 86 |
env = EnterpriseEmailEnv()
|
| 87 |
|
| 88 |
def format_observation_to_prompt(obs):
|
|
|
|
| 89 |
current_email = obs.get('current_email', {})
|
| 90 |
email_id = current_email.get('email_id', 'UNKNOWN_ID')
|
| 91 |
sender = current_email.get('sender', 'Unknown')
|
|
|
|
| 94 |
|
| 95 |
prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
|
| 96 |
You are a Corporate Email Triage Agent. You must respond ONLY with a JSON object.
|
|
|
|
| 97 |
### AVAILABLE TOOLS:
|
| 98 |
1. {{"tool": "route_to_human", "arguments": {{"email_id": "{email_id}", "department": "IT/Support/HR"}}}}
|
| 99 |
*RULE: Use this for VIPs, Angry customers, Server Outages, or Sensitive HR issues.*
|
|
|
|
| 100 |
2. {{"tool": "auto_reply", "arguments": {{"email_id": "{email_id}", "message": "REPLY_TEXT"}}}}
|
| 101 |
*RULE: Use this for routine tasks like password resets or feature requests.*
|
|
|
|
| 102 |
3. {{"tool": "ask_for_clarification", "arguments": {{"email_id": "{email_id}"}}}}
|
| 103 |
*RULE: Use this only if the email is confusing or missing data.*
|
| 104 |
+
Always use the correct Email ID: {email_id}<|eot_id|><|start_header_id|>user<|end_header_id|>
|
|
|
|
|
|
|
| 105 |
Email ID: {email_id}
|
| 106 |
From: {sender}
|
| 107 |
Subject: {subject}
|
| 108 |
+
Body: {body}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
|
|
|
|
| 109 |
return prompt
|
| 110 |
|
| 111 |
def collect_rollouts(env, model, tokenizer, num_episodes=30):
|
|
|
|
| 213 |
print("Training completed! Saving LoRA adapters...")
|
| 214 |
model.save_pretrained("email-triage-lora-final")
|
| 215 |
tokenizer.save_pretrained("email-triage-lora-final")
|
| 216 |
+
print("SUCCESS: Model weights saved locally!")
|
| 217 |
+
|
| 218 |
+
# ==========================================
|
| 219 |
+
# 7. GENERATE HACKATHON EVIDENCE (PLOTS)
|
| 220 |
+
# ==========================================
|
| 221 |
+
print("Generating validation plots...")
|
| 222 |
+
|
| 223 |
+
# Plot 1: Training Loss
|
| 224 |
+
try:
|
| 225 |
+
history = sft_trainer.state.log_history
|
| 226 |
+
steps = [x['step'] for x in history if 'loss' in x]
|
| 227 |
+
loss = [x['loss'] for x in history if 'loss' in x]
|
| 228 |
+
|
| 229 |
+
if loss:
|
| 230 |
+
plt.figure(figsize=(10, 5))
|
| 231 |
+
plt.plot(steps, loss, color='#1f77b4', linewidth=2, label='Training Loss')
|
| 232 |
+
plt.title('Agent Training Loss: Enterprise Email Triage')
|
| 233 |
+
plt.xlabel('Step')
|
| 234 |
+
plt.ylabel('Loss')
|
| 235 |
+
plt.grid(True, linestyle='--', alpha=0.6)
|
| 236 |
+
plt.legend()
|
| 237 |
+
plt.savefig('training_loss.png')
|
| 238 |
+
print("β
Saved training_loss.png")
|
| 239 |
+
except Exception as e:
|
| 240 |
+
print(f"β οΈ Could not generate loss curve: {e}")
|
| 241 |
+
|
| 242 |
+
# Plot 2: Reward Distribution
|
| 243 |
+
try:
|
| 244 |
+
rewards = [item['reward'] for item in rollout_data]
|
| 245 |
+
if rewards:
|
| 246 |
+
plt.figure(figsize=(10, 5))
|
| 247 |
+
plt.hist(rewards, bins=10, color='green', alpha=0.7, edgecolor='black')
|
| 248 |
+
plt.title('Expert Rollout Reward Distribution')
|
| 249 |
+
plt.xlabel('Reward Value')
|
| 250 |
+
plt.ylabel('Frequency')
|
| 251 |
+
plt.axvline(0, color='red', linestyle='--')
|
| 252 |
+
plt.savefig('reward_curve.png')
|
| 253 |
+
print("β
Saved reward_curve.png")
|
| 254 |
+
except Exception as e:
|
| 255 |
+
print(f"β οΈ Could not generate reward curve: {e}")
|
| 256 |
|
| 257 |
+
print("π ALL TASKS COMPLETE. Script is ready for judging!")
|