Download train.py from taiy0/Rae: direct link, hf CLI and curl.
- Browser
- Download file 2.54 kB
-
https://huggingface.co/spaces/taiy0/Rae/resolve/main/train.py
- Command line
-
hf download hf://spaces/taiy0/Rae/train.py
-
curl -L -o train.py https://huggingface.co/spaces/taiy0/Rae/resolve/main/train.py
2.54 kB
| from datasets import load_dataset | |
| from transformers import GPT2LMHeadModel, GPT2Tokenizer, Trainer, TrainingArguments | |
| # Load BlendedSkillTalk dataset (train & validation) | |
| general_ds_train = load_dataset("daily_dialog", split="train", trust_remote_code=True) | |
| general_ds_val = load_dataset("daily_dialog", split="validation", trust_remote_code=True) | |
| def format_general_dataset(examples): | |
| conversations = [] | |
| for dialog in examples["dialog"]: | |
| conversation = "" | |
| for i, utterance in enumerate(dialog): | |
| speaker = "User: " if i % 2 == 0 else "Chatbot: " | |
| utterance_text = " ".join(utterance) if isinstance(utterance, list) else utterance | |
| conversation += speaker + utterance_text + " " | |
| if speaker == "Chatbot: ": | |
| conversation += "<|endoftext|> " | |
| conversations.append(conversation.strip()) | |
| return {"text": conversations} | |
| general_ds_train = general_ds_train.map(format_general_dataset, batched=True, remove_columns=["dialog", "act", "emotion"]) | |
| general_ds_val = general_ds_val.map(format_general_dataset, batched=True, remove_columns=["dialog", "act", "emotion"]) | |
| # Initialize tokenizer | |
| tokenizer = GPT2Tokenizer.from_pretrained("gpt2", local_files_only=True) | |
| tokenizer.pad_token = tokenizer.eos_token | |
| # Tokenization function | |
| def tokenizing_function(examples): | |
| tokenized_output = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=128) | |
| tokenized_output["labels"] = tokenized_output["input_ids"].copy() | |
| return tokenized_output | |
| # Tokenize datasets | |
| general_ds_train = general_ds_train.map(tokenizing_function, batched=True) | |
| general_ds_val = general_ds_val.map(tokenizing_function, batched=True) | |
| # Load GPT-2 model | |
| model = GPT2LMHeadModel.from_pretrained("./gpt2_finetuned1", local_files_only=True) | |
| training_args = TrainingArguments( | |
| output_dir="./gpt2_finetuned", | |
| eval_strategy="epoch", | |
| save_strategy="epoch", | |
| per_device_train_batch_size=4, | |
| per_device_eval_batch_size=4, | |
| gradient_accumulation_steps=2, | |
| num_train_epochs=5, | |
| weight_decay=0.01, | |
| logging_dir="./logs", | |
| resume_from_checkpoint=True, | |
| fp16=True, | |
| ) | |
| trainer = Trainer( | |
| model=model.to("cuda"), | |
| args=training_args, | |
| train_dataset=general_ds_train, | |
| eval_dataset=general_ds_val | |
| ) | |
| trainer.train() | |
| # Save model and tokenizer | |
| model.save_pretrained("./gpt2_finetuned") | |
| tokenizer.save_pretrained("./gpt2_finetuned") | |