Spaces:
Running
Running
geekyrakshit
commited on
Commit
·
573a89c
1
Parent(s):
8647e3b
add: llama guard fine-tuner[WIP]
Browse files- app.py +12 -1
- application_pages/llama_guard_fine_tuning.py +43 -0
- guardrails_genie/train/llama_guard.py +128 -0
- pyproject.toml +3 -0
app.py
CHANGED
@@ -18,8 +18,19 @@ train_classifier_page = st.Page(
|
|
18 |
title="Train Classifier",
|
19 |
icon=":material/fitness_center:",
|
20 |
)
|
|
|
|
|
|
|
|
|
|
|
21 |
page_navigation = st.navigation(
|
22 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
)
|
24 |
st.set_page_config(page_title="Guardrails Genie", page_icon=":material/guardian:")
|
25 |
page_navigation.run()
|
|
|
18 |
title="Train Classifier",
|
19 |
icon=":material/fitness_center:",
|
20 |
)
|
21 |
+
llama_guard_fine_tuning_page = st.Page(
|
22 |
+
"application_pages/llama_guard_fine_tuning.py",
|
23 |
+
title="Fine-Tune LLama Guard",
|
24 |
+
icon=":material/star:",
|
25 |
+
)
|
26 |
page_navigation = st.navigation(
|
27 |
+
[
|
28 |
+
intro_page,
|
29 |
+
chat_page,
|
30 |
+
evaluation_page,
|
31 |
+
train_classifier_page,
|
32 |
+
llama_guard_fine_tuning_page,
|
33 |
+
]
|
34 |
)
|
35 |
st.set_page_config(page_title="Guardrails Genie", page_icon=":material/guardian:")
|
36 |
page_navigation.run()
|
application_pages/llama_guard_fine_tuning.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
from guardrails_genie.train.llama_guard import DatasetArgs, LlamaGuardFineTuner
|
4 |
+
|
5 |
+
|
6 |
+
def initialize_session_state():
|
7 |
+
st.session_state.llama_guard_fine_tuner = LlamaGuardFineTuner(streamlit_mode=True)
|
8 |
+
if "dataset_address" not in st.session_state:
|
9 |
+
st.session_state.dataset_address = ""
|
10 |
+
if "train_dataset_range" not in st.session_state:
|
11 |
+
st.session_state.train_dataset_range = 0
|
12 |
+
if "test_dataset_range" not in st.session_state:
|
13 |
+
st.session_state.test_dataset_range = 0
|
14 |
+
if "load_dataset_button" not in st.session_state:
|
15 |
+
st.session_state.load_dataset_button = False
|
16 |
+
|
17 |
+
|
18 |
+
initialize_session_state()
|
19 |
+
st.title(":material/star: Fine-Tune LLama Guard")
|
20 |
+
|
21 |
+
dataset_address = st.sidebar.text_input("Dataset Address", value="")
|
22 |
+
st.session_state.dataset_address = dataset_address
|
23 |
+
|
24 |
+
if st.session_state.dataset_address != "":
|
25 |
+
train_dataset_range = st.sidebar.number_input(
|
26 |
+
"Train Dataset Range", value=0, min_value=0, max_value=252956
|
27 |
+
)
|
28 |
+
test_dataset_range = st.sidebar.number_input(
|
29 |
+
"Test Dataset Range", value=0, min_value=0, max_value=63240
|
30 |
+
)
|
31 |
+
st.session_state.train_dataset_range = train_dataset_range
|
32 |
+
st.session_state.test_dataset_range = test_dataset_range
|
33 |
+
load_dataset_button = st.sidebar.button("Load Dataset")
|
34 |
+
st.session_state.load_dataset_button = load_dataset_button
|
35 |
+
if load_dataset_button:
|
36 |
+
with st.status("Dataset Arguments"):
|
37 |
+
dataset_args = DatasetArgs(
|
38 |
+
dataset_address=st.session_state.dataset_address,
|
39 |
+
train_dataset_range=st.session_state.train_dataset_range,
|
40 |
+
test_dataset_range=st.session_state.test_dataset_range,
|
41 |
+
)
|
42 |
+
st.session_state.llama_guard_fine_tuner.load_dataset(dataset_args)
|
43 |
+
st.session_state.llama_guard_fine_tuner.show_dataset_sample()
|
guardrails_genie/train/llama_guard.py
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import matplotlib.pyplot as plt
|
2 |
+
import streamlit as st
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from datasets import load_dataset
|
6 |
+
from pydantic import BaseModel
|
7 |
+
from rich.progress import track
|
8 |
+
from sklearn.metrics import roc_auc_score, roc_curve
|
9 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
10 |
+
|
11 |
+
|
12 |
+
class DatasetArgs(BaseModel):
|
13 |
+
dataset_address: str
|
14 |
+
train_dataset_range: int
|
15 |
+
test_dataset_range: int
|
16 |
+
|
17 |
+
|
18 |
+
class LlamaGuardFineTuner:
|
19 |
+
def __init__(self, streamlit_mode: bool = False):
|
20 |
+
self.streamlit_mode = streamlit_mode
|
21 |
+
|
22 |
+
def load_dataset(self, dataset_args: DatasetArgs):
|
23 |
+
dataset = load_dataset(dataset_args.dataset_address)
|
24 |
+
self.train_dataset = (
|
25 |
+
dataset["train"]
|
26 |
+
if dataset_args.train_dataset_range > 0
|
27 |
+
else dataset["train"].select(range(dataset_args.train_dataset_range))
|
28 |
+
)
|
29 |
+
self.test_dataset = (
|
30 |
+
dataset["test"]
|
31 |
+
if dataset_args.test_dataset_range > 0
|
32 |
+
else dataset["test"].select(range(dataset_args.test_dataset_range))
|
33 |
+
)
|
34 |
+
|
35 |
+
def load_model(self, model_name: str = "meta-llama/Prompt-Guard-86M"):
|
36 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
37 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
38 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(model_name).to(
|
39 |
+
self.device
|
40 |
+
)
|
41 |
+
|
42 |
+
def show_dataset_sample(self):
|
43 |
+
if self.streamlit_mode:
|
44 |
+
st.markdown("### Train Dataset Sample")
|
45 |
+
st.dataframe(self.train_dataset.to_pandas().head())
|
46 |
+
st.markdown("### Test Dataset Sample")
|
47 |
+
st.dataframe(self.test_dataset.to_pandas().head())
|
48 |
+
|
49 |
+
def evaluate_batch(
|
50 |
+
self,
|
51 |
+
texts,
|
52 |
+
batch_size: int = 32,
|
53 |
+
positive_label: int = 2,
|
54 |
+
temperature: float = 1.0,
|
55 |
+
truncation: bool = True,
|
56 |
+
max_length: int = 512,
|
57 |
+
) -> list[float]:
|
58 |
+
self.model.eval()
|
59 |
+
encoded_texts = self.tokenizer(
|
60 |
+
texts,
|
61 |
+
padding=True,
|
62 |
+
truncation=truncation,
|
63 |
+
max_length=max_length,
|
64 |
+
return_tensors="pt",
|
65 |
+
)
|
66 |
+
dataset = torch.utils.data.TensorDataset(
|
67 |
+
encoded_texts["input_ids"], encoded_texts["attention_mask"]
|
68 |
+
)
|
69 |
+
data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)
|
70 |
+
|
71 |
+
scores = []
|
72 |
+
for batch in track(data_loader, description="Evaluating"):
|
73 |
+
input_ids, attention_mask = [b.to(self.device) for b in batch]
|
74 |
+
with torch.no_grad():
|
75 |
+
logits = self.model(
|
76 |
+
input_ids=input_ids, attention_mask=attention_mask
|
77 |
+
).logits
|
78 |
+
scaled_logits = logits / temperature
|
79 |
+
probabilities = F.softmax(scaled_logits, dim=-1)
|
80 |
+
positive_class_probabilities = (
|
81 |
+
probabilities[:, positive_label].cpu().numpy()
|
82 |
+
)
|
83 |
+
scores.extend(positive_class_probabilities)
|
84 |
+
|
85 |
+
return scores
|
86 |
+
|
87 |
+
def visualize_roc_curve(self, test_scores: list[float]):
|
88 |
+
plt.figure(figsize=(8, 6))
|
89 |
+
test_labels = [int(elt) for elt in self.test_dataset["label"]]
|
90 |
+
fpr, tpr, _ = roc_curve(test_labels, test_scores)
|
91 |
+
roc_auc = roc_auc_score(test_labels, test_scores)
|
92 |
+
plt.plot(
|
93 |
+
fpr,
|
94 |
+
tpr,
|
95 |
+
color="darkorange",
|
96 |
+
lw=2,
|
97 |
+
label=f"ROC curve (area = {roc_auc:.3f})",
|
98 |
+
)
|
99 |
+
plt.plot([0, 1], [0, 1], color="navy", lw=2, linestyle="--")
|
100 |
+
plt.xlim([0.0, 1.0])
|
101 |
+
plt.ylim([0.0, 1.05])
|
102 |
+
plt.xlabel("False Positive Rate")
|
103 |
+
plt.ylabel("True Positive Rate")
|
104 |
+
plt.title("Receiver Operating Characteristic")
|
105 |
+
plt.legend(loc="lower right")
|
106 |
+
if self.streamlit_mode:
|
107 |
+
st.pyplot(plt)
|
108 |
+
else:
|
109 |
+
plt.show()
|
110 |
+
|
111 |
+
def evaluate_model(
|
112 |
+
self,
|
113 |
+
batch_size: int = 32,
|
114 |
+
positive_label: int = 2,
|
115 |
+
temperature: float = 3.0,
|
116 |
+
truncation: bool = True,
|
117 |
+
max_length: int = 512,
|
118 |
+
):
|
119 |
+
test_scores = self.evaluate_batch(
|
120 |
+
self.test_dataset["text"],
|
121 |
+
batch_size=batch_size,
|
122 |
+
positive_label=positive_label,
|
123 |
+
temperature=temperature,
|
124 |
+
truncation=truncation,
|
125 |
+
max_length=max_length,
|
126 |
+
)
|
127 |
+
self.visualize_roc_curve(test_scores)
|
128 |
+
return test_scores
|
pyproject.toml
CHANGED
@@ -16,6 +16,9 @@ dependencies = [
|
|
16 |
"transformers>=4.46.3",
|
17 |
"torch>=2.5.1",
|
18 |
"instructor>=1.7.0",
|
|
|
|
|
|
|
19 |
]
|
20 |
|
21 |
[project.optional-dependencies]
|
|
|
16 |
"transformers>=4.46.3",
|
17 |
"torch>=2.5.1",
|
18 |
"instructor>=1.7.0",
|
19 |
+
"matplotlib>=3.9.3",
|
20 |
+
"plotly>=5.24.1",
|
21 |
+
"scikit-learn>=1.5.2",
|
22 |
]
|
23 |
|
24 |
[project.optional-dependencies]
|