Download notebook2_classifier_phase2.py from ayshajavd/vuln-classifier-training-notebooks: direct link, hf CLI and curl.
- Browser
- Download file 8.93 kB
-
https://huggingface.co/ayshajavd/vuln-classifier-training-notebooks/resolve/main/notebook2_classifier_phase2.py
- Command line
-
hf download hf://ayshajavd/vuln-classifier-training-notebooks/notebook2_classifier_phase2.py
-
curl -L -o notebook2_classifier_phase2.py https://huggingface.co/ayshajavd/vuln-classifier-training-notebooks/resolve/main/notebook2_classifier_phase2.py
8.93 kB
| #!/usr/bin/env python | |
| # ============================================================ | |
| # NOTEBOOK 2/4: Classifier Phase 2 β Full Fine-tuning | |
| # ============================================================ | |
| # Run on Kaggle with T4 GPU AFTER Notebook 1 | |
| # Loads Phase 1 checkpoint from HF Hub | |
| # Estimated time: ~4-5 hours | |
| # Saves best model to HF Hub after every epoch | |
| # ============================================================ | |
| # %% | |
| # --- CELL 1: Install + Login --- | |
| import subprocess | |
| subprocess.run(["pip", "install", "-q", "transformers", "datasets", "scikit-learn", | |
| "accelerate", "huggingface_hub", "evaluate", "sentencepiece"]) | |
| from huggingface_hub import login | |
| import os | |
| try: | |
| from kaggle_secrets import UserSecretsClient | |
| token = UserSecretsClient().get_secret("HF_TOKEN") | |
| except: | |
| token = os.environ.get("HF_TOKEN", None) | |
| if token: | |
| login(token=token) | |
| print("β Logged in") | |
| else: | |
| print("β οΈ Run: login(token='your_token')") | |
| # %% | |
| # --- CELL 2: Imports + Config --- | |
| import json, numpy as np, torch, torch.nn as nn | |
| from datasets import load_dataset | |
| from transformers import ( | |
| AutoTokenizer, AutoModelForSequenceClassification, | |
| TrainingArguments, Trainer, EarlyStoppingCallback, | |
| ) | |
| from sklearn.metrics import f1_score, precision_score, recall_score | |
| from huggingface_hub import HfApi | |
| CHECKPOINT_REPO = "ayshajavd/graphcodebert-vuln-classifier" | |
| DATASET_ID = "ayshajavd/code-security-vulnerability-dataset" | |
| MAX_LENGTH = 512 | |
| SEED = 42 | |
| TARGET_CWES = [ | |
| "safe","CWE-20","CWE-22","CWE-78","CWE-79","CWE-89","CWE-94", | |
| "CWE-119","CWE-125","CWE-190","CWE-200","CWE-264","CWE-269", | |
| "CWE-276","CWE-284","CWE-287","CWE-310","CWE-327","CWE-330", | |
| "CWE-352","CWE-362","CWE-399","CWE-401","CWE-416","CWE-434", | |
| "CWE-476","CWE-502","CWE-601","CWE-787","CWE-798","CWE-918", | |
| ] | |
| NUM_LABELS = len(TARGET_CWES) | |
| if torch.cuda.is_available(): | |
| print(f"β GPU: {torch.cuda.get_device_name(0)} ({torch.cuda.get_device_properties(0).total_mem/1e9:.1f}GB)") | |
| else: | |
| print("β οΈ No GPU!") | |
| # %% | |
| # --- CELL 3: ASL Loss + Trainer (same as Notebook 1) --- | |
| class AsymmetricLoss(nn.Module): | |
| def __init__(self, gamma_neg=4, gamma_pos=0, clip=0.05, eps=1e-8): | |
| super().__init__() | |
| self.gamma_neg = gamma_neg | |
| self.gamma_pos = gamma_pos | |
| self.clip = clip | |
| self.eps = eps | |
| def forward(self, x, y): | |
| xs_pos = torch.sigmoid(x) | |
| xs_neg = 1.0 - xs_pos | |
| if self.clip and self.clip > 0: | |
| xs_neg = (xs_neg + self.clip).clamp(max=1.0) | |
| los_pos = y * torch.log(xs_pos.clamp(min=self.eps)) | |
| los_neg = (1.0 - y) * torch.log(xs_neg.clamp(min=self.eps)) | |
| loss = los_pos + los_neg | |
| if self.gamma_neg > 0 or self.gamma_pos > 0: | |
| pt0 = xs_pos * y | |
| pt1 = xs_neg * (1.0 - y) | |
| pt = pt0 + pt1 | |
| one_sided_gamma = self.gamma_pos * y + self.gamma_neg * (1.0 - y) | |
| one_sided_w = torch.pow(1.0 - pt, one_sided_gamma) | |
| loss *= one_sided_w | |
| return -loss.sum() / x.shape[0] | |
| class ASLTrainer(Trainer): | |
| def __init__(self, *args, loss_fn=None, **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.loss_fn = loss_fn or AsymmetricLoss() | |
| def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): | |
| labels = inputs.pop("labels").float() | |
| outputs = model(**inputs) | |
| loss = self.loss_fn(outputs.logits, labels) | |
| return (loss, outputs) if return_outputs else loss | |
| def compute_metrics(eval_pred): | |
| logits, labels = eval_pred | |
| probs = 1 / (1 + np.exp(-logits)) | |
| preds = (probs > 0.3).astype(int) | |
| metrics = { | |
| 'macro_f1': f1_score(labels, preds, average='macro', zero_division=0), | |
| 'micro_f1': f1_score(labels, preds, average='micro', zero_division=0), | |
| 'weighted_f1': f1_score(labels, preds, average='weighted', zero_division=0), | |
| 'macro_precision': precision_score(labels, preds, average='macro', zero_division=0), | |
| 'macro_recall': recall_score(labels, preds, average='macro', zero_division=0), | |
| } | |
| per_class_f1 = f1_score(labels, preds, average=None, zero_division=0) | |
| for i, cwe in enumerate(TARGET_CWES): | |
| if i < len(per_class_f1): | |
| metrics[f'f1_{cwe}'] = per_class_f1[i] | |
| return metrics | |
| # %% | |
| # --- CELL 4: Load Phase 1 Checkpoint from HF Hub --- | |
| print("π₯ Loading Phase 1 checkpoint from HF Hub...") | |
| tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_REPO, revision="phase1-checkpoint") | |
| model = AutoModelForSequenceClassification.from_pretrained( | |
| CHECKPOINT_REPO, revision="phase1-checkpoint" | |
| ) | |
| # Load Phase 1 metrics for reference | |
| try: | |
| from huggingface_hub import hf_hub_download | |
| p1_path = hf_hub_download(CHECKPOINT_REPO, "phase1_metrics.json", revision="phase1-checkpoint") | |
| with open(p1_path) as f: | |
| p1_metrics = json.load(f) | |
| print(f"β Phase 1 Macro F1 was: {p1_metrics.get('eval_macro_f1', 'N/A')}") | |
| except: | |
| print("β οΈ Couldn't load Phase 1 metrics (not critical)") | |
| print(f"β Model loaded: {sum(p.numel() for p in model.parameters()):,} params") | |
| # %% | |
| # --- CELL 5: Load + Tokenize Dataset --- | |
| print("Loading dataset...") | |
| ds = load_dataset(DATASET_ID) | |
| def tokenize_fn(examples): | |
| return tokenizer(examples['code'], max_length=MAX_LENGTH, truncation=True, padding='max_length') | |
| print("Tokenizing...") | |
| ds = ds.map(tokenize_fn, batched=True, batch_size=1000, num_proc=2, | |
| remove_columns=['code','code_fixed','cwe_id','owasp','language','source','is_vulnerable']) | |
| ds.set_format('torch') | |
| print(f"β Train: {len(ds['train']):,} | Val: {len(ds['validation']):,} | Test: {len(ds['test']):,}") | |
| # %% | |
| # --- CELL 6: Phase 2 β Unfreeze ALL layers + Fine-tune --- | |
| print("\n" + "="*60) | |
| print("π PHASE 2: Full Fine-tuning (ALL layers unfrozen)") | |
| print(" 9 epochs | lr=2e-5 | cosine schedule | ASL loss") | |
| print(" Early stopping patience=3 (stops if no improvement)") | |
| print("="*60) | |
| # Unfreeze everything | |
| for param in model.parameters(): | |
| param.requires_grad = True | |
| total = sum(p.numel() for p in model.parameters()) | |
| print(f"Trainable: {total:,} / {total:,} (100%)") | |
| phase2_args = TrainingArguments( | |
| output_dir="./phase2_output", | |
| num_train_epochs=9, | |
| per_device_train_batch_size=16, | |
| per_device_eval_batch_size=32, | |
| gradient_accumulation_steps=2, # effective batch = 32 | |
| learning_rate=2e-5, | |
| lr_scheduler_type="cosine", | |
| warmup_ratio=0.06, | |
| weight_decay=0.01, | |
| max_grad_norm=1.0, | |
| fp16=True, | |
| eval_strategy="epoch", | |
| save_strategy="epoch", | |
| logging_strategy="steps", | |
| logging_steps=50, | |
| logging_first_step=True, | |
| disable_tqdm=False, | |
| load_best_model_at_end=True, | |
| metric_for_best_model="eval_macro_f1", | |
| greater_is_better=True, | |
| save_total_limit=3, | |
| seed=SEED, | |
| dataloader_num_workers=2, | |
| report_to="none", | |
| label_names=["labels"], | |
| ) | |
| trainer = ASLTrainer( | |
| model=model, | |
| args=phase2_args, | |
| train_dataset=ds['train'], | |
| eval_dataset=ds['validation'], | |
| compute_metrics=compute_metrics, | |
| loss_fn=AsymmetricLoss(gamma_neg=4, gamma_pos=0, clip=0.05), | |
| callbacks=[EarlyStoppingCallback(early_stopping_patience=3)], | |
| ) | |
| print("ποΈ Training Phase 2 (this takes ~4-5 hours on T4)...") | |
| trainer.train() | |
| # %% | |
| # --- CELL 7: Evaluate Phase 2 --- | |
| p2_metrics = trainer.evaluate() | |
| print("\n" + "="*60) | |
| print("π PHASE 2 RESULTS:") | |
| print(f" Macro F1: {p2_metrics.get('eval_macro_f1', 0):.4f} (baseline: 0.1157)") | |
| print(f" Micro F1: {p2_metrics.get('eval_micro_f1', 0):.4f}") | |
| print(f" Weighted F1: {p2_metrics.get('eval_weighted_f1', 0):.4f}") | |
| print(f" Macro Prec: {p2_metrics.get('eval_macro_precision', 0):.4f}") | |
| print(f" Macro Rec: {p2_metrics.get('eval_macro_recall', 0):.4f}") | |
| print("="*60) | |
| print("\nPer-class F1:") | |
| for cwe in TARGET_CWES: | |
| f1 = p2_metrics.get(f'eval_f1_{cwe}', 0) | |
| marker = "β " if f1 > 0.1 else "β οΈ" if f1 > 0 else "β" | |
| print(f" {marker} {cwe:>12}: {f1:.4f}") | |
| # %% | |
| # --- CELL 8: Save Phase 2 to HF Hub --- | |
| print("\nπΎ Saving Phase 2 model to HF Hub...") | |
| model.save_pretrained("./phase2_checkpoint") | |
| tokenizer.save_pretrained("./phase2_checkpoint") | |
| with open("./phase2_checkpoint/phase2_metrics.json", 'w') as f: | |
| json.dump({k: float(v) if isinstance(v, (float, np.floating)) else v | |
| for k, v in p2_metrics.items()}, f, indent=2) | |
| api = HfApi() | |
| try: | |
| api.create_branch(repo_id=CHECKPOINT_REPO, branch="phase2-checkpoint") | |
| except: | |
| pass | |
| api.upload_folder( | |
| folder_path="./phase2_checkpoint", | |
| repo_id=CHECKPOINT_REPO, | |
| revision="phase2-checkpoint", | |
| commit_message="Phase 2 checkpoint: full fine-tuning complete", | |
| ) | |
| print(f"\nβ Phase 2 saved to: https://huggingface.co/{CHECKPOINT_REPO}/tree/phase2-checkpoint") | |
| print("\n" + "="*60) | |
| print("π― NEXT: Run Notebook 3 (Threshold optimization + Calibration + Final eval)") | |
| print("="*60) | |