File size: 1,740 Bytes
4dfb4e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
from datasets import load_dataset
import torch

# Step 1: Load tokenizer and model (use full BERT)
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=3)

# Move model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
print("Using device:", device)

# Step 2: Load your cleaned dataset
dataset = load_dataset("csv", data_files="Qbias/cleaned_qbias_balanced.csv")["train"]

# Step 3: Split into train and test
dataset = dataset.train_test_split(test_size=0.1)

# Step 4: Tokenization function
def tokenize_function(example):
    return tokenizer(example["text"], padding="max_length", truncation=True, max_length=512)

# Step 5: Tokenize the dataset
tokenized_dataset = dataset.map(tokenize_function, batched=True)

# Step 6: Set the format for PyTorch
tokenized_dataset.set_format(type="torch", columns=["input_ids", "attention_mask",
 "label"])

# Step 7: Define training arguments
training_args = TrainingArguments(
    output_dir="./bert-bias-detector",
    evaluation_strategy="epoch",
    save_strategy="epoch",
    per_device_train_batch_size=8,  # Lower for full BERT on 2080 Ti
    per_device_eval_batch_size=8,
    num_train_epochs=3,
    weight_decay=0.01,
    logging_dir="./logs",
    logging_steps=500,
)

# Step 8: Define Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["test"],
    tokenizer=tokenizer,
)

# Step 9: Train the model
trainer.train()