Train Llama Guard
LlamaGuardFineTuner
LlamaGuardFineTuner
is a class designed to fine-tune and evaluate the
Prompt Guard model by Meta LLama for prompt
classification tasks, specifically for detecting prompt injection attacks. It
integrates with Weights & Biases for experiment tracking and optionally
displays progress in a Streamlit app.
Sample Usage
from guardrails_genie.train.llama_guard import LlamaGuardFineTuner, DatasetArgs
fine_tuner = LlamaGuardFineTuner(
wandb_project="guardrails-genie",
wandb_entity="geekyrakshit",
streamlit_mode=False,
)
fine_tuner.load_dataset(
DatasetArgs(
dataset_address="wandb/synthetic-prompt-injections",
train_dataset_range=-1,
test_dataset_range=-1,
)
)
fine_tuner.load_model()
fine_tuner.train(save_interval=100)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
wandb_project
|
str
|
The name of the Weights & Biases project. |
required |
wandb_entity
|
str
|
The Weights & Biases entity (user or team). |
required |
streamlit_mode
|
bool
|
If True, integrates with Streamlit to display progress. |
False
|
Source code in safeguards/train/llama_guard.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
|
evaluate_model(batch_size=32, positive_label=2, temperature=3.0, truncation=True, max_length=512)
Evaluates the fine-tuned model on the test dataset and visualizes the results.
This function evaluates the model by processing the test dataset in batches.
It computes the test scores using the evaluate_batch
method, which takes
several parameters to control the evaluation process, such as batch size,
positive label, temperature, truncation, and maximum sequence length.
After obtaining the test scores, it visualizes the performance of the model
using two methods:
1. visualize_roc_curve
: Plots the Receiver Operating Characteristic (ROC) curve
to show the trade-off between the true positive rate and false positive rate.
2. visualize_score_distribution
: Plots the distribution of scores for positive
and negative examples to provide insights into the model's performance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
The number of samples to process in each batch. |
32
|
positive_label
|
int
|
The label considered as positive for evaluation. |
2
|
temperature
|
float
|
The temperature parameter for scaling logits. |
3.0
|
truncation
|
bool
|
Whether to truncate sequences to the maximum length. |
True
|
max_length
|
int
|
The maximum length of sequences after truncation. |
512
|
Returns:
Type | Description |
---|---|
list[float]: The test scores obtained from the evaluation. |
Source code in safeguards/train/llama_guard.py
load_dataset(dataset_args)
Loads the training and testing datasets based on the provided dataset arguments.
This function uses the load_dataset
function from the datasets
library to load
the dataset specified by the dataset_address
attribute of the dataset_args
parameter.
It then selects a subset of the training and testing datasets based on the specified
ranges in train_dataset_range
and test_dataset_range
attributes of dataset_args
.
If the specified range is less than or equal to 0 or exceeds the length of the dataset,
the entire dataset is used.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_args
|
DatasetArgs
|
An instance of the |
required |
Attributes:
Name | Type | Description |
---|---|---|
train_dataset |
The selected training dataset. |
|
test_dataset |
The selected testing dataset. |
Source code in safeguards/train/llama_guard.py
load_model(model_name='meta-llama/Prompt-Guard-86M', checkpoint=None)
Loads the specified pre-trained model and tokenizer for sequence classification tasks.
This function sets the device to GPU if available, otherwise defaults to CPU. It then loads the tokenizer and model from the Hugging Face model hub using the provided model name. The model is moved to the specified device (GPU or CPU).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name
|
str
|
The name of the pre-trained model to load. |
'meta-llama/Prompt-Guard-86M'
|
Attributes:
Name | Type | Description |
---|---|---|
device |
str
|
The device to run the model on, either "cuda" for GPU or "cpu". |
model_name |
str
|
The name of the loaded pre-trained model. |
tokenizer |
AutoTokenizer
|
The tokenizer associated with the pre-trained model. |
model |
AutoModelForSequenceClassification
|
The loaded pre-trained model for sequence classification. |
Source code in safeguards/train/llama_guard.py
show_dataset_sample()
Displays a sample of the training and testing datasets using Streamlit.
This function checks if the streamlit_mode
attribute is enabled. If it is,
it converts the training and testing datasets to pandas DataFrames and displays
the first few rows of each dataset using Streamlit's dataframe
function. The
training dataset sample is displayed under the heading "Train Dataset Sample",
and the testing dataset sample is displayed under the heading "Test Dataset Sample".
Note
This function requires the streamlit
library to be installed and the
streamlit_mode
attribute to be set to True.
Source code in safeguards/train/llama_guard.py
train(batch_size=16, starting_lr=1e-07, num_classes=2, log_interval=1, save_interval=50)
Fine-tunes the pre-trained LlamaGuard model on the training dataset for a single epoch.
This function sets up and executes the training loop for the LlamaGuard model. It initializes the Weights & Biases (wandb) logging, configures the model's classifier layer to match the specified number of classes, and sets the model to training mode. The function uses an AdamW optimizer to update the model parameters based on the computed loss.
The training process involves iterating over the training dataset in batches,
computing the loss for each batch, and updating the model parameters. The
function logs the loss to wandb at specified intervals and optionally displays
a progress bar using Streamlit if streamlit_mode
is enabled. Model checkpoints
are saved at specified intervals during training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
The number of samples per batch during training. |
16
|
starting_lr
|
float
|
The starting learning rate for the optimizer. |
1e-07
|
num_classes
|
int
|
The number of output classes for the classifier. |
2
|
log_interval
|
int
|
The interval (in batches) at which to log the loss. |
1
|
save_interval
|
int
|
The interval (in batches) at which to save model checkpoints. |
50
|
Note
This function requires the wandb
and streamlit
libraries to be installed
and configured appropriately.
Source code in safeguards/train/llama_guard.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
|