Canstralian commited on
Commit
787a425
·
verified ·
1 Parent(s): 495e9d3

Update train_and_save_model.py

Browse files
Files changed (1) hide show
  1. train_and_save_model.py +54 -99
train_and_save_model.py CHANGED
@@ -1,99 +1,54 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.optim as optim
4
- from torch.utils.data import DataLoader, Dataset
5
- import json
6
- import os
7
-
8
- # Step 1: Define Your Dataset Class
9
- class CustomDataset(Dataset):
10
- def __init__(self, texts, labels):
11
- self.texts = texts
12
- self.labels = labels
13
-
14
- def __len__(self):
15
- return len(self.texts)
16
-
17
- def __getitem__(self, idx):
18
- return self.texts[idx], self.labels[idx]
19
-
20
- # Step 2: Define Your Model Class
21
- class LSTMModel(nn.Module):
22
- def __init__(self, input_size, hidden_size, output_size):
23
- super(LSTMModel, self).__init__()
24
- self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
25
- self.fc = nn.Linear(hidden_size, output_size)
26
-
27
- def forward(self, x):
28
- lstm_out, _ = self.lstm(x)
29
- out = self.fc(lstm_out[:, -1, :]) # Get the last time step output
30
- return out
31
-
32
- # Step 3: Initialize Hyperparameters and Model
33
- input_size = 100 # Example input size (e.g., embedding size)
34
- hidden_size = 64 # Number of LSTM units
35
- output_size = 10 # Number of output classes
36
- num_epochs = 5
37
- learning_rate = 0.001
38
-
39
- # Initialize the model
40
- model = LSTMModel(input_size, hidden_size, output_size)
41
-
42
- # Step 4: Set Up Loss and Optimizer
43
- criterion = nn.CrossEntropyLoss()
44
- optimizer = optim.Adam(model.parameters(), lr=learning_rate)
45
-
46
- # Step 5: Sample Data (You would replace this with your actual data)
47
- # Here, we create random data for demonstration purposes
48
- texts = torch.randn(100, 10, input_size) # 100 samples, sequence length of 10
49
- labels = torch.randint(0, output_size, (100,)) # 100 random labels
50
-
51
- # Create a DataLoader
52
- dataset = CustomDataset(texts, labels)
53
- data_loader = DataLoader(dataset, batch_size=16, shuffle=True)
54
-
55
- # Step 6: Training Loop
56
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
57
- model.to(device) # Move model to the correct device
58
-
59
- for epoch in range(num_epochs):
60
- for inputs, targets in data_loader:
61
- # Move data to the same device as the model
62
- inputs, targets = inputs.to(device), targets.to(device)
63
-
64
- # Forward pass
65
- outputs = model(inputs)
66
- loss = criterion(outputs, targets)
67
-
68
- # Backward pass and optimization
69
- optimizer.zero_grad()
70
- loss.backward()
71
- optimizer.step()
72
-
73
- # Print loss for every batch
74
- print(f'Epoch [{epoch+1}/{num_epochs}], Batch Loss: {loss.item():.4f}')
75
-
76
- # Print epoch summary
77
- print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
78
-
79
- # Step 7: Save the Model
80
- model_save_path = "path/to/save/model_directory" # Change this to your desired path
81
- os.makedirs(model_save_path, exist_ok=True) # Create the directory if it doesn't exist
82
-
83
- # Save the model weights
84
- torch.save(model.state_dict(), os.path.join(model_save_path, "pytorch_model.bin"))
85
-
86
- # Step 8: Create and Save the Configuration File
87
- config = {
88
- "input_size": input_size,
89
- "hidden_size": hidden_size,
90
- "output_size": output_size,
91
- "num_layers": 1, # Add more parameters as needed
92
- "dropout": 0.2
93
- }
94
-
95
- # Save the configuration to a JSON file
96
- with open(os.path.join(model_save_path, "config.json"), "w") as f:
97
- json.dump(config, f)
98
-
99
- print("Model and configuration saved successfully!")
 
1
+ from datasets import load_dataset
2
+ from transformers import AutoAdapterModel, AutoTokenizer, Trainer, TrainingArguments
3
+
4
+ # Load datasets
5
+ dataset_pentesting = load_dataset("canstralian/pentesting-ai")
6
+ dataset_redpajama = load_dataset("togethercomputer/RedPajama-Data-1T")
7
+
8
+ # Tokenizer
9
+ tokenizer = AutoTokenizer.from_pretrained("canstralian/rabbitredeux")
10
+
11
+ def tokenize_function(examples):
12
+ return tokenizer(examples['text'], padding="max_length", truncation=True)
13
+
14
+ # Tokenize datasets
15
+ tokenized_dataset_pentesting = dataset_pentesting.map(tokenize_function, batched=True)
16
+ tokenized_dataset_redpajama = dataset_redpajama.map(tokenize_function, batched=True)
17
+
18
+ # Prepare datasets
19
+ train_dataset_pentesting = tokenized_dataset_pentesting["train"]
20
+ validation_dataset_pentesting = tokenized_dataset_pentesting["validation"]
21
+
22
+ # Load model and adapter
23
+ model = AutoAdapterModel.from_pretrained("canstralian/rabbitredeux")
24
+ model.load_adapter("Canstralian/RabbitRedux", set_active=True)
25
+
26
+ # Training arguments
27
+ training_args = TrainingArguments(
28
+ output_dir="./results",
29
+ num_train_epochs=3,
30
+ per_device_train_batch_size=8,
31
+ per_device_eval_batch_size=8,
32
+ warmup_steps=500,
33
+ weight_decay=0.01,
34
+ logging_dir="./logs",
35
+ logging_steps=10,
36
+ evaluation_strategy="epoch",
37
+ )
38
+
39
+ # Trainer setup
40
+ trainer = Trainer(
41
+ model=model,
42
+ args=training_args,
43
+ train_dataset=train_dataset_pentesting,
44
+ eval_dataset=validation_dataset_pentesting,
45
+ )
46
+
47
+ # Training
48
+ trainer.train()
49
+
50
+ # Evaluate model
51
+ trainer.evaluate()
52
+
53
+ # Save the fine-tuned model
54
+ model.save_pretrained("./fine_tuned_model")