| import torch |
| from transformers import GPT2LMHeadModel, GPT2Tokenizer, DataCollatorForLanguageModeling |
| from transformers import Trainer, TrainingArguments |
| from datasets import load_dataset |
| import pandas as pd |
| import os |
|
|
| def check_device(): |
| """Check and return the available device""" |
| if torch.cuda.is_available(): |
| print("Using GPU:", torch.cuda.get_device_name(0)) |
| return "cuda" |
| else: |
| print("No GPU available, using CPU") |
| return "cpu" |
|
|
| def prepare_data(csv_file, text_column): |
| """Prepare training data, filtering out empty rows.""" |
| df = pd.read_csv(csv_file) |
| |
| |
| df = df.dropna(subset=[text_column]) |
| |
| |
| with open('train_data.txt', 'w', encoding='utf-8') as f: |
| for text in df[text_column]: |
| f.write(str(text) + '\n') |
| |
| return 'train_data.txt' |
|
|
| def tokenize_function(examples, tokenizer): |
| """Tokenize the text using the GPT-2 tokenizer""" |
| |
| return tokenizer(examples['text'], padding="max_length", truncation=True, max_length=128) |
|
|
| def train_model(model, dataset, tokenizer): |
| """Train the model with proper device configuration""" |
| |
| data_collator = DataCollatorForLanguageModeling( |
| tokenizer=tokenizer, |
| mlm=False |
| ) |
| |
| |
| os.makedirs("./gpt2-custom", exist_ok=True) |
| |
| |
| training_args = TrainingArguments( |
| output_dir="./gpt2-custom", |
| overwrite_output_dir=True, |
| num_train_epochs=5, |
| per_device_train_batch_size=3, |
| per_device_eval_batch_size=3, |
| save_steps=10_000, |
| save_total_limit=2, |
| logging_dir="./logs", |
| logging_steps=500, |
| use_cpu=(check_device() == "cpu"), |
| ) |
| |
| |
| dataset = dataset.map(lambda examples: tokenize_function(examples, tokenizer), batched=True) |
| dataset.set_format(type="torch", columns=["input_ids", "attention_mask"]) |
|
|
| |
| trainer = Trainer( |
| model=model, |
| args=training_args, |
| data_collator=data_collator, |
| train_dataset=dataset['train'], |
| ) |
| |
| |
| trainer.train() |
| |
| |
| model.save_pretrained('./gpt2-custom') |
| tokenizer.save_pretrained('./gpt2-custom') |
|
|
| def main(): |
| try: |
| |
| device = check_device() |
| |
| |
| csv_file = './csvs/mission.csv' |
| text_column = 'Mission' |
| |
| |
| print("Preparing data...") |
| train_file = prepare_data(csv_file, text_column) |
| |
| |
| print("Loading model and tokenizer...") |
| tokenizer = GPT2Tokenizer.from_pretrained('gpt2') |
| model = GPT2LMHeadModel.from_pretrained('gpt2') |
| |
| |
| model = model.to(device) |
| |
| |
| tokenizer.pad_token = tokenizer.eos_token |
| |
| |
| print("Loading dataset...") |
| dataset = load_dataset('text', data_files={'train': train_file}) |
|
|
| |
| print("Training model...") |
| train_model(model, dataset, tokenizer) |
| |
| print("Training completed successfully!") |
| |
| except Exception as e: |
| print(f"An error occurred: {str(e)}") |
| print("Stack trace:") |
| import traceback |
| traceback.print_exc() |
|
|
| if __name__ == "__main__": |
| main() |
|
|