| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """ |
| PolyGuard SFT Training Job β runs on Hugging Face Jobs cloud GPU. |
| |
| This script: |
| 1. Clones the project from GitHub |
| 2. Installs the polyguard-rl package |
| 3. Generates the SFT dataset from the PolyGuard environment |
| 4. Fine-tunes Qwen2.5-1.5B-Instruct with LoRA via TRL SFTTrainer |
| 5. Pushes the LoRA adapter + tokenizer to the Hugging Face Hub |
| |
| Submit via CLI: |
| hf jobs uv run \ |
| --flavor a10g-large \ |
| --timeout 3h \ |
| --secrets HF_TOKEN \ |
| "https://huggingface.co/TheJackBright/polyguard-training-scripts/resolve/main/hf_sft_train.py" |
| |
| Environment variables (passed as --env or via job secrets): |
| HF_TOKEN : HF write token (required for Hub push) |
| GITHUB_REPO : override GitHub repo URL (optional) |
| MODEL_NAME : base model (default: Qwen/Qwen2.5-1.5B-Instruct) |
| HUB_MODEL_ID : output model repo on Hub (default: TheJackBright/polyguard-qwen-sft) |
| N_EPISODES : SFT dataset episodes (default: 500) |
| EPOCHS : training epochs (default: 3) |
| BATCH_SIZE : per-device batch size (default: 2) |
| GRAD_ACCUM : gradient accumulation steps (default: 8) |
| MAX_LENGTH : max token length (default: 1024) |
| LEARNING_RATE : learning rate (default: 2e-4) |
| LORA_RANK : LoRA rank (default: 16) |
| """ |
| from __future__ import annotations |
|
|
| import inspect |
| import json |
| import os |
| import random |
| import subprocess |
| import sys |
| from pathlib import Path |
| from typing import Any, Dict, List, Optional |
|
|
| |
| GITHUB_REPO = os.environ.get("GITHUB_REPO", "https://github.com/Vishwa-docs/Meta_PyTorch_Scalar_OpenEnv-Hackathon.git") |
| MODEL_NAME = os.environ.get("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct") |
| HUB_MODEL_ID = os.environ.get("HUB_MODEL_ID", "TheJackBright/polyguard-qwen-sft") |
| N_EPISODES = int(os.environ.get("N_EPISODES", "500")) |
| EPOCHS = int(os.environ.get("EPOCHS", "3")) |
| BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "2")) |
| GRAD_ACCUM = int(os.environ.get("GRAD_ACCUM", "8")) |
| MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "1024")) |
| LEARNING_RATE = float(os.environ.get("LEARNING_RATE", "2e-4")) |
| LORA_RANK = int(os.environ.get("LORA_RANK", "16")) |
| SEED = 42 |
| OUTPUT_DIR = "/tmp/polyguard_sft_output" |
| DATA_PATH = "/tmp/polyguard_sft_data.jsonl" |
| DATA_FMT_PATH = "/tmp/polyguard_sft_data_formatted.jsonl" |
|
|
| SYSTEM_PROMPT = ( |
| "You are a clinical pharmacist agent performing polypharmacy medication review. " |
| "Analyze drug-drug interactions, Beers criteria violations, and propose safe interventions. " |
| "Respond only with a structured <decision>...</decision> XML action." |
| ) |
|
|
| print("=" * 60) |
| print("PolyGuard SFT Training on HF Jobs") |
| print(f" Model: {MODEL_NAME}") |
| print(f" Hub output: {HUB_MODEL_ID}") |
| print(f" Episodes: {N_EPISODES}") |
| print(f" Epochs: {EPOCHS}") |
| print(f" Batch size: {BATCH_SIZE} x {GRAD_ACCUM} grad accum") |
| print(f" Max length: {MAX_LENGTH}") |
| print(f" LoRA rank: {LORA_RANK}") |
| print("=" * 60) |
|
|
|
|
| |
| print("\n[1/5] Cloning project from GitHub...") |
| clone_dir = Path("/tmp/polyguard_project") |
| if not clone_dir.exists(): |
| subprocess.run( |
| ["git", "clone", "--depth=1", GITHUB_REPO, str(clone_dir)], |
| check=True, |
| ) |
| print(f" Cloned to {clone_dir}") |
| else: |
| print(f" Already cloned at {clone_dir}") |
|
|
| polyguard_rl_dir = clone_dir / "polyguard-rl" |
| print(f"\n[2/5] Installing polyguard-rl from {polyguard_rl_dir}...") |
| subprocess.run( |
| [sys.executable, "-m", "pip", "install", "-e", str(polyguard_rl_dir), "--quiet"], |
| check=True, |
| ) |
| print(" polyguard-rl installed.") |
|
|
| |
| if str(polyguard_rl_dir) not in sys.path: |
| sys.path.insert(0, str(polyguard_rl_dir)) |
|
|
|
|
| |
| print(f"\n[3/5] Generating SFT dataset ({N_EPISODES} episodes)...") |
|
|
| os.chdir(polyguard_rl_dir) |
|
|
| from app.training.sft_dataset import generate_sft_dataset, build_external_ddi_sft_examples, format_for_training |
|
|
| examples = generate_sft_dataset( |
| n_episodes=N_EPISODES, |
| seed=SEED, |
| output_path=DATA_PATH, |
| ) |
|
|
| print(f" Generated {len(examples)} episodes.") |
|
|
| |
| formatted = format_for_training(examples, system_prompt=SYSTEM_PROMPT) |
| print(f" Formatted {len(formatted)} training rows.") |
|
|
| with open(DATA_FMT_PATH, "w") as f: |
| for row in formatted: |
| f.write(json.dumps(row) + "\n") |
|
|
| print(f" Saved formatted dataset to {DATA_FMT_PATH}") |
|
|
|
|
| |
| print(f"\n[4/5] Loading model and running SFT training...") |
|
|
| import torch |
| from datasets import Dataset |
| from peft import LoraConfig, get_peft_model |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| from trl import SFTConfig, SFTTrainer |
|
|
| device_map = "auto" if torch.cuda.is_available() else "cpu" |
| dtype = torch.bfloat16 if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) else torch.float16 |
|
|
| print(f" CUDA available: {torch.cuda.is_available()}") |
| if torch.cuda.is_available(): |
| print(f" GPU: {torch.cuda.get_device_name(0)}") |
| print(f" VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB") |
|
|
| print(f" Loading tokenizer from {MODEL_NAME}...") |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
| tokenizer.pad_token_id = tokenizer.eos_token_id |
|
|
| print(f" Loading base model...") |
| model = AutoModelForCausalLM.from_pretrained( |
| MODEL_NAME, |
| torch_dtype=dtype, |
| device_map=device_map, |
| trust_remote_code=True, |
| ) |
|
|
| lora_config = LoraConfig( |
| r=LORA_RANK, |
| lora_alpha=LORA_RANK * 2, |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], |
| lora_dropout=0.05, |
| bias="none", |
| task_type="CAUSAL_LM", |
| ) |
| model = get_peft_model(model, lora_config) |
| model.print_trainable_parameters() |
|
|
|
|
| |
| random.seed(SEED) |
| ds_full = Dataset.from_list(formatted).shuffle(seed=SEED) |
| split = ds_full.train_test_split(test_size=0.1, seed=SEED) |
|
|
| sft_config_kwargs: Dict[str, Any] = { |
| "output_dir": OUTPUT_DIR, |
| "num_train_epochs": EPOCHS, |
| "per_device_train_batch_size": BATCH_SIZE, |
| "gradient_accumulation_steps": GRAD_ACCUM, |
| "learning_rate": LEARNING_RATE, |
| "warmup_ratio": 0.05, |
| "weight_decay": 0.01, |
| "bf16": dtype == torch.bfloat16, |
| "fp16": dtype == torch.float16, |
| "logging_steps": 10, |
| "save_steps": 100, |
| "save_total_limit": 2, |
| "max_grad_norm": 1.0, |
| "seed": SEED, |
| "report_to": ["trackio"], |
| "run_name": "polyguard-sft-qwen", |
| "project": "polyguard-training", |
| "push_to_hub": True, |
| "hub_model_id": HUB_MODEL_ID, |
| "hub_strategy": "every_save", |
| "eval_strategy": "steps", |
| "eval_steps": 50, |
| } |
|
|
| |
| sft_params = set(inspect.signature(SFTConfig).parameters) |
| if "max_length" in sft_params: |
| sft_config_kwargs["max_length"] = MAX_LENGTH |
| elif "max_seq_length" in sft_params: |
| sft_config_kwargs["max_seq_length"] = MAX_LENGTH |
| if "eos_token" in sft_params: |
| sft_config_kwargs["eos_token"] = "<|im_end|>" |
|
|
| sft_config = SFTConfig(**{k: v for k, v in sft_config_kwargs.items() if k in sft_params}) |
|
|
| trainer_kwargs: Dict[str, Any] = { |
| "model": model, |
| "args": sft_config, |
| "train_dataset": split["train"], |
| "eval_dataset": split["test"], |
| } |
| trainer_params = set(inspect.signature(SFTTrainer).parameters) |
| if "processing_class" in trainer_params: |
| trainer_kwargs["processing_class"] = tokenizer |
| elif "tokenizer" in trainer_params: |
| trainer_kwargs["tokenizer"] = tokenizer |
|
|
| trainer = SFTTrainer(**{k: v for k, v in trainer_kwargs.items() if v is not None}) |
|
|
| print(f"\n Training dataset: {len(split['train'])} rows") |
| print(f" Eval dataset: {len(split['test'])} rows") |
| print("\n Starting training...\n") |
|
|
|
|
| |
| train_result = trainer.train() |
|
|
| print("\n Training complete.") |
| print(f" Train loss: {train_result.training_loss:.4f}") |
| print(f" Train steps: {train_result.global_step}") |
|
|
| print(f"\n[5/5] Pushing model to Hub: {HUB_MODEL_ID}...") |
| trainer.push_to_hub() |
| tokenizer.push_to_hub(HUB_MODEL_ID) |
|
|
| print("\n" + "=" * 60) |
| print("SFT training complete!") |
| print(f"Model saved to: https://huggingface.co/{HUB_MODEL_ID}") |
| print("=" * 60) |
|
|