TheJackBright commited on
Commit
d8ba5fb
Β·
verified Β·
1 Parent(s): 0cd4d8e

Upload hf_sft_train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hf_sft_train.py +268 -0
hf_sft_train.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = [
3
+ # "torch>=2.2.0",
4
+ # "transformers>=4.40.0",
5
+ # "trl>=1.2.0",
6
+ # "peft>=0.10.0",
7
+ # "accelerate>=0.27.0",
8
+ # "bitsandbytes>=0.43.0",
9
+ # "datasets>=2.18.0",
10
+ # "huggingface-hub>=0.22.0",
11
+ # "trackio",
12
+ # "pydantic>=2.0",
13
+ # "numpy>=1.24",
14
+ # "pandas>=2.0",
15
+ # "matplotlib>=3.8",
16
+ # "tqdm>=4.60",
17
+ # "networkx>=3.0",
18
+ # "scipy>=1.10",
19
+ # "fastapi>=0.100",
20
+ # "uvicorn>=0.22",
21
+ # "httpx>=0.24",
22
+ # "pyyaml>=6.0",
23
+ # ]
24
+ # ///
25
+ """
26
+ PolyGuard SFT Training Job β€” runs on Hugging Face Jobs cloud GPU.
27
+
28
+ This script:
29
+ 1. Clones the project from GitHub
30
+ 2. Installs the polyguard-rl package
31
+ 3. Generates the SFT dataset from the PolyGuard environment
32
+ 4. Fine-tunes Qwen2.5-1.5B-Instruct with LoRA via TRL SFTTrainer
33
+ 5. Pushes the LoRA adapter + tokenizer to the Hugging Face Hub
34
+
35
+ Submit via CLI:
36
+ hf jobs uv run \
37
+ --flavor a10g-large \
38
+ --timeout 3h \
39
+ --secrets HF_TOKEN \
40
+ "https://huggingface.co/TheJackBright/polyguard-training-scripts/resolve/main/hf_sft_train.py"
41
+
42
+ Environment variables (passed as --env or via job secrets):
43
+ HF_TOKEN : HF write token (required for Hub push)
44
+ GITHUB_REPO : override GitHub repo URL (optional)
45
+ MODEL_NAME : base model (default: Qwen/Qwen2.5-1.5B-Instruct)
46
+ HUB_MODEL_ID : output model repo on Hub (default: TheJackBright/polyguard-qwen-sft)
47
+ N_EPISODES : SFT dataset episodes (default: 500)
48
+ EPOCHS : training epochs (default: 3)
49
+ BATCH_SIZE : per-device batch size (default: 2)
50
+ GRAD_ACCUM : gradient accumulation steps (default: 8)
51
+ MAX_LENGTH : max token length (default: 1024)
52
+ LEARNING_RATE : learning rate (default: 2e-4)
53
+ LORA_RANK : LoRA rank (default: 16)
54
+ """
55
+ from __future__ import annotations
56
+
57
+ import inspect
58
+ import json
59
+ import os
60
+ import random
61
+ import subprocess
62
+ import sys
63
+ from pathlib import Path
64
+ from typing import Any, Dict, List, Optional
65
+
66
+ # ─── Config from environment ────────────────────────────────────────────────
67
+ GITHUB_REPO = os.environ.get("GITHUB_REPO", "https://github.com/Vishwa-docs/Meta_PyTorch_Scalar_OpenEnv-Hackathon.git")
68
+ MODEL_NAME = os.environ.get("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct")
69
+ HUB_MODEL_ID = os.environ.get("HUB_MODEL_ID", "TheJackBright/polyguard-qwen-sft")
70
+ N_EPISODES = int(os.environ.get("N_EPISODES", "500"))
71
+ EPOCHS = int(os.environ.get("EPOCHS", "3"))
72
+ BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "2"))
73
+ GRAD_ACCUM = int(os.environ.get("GRAD_ACCUM", "8"))
74
+ MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "1024"))
75
+ LEARNING_RATE = float(os.environ.get("LEARNING_RATE", "2e-4"))
76
+ LORA_RANK = int(os.environ.get("LORA_RANK", "16"))
77
+ SEED = 42
78
+ OUTPUT_DIR = "/tmp/polyguard_sft_output"
79
+ DATA_PATH = "/tmp/polyguard_sft_data.jsonl"
80
+ DATA_FMT_PATH = "/tmp/polyguard_sft_data_formatted.jsonl"
81
+
82
+ SYSTEM_PROMPT = (
83
+ "You are a clinical pharmacist agent performing polypharmacy medication review. "
84
+ "Analyze drug-drug interactions, Beers criteria violations, and propose safe interventions. "
85
+ "Respond only with a structured <decision>...</decision> XML action."
86
+ )
87
+
88
+ print("=" * 60)
89
+ print("PolyGuard SFT Training on HF Jobs")
90
+ print(f" Model: {MODEL_NAME}")
91
+ print(f" Hub output: {HUB_MODEL_ID}")
92
+ print(f" Episodes: {N_EPISODES}")
93
+ print(f" Epochs: {EPOCHS}")
94
+ print(f" Batch size: {BATCH_SIZE} x {GRAD_ACCUM} grad accum")
95
+ print(f" Max length: {MAX_LENGTH}")
96
+ print(f" LoRA rank: {LORA_RANK}")
97
+ print("=" * 60)
98
+
99
+
100
+ # ─── Step 1: Clone repo and install polyguard-rl ────────────────────────────
101
+ print("\n[1/5] Cloning project from GitHub...")
102
+ clone_dir = Path("/tmp/polyguard_project")
103
+ if not clone_dir.exists():
104
+ subprocess.run(
105
+ ["git", "clone", "--depth=1", GITHUB_REPO, str(clone_dir)],
106
+ check=True,
107
+ )
108
+ print(f" Cloned to {clone_dir}")
109
+ else:
110
+ print(f" Already cloned at {clone_dir}")
111
+
112
+ polyguard_rl_dir = clone_dir / "polyguard-rl"
113
+ print(f"\n[2/5] Installing polyguard-rl from {polyguard_rl_dir}...")
114
+ subprocess.run(
115
+ [sys.executable, "-m", "pip", "install", "-e", str(polyguard_rl_dir), "--quiet"],
116
+ check=True,
117
+ )
118
+ print(" polyguard-rl installed.")
119
+
120
+ # Add to sys.path so relative imports work during dataset generation
121
+ if str(polyguard_rl_dir) not in sys.path:
122
+ sys.path.insert(0, str(polyguard_rl_dir))
123
+
124
+
125
+ # ─── Step 2: Generate SFT dataset ───────────────────────────────────────────
126
+ print(f"\n[3/5] Generating SFT dataset ({N_EPISODES} episodes)...")
127
+
128
+ os.chdir(polyguard_rl_dir)
129
+
130
+ from app.training.sft_dataset import generate_sft_dataset, build_external_ddi_sft_examples, format_for_training # noqa: E402
131
+
132
+ examples = generate_sft_dataset(
133
+ n_episodes=N_EPISODES,
134
+ seed=SEED,
135
+ output_path=DATA_PATH,
136
+ )
137
+
138
+ print(f" Generated {len(examples)} episodes.")
139
+
140
+ # Format for TRL (convert to messages format)
141
+ formatted = format_for_training(examples, system_prompt=SYSTEM_PROMPT)
142
+ print(f" Formatted {len(formatted)} training rows.")
143
+
144
+ with open(DATA_FMT_PATH, "w") as f:
145
+ for row in formatted:
146
+ f.write(json.dumps(row) + "\n")
147
+
148
+ print(f" Saved formatted dataset to {DATA_FMT_PATH}")
149
+
150
+
151
+ # ─── Step 3: Load model with LoRA ───────────────────────────────────────────
152
+ print(f"\n[4/5] Loading model and running SFT training...")
153
+
154
+ import torch
155
+ from datasets import Dataset
156
+ from peft import LoraConfig, get_peft_model
157
+ from transformers import AutoModelForCausalLM, AutoTokenizer
158
+ from trl import SFTConfig, SFTTrainer
159
+
160
+ device_map = "auto" if torch.cuda.is_available() else "cpu"
161
+ dtype = torch.bfloat16 if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) else torch.float16
162
+
163
+ print(f" CUDA available: {torch.cuda.is_available()}")
164
+ if torch.cuda.is_available():
165
+ print(f" GPU: {torch.cuda.get_device_name(0)}")
166
+ print(f" VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
167
+
168
+ print(f" Loading tokenizer from {MODEL_NAME}...")
169
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
170
+ if tokenizer.pad_token is None:
171
+ tokenizer.pad_token = tokenizer.eos_token
172
+ tokenizer.pad_token_id = tokenizer.eos_token_id
173
+
174
+ print(f" Loading base model...")
175
+ model = AutoModelForCausalLM.from_pretrained(
176
+ MODEL_NAME,
177
+ torch_dtype=dtype,
178
+ device_map=device_map,
179
+ trust_remote_code=True,
180
+ )
181
+
182
+ lora_config = LoraConfig(
183
+ r=LORA_RANK,
184
+ lora_alpha=LORA_RANK * 2,
185
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
186
+ lora_dropout=0.05,
187
+ bias="none",
188
+ task_type="CAUSAL_LM",
189
+ )
190
+ model = get_peft_model(model, lora_config)
191
+ model.print_trainable_parameters()
192
+
193
+
194
+ # ─── Step 4: Build dataset and trainer ──────────────────────────────────────
195
+ random.seed(SEED)
196
+ ds_full = Dataset.from_list(formatted).shuffle(seed=SEED)
197
+ split = ds_full.train_test_split(test_size=0.1, seed=SEED)
198
+
199
+ sft_config_kwargs: Dict[str, Any] = {
200
+ "output_dir": OUTPUT_DIR,
201
+ "num_train_epochs": EPOCHS,
202
+ "per_device_train_batch_size": BATCH_SIZE,
203
+ "gradient_accumulation_steps": GRAD_ACCUM,
204
+ "learning_rate": LEARNING_RATE,
205
+ "warmup_ratio": 0.05,
206
+ "weight_decay": 0.01,
207
+ "bf16": dtype == torch.bfloat16,
208
+ "fp16": dtype == torch.float16,
209
+ "logging_steps": 10,
210
+ "save_steps": 100,
211
+ "save_total_limit": 2,
212
+ "max_grad_norm": 1.0,
213
+ "seed": SEED,
214
+ "report_to": ["trackio"],
215
+ "run_name": "polyguard-sft-qwen",
216
+ "project": "polyguard-training",
217
+ "push_to_hub": True,
218
+ "hub_model_id": HUB_MODEL_ID,
219
+ "hub_strategy": "every_save",
220
+ "eval_strategy": "steps",
221
+ "eval_steps": 50,
222
+ }
223
+
224
+ # Adapt to TRL version
225
+ sft_params = set(inspect.signature(SFTConfig).parameters)
226
+ if "max_length" in sft_params:
227
+ sft_config_kwargs["max_length"] = MAX_LENGTH
228
+ elif "max_seq_length" in sft_params:
229
+ sft_config_kwargs["max_seq_length"] = MAX_LENGTH
230
+ if "eos_token" in sft_params:
231
+ sft_config_kwargs["eos_token"] = "<|im_end|>"
232
+
233
+ sft_config = SFTConfig(**{k: v for k, v in sft_config_kwargs.items() if k in sft_params})
234
+
235
+ trainer_kwargs: Dict[str, Any] = {
236
+ "model": model,
237
+ "args": sft_config,
238
+ "train_dataset": split["train"],
239
+ "eval_dataset": split["test"],
240
+ }
241
+ trainer_params = set(inspect.signature(SFTTrainer).parameters)
242
+ if "processing_class" in trainer_params:
243
+ trainer_kwargs["processing_class"] = tokenizer
244
+ elif "tokenizer" in trainer_params:
245
+ trainer_kwargs["tokenizer"] = tokenizer
246
+
247
+ trainer = SFTTrainer(**{k: v for k, v in trainer_kwargs.items() if v is not None})
248
+
249
+ print(f"\n Training dataset: {len(split['train'])} rows")
250
+ print(f" Eval dataset: {len(split['test'])} rows")
251
+ print("\n Starting training...\n")
252
+
253
+
254
+ # ─── Step 5: Train and push to Hub ─────────────────────────────────────────
255
+ train_result = trainer.train()
256
+
257
+ print("\n Training complete.")
258
+ print(f" Train loss: {train_result.training_loss:.4f}")
259
+ print(f" Train steps: {train_result.global_step}")
260
+
261
+ print(f"\n[5/5] Pushing model to Hub: {HUB_MODEL_ID}...")
262
+ trainer.push_to_hub()
263
+ tokenizer.push_to_hub(HUB_MODEL_ID)
264
+
265
+ print("\n" + "=" * 60)
266
+ print("SFT training complete!")
267
+ print(f"Model saved to: https://huggingface.co/{HUB_MODEL_ID}")
268
+ print("=" * 60)