Spaces:
Running
Running
Jin Zhu commited on
Commit ·
caf334f
1
Parent(s): 94acd9c
update code
Browse files- src/FineTune/.gitignore +1 -1
- src/FineTune/engine.py +0 -173
- src/FineTune/model.py +2 -9
src/FineTune/.gitignore
CHANGED
|
@@ -8,7 +8,7 @@ __pycache__/
|
|
| 8 |
|
| 9 |
# Distribution / packaging
|
| 10 |
.Python
|
| 11 |
-
ckpt/*
|
| 12 |
logs/*/
|
| 13 |
models/*/
|
| 14 |
build/
|
|
|
|
| 8 |
|
| 9 |
# Distribution / packaging
|
| 10 |
.Python
|
| 11 |
+
ckpt/*
|
| 12 |
logs/*/
|
| 13 |
models/*/
|
| 14 |
build/
|
src/FineTune/engine.py
DELETED
|
@@ -1,173 +0,0 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
from torch.utils.data import DataLoader
|
| 3 |
-
import tqdm
|
| 4 |
-
from torch.cuda.amp import GradScaler, autocast
|
| 5 |
-
import torch.nn.functional as F
|
| 6 |
-
from torch import nn
|
| 7 |
-
import torch
|
| 8 |
-
import numpy as np
|
| 9 |
-
import os
|
| 10 |
-
import json
|
| 11 |
-
from metrics import get_roc_metrics, get_precision_recall_metrics, get_rejection_rate
|
| 12 |
-
import random
|
| 13 |
-
from torch.optim.lr_scheduler import CosineAnnealingLR
|
| 14 |
-
import time
|
| 15 |
-
from utils import GpuMem
|
| 16 |
-
try:
|
| 17 |
-
from transformers import AdamW
|
| 18 |
-
except:
|
| 19 |
-
from torch.optim import AdamW
|
| 20 |
-
|
| 21 |
-
def set_seed(seed):
|
| 22 |
-
torch.manual_seed(seed)
|
| 23 |
-
torch.cuda.manual_seed_all(seed)
|
| 24 |
-
np.random.seed(seed)
|
| 25 |
-
random.seed(seed)
|
| 26 |
-
torch.backends.cudnn.deterministic = True
|
| 27 |
-
torch.backends.cudnn.benchmark = False
|
| 28 |
-
|
| 29 |
-
def evaluate_model(model, data, device, verbose=True):
|
| 30 |
-
model.to(device)
|
| 31 |
-
model.eval()
|
| 32 |
-
loss = 0
|
| 33 |
-
eval_loader = DataLoader(data, batch_size=1, shuffle=False)
|
| 34 |
-
epoch_crit_train_original, epoch_crit_train_sampled = [],[]
|
| 35 |
-
time_list = []
|
| 36 |
-
memory_list = []
|
| 37 |
-
tracker = GpuMem()
|
| 38 |
-
with torch.no_grad():
|
| 39 |
-
for batch in tqdm.tqdm(eval_loader, desc="Evaluating"):
|
| 40 |
-
text = batch
|
| 41 |
-
start = time.perf_counter()
|
| 42 |
-
with tracker:
|
| 43 |
-
output = model(text, training_module=False)
|
| 44 |
-
time_list.append(time.perf_counter() - start)
|
| 45 |
-
memory_list.append(tracker.memory_usage())
|
| 46 |
-
|
| 47 |
-
loss += output['loss'].item()
|
| 48 |
-
epoch_crit_train_original.extend(output['crit'][1].tolist())
|
| 49 |
-
epoch_crit_train_sampled.extend(output['crit'][3].tolist())
|
| 50 |
-
|
| 51 |
-
fpr, tpr, roc_auc = get_roc_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 52 |
-
p, r, pr_auc = get_precision_recall_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 53 |
-
|
| 54 |
-
if verbose:
|
| 55 |
-
print(f"Total time: {sum(time_list):.4f}s")
|
| 56 |
-
print(f"<Valid> ROC_AUC: {roc_auc:.4f}, PR AUC: {pr_auc:.4f}")
|
| 57 |
-
print(f"<Valid> Real_mean/std: {np.mean(epoch_crit_train_original):.2f}/{np.std(epoch_crit_train_original):.2f}, val_Samples_mean/std: {np.mean(epoch_crit_train_sampled):.2f}/{np.std(epoch_crit_train_sampled):.2f}")
|
| 58 |
-
|
| 59 |
-
results_dict = {
|
| 60 |
-
"name": "AdaJASAdetectgpt",
|
| 61 |
-
'info': {'n_samples': len(epoch_crit_train_original)},
|
| 62 |
-
'predictions': {'real': epoch_crit_train_original,
|
| 63 |
-
'samples': epoch_crit_train_sampled},
|
| 64 |
-
'metrics': {'roc_auc': roc_auc, 'fpr': fpr, 'tpr': tpr},
|
| 65 |
-
'pr_metrics': {'pr_auc': pr_auc, 'precision': p, 'recall': r},
|
| 66 |
-
'runtime': time_list,
|
| 67 |
-
'memory': memory_list,
|
| 68 |
-
}
|
| 69 |
-
return results_dict
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def fine_tune(model, data, device, args=None, ckpt_dir='./ckpt',):
|
| 73 |
-
train_loader = DataLoader(data, batch_size=1, shuffle=True)
|
| 74 |
-
epochs = args.epochs
|
| 75 |
-
optimizer = AdamW(model.parameters(), lr=args.lr)
|
| 76 |
-
scheduler = CosineAnnealingLR(optimizer, T_max=len(train_loader) * epochs, eta_min=0,
|
| 77 |
-
last_epoch=-1)
|
| 78 |
-
|
| 79 |
-
scaler = GradScaler()
|
| 80 |
-
model.to(device)
|
| 81 |
-
|
| 82 |
-
# Number of iterations for gradient accumulation
|
| 83 |
-
accumulation_steps = args.a
|
| 84 |
-
epoch_losses, i, loss = [], 0, torch.tensor(0.0).to(device)
|
| 85 |
-
epoch_crit_train_original, epoch_crit_train_sampled = [],[]
|
| 86 |
-
print('Fine-tuning model...')
|
| 87 |
-
tracker = GpuMem()
|
| 88 |
-
start = time.perf_counter()
|
| 89 |
-
with tracker:
|
| 90 |
-
for epoch in range(epochs):
|
| 91 |
-
optimizer.zero_grad()
|
| 92 |
-
for batch in tqdm.tqdm(train_loader, desc=f"Fine-tuning: {epoch} epoch"):
|
| 93 |
-
text = batch
|
| 94 |
-
scheduler.step()
|
| 95 |
-
with autocast():
|
| 96 |
-
outputs_1 = model(text)
|
| 97 |
-
epoch_crit_train_original.extend(outputs_1['crit'][1].tolist())
|
| 98 |
-
epoch_crit_train_sampled.extend(outputs_1['crit'][3].tolist())
|
| 99 |
-
loss += (outputs_1['loss'].to(torch.float32)) / accumulation_steps
|
| 100 |
-
|
| 101 |
-
del outputs_1
|
| 102 |
-
|
| 103 |
-
if ((i + 1) % accumulation_steps) == 0:
|
| 104 |
-
scaler.scale(loss).backward()
|
| 105 |
-
scaler.step(optimizer)
|
| 106 |
-
optimizer.zero_grad()
|
| 107 |
-
scaler.update()
|
| 108 |
-
|
| 109 |
-
if i % 100 == 0:
|
| 110 |
-
torch.cuda.empty_cache()
|
| 111 |
-
|
| 112 |
-
epoch_losses.append(loss.item())
|
| 113 |
-
loss = torch.tensor(0.0).to(device)
|
| 114 |
-
epoch_losses.append(loss.item())
|
| 115 |
-
i += 1
|
| 116 |
-
|
| 117 |
-
fpr, tpr, roc_auc = get_roc_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 118 |
-
p, r, pr_auc = get_precision_recall_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 119 |
-
|
| 120 |
-
print(f"<Train> ROC AUC: {roc_auc:.4f}, PR AUC: {pr_auc:.4f}")
|
| 121 |
-
print(f"<Train> Real mean/std: {np.mean(epoch_crit_train_original):.2f}/{np.std(epoch_crit_train_original):.2f}, Samples mean/std: {np.mean(epoch_crit_train_sampled):.2f}/{np.std(epoch_crit_train_sampled):.2f}")
|
| 122 |
-
epoch_avg_loss = np.mean(epoch_losses)
|
| 123 |
-
print(f"<Train> Average Loss for Epoch {epoch}: {epoch_avg_loss}\n")
|
| 124 |
-
epoch_crit_train_original, epoch_crit_train_sampled = [], [] # reset crit
|
| 125 |
-
pre_memory = tracker.memory_usage()
|
| 126 |
-
pre_time = time.perf_counter() - start
|
| 127 |
-
print(f"Total time: {pre_time:.4f}s; Peak memory: {pre_memory:.4f}Gb")
|
| 128 |
-
|
| 129 |
-
if args.save_trained:
|
| 130 |
-
if not os.path.exists(ckpt_dir):
|
| 131 |
-
os.makedirs(ckpt_dir)
|
| 132 |
-
model.save_pretrained(ckpt_dir)
|
| 133 |
-
print(f"Saved finetuned model to directory {ckpt_dir}")
|
| 134 |
-
|
| 135 |
-
return model
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
def infer_model(
|
| 139 |
-
model,
|
| 140 |
-
data,
|
| 141 |
-
device,
|
| 142 |
-
domain,
|
| 143 |
-
):
|
| 144 |
-
test_loader = DataLoader(data, batch_size=1, shuffle=False)
|
| 145 |
-
model.to(device)
|
| 146 |
-
|
| 147 |
-
test_original = []
|
| 148 |
-
test_sampled = []
|
| 149 |
-
p_value_original = []
|
| 150 |
-
p_value_sampled = []
|
| 151 |
-
for batch in tqdm.tqdm(test_loader, desc=f"Testing"):
|
| 152 |
-
human_crit, human_p_value = model.compute_p_value(batch[0], domain)
|
| 153 |
-
llm_crit, llm_p_value = model.compute_p_value(batch[1], domain)
|
| 154 |
-
test_original.append(human_crit.item())
|
| 155 |
-
test_sampled.append(llm_crit.item())
|
| 156 |
-
p_value_original.append(human_p_value.item())
|
| 157 |
-
p_value_sampled.append(llm_p_value.item())
|
| 158 |
-
|
| 159 |
-
alphas = [0.01, 0.05, 0.1]
|
| 160 |
-
typeI_error = [get_rejection_rate(p_value_original, alpha) for alpha in alphas]
|
| 161 |
-
power = [get_rejection_rate(p_value_sampled, alpha) for alpha in alphas]
|
| 162 |
-
print("alpha Type-I error Power")
|
| 163 |
-
for a, t, p in zip(alphas, typeI_error, power):
|
| 164 |
-
print(f"{a:<10.2f}{t:<15.3f}{p:<15.3f}")
|
| 165 |
-
|
| 166 |
-
results_dict = {
|
| 167 |
-
'info': {'n_samples': len(test_original)},
|
| 168 |
-
'predictions': {'real': test_original, 'samples': test_sampled},
|
| 169 |
-
'inference': {'real': p_value_original, 'samples': p_value_sampled},
|
| 170 |
-
'inference_metrics': {'typeI_error': typeI_error, 'power': power, 'alpha': alphas},
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
return results_dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/FineTune/model.py
CHANGED
|
@@ -7,10 +7,6 @@ import json
|
|
| 7 |
|
| 8 |
import os
|
| 9 |
|
| 10 |
-
def calculate_MMD_loss(human_crit, sample_crit):
|
| 11 |
-
mmd_loss = human_crit.mean() - sample_crit.mean()
|
| 12 |
-
return mmd_loss
|
| 13 |
-
|
| 14 |
def from_pretrained(cls, model_name, kwargs, cache_dir):
|
| 15 |
# use local model if it exists
|
| 16 |
if "/" in model_name:
|
|
@@ -23,11 +19,9 @@ def from_pretrained(cls, model_name, kwargs, cache_dir):
|
|
| 23 |
return cls.from_pretrained(model_name, **kwargs, cache_dir=cache_dir, device_map='auto')
|
| 24 |
|
| 25 |
model_fullnames = {
|
| 26 |
-
'gemma-9b': 'google/gemma-2-9b',
|
| 27 |
-
'gemma-4b': 'google/gemma-3-4b-pt',
|
| 28 |
'gemma-1b': 'google/gemma-3-1b-pt',
|
| 29 |
}
|
| 30 |
-
float16_models = [
|
| 31 |
|
| 32 |
def get_model_fullname(model_name):
|
| 33 |
return model_fullnames[model_name] if model_name in model_fullnames else model_name
|
|
@@ -243,8 +237,7 @@ class ComputeScore(nn.Module):
|
|
| 243 |
labels = tokenized.input_ids[:, 1:]
|
| 244 |
train_sampled_crit, _, _ = self.get_SPO_input(tokenized, sampled_text, labels,training_module=training_module)
|
| 245 |
|
| 246 |
-
|
| 247 |
-
output = dict(crit=[train_original_crit.detach(), train_original_crit, train_sampled_crit.detach(), train_sampled_crit], loss=MMDloss)
|
| 248 |
return output
|
| 249 |
|
| 250 |
def set_null_distr(self, null_distr: torch.Tensor, domain: str):
|
|
|
|
| 7 |
|
| 8 |
import os
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def from_pretrained(cls, model_name, kwargs, cache_dir):
|
| 11 |
# use local model if it exists
|
| 12 |
if "/" in model_name:
|
|
|
|
| 19 |
return cls.from_pretrained(model_name, **kwargs, cache_dir=cache_dir, device_map='auto')
|
| 20 |
|
| 21 |
model_fullnames = {
|
|
|
|
|
|
|
| 22 |
'gemma-1b': 'google/gemma-3-1b-pt',
|
| 23 |
}
|
| 24 |
+
float16_models = []
|
| 25 |
|
| 26 |
def get_model_fullname(model_name):
|
| 27 |
return model_fullnames[model_name] if model_name in model_fullnames else model_name
|
|
|
|
| 237 |
labels = tokenized.input_ids[:, 1:]
|
| 238 |
train_sampled_crit, _, _ = self.get_SPO_input(tokenized, sampled_text, labels,training_module=training_module)
|
| 239 |
|
| 240 |
+
output = dict(crit=[train_original_crit.detach(), train_original_crit, train_sampled_crit.detach(), train_sampled_crit])
|
|
|
|
| 241 |
return output
|
| 242 |
|
| 243 |
def set_null_distr(self, null_distr: torch.Tensor, domain: str):
|