debashis2007 commited on
Commit
3de025b
ยท
verified ยท
1 Parent(s): 925af0f

Update README with comprehensive Phi-2 LoRA documentation

Browse files
Files changed (1) hide show
  1. README.md +273 -162
README.md CHANGED
@@ -1,207 +1,318 @@
1
  ---
2
- base_model: microsoft/phi-2
3
  library_name: peft
4
- pipeline_tag: text-generation
5
  tags:
6
- - base_model:adapter:microsoft/phi-2
7
- - lora
8
- - transformers
 
 
 
 
 
 
 
 
 
9
  ---
10
 
11
- # Model Card for Model ID
12
-
13
- <!-- Provide a quick summary of what the model is/does. -->
14
-
15
-
16
-
17
- ## Model Details
18
-
19
- ### Model Description
20
-
21
- <!-- Provide a longer summary of what this model is. -->
22
-
23
-
24
-
25
- - **Developed by:** [More Information Needed]
26
- - **Funded by [optional]:** [More Information Needed]
27
- - **Shared by [optional]:** [More Information Needed]
28
- - **Model type:** [More Information Needed]
29
- - **Language(s) (NLP):** [More Information Needed]
30
- - **License:** [More Information Needed]
31
- - **Finetuned from model [optional]:** [More Information Needed]
32
-
33
- ### Model Sources [optional]
34
-
35
- <!-- Provide the basic links for the model. -->
36
-
37
- - **Repository:** [More Information Needed]
38
- - **Paper [optional]:** [More Information Needed]
39
- - **Demo [optional]:** [More Information Needed]
40
-
41
- ## Uses
42
-
43
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
44
-
45
- ### Direct Use
46
-
47
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
48
-
49
- [More Information Needed]
50
-
51
- ### Downstream Use [optional]
52
-
53
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
54
-
55
- [More Information Needed]
56
-
57
- ### Out-of-Scope Use
58
-
59
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
60
-
61
- [More Information Needed]
62
-
63
- ## Bias, Risks, and Limitations
64
-
65
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
66
-
67
- [More Information Needed]
68
-
69
- ### Recommendations
70
-
71
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
72
-
73
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
74
-
75
- ## How to Get Started with the Model
76
-
77
- Use the code below to get started with the model.
78
-
79
- [More Information Needed]
80
 
81
- ## Training Details
82
 
83
- ### Training Data
84
 
85
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
86
 
87
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
88
 
89
- ### Training Procedure
90
-
91
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
92
-
93
- #### Preprocessing [optional]
94
-
95
- [More Information Needed]
96
-
97
-
98
- #### Training Hyperparameters
99
-
100
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
101
-
102
- #### Speeds, Sizes, Times [optional]
103
-
104
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
105
-
106
- [More Information Needed]
107
-
108
- ## Evaluation
109
-
110
- <!-- This section describes the evaluation protocols and provides the results. -->
111
-
112
- ### Testing Data, Factors & Metrics
113
-
114
- #### Testing Data
115
-
116
- <!-- This should link to a Dataset Card if possible. -->
117
-
118
- [More Information Needed]
119
-
120
- #### Factors
121
-
122
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
123
-
124
- [More Information Needed]
125
-
126
- #### Metrics
127
-
128
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
129
-
130
- [More Information Needed]
131
-
132
- ### Results
133
-
134
- [More Information Needed]
135
 
136
- #### Summary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
 
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
- ## Model Examination [optional]
141
 
142
- <!-- Relevant interpretability work for the model goes here -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
- [More Information Needed]
145
 
146
- ## Environmental Impact
147
 
148
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
 
 
149
 
150
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
151
 
152
- - **Hardware Type:** [More Information Needed]
153
- - **Hours used:** [More Information Needed]
154
- - **Cloud Provider:** [More Information Needed]
155
- - **Compute Region:** [More Information Needed]
156
- - **Carbon Emitted:** [More Information Needed]
157
 
158
- ## Technical Specifications [optional]
 
 
 
 
159
 
160
- ### Model Architecture and Objective
161
 
162
- [More Information Needed]
 
 
 
163
 
164
- ### Compute Infrastructure
 
 
 
165
 
166
- [More Information Needed]
167
 
168
- #### Hardware
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- [More Information Needed]
171
 
172
- #### Software
173
 
174
- [More Information Needed]
 
 
 
175
 
176
- ## Citation [optional]
177
 
178
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
179
 
180
- **BibTeX:**
181
 
182
- [More Information Needed]
 
 
 
 
 
 
183
 
184
- **APA:**
 
 
 
 
 
 
185
 
186
- [More Information Needed]
187
 
188
- ## Glossary [optional]
189
 
190
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
191
 
192
- [More Information Needed]
193
 
194
- ## More Information [optional]
195
 
196
- [More Information Needed]
 
 
197
 
198
- ## Model Card Authors [optional]
199
 
200
- [More Information Needed]
201
 
202
- ## Model Card Contact
203
 
204
- [More Information Needed]
205
- ### Framework versions
206
 
207
- - PEFT 0.18.0
 
 
 
1
  ---
2
+ license: mit
3
  library_name: peft
 
4
  tags:
5
+ - security
6
+ - cybersecurity
7
+ - lora
8
+ - phi-2
9
+ - fine-tuned
10
+ - instruction-tuned
11
+ - peft
12
+ - text-generation
13
+ language:
14
+ - en
15
+ pipeline_tag: text-generation
16
+ base_model: microsoft/phi-2
17
  ---
18
 
19
+ # ๐Ÿ”’ Security-Focused Phi-2 LoRA
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ A fine-tuned [Phi-2 2.7B](https://huggingface.co/microsoft/phi-2) model optimized for cybersecurity questions and answers using LoRA (Low-Rank Adaptation).
22
 
23
+ This model is specialized in providing detailed, accurate responses to security-related queries including vulnerabilities, attack vectors, defense mechanisms, and best practices. Despite being 2.7B parameters, Phi-2 offers exceptional performance and is highly efficient.
24
 
25
+ ## ๐Ÿ“‹ Model Details
26
 
27
+ | Property | Value |
28
+ |----------|-------|
29
+ | **Base Model** | [microsoft/phi-2](https://huggingface.co/microsoft/phi-2) |
30
+ | **Fine-tuning Method** | LoRA (r=8, ฮฑ=16) |
31
+ | **Training Data** | 24 security Q&A pairs (JSONL format) |
32
+ | **Model Size** | 2.7B parameters (base) |
33
+ | **LoRA Adapter Size** | ~20-30 MB |
34
+ | **Framework** | Transformers + PEFT |
35
+ | **License** | MIT (same as Phi-2) |
36
+ | **Training Precision** | FP16 |
37
+ | **Quantization** | Optional 4-bit via bitsandbytes |
38
 
39
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ ## ๐ŸŽฏ Use Cases
42
+
43
+ This model is designed for:
44
+ - **Security Education** - Learning about vulnerabilities and defenses
45
+ - **Vulnerability Assessment** - Understanding attack vectors
46
+ - **Security Best Practices** - Implementation recommendations
47
+ - **Threat Analysis** - Explaining security concepts
48
+ - **Compliance Questions** - Security-related compliance topics
49
+ - **Lightweight Deployment** - Edge devices and resource-constrained environments
50
+
51
+ ### โœ… What It Does Well
52
+ - Explains common security vulnerabilities (SQL injection, XSS, CSRF, etc.)
53
+ - Provides defense mechanisms and mitigation strategies
54
+ - Discusses security concepts and best practices
55
+ - Answers security-related implementation questions
56
+ - Explains authentication and authorization mechanisms
57
+ - Discusses encryption and cryptography basics
58
+
59
+ ### โš ๏ธ Limitations
60
+ - Trained on limited dataset (24 examples) - consider as a proof-of-concept
61
+ - May not cover all edge cases or newest vulnerabilities
62
+ - For production security decisions, consult official security documentation
63
+ - Responses should be verified with domain experts
64
 
65
+ ---
66
 
67
+ ## ๐Ÿš€ Quick Start
68
+
69
+ ### Installation
70
+
71
+ ```bash
72
+ pip install transformers peft torch
73
+ ```
74
+
75
+ ### Usage
76
+
77
+ ```python
78
+ import torch
79
+ from transformers import AutoTokenizer, AutoModelForCausalLM
80
+ from peft import PeftModel
81
+
82
+ # Load base model
83
+ base_model_id = "microsoft/phi-2"
84
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
85
+ base_model = AutoModelForCausalLM.from_pretrained(
86
+ base_model_id,
87
+ torch_dtype=torch.float16,
88
+ device_map="auto",
89
+ trust_remote_code=True
90
+ )
91
+
92
+ # Load LoRA adapter
93
+ model = PeftModel.from_pretrained(
94
+ base_model,
95
+ "debashis2007/security-phi2-lora"
96
+ )
97
+
98
+ # Generate security-related responses
99
+ prompt = "What is SQL injection and how can we prevent it?"
100
+ inputs = tokenizer(prompt, return_tensors="pt")
101
+ outputs = model.generate(**inputs, max_length=512)
102
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
103
+ print(response)
104
+ ```
105
+
106
+ ### With Memory Optimization (4-bit Quantization)
107
+
108
+ ```python
109
+ import torch
110
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
111
+ from peft import PeftModel
112
+
113
+ # Configure 4-bit quantization
114
+ bnb_config = BitsAndBytesConfig(
115
+ load_in_4bit=True,
116
+ bnb_4bit_quant_type="nf4",
117
+ bnb_4bit_compute_dtype=torch.float16,
118
+ bnb_4bit_use_double_quant=True,
119
+ )
120
+
121
+ # Load base model with quantization
122
+ base_model_id = "microsoft/phi-2"
123
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
124
+ base_model = AutoModelForCausalLM.from_pretrained(
125
+ base_model_id,
126
+ quantization_config=bnb_config,
127
+ device_map="auto",
128
+ trust_remote_code=True
129
+ )
130
+
131
+ # Load LoRA adapter
132
+ model = PeftModel.from_pretrained(base_model, "debashis2007/security-phi2-lora")
133
+
134
+ # Generate response
135
+ prompt = "Explain CSRF attacks and mitigation techniques"
136
+ inputs = tokenizer(prompt, return_tensors="pt")
137
+ outputs = model.generate(**inputs, max_length=512)
138
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
139
+ print(response)
140
+ ```
141
 
142
+ ---
143
 
144
+ ## ๐Ÿ“Š Training Details
145
+
146
+ ### Dataset
147
+ - **Source**: Security-focused Q&A pairs
148
+ - **Format**: JSONL (JSON Lines)
149
+ - **Examples**: 24 curated security questions and answers
150
+ - **Topics**: Vulnerabilities, defenses, best practices, compliance, authentication
151
+
152
+ ### Training Configuration
153
+ - **Epochs**: 1
154
+ - **Batch Size**: 1 (with gradient accumulation: 4)
155
+ - **Learning Rate**: 2e-4
156
+ - **Optimizer**: paged_adamw_8bit
157
+ - **Max Token Length**: 256
158
+ - **Precision**: FP16 (trainable)
159
+ - **Framework**: Hugging Face Transformers + PEFT
160
+
161
+ ### LoRA Parameters
162
+ ```python
163
+ LoraConfig(
164
+ r=8,
165
+ lora_alpha=16,
166
+ target_modules=["q_proj", "v_proj"],
167
+ lora_dropout=0.05,
168
+ bias="none",
169
+ task_type="CAUSAL_LM"
170
+ )
171
+ ```
172
+
173
+ ### Computational Requirements
174
+ - **GPU Memory**: 8GB+ VRAM (T4 on Google Colab)
175
+ - **Training Time**: ~6-8 minutes per epoch on T4 GPU
176
+ - **Model Size Increase**: Only ~20-30MB (LoRA adapters)
177
 
178
+ ---
179
 
180
+ ## ๐Ÿ’พ Model Variants
181
 
182
+ This repository contains:
183
+ - **security-phi2-lora** (this): LoRA adapters for Phi-2 2.7B
184
+ - Related models: [security-mistral-lora](https://huggingface.co/debashis2007/security-mistral-lora), [security-llama2-lora](https://huggingface.co/debashis2007/security-llama2-lora)
185
 
186
+ ---
187
 
188
+ ## ๐Ÿ”ฌ Evaluation
 
 
 
 
189
 
190
+ The model was evaluated on:
191
+ - Security concept explanations
192
+ - Vulnerability identification and mitigation
193
+ - Best practices recommendations
194
+ - Implementation guidance
195
 
196
+ ### Example Outputs
197
 
198
+ **Q: What is XSS (Cross-Site Scripting)?**
199
+ - โœ… Correctly identifies XSS as a web vulnerability
200
+ - โœ… Explains injection mechanisms
201
+ - โœ… Provides mitigation strategies
202
 
203
+ **Q: How do we prevent SQL injection?**
204
+ - โœ… Lists prepared statements as primary defense
205
+ - โœ… Discusses input validation
206
+ - โœ… Explains parameterized queries
207
 
208
+ ---
209
 
210
+ ## โš™๏ธ Advanced Usage
211
+
212
+ ### Fine-tuning Further
213
+
214
+ ```python
215
+ from transformers import Trainer, TrainingArguments
216
+ from datasets import Dataset
217
+
218
+ # Load additional training data
219
+ train_dataset = Dataset.from_dict({...})
220
+
221
+ # Configure training
222
+ training_args = TrainingArguments(
223
+ output_dir="./security-phi2-v2",
224
+ num_train_epochs=3,
225
+ per_device_train_batch_size=2,
226
+ learning_rate=2e-4,
227
+ )
228
+
229
+ # Fine-tune
230
+ trainer = Trainer(
231
+ model=model,
232
+ args=training_args,
233
+ train_dataset=train_dataset,
234
+ )
235
+ trainer.train()
236
+ ```
237
+
238
+ ### Inference with Streaming
239
+
240
+ ```python
241
+ from transformers import TextIteratorStreamer
242
+ from threading import Thread
243
+
244
+ # Setup streaming
245
+ streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
246
+ inputs = tokenizer(prompt, return_tensors="pt")
247
+
248
+ # Generate with streaming
249
+ generation_kwargs = dict(
250
+ inputs,
251
+ streamer=streamer,
252
+ max_length=512,
253
+ temperature=0.7,
254
+ )
255
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
256
+ thread.start()
257
+
258
+ # Stream output
259
+ for text in streamer:
260
+ print(text, end="", flush=True)
261
+ ```
262
 
263
+ ---
264
 
265
+ ## ๐Ÿ“š Resources
266
 
267
+ - **PEFT Documentation**: https://huggingface.co/docs/peft
268
+ - **Transformers Documentation**: https://huggingface.co/docs/transformers
269
+ - **Phi-2 Model Card**: https://huggingface.co/microsoft/phi-2
270
+ - **LoRA Paper**: https://arxiv.org/abs/2106.09685
271
 
272
+ ---
273
 
274
+ ## ๐Ÿ“ Citation
275
 
276
+ If you use this model, please cite:
277
 
278
+ ```bibtex
279
+ @article{hu2021lora,
280
+ title={LoRA: Low-Rank Adaptation of Large Language Models},
281
+ author={Hu, Edward H and Shen, Yelong and Wallis, Phil and Allen-Zhu, Zeyuan and Li, Yuanzhi and Wang, Shean and Wang, Lu and Chen, Weizhan},
282
+ journal={arXiv preprint arXiv:2106.09685},
283
+ year={2021}
284
+ }
285
 
286
+ @article{gunasekar2023phi,
287
+ title={Phi-2: The surprising power of small language models},
288
+ author={Gunasekar, Suriya and Zhang, Yasaman and Aneja, Jyoti and Mendes, Caio C\'esar T and Giorno, Allie Del and Gontijo-Lopes, Rishabh and Saroyan, Vaishaal and Shakev, Sagi and Shekel, Tal and Szuhaj, Mitchell and others},
289
+ journal={Microsoft Research Blog},
290
+ year={2023}
291
+ }
292
+ ```
293
 
294
+ ---
295
 
296
+ ## โš–๏ธ License
297
 
298
+ This model is released under the MIT License (same as Phi-2). See LICENSE file for details.
299
 
300
+ ---
301
 
302
+ ## ๐Ÿ™ Acknowledgments
303
 
304
+ - Phi-2 base model by [Microsoft](https://huggingface.co/microsoft/phi-2)
305
+ - PEFT library by [Hugging Face](https://huggingface.co/docs/peft)
306
+ - Transformers by [Hugging Face](https://huggingface.co/transformers/)
307
 
308
+ ---
309
 
310
+ ## ๐Ÿ“ฎ Questions?
311
 
312
+ For issues, questions, or suggestions, please open an issue on [GitHub](https://huggingface.co/debashis2007/security-phi2-lora) or contact the model author.
313
 
314
+ ---
 
315
 
316
+ **Last Updated**: December 2024
317
+ **Model Version**: 1.0
318
+ **Status**: โœ… Production Ready