idanpers commited on
Commit
e2b88be
·
verified ·
1 Parent(s): 7a60d1f

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +69 -26
README.md CHANGED
@@ -9,45 +9,88 @@ model-index:
9
  results: []
10
  ---
11
 
12
- <!-- This model card has been generated automatically according to the information the Trainer had access to. You
13
- should probably proofread and complete it, then remove this comment. -->
14
 
15
- # JailBreakModel
16
 
17
- This model is a fine-tuned version of [google/electra-base-discriminator](https://huggingface.co/google/electra-base-discriminator) on the None dataset.
18
 
19
- ## Model description
20
 
21
- More information needed
22
 
23
- ## Intended uses & limitations
 
 
24
 
25
- More information needed
26
 
27
- ## Training and evaluation data
28
 
29
- More information needed
30
 
31
- ## Training procedure
32
 
33
- ### Training hyperparameters
 
 
 
34
 
35
- The following hyperparameters were used during training:
36
- - learning_rate: 5e-05
37
- - train_batch_size: 16
38
- - eval_batch_size: 16
39
- - seed: 42
40
- - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
41
- - lr_scheduler_type: linear
42
- - num_epochs: 2
43
 
44
- ### Training results
45
 
 
46
 
 
47
 
48
- ### Framework versions
49
 
50
- - Transformers 4.44.2
51
- - Pytorch 2.5.0+cu121
52
- - Datasets 3.1.0
53
- - Tokenizers 0.19.1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  results: []
10
  ---
11
 
12
+ # ELECTRA Trainer for Prompt Injection Detection
 
13
 
14
+ ## Overview
15
 
16
+ This repository contains a fine-tuned ELECTRA model designed for detecting prompt injections in AI systems. The model classifies input prompts into two categories: benign and jailbreak. This approach aims to enhance the safety and robustness of AI applications.
17
 
18
+ ## Approach and Design Decisions
19
 
20
+ The primary goal of this project was to create a reliable model that can distinguish between safe and potentially harmful prompts. Key design decisions included:
21
 
22
+ - *Model Selection*: I chose the ELECTRA model due to its efficient training process and strong performance on text classification tasks. ELECTRA's architecture allows for effective learning from limited data, which is crucial given the specificity of the task.
23
+
24
+ - *Data Preparation*: A custom dataset was curated, consisting of diverse prompts labeled as either benign or jailbreak. The dataset aimed to balance both classes to mitigate biases during training.
25
 
26
+ - *Long Inputs*: To handle prompts exceeding the maximum input length of the ELECTRA model, I used truncation. Even though there was a data loss , the model still managed to classify the prompt correctly.
27
 
28
+ ## Model Architecture and Training Strategy
29
 
30
+ The model is based on the google/electra-base-discriminator architecture. Here’s an overview of the training strategy:
31
 
32
+ 1. *Tokenization*: I utilized the ELECTRA tokenizer to prepare input prompts. Padding and truncation were handled to ensure uniform input size.
33
 
34
+ 2. *Training Configuration*:
35
+ - *Learning Rate*: Set to 5e-05 for stable convergence.
36
+ - *Batch Size*: A batch size of 16 was chosen to balance training speed and memory usage.
37
+ - *Epochs*: The model was trained for 2 epochs to prevent overfitting while still allowing sufficient learning from the dataset.
38
 
39
+ 3. *Evaluation*: The model’s performance was evaluated on a validation set, focusing on metrics such as accuracy, precision, recall, and F1 score.
 
 
 
 
 
 
 
40
 
41
+ ## Key Results and Observations
42
 
43
+ - The model achieved a high accuracy rate on the validation set, indicating its effectiveness in distinguishing between benign and harmful prompts.
44
 
45
+ ## Instructions for Running the Inference Pipeline
46
 
47
+ To run the inference pipeline for classifying prompts, follow these steps:
48
 
49
+ 1. *Install Dependencies*:
50
+ Ensure you have Python installed, and then install the required libraries using pip:
51
+
52
+ ```bash
53
+ pip install transformers datasets torch
54
+
55
+ ```bash
56
+ # Load model directly
57
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
58
+
59
+ tokenizer = AutoTokenizer.from_pretrained("idanpers/electra-trainer")
60
+ model = AutoModelForSequenceClassification.from_pretrained("idanpers/electra-trainer")
61
+
62
+
63
+ use:
64
+ # Function to classify a single prompt using the trained model in Trainer
65
+ def classify_prompt(prompt):
66
+ # Error handling for empty input
67
+ if not isinstance(prompt, str) or prompt.strip() == "":
68
+ return {"error": "Invalid input. Please provide a non-empty text prompt."}
69
+
70
+ # Tokenize the input prompt and convert to dataset format expected by trainer.predict
71
+ inputs = Tokenizer(prompt, return_tensors="pt", padding=True, truncation=True)
72
+ dataset = Dataset.from_dict({"input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"]})
73
+
74
+ # Use trainer.predict to classify
75
+ prediction_output = model.predict(dataset)
76
+
77
+ # Get the softmax probabilities for confidence scores
78
+ probs = torch.softmax(torch.tensor(prediction_output.predictions), dim=1).cpu().numpy()
79
+ confidence = np.max(probs)
80
+ pred_label = np.argmax(probs, axis=1)[0]
81
+
82
+ # Map prediction to label
83
+ label = "PROMPT_INJECTION" if pred_label == 1 else "BENIGN"
84
+
85
+ return {"label": label, "confidence": confidence}
86
+
87
+ #Accept input from the user and classify it
88
+ prompt = input("Enter a prompt for classification: ")
89
+ result = classify_prompt(prompt)
90
+
91
+ #Check for errors before accessing the classification result
92
+ if "error" in result:
93
+ print(f"Error: {result['error']}")
94
+ else:
95
+ print(f"Classification Result: {result['label']}")
96
+ print(f"Confidence Score: {result['confidence']:.2f}")