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()