Canstralian commited on
Commit
d724ba4
·
verified ·
1 Parent(s): 43971f1

Update model.py

Browse files
Files changed (1) hide show
  1. model.py +122 -1
model.py CHANGED
@@ -1,15 +1,136 @@
1
- from transformers import AutoTokenizer, AutoModelForCausalLM
 
2
  from config import Config
 
 
 
3
 
4
  class CyberAttackDetectionModel:
5
  def __init__(self):
 
6
  self.tokenizer = AutoTokenizer.from_pretrained(Config.TOKENIZER_NAME)
7
  self.model = AutoModelForCausalLM.from_pretrained(Config.MODEL_NAME)
8
  self.model.to(Config.DEVICE)
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def predict(self, prompt):
11
  inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=Config.MAX_LENGTH)
12
  inputs = {key: value.to(Config.DEVICE) for key, value in inputs.items()}
13
 
14
  outputs = self.model.generate(**inputs, max_length=Config.MAX_LENGTH)
15
  return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
2
+ from datasets import load_dataset, Dataset, DatasetDict
3
  from config import Config
4
+ import torch
5
+ from sklearn.model_selection import train_test_split
6
+ import pandas as pd
7
 
8
  class CyberAttackDetectionModel:
9
  def __init__(self):
10
+ # Initialize tokenizer and model
11
  self.tokenizer = AutoTokenizer.from_pretrained(Config.TOKENIZER_NAME)
12
  self.model = AutoModelForCausalLM.from_pretrained(Config.MODEL_NAME)
13
  self.model.to(Config.DEVICE)
14
 
15
+ def preprocess_data(self, dataset):
16
+ """
17
+ Preprocess the raw text dataset by cleaning and tokenizing.
18
+ """
19
+ # Clean the dataset (basic text normalization, removing unwanted characters)
20
+ def clean_text(text):
21
+ # Implement custom cleaning function based on dataset's characteristics
22
+ # E.g., removing unwanted characters, special symbols, etc.
23
+ text = text.lower() # Example of making text lowercase
24
+ text = text.replace("\n", " ") # Removing newlines
25
+ return text
26
+
27
+ # Apply cleaning to the dataset
28
+ dataset = dataset.map(lambda x: {'text': clean_text(x['text'])})
29
+
30
+ # Tokenization
31
+ def tokenize_function(examples):
32
+ return self.tokenizer(examples['text'], truncation=True, padding='max_length', max_length=Config.MAX_LENGTH)
33
+
34
+ # Tokenize the entire dataset
35
+ tokenized_dataset = dataset.map(tokenize_function, batched=True)
36
+
37
+ # Set format for PyTorch
38
+ tokenized_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
39
+
40
+ return tokenized_dataset
41
+
42
+ def fine_tune(self, datasets):
43
+ """
44
+ Fine-tune the model with the preprocessed datasets.
45
+ """
46
+ # Load datasets (after pre-processing)
47
+ dataset_dict = DatasetDict({
48
+ "train": datasets['train'],
49
+ "validation": datasets['validation'],
50
+ })
51
+
52
+ # Training arguments
53
+ training_args = TrainingArguments(
54
+ output_dir=Config.OUTPUT_DIR,
55
+ evaluation_strategy="epoch",
56
+ learning_rate=Config.LEARNING_RATE,
57
+ per_device_train_batch_size=Config.BATCH_SIZE,
58
+ per_device_eval_batch_size=Config.BATCH_SIZE,
59
+ weight_decay=Config.WEIGHT_DECAY,
60
+ save_total_limit=3,
61
+ num_train_epochs=Config.NUM_EPOCHS,
62
+ logging_dir=Config.LOGGING_DIR,
63
+ load_best_model_at_end=True
64
+ )
65
+
66
+ # Trainer
67
+ trainer = Trainer(
68
+ model=self.model,
69
+ args=training_args,
70
+ train_dataset=dataset_dict['train'],
71
+ eval_dataset=dataset_dict['validation'],
72
+ )
73
+
74
+ # Fine-tuning
75
+ trainer.train()
76
+
77
  def predict(self, prompt):
78
  inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=Config.MAX_LENGTH)
79
  inputs = {key: value.to(Config.DEVICE) for key, value in inputs.items()}
80
 
81
  outputs = self.model.generate(**inputs, max_length=Config.MAX_LENGTH)
82
  return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
83
+
84
+ def load_and_process_datasets(self):
85
+ """
86
+ Loads and preprocesses the datasets for fine-tuning.
87
+ """
88
+ # Load your OSINT and WhiteRabbitNeo datasets
89
+ osint_datasets = [
90
+ 'gonferspanish/OSINT',
91
+ 'Inforensics/missing-persons-clue-analysis-osint',
92
+ 'jester6136/osint',
93
+ 'originalbox/osint'
94
+ ]
95
+
96
+ wrn_datasets = [
97
+ 'WhiteRabbitNeo/WRN-Chapter-2',
98
+ 'WhiteRabbitNeo/WRN-Chapter-1',
99
+ 'WhiteRabbitNeo/Code-Functions-Level-Cyber'
100
+ ]
101
+
102
+ # Combine all datasets into one for training
103
+ combined_datasets = []
104
+
105
+ # Load and preprocess OSINT datasets
106
+ for dataset_name in osint_datasets:
107
+ dataset = load_dataset(dataset_name)
108
+ processed_data = self.preprocess_data(dataset['train']) # Assuming the 'train' split exists
109
+ combined_datasets.append(processed_data)
110
+
111
+ # Load and preprocess WhiteRabbitNeo datasets
112
+ for dataset_name in wrn_datasets:
113
+ dataset = load_dataset(dataset_name)
114
+ processed_data = self.preprocess_data(dataset['train']) # Assuming the 'train' split exists
115
+ combined_datasets.append(processed_data)
116
+
117
+ # Combine all preprocessed datasets
118
+ full_dataset = DatasetDict()
119
+ full_dataset['train'] = Dataset.from_dict(pd.concat([d['train'] for d in combined_datasets]))
120
+ full_dataset['validation'] = Dataset.from_dict(pd.concat([d['validation'] for d in combined_datasets]))
121
+
122
+ return full_dataset
123
+
124
+ if __name__ == "__main__":
125
+ # Create the model object
126
+ model = CyberAttackDetectionModel()
127
+
128
+ # Load and preprocess datasets
129
+ preprocessed_datasets = model.load_and_process_datasets()
130
+
131
+ # Fine-tune the model
132
+ model.fine_tune(preprocessed_datasets)
133
+
134
+ # Example prediction
135
+ prompt = "A network scan reveals an open port 22 with an outdated SSH service."
136
+ print(model.predict(prompt))